/**
  * Common actions for all methods in the class
  */
 public function pre_dispatch()
 {
     global $context;
     $context['page_title'] = $context['forum_name'];
     if (isset($context['page_title_html_safe'])) {
         $context['page_title_html_safe'] = Util::htmlspecialchars(un_htmlspecialchars($context['page_title']));
     }
     if (!empty($context['standalone'])) {
         setupMenuContext();
     }
 }
Example #2
0
function GetJumpTo()
{
    global $user_info, $context, $smcFunc, $sourcedir;
    // Find the boards/cateogories they can see.
    require_once $sourcedir . '/Subs-MessageIndex.php';
    $boardListOptions = array('use_permissions' => true, 'selected_board' => isset($context['current_board']) ? $context['current_board'] : 0);
    $context['jump_to'] = getBoardList($boardListOptions);
    // Make the board safe for display.
    foreach ($context['jump_to'] as $id_cat => $cat) {
        $context['jump_to'][$id_cat]['name'] = un_htmlspecialchars(strip_tags($cat['name']));
        foreach ($cat['boards'] as $id_board => $board) {
            $context['jump_to'][$id_cat]['boards'][$id_board]['name'] = un_htmlspecialchars(strip_tags($board['name']));
        }
    }
    $context['sub_template'] = 'jump_to';
}
Example #3
0
 /**
  * Get a list of boards and categories used for the jumpto dropdown.
  */
 public function action_jumpto()
 {
     global $context;
     // Find the boards/categories they can see.
     require_once SUBSDIR . '/Boards.subs.php';
     $boardListOptions = array('selected_board' => isset($context['current_board']) ? $context['current_board'] : 0);
     $context += getBoardList($boardListOptions);
     // Make the board safe for display.
     foreach ($context['categories'] as $id_cat => $cat) {
         $context['categories'][$id_cat]['name'] = un_htmlspecialchars(strip_tags($cat['name']));
         foreach ($cat['boards'] as $id_board => $board) {
             $context['categories'][$id_cat]['boards'][$id_board]['name'] = un_htmlspecialchars(strip_tags($board['name']));
         }
     }
     $context['sub_template'] = 'jump_to';
 }
function retrieveGlobalHFContent($placement)
{
    global $context, $boarddir, $sourcedir, $global_hf, $modSettings;
    if (!isset($_GET['xml']) && (!isset($_GET['action']) || $_GET['action'] != 'dlattach')) {
        $global_hf = array('head' => un_htmlspecialchars(file_get_contents($boarddir . '/smfhacks_resources/global-hf-head.txt')), 'header' => un_htmlspecialchars(file_get_contents($boarddir . '/smfhacks_resources/global-hf-header.txt')), 'footer' => un_htmlspecialchars(file_get_contents($boarddir . '/smfhacks_resources/global-hf-footer.txt')));
        if ($placement != 'load') {
            if (!empty($modSettings['global_header_bbc'])) {
                $global_hf['parsed']['header'] = parse_bbc($global_hf['header']);
            }
            if (!empty($modSettings['global_footer_bbc'])) {
                $global_hf['parsed']['footer'] = parse_bbc($global_hf['footer']);
            }
            loadTemplate('smfhacks_templates/global-hf');
            loadSubTemplate('global_hf' . $placement, true);
        } elseif (!empty($global_hf['head'])) {
            $context['html_headers'] .= "\n" . $global_hf['head'];
        }
    }
}
Example #5
0
function EditorMain()
{
    global $context, $smcFunc;
    checkSession('get');
    if (!isset($_REQUEST['view']) || !isset($_REQUEST['message'])) {
        fatal_lang_error('no_access', false);
    }
    $context['sub_template'] = 'sendbody';
    $context['view'] = (int) $_REQUEST['view'];
    // Return the right thing for the mode.
    if ($context['view']) {
        $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '<', '#smgt#' => '>', '#smamp#' => '&'));
        $context['message'] = bbc_to_html($_REQUEST['message']);
    } else {
        $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
        $_REQUEST['message'] = strtr($_REQUEST['message'], array('#smcol#' => ';', '#smlt#' => '<', '#smgt#' => '>', '#smamp#' => '&'));
        $context['message'] = html_to_bbc($_REQUEST['message']);
    }
    $context['message'] = commonAPI::htmlspecialchars($context['message']);
}
function sportal_main()
{
    global $smcFunc, $context, $sourcedir;
    if (WIRELESS) {
        redirectexit('action=forum');
    }
    $context['page_title'] = $context['forum_name'];
    if (isset($context['page_title_html_safe'])) {
        $context['page_title_html_safe'] = $smcFunc['htmlspecialchars'](un_htmlspecialchars($context['page_title']));
    }
    if (!empty($context['standalone'])) {
        setupMenuContext();
    }
    $actions = array('addarticle' => array('PortalArticles.php', 'sportal_add_article'), 'articles' => array('PortalArticles.php', 'sportal_articles'), 'credits' => array('', 'sportal_credits'), 'pages' => array('PortalPages.php', 'sportal_pages'), 'removearticle' => array('PortalArticles.php', 'sportal_remove_article'), 'shoutbox' => array('PortalShoutbox.php', 'sportal_shoutbox'));
    if (!isset($_REQUEST['sa']) || !isset($actions[$_REQUEST['sa']])) {
        $_REQUEST['sa'] = 'articles';
    }
    if (!empty($actions[$_REQUEST['sa']][0])) {
        require_once $sourcedir . '/' . $actions[$_REQUEST['sa']][0];
    }
    $actions[$_REQUEST['sa']][1]();
}
    /**
     * Issue/manage an user's warning status.
     * @uses ProfileAccount template issueWarning sub template
     * @uses Profile template
     */
    public function action_issuewarning()
    {
        global $txt, $scripturl, $modSettings, $mbname, $context, $cur_profile;
        $memID = currentMemberID();
        // make sure the sub-template is set...
        loadTemplate('ProfileAccount');
        $context['sub_template'] = 'issueWarning';
        // We need this because of template_load_warning_variables
        loadTemplate('Profile');
        loadJavascriptFile('profile.js');
        // jQuery-UI FTW!
        $modSettings['jquery_include_ui'] = true;
        loadCSSFile('jquery.ui.slider.css');
        loadCSSFile('jquery.ui.theme.css');
        // Get all the actual settings.
        list($modSettings['warning_enable'], $modSettings['user_limit']) = explode(',', $modSettings['warning_settings']);
        // This stores any legitimate errors.
        $issueErrors = array();
        // Doesn't hurt to be overly cautious.
        if (empty($modSettings['warning_enable']) || $context['user']['is_owner'] && !$cur_profile['warning'] || !allowedTo('issue_warning')) {
            fatal_lang_error('no_access', false);
        }
        // Get the base (errors related) stuff done.
        loadLanguage('Errors');
        $context['custom_error_title'] = $txt['profile_warning_errors_occurred'];
        // Make sure things which are disabled stay disabled.
        $modSettings['warning_watch'] = !empty($modSettings['warning_watch']) ? $modSettings['warning_watch'] : 110;
        $modSettings['warning_moderate'] = !empty($modSettings['warning_moderate']) && !empty($modSettings['postmod_active']) ? $modSettings['warning_moderate'] : 110;
        $modSettings['warning_mute'] = !empty($modSettings['warning_mute']) ? $modSettings['warning_mute'] : 110;
        $context['warning_limit'] = allowedTo('admin_forum') ? 0 : $modSettings['user_limit'];
        $context['member']['warning'] = $cur_profile['warning'];
        $context['member']['name'] = $cur_profile['real_name'];
        // What are the limits we can apply?
        $context['min_allowed'] = 0;
        $context['max_allowed'] = 100;
        if ($context['warning_limit'] > 0) {
            require_once SUBSDIR . '/Moderation.subs.php';
            $current_applied = warningDailyLimit($memID);
            $context['min_allowed'] = max(0, $cur_profile['warning'] - $current_applied - $context['warning_limit']);
            $context['max_allowed'] = min(100, $cur_profile['warning'] - $current_applied + $context['warning_limit']);
        }
        // Defaults.
        $context['warning_data'] = array('reason' => '', 'notify' => '', 'notify_subject' => '', 'notify_body' => '');
        // Are we saving?
        if (isset($_POST['save'])) {
            // Security is good here.
            checkSession('post');
            // This cannot be empty!
            $_POST['warn_reason'] = isset($_POST['warn_reason']) ? trim($_POST['warn_reason']) : '';
            if ($_POST['warn_reason'] == '' && !$context['user']['is_owner']) {
                $issueErrors[] = 'warning_no_reason';
            }
            $_POST['warn_reason'] = Util::htmlspecialchars($_POST['warn_reason']);
            // If the value hasn't changed it's either no JS or a real no change (Which this will pass)
            if ($_POST['warning_level'] == 'SAME') {
                $_POST['warning_level'] = $_POST['warning_level_nojs'];
            }
            $_POST['warning_level'] = (int) $_POST['warning_level'];
            $_POST['warning_level'] = max(0, min(100, $_POST['warning_level']));
            if ($_POST['warning_level'] < $context['min_allowed']) {
                $_POST['warning_level'] = $context['min_allowed'];
            } elseif ($_POST['warning_level'] > $context['max_allowed']) {
                $_POST['warning_level'] = $context['max_allowed'];
            }
            require_once SUBSDIR . '/Moderation.subs.php';
            // Do we actually have to issue them with a PM?
            $id_notice = 0;
            if (!empty($_POST['warn_notify']) && empty($issueErrors)) {
                $_POST['warn_sub'] = trim($_POST['warn_sub']);
                $_POST['warn_body'] = trim($_POST['warn_body']);
                if (empty($_POST['warn_sub']) || empty($_POST['warn_body'])) {
                    $issueErrors[] = 'warning_notify_blank';
                } else {
                    require_once SUBSDIR . '/PersonalMessage.subs.php';
                    $from = array('id' => 0, 'name' => $context['forum_name'], 'username' => $context['forum_name']);
                    sendpm(array('to' => array($memID), 'bcc' => array()), $_POST['warn_sub'], $_POST['warn_body'], false, $from);
                    // Log the notice.
                    $id_notice = logWarningNotice($_POST['warn_sub'], $_POST['warn_body']);
                }
            }
            // Just in case - make sure notice is valid!
            $id_notice = (int) $id_notice;
            // What have we changed?
            $level_change = $_POST['warning_level'] - $cur_profile['warning'];
            // No errors? Proceed! Only log if you're not the owner.
            if (empty($issueErrors)) {
                // Log what we've done!
                if (!$context['user']['is_owner']) {
                    logWarning($memID, $cur_profile['real_name'], $id_notice, $level_change, $_POST['warn_reason']);
                }
                // Make the change.
                updateMemberData($memID, array('warning' => $_POST['warning_level']));
                // Leave a lovely message.
                $context['profile_updated'] = $context['user']['is_owner'] ? $txt['profile_updated_own'] : $txt['profile_warning_success'];
            } else {
                // Try to remember some bits.
                $context['warning_data'] = array('reason' => $_POST['warn_reason'], 'notify' => !empty($_POST['warn_notify']), 'notify_subject' => isset($_POST['warn_sub']) ? $_POST['warn_sub'] : '', 'notify_body' => isset($_POST['warn_body']) ? $_POST['warn_body'] : '');
            }
            // Show the new improved warning level.
            $context['member']['warning'] = $_POST['warning_level'];
        }
        // Taking a look first, good idea that one.
        if (isset($_POST['preview'])) {
            $warning_body = !empty($_POST['warn_body']) ? trim(censorText($_POST['warn_body'])) : '';
            $context['preview_subject'] = !empty($_POST['warn_sub']) ? trim(Util::htmlspecialchars($_POST['warn_sub'])) : '';
            if (empty($_POST['warn_sub']) || empty($_POST['warn_body'])) {
                $issueErrors[] = 'warning_notify_blank';
            }
            if (!empty($_POST['warn_body'])) {
                require_once SUBSDIR . '/Post.subs.php';
                preparsecode($warning_body);
                $warning_body = parse_bbc($warning_body, true);
            }
            // Try to remember some bits.
            $context['warning_data'] = array('reason' => $_POST['warn_reason'], 'notify' => !empty($_POST['warn_notify']), 'notify_subject' => isset($_POST['warn_sub']) ? $_POST['warn_sub'] : '', 'notify_body' => isset($_POST['warn_body']) ? $_POST['warn_body'] : '', 'body_preview' => $warning_body);
        }
        if (!empty($issueErrors)) {
            // Fill in the suite of errors.
            $context['post_errors'] = array();
            foreach ($issueErrors as $error) {
                $context['post_errors'][] = $txt[$error];
            }
        }
        $context['page_title'] = $txt['profile_issue_warning'];
        // Let's use a generic list to get all the current warnings
        require_once SUBSDIR . '/GenericList.class.php';
        require_once SUBSDIR . '/Profile.subs.php';
        // Work our the various levels.
        $context['level_effects'] = array(0 => $txt['profile_warning_effect_none'], $modSettings['warning_watch'] => $txt['profile_warning_effect_watch'], $modSettings['warning_moderate'] => $txt['profile_warning_effect_moderation'], $modSettings['warning_mute'] => $txt['profile_warning_effect_mute']);
        $context['current_level'] = 0;
        foreach ($context['level_effects'] as $limit => $dummy) {
            if ($context['member']['warning'] >= $limit) {
                $context['current_level'] = $limit;
            }
        }
        // Build a list to view the warnings
        $listOptions = array('id' => 'issued_warnings', 'title' => $txt['profile_viewwarning_previous_warnings'], 'items_per_page' => $modSettings['defaultMaxMessages'], 'no_items_label' => $txt['profile_viewwarning_no_warnings'], 'base_href' => $scripturl . '?action=profile;area=issuewarning;sa=user;u=' . $memID, 'default_sort_col' => 'log_time', 'get_items' => array('function' => 'list_getUserWarnings', 'params' => array($memID)), 'get_count' => array('function' => 'list_getUserWarningCount', 'params' => array($memID)), 'columns' => array('issued_by' => array('header' => array('value' => $txt['profile_warning_previous_issued'], 'style' => 'width: 20%;'), 'data' => array('function' => create_function('$warning', '
							return $warning[\'issuer\'][\'link\'];
						')), 'sort' => array('default' => 'lc.member_name DESC', 'reverse' => 'lc.member_name')), 'log_time' => array('header' => array('value' => $txt['profile_warning_previous_time'], 'style' => 'width: 30%;'), 'data' => array('db' => 'time'), 'sort' => array('default' => 'lc.log_time DESC', 'reverse' => 'lc.log_time')), 'reason' => array('header' => array('value' => $txt['profile_warning_previous_reason']), 'data' => array('function' => create_function('$warning', '
							global $scripturl, $txt, $settings;

							$ret = \'
							<div class="floatleft">
								\' . $warning[\'reason\'] . \'
							</div>\';

							// If a notice was sent, provide a way to view it
							if (!empty($warning[\'id_notice\']))
								$ret .= \'
							<div class="floatright">
								<a href="\' . $scripturl . \'?action=moderate;area=notice;nid=\' . $warning[\'id_notice\'] . \'" onclick="window.open(this.href, \\\'\\\', \\\'scrollbars=yes,resizable=yes,width=400,height=250\\\');return false;" target="_blank" class="new_win" title="\' . $txt[\'profile_warning_previous_notice\'] . \'"><img src="\' . $settings[\'images_url\'] . \'/filter.png" alt="" /></a>
							</div>\';

							return $ret;'))), 'level' => array('header' => array('value' => $txt['profile_warning_previous_level'], 'style' => 'width: 6%;'), 'data' => array('db' => 'counter'), 'sort' => array('default' => 'lc.counter DESC', 'reverse' => 'lc.counter'))));
        // Create the list for viewing.
        createList($listOptions);
        $warning_for_message = isset($_REQUEST['msg']) ? (int) $_REQUEST['msg'] : false;
        $warned_message_subject = '';
        // Are they warning because of a message?
        if (isset($_REQUEST['msg']) && 0 < (int) $_REQUEST['msg']) {
            require_once SUBSDIR . '/Messages.subs.php';
            $message = basicMessageInfo((int) $_REQUEST['msg']);
            if (!empty($message)) {
                $warned_message_subject = $message['subject'];
            }
        }
        require_once SUBSDIR . '/Maillist.subs.php';
        // Any custom templates?
        $context['notification_templates'] = array();
        $notification_templates = maillist_templates('warntpl');
        foreach ($notification_templates as $row) {
            // If we're not warning for a message skip any that are.
            if (!$warning_for_message && strpos($row['body'], '{MESSAGE}') !== false) {
                continue;
            }
            $context['notification_templates'][] = array('title' => $row['title'], 'body' => $row['body']);
        }
        // Setup the "default" templates.
        foreach (array('spamming', 'offence', 'insulting') as $type) {
            $context['notification_templates'][] = array('title' => $txt['profile_warning_notify_title_' . $type], 'body' => sprintf($txt['profile_warning_notify_template_outline' . (!empty($warning_for_message) ? '_post' : '')], $txt['profile_warning_notify_for_' . $type]));
        }
        // Replace all the common variables in the templates.
        foreach ($context['notification_templates'] as $k => $name) {
            $context['notification_templates'][$k]['body'] = strtr($name['body'], array('{MEMBER}' => un_htmlspecialchars($context['member']['name']), '{MESSAGE}' => '[url=' . $scripturl . '?msg=' . $warning_for_message . ']' . un_htmlspecialchars($warned_message_subject) . '[/url]', '{SCRIPTURL}' => $scripturl, '{FORUMNAME}' => $mbname, '{REGARDS}' => replaceBasicActionUrl($txt['regards_team'])));
        }
    }
Example #8
0
/**
* Will authenticate the username/password combo
*
* Use this before setting the cookie to check if the username password are correct.
*
* @param  mixed $username the user's member name, email or member id
* @param  string $password the password plaintext or encrypted in any of several
*         methods including smf's method: sha1(strtolower($username) . $password)
* @param  bool $encrypted whether the password is encrypted or not. If you get
          this wrong we'll figure it out anyways, just saves some work if it's right
* @return bool whether the user is authenticated or not
* @since  0.1.0
*/
function smfapi_authenticate($username = '', $password = '', $encrypted = true)
{
    global $scripturl, $user_info, $user_settings, $smcFunc;
    global $cookiename, $modSettings, $sc, $sourcedir;
    if ('' == $username || '' == $password) {
        return false;
    }
    // just in case they used the email or member id...
    $data = smfapi_getUserData($username);
    if (empty($data)) {
        return false;
    } else {
        $username = $data['member_name'];
    }
    // load the data up!
    $request = $smcFunc['db_query']('', '
		SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
			openid_uri, passwd_flood
		FROM {db_prefix}members
		WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name) = LOWER({string:user_name})' : 'member_name = {string:user_name}') . '
		LIMIT 1', array('user_name' => $smcFunc['db_case_sensitive'] ? strtolower($username) : $username));
    // no user data found... invalid username
    if ($smcFunc['db_num_rows']($request) == 0) {
        return false;
    }
    $user_settings = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);
    if (40 != strlen($user_settings['passwd'])) {
        // invalid hash in the db
        return false;
    }
    // if it's not encrypted, do it now
    if (!$encrypted) {
        $sha_passwd = sha1(strtolower($user_settings['member_name']) . smfapi_unHtmlspecialchars($password));
    } else {
        $sha_passwd = $password;
    }
    // if they match the password/hash is correct
    if ($user_settings['passwd'] == $sha_passwd) {
        $user_info["id"] = $user_settings['id_member'];
        return true;
    } else {
        // try other hashing schemes
        $other_passwords = array();
        // in case they sent the encrypted password into this as unencrypted
        $other_passwords[] = $password;
        // none of the below cases will be used most of the time
        // (because the salt is normally set)
        if ('' == $user_settings['password_salt']) {
            // YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x,
            // IkonBoard, and none at all
            $other_passwords[] = crypt($password, substr($password, 0, 2));
            $other_passwords[] = crypt($password, substr($user_settings['passwd'], 0, 2));
            $other_passwords[] = md5($password);
            $other_passwords[] = sha1($password);
            $other_passwords[] = md5_hmac($password, strtolower($user_settings['member_name']));
            $other_passwords[] = md5($password . strtolower($user_settings['member_name']));
            $other_passwords[] = md5(md5($password));
            $other_passwords[] = $password;
            // this one is a strange one... MyPHP, crypt() on the MD5 hash
            $other_passwords[] = crypt(md5($password), md5($password));
            // Snitz style - SHA-256.  Technically, this is a downgrade, but most PHP
            // configurations don't support sha256 anyway.
            if (strlen($user_settings['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256')) {
                $other_passwords[] = bin2hex(mhash(MHASH_SHA256, $password));
            }
            // phpBB3 users new hashing.  We now support it as well ;)
            $other_passwords[] = phpBB3_password_check($password, $user_settings['passwd']);
            // APBoard 2 login method
            $other_passwords[] = md5(crypt($password, 'CRYPT_MD5'));
        } elseif (strlen($user_settings['passwd']) == 32) {
            // vBulletin 3 style hashing?  Let's welcome them with open arms \o/
            $other_passwords[] = md5(md5($password) . $user_settings['password_salt']);
            // hmm.. p'raps it's Invision 2 style?
            $other_passwords[] = md5(md5($user_settings['password_salt']) . md5($password));
            // some common md5 ones
            $other_passwords[] = md5($user_settings['password_salt'] . $password);
            $other_passwords[] = md5($password . $user_settings['password_salt']);
        } elseif (strlen($user_settings['passwd']) == 40) {
            // maybe they are using a hash from before the password fix
            $other_passwords[] = sha1(strtolower($user_settings['member_name']) . smfapi_unHtmlspecialchars($password));
            // BurningBoard3 style of hashing
            $other_passwords[] = sha1($user_settings['password_salt'] . sha1($user_settings['password_salt'] . sha1($password)));
            // perhaps we converted to UTF-8 and have a valid password being
            // hashed differently
            if (!empty($modSettings['previousCharacterSet']) && $modSettings['previousCharacterSet'] != 'utf8') {
                // try iconv first, for no particular reason
                if (function_exists('iconv')) {
                    $other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', $modSettings['previousCharacterSet'], $user_settings['member_name'])) . un_htmlspecialchars(iconv('UTF-8', $modSettings['previousCharacterSet'], $password)));
                }
                // say it aint so, iconv failed
                if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding')) {
                    $other_passwords[] = sha1(strtolower(mb_convert_encoding($user_settings['member_name'], 'UTF-8', $modSettings['previousCharacterSet'])) . un_htmlspecialchars(mb_convert_encoding($password, 'UTF-8', $modSettings['previousCharacterSet'])));
                }
            }
        }
        // SMF's sha1 function can give a funny result on Linux (not our fault!)
        // if we've now got the real one let the old one be valid!
        if (strpos(strtolower(PHP_OS), 'win') !== 0) {
            require_once $sourcedir . '/Subs-Compat.php';
            $other_passwords[] = sha1_smf(strtolower($user_settings['member_name']) . smfapi_unHtmlspecialchars($password));
        }
        // if ANY of these other hashes match we'll accept it
        if (in_array($user_settings['passwd'], $other_passwords)) {
            // we're not going to update the password or the hash. whatever was
            // used worked, so it will work again through this api, or SMF will
            // update it if the user authenticates through there. No sense messing
            // with it if it's not broken imo. Authentication successful
            $user_info["id"] = $user_settings['id_member'];
            return true;
        }
    }
    //authentication failed
    return false;
}
Example #9
0
function sendNotifications($ID_TOPIC, $type)
{
    global $txt, $scripturl, $db_prefix, $language, $user_info;
    global $ID_MEMBER, $modSettings, $sourcedir;
    $notification_types = array('reply' => array('subject' => 'notification_reply_subject', 'message' => 'notification_reply'), 'sticky' => array('subject' => 'notification_sticky_subject', 'message' => 'notification_sticky'), 'lock' => array('subject' => 'notification_lock_subject', 'message' => 'notification_lock'), 'unlock' => array('subject' => 'notification_unlock_subject', 'message' => 'notification_unlock'), 'remove' => array('subject' => 'notification_remove_subject', 'message' => 'notification_remove'), 'move' => array('subject' => 'notification_move_subject', 'message' => 'notification_move'), 'merge' => array('subject' => 'notification_merge_subject', 'message' => 'notification_merge'), 'split' => array('subject' => 'notification_split_subject', 'message' => 'notification_split'));
    $current_type = $notification_types[$type];
    // Can't do it if there's no topic.
    if (empty($ID_TOPIC)) {
        return;
    } elseif (!is_numeric($ID_TOPIC)) {
        trigger_error('sendNotifications(): \'' . $ID_TOPIC . '\' is not a topic id', E_USER_NOTICE);
    }
    // Get the subject and body...
    $result = db_query("\n\t\tSELECT mf.subject, ml.body, t.ID_LAST_MSG\n\t\tFROM ({$db_prefix}topics AS t, {$db_prefix}messages AS mf, {$db_prefix}messages AS ml)\n\t\tWHERE t.ID_TOPIC = {$ID_TOPIC}\n\t\t\tAND mf.ID_MSG = t.ID_FIRST_MSG\n\t\t\tAND ml.ID_MSG = t.ID_LAST_MSG\n\t\tLIMIT 1", __FILE__, __LINE__);
    list($subject, $body, $last_id) = mysql_fetch_row($result);
    mysql_free_result($result);
    if (empty($last_id)) {
        trigger_error('sendNotifications(): non-existant topic passed', E_USER_NOTICE);
    }
    // Censor...
    censorText($subject);
    censorText($body);
    $subject = un_htmlspecialchars($subject);
    $body = trim(un_htmlspecialchars(strip_tags(strtr(parse_bbc($body, false, $last_id), array('<br />' => "\n", '</div>' => "\n", '</li>' => "\n", '&#91;' => '[', '&#93;' => ']')))));
    // Find the members with notification on for this topic.
    $members = db_query("\n\t\tSELECT\n\t\t\tmem.ID_MEMBER, mem.emailAddress, mem.notifyOnce, mem.notifyTypes, mem.notifySendBody, mem.lngfile,\n\t\t\tln.sent, mem.ID_GROUP, mem.additionalGroups, b.memberGroups, mem.ID_POST_GROUP, t.ID_MEMBER_STARTED\n\t\tFROM ({$db_prefix}log_notify AS ln, {$db_prefix}members AS mem, {$db_prefix}topics AS t, {$db_prefix}boards AS b)\n\t\tWHERE ln.ID_TOPIC = {$ID_TOPIC}\n\t\t\tAND t.ID_TOPIC = {$ID_TOPIC}\n\t\t\tAND b.ID_BOARD = t.ID_BOARD\n\t\t\tAND mem.ID_MEMBER != {$ID_MEMBER}\n\t\t\tAND mem.is_activated = 1\n\t\t\tAND mem.notifyTypes < " . ($type == 'reply' ? '4' : '3') . "\n\t\t\tAND ln.ID_MEMBER = mem.ID_MEMBER\n\t\tGROUP BY mem.ID_MEMBER\n\t\tORDER BY mem.lngfile", __FILE__, __LINE__);
    $sent = 0;
    while ($row = mysql_fetch_assoc($members)) {
        // Easier to check this here... if they aren't the topic poster do they really want to know?
        if ($type != 'reply' && $row['notifyTypes'] == 2 && $row['ID_MEMBER'] != $row['ID_MEMBER_STARTED']) {
            continue;
        }
        if ($row['ID_GROUP'] != 1) {
            $allowed = explode(',', $row['memberGroups']);
            $row['additionalGroups'] = explode(',', $row['additionalGroups']);
            $row['additionalGroups'][] = $row['ID_GROUP'];
            $row['additionalGroups'][] = $row['ID_POST_GROUP'];
            if (count(array_intersect($allowed, $row['additionalGroups'])) == 0) {
                continue;
            }
        }
        $needed_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
        if (empty($current_language) || $current_language != $needed_language) {
            $current_language = loadLanguage('Post', $needed_language, false);
        }
        $message = sprintf($txt[$current_type['message']], un_htmlspecialchars($user_info['name']));
        if ($type != 'remove') {
            $message .= $scripturl . '?topic=' . $ID_TOPIC . '.new;topicseen#new' . "\n\n" . $txt['notifyUnsubscribe'] . ': ' . $scripturl . '?action=notify;topic=' . $ID_TOPIC . '.0';
        }
        // Do they want the body of the message sent too?
        if (!empty($row['notifySendBody']) && $type == 'reply' && empty($modSettings['disallow_sendBody'])) {
            $message .= "\n\n" . $txt['notification_reply_body'] . "\n\n" . $body;
        }
        if (!empty($row['notifyOnce']) && $type == 'reply') {
            $message .= "\n\n" . $txt['notifyXOnce2'];
        }
        // Send only if once is off or it's on and it hasn't been sent.
        if ($type != 'reply' || empty($row['notifyOnce']) || empty($row['sent'])) {
            sendmail($row['emailAddress'], sprintf($txt[$current_type['subject']], $subject), $message . "\n\n" . $txt[130], null, 'm' . $last_id);
            $sent++;
        }
    }
    mysql_free_result($members);
    if (isset($current_language) && $current_language != $user_info['language']) {
        loadLanguage('Post');
    }
    // Sent!
    if ($type == 'reply' && !empty($sent)) {
        db_query("\n\t\t\tUPDATE {$db_prefix}log_notify\n\t\t\tSET sent = 1\n\t\t\tWHERE ID_TOPIC = {$ID_TOPIC}\n\t\t\t\tAND ID_MEMBER != {$ID_MEMBER}", __FILE__, __LINE__);
    }
}
Example #10
0
function EditPost2()
{
    global $txt, $smcFunc, $sourcedir;
    checkSession('post');
    // Get the ID
    $id = (int) $_REQUEST['id'];
    if (empty($id)) {
        fatal_error($txt['postscheduler_nopostselected'], false);
    }
    // If we came from WYSIWYG then turn it back into BBC regardless.
    if (!empty($_REQUEST['message_mode']) && isset($_REQUEST['message'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $_REQUEST['message'] = html_to_bbc($_REQUEST['message']);
        // We need to unhtml it now as it gets done shortly.
        $_REQUEST['message'] = un_htmlspecialchars($_REQUEST['message']);
    }
    $subject = $smcFunc['htmlspecialchars']($_REQUEST['subject'], ENT_QUOTES);
    $boardselect = (int) $_REQUEST['boardselect'];
    $postername = str_replace('"', '', $_REQUEST['postername']);
    $postername = str_replace("'", '', $postername);
    $postername = str_replace('\\', '', $postername);
    $postername = $smcFunc['htmlspecialchars']($postername, ENT_QUOTES);
    $msgicon = $smcFunc['htmlspecialchars']($_REQUEST['msgicon'], ENT_QUOTES);
    $message = $smcFunc['htmlspecialchars']($_REQUEST['message'], ENT_QUOTES);
    $topicid = (int) $_REQUEST['topicid'];
    if ($subject == '') {
        fatal_error($txt['postscheduler_err_subject'], false);
    }
    if ($postername == '') {
        fatal_error($txt['postscheduler_err_postername'], false);
    }
    if ($boardselect == 0) {
        fatal_error($txt['postscheduler_err_forum'], false);
    }
    if ($message == '') {
        fatal_error($txt['postscheduler_err_message'], false);
    }
    $topiclocked = isset($_REQUEST['topiclocked']) ? 1 : 0;
    $month = (int) $_REQUEST['month'];
    $day = (int) $_REQUEST['day'];
    $year = (int) $_REQUEST['year'];
    $hour = (int) $_REQUEST['hour'];
    $minute = (int) $_REQUEST['minute'];
    $ampm = $_REQUEST['ampm'];
    $minute = str_pad($minute, 2, "0", STR_PAD_LEFT);
    $time_in_24_hour_format = DATE("H", STRTOTIME("{$hour}:{$minute} {$ampm}"));
    if (!empty($month) && !empty($day) && !empty($year)) {
        $post_time = mktime($time_in_24_hour_format, $minute, 0, $month, $day, $year);
    } else {
        fatal_error($txt['postscheduler_err_date'], false);
    }
    // Lookup the Memeber ID of the postername
    $memid = 0;
    $dbresult = $smcFunc['db_query']('', "\n\tSELECT \n\t\treal_name, ID_MEMBER \n\tFROM {db_prefix}members \n\tWHERE real_name = '{$postername}' OR member_name = '{$postername}'  LIMIT 1");
    $row = $smcFunc['db_fetch_assoc']($dbresult);
    $smcFunc['db_free_result']($dbresult);
    if ($smcFunc['db_affected_rows']() != 0) {
        $memid = $row['ID_MEMBER'];
    }
    $smcFunc['db_query']('', "\n\t\tUPDATE {db_prefix}postscheduler \n\t\tSET \n\t\t\tID_BOARD = {$boardselect}, subject = '{$subject}', postername  = '{$postername}', ID_MEMBER = {$memid}, locked = '{$topiclocked}', \n\t\t\tbody = '{$message}',id_topic = '{$topicid}',post_time = '{$post_time}',\n\t\t\tmsgicon  = '{$msgicon}'\n\n\t    WHERE ID_POST = {$id} LIMIT 1");
    // Redirect to the Admin
    redirectexit('action=admin;area=postscheduler;sa=admin');
}
Example #11
0
/**
 * Show the list of topics in this board, along with any child boards.
 */
function MessageIndex()
{
    global $txt, $scripturl, $board, $modSettings, $context;
    global $options, $settings, $board_info, $user_info, $smcFunc, $sourcedir;
    // If this is a redirection board head off.
    if ($board_info['redirect']) {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}boards
			SET num_posts = num_posts + 1
			WHERE id_board = {int:current_board}', array('current_board' => $board));
        redirectexit($board_info['redirect']);
    }
    if (WIRELESS) {
        $context['sub_template'] = WIRELESS_PROTOCOL . '_messageindex';
    } else {
        loadTemplate('MessageIndex');
    }
    $context['name'] = $board_info['name'];
    $context['description'] = $board_info['description'];
    // How many topics do we have in total?
    $board_info['total_topics'] = allowedTo('approve_posts') ? $board_info['num_topics'] + $board_info['unapproved_topics'] : $board_info['num_topics'] + $board_info['unapproved_user_topics'];
    // View all the topics, or just a few?
    $context['topics_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) && !WIRELESS ? $options['topics_per_page'] : $modSettings['defaultMaxTopics'];
    $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) && !WIRELESS ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
    $maxindex = isset($_REQUEST['all']) && !empty($modSettings['enableAllMessages']) ? $board_info['total_topics'] : $context['topics_per_page'];
    // Right, let's only index normal stuff!
    if (count($_GET) > 1) {
        $session_name = session_name();
        foreach ($_GET as $k => $v) {
            if (!in_array($k, array('board', 'start', $session_name))) {
                $context['robot_no_index'] = true;
            }
        }
    }
    if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0)) {
        $context['robot_no_index'] = true;
    }
    // If we can view unapproved messages and there are some build up a list.
    if (allowedTo('approve_posts') && ($board_info['unapproved_topics'] || $board_info['unapproved_posts'])) {
        $untopics = $board_info['unapproved_topics'] ? '<a href="' . $scripturl . '?action=moderate;area=postmod;sa=topics;brd=' . $board . '">' . $board_info['unapproved_topics'] . '</a>' : 0;
        $unposts = $board_info['unapproved_posts'] ? '<a href="' . $scripturl . '?action=moderate;area=postmod;sa=posts;brd=' . $board . '">' . ($board_info['unapproved_posts'] - $board_info['unapproved_topics']) . '</a>' : 0;
        $context['unapproved_posts_message'] = sprintf($txt['there_are_unapproved_topics'], $untopics, $unposts, $scripturl . '?action=moderate;area=postmod;sa=' . ($board_info['unapproved_topics'] ? 'topics' : 'posts') . ';brd=' . $board);
    }
    // Make sure the starting place makes sense and construct the page index.
    if (isset($_REQUEST['sort'])) {
        $context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d;sort=' . $_REQUEST['sort'] . (isset($_REQUEST['desc']) ? ';desc' : ''), $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
    } else {
        $context['page_index'] = constructPageIndex($scripturl . '?board=' . $board . '.%1$d', $_REQUEST['start'], $board_info['total_topics'], $maxindex, true);
    }
    $context['start'] =& $_REQUEST['start'];
    // Set a canonical URL for this page.
    $context['canonical_url'] = $scripturl . '?board=' . $board . '.' . $context['start'];
    $context['links'] = array('first' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?board=' . $board . '.0' : '', 'prev' => $_REQUEST['start'] >= $context['topics_per_page'] ? $scripturl . '?board=' . $board . '.' . ($_REQUEST['start'] - $context['topics_per_page']) : '', 'next' => $_REQUEST['start'] + $context['topics_per_page'] < $board_info['total_topics'] ? $scripturl . '?board=' . $board . '.' . ($_REQUEST['start'] + $context['topics_per_page']) : '', 'last' => $_REQUEST['start'] + $context['topics_per_page'] < $board_info['total_topics'] ? $scripturl . '?board=' . $board . '.' . floor(($board_info['total_topics'] - 1) / $context['topics_per_page']) * $context['topics_per_page'] : '', 'up' => $board_info['parent'] == 0 ? $scripturl . '?' : $scripturl . '?board=' . $board_info['parent'] . '.0');
    $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['topics_per_page'] + 1, 'num_pages' => floor(($board_info['total_topics'] - 1) / $context['topics_per_page']) + 1);
    if (isset($_REQUEST['all']) && !empty($modSettings['enableAllMessages']) && $maxindex > $modSettings['enableAllMessages']) {
        $maxindex = $modSettings['enableAllMessages'];
        $_REQUEST['start'] = 0;
    }
    // Build a list of the board's moderators.
    $context['moderators'] =& $board_info['moderators'];
    $context['link_moderators'] = array();
    if (!empty($board_info['moderators'])) {
        foreach ($board_info['moderators'] as $mod) {
            $context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
        }
        $context['linktree'][count($context['linktree']) - 1]['extra_after'] = '<span class="board_moderators"> (' . (count($context['link_moderators']) == 1 ? $txt['moderator'] : $txt['moderators']) . ': ' . implode(', ', $context['link_moderators']) . ')</span>';
    }
    // Mark current and parent boards as seen.
    if (!$user_info['is_guest']) {
        // We can't know they read it if we allow prefetches.
        if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
            ob_end_clean();
            header('HTTP/1.1 403 Prefetch Forbidden');
            die;
        }
        $smcFunc['db_insert']('replace', '{db_prefix}log_boards', array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'), array($modSettings['maxMsgID'], $user_info['id'], $board), array('id_member', 'id_board'));
        if (!empty($board_info['parent_boards'])) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}log_boards
				SET id_msg = {int:id_msg}
				WHERE id_member = {int:current_member}
					AND id_board IN ({array_int:board_list})', array('current_member' => $user_info['id'], 'board_list' => array_keys($board_info['parent_boards']), 'id_msg' => $modSettings['maxMsgID']));
            // We've seen all these boards now!
            foreach ($board_info['parent_boards'] as $k => $dummy) {
                if (isset($_SESSION['topicseen_cache'][$k])) {
                    unset($_SESSION['topicseen_cache'][$k]);
                }
            }
        }
        if (isset($_SESSION['topicseen_cache'][$board])) {
            unset($_SESSION['topicseen_cache'][$board]);
        }
        $request = $smcFunc['db_query']('', '
			SELECT sent
			FROM {db_prefix}log_notify
			WHERE id_board = {int:current_board}
				AND id_member = {int:current_member}
			LIMIT 1', array('current_board' => $board, 'current_member' => $user_info['id']));
        $context['is_marked_notify'] = $smcFunc['db_num_rows']($request) != 0;
        if ($context['is_marked_notify']) {
            list($sent) = $smcFunc['db_fetch_row']($request);
            if (!empty($sent)) {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}log_notify
					SET sent = {int:is_sent}
					WHERE id_board = {int:current_board}
						AND id_member = {int:current_member}', array('current_board' => $board, 'current_member' => $user_info['id'], 'is_sent' => 0));
            }
        }
        $smcFunc['db_free_result']($request);
    } else {
        $context['is_marked_notify'] = false;
    }
    // 'Print' the header and board info.
    $context['page_title'] = strip_tags($board_info['name']);
    // Set the variables up for the template.
    $context['can_mark_notify'] = allowedTo('mark_notify') && !$user_info['is_guest'];
    $context['can_post_new'] = allowedTo('post_new') || $modSettings['postmod_active'] && allowedTo('post_unapproved_topics');
    $context['can_post_poll'] = $modSettings['pollMode'] == '1' && allowedTo('poll_post') && $context['can_post_new'];
    $context['can_moderate_forum'] = allowedTo('moderate_forum');
    $context['can_approve_posts'] = allowedTo('approve_posts');
    require_once $sourcedir . '/Subs-BoardIndex.php';
    $boardIndexOptions = array('include_categories' => false, 'base_level' => $board_info['child_level'] + 1, 'parent_id' => $board_info['id'], 'set_latest_post' => false, 'countChildPosts' => !empty($modSettings['countChildPosts']));
    $context['boards'] = getBoardIndex($boardIndexOptions);
    // Nosey, nosey - who's viewing this topic?
    if (!empty($settings['display_who_viewing'])) {
        $context['view_members'] = array();
        $context['view_members_list'] = array();
        $context['view_num_hidden'] = 0;
        $request = $smcFunc['db_query']('', '
			SELECT
				lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
				mg.online_color, mg.id_group, mg.group_name
			FROM {db_prefix}log_online AS lo
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_member_group} THEN mem.id_post_group ELSE mem.id_group END)
			WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}', array('reg_member_group' => 0, 'in_url_string' => 's:5:"board";i:' . $board . ';', 'session' => $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id()));
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            if (empty($row['id_member'])) {
                continue;
            }
            if (!empty($row['online_color'])) {
                $link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
            } else {
                $link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
            }
            $is_buddy = in_array($row['id_member'], $user_info['buddies']);
            if ($is_buddy) {
                $link = '<strong>' . $link . '</strong>';
            }
            if (!empty($row['show_online']) || allowedTo('moderate_forum')) {
                $context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
            }
            $context['view_members'][$row['log_time'] . $row['member_name']] = array('id' => $row['id_member'], 'username' => $row['member_name'], 'name' => $row['real_name'], 'group' => $row['id_group'], 'href' => $scripturl . '?action=profile;u=' . $row['id_member'], 'link' => $link, 'is_buddy' => $is_buddy, 'hidden' => empty($row['show_online']));
            if (empty($row['show_online'])) {
                $context['view_num_hidden']++;
            }
        }
        $context['view_num_guests'] = $smcFunc['db_num_rows']($request) - count($context['view_members']);
        $smcFunc['db_free_result']($request);
        // Put them in "last clicked" order.
        krsort($context['view_members_list']);
        krsort($context['view_members']);
    }
    // Default sort methods.
    $sort_methods = array('subject' => 'mf.subject', 'starter' => 'IFNULL(memf.real_name, mf.poster_name)', 'last_poster' => 'IFNULL(meml.real_name, ml.poster_name)', 'replies' => 't.num_replies', 'views' => 't.num_views', 'first_post' => 't.id_topic', 'last_post' => 't.id_last_msg');
    // They didn't pick one, default to by last post descending.
    if (!isset($_REQUEST['sort']) || !isset($sort_methods[$_REQUEST['sort']])) {
        $context['sort_by'] = 'last_post';
        $_REQUEST['sort'] = 'id_last_msg';
        $ascending = isset($_REQUEST['asc']);
    } else {
        $context['sort_by'] = $_REQUEST['sort'];
        $_REQUEST['sort'] = $sort_methods[$_REQUEST['sort']];
        $ascending = !isset($_REQUEST['desc']);
    }
    $context['sort_direction'] = $ascending ? 'up' : 'down';
    // Calculate the fastest way to get the topics.
    $start = (int) $_REQUEST['start'];
    if ($start > ($board_info['total_topics'] - 1) / 2) {
        $ascending = !$ascending;
        $fake_ascending = true;
        $maxindex = $board_info['total_topics'] < $start + $maxindex + 1 ? $board_info['total_topics'] - $start : $maxindex;
        $start = $board_info['total_topics'] < $start + $maxindex + 1 ? 0 : $board_info['total_topics'] - $start - $maxindex;
    } else {
        $fake_ascending = false;
    }
    // Setup the default topic icons...
    $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'poll', 'moved', 'recycled', 'wireless', 'clip');
    $context['icon_sources'] = array();
    foreach ($stable_icons as $icon) {
        $context['icon_sources'][$icon] = 'images_url';
    }
    $topic_ids = array();
    $context['topics'] = array();
    // Sequential pages are often not optimized, so we add an additional query.
    $pre_query = $start > 0;
    if ($pre_query && $maxindex > 0) {
        $request = $smcFunc['db_query']('', '
			SELECT t.id_topic
			FROM {db_prefix}topics AS t' . ($context['sort_by'] === 'last_poster' ? '
				INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)' : (in_array($context['sort_by'], array('starter', 'subject')) ? '
				INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)' : '')) . ($context['sort_by'] === 'starter' ? '
				LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)' : '') . ($context['sort_by'] === 'last_poster' ? '
				LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)' : '') . '
			WHERE t.id_board = {int:current_board}' . (!$modSettings['postmod_active'] || $context['can_approve_posts'] ? '' : '
				AND (t.approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR t.id_member_started = {int:current_member}') . ')') . '
			ORDER BY ' . (!empty($modSettings['enableStickyTopics']) ? 'is_sticky' . ($fake_ascending ? '' : ' DESC') . ', ' : '') . $_REQUEST['sort'] . ($ascending ? '' : ' DESC') . '
			LIMIT {int:start}, {int:maxindex}', array('current_board' => $board, 'current_member' => $user_info['id'], 'is_approved' => 1, 'id_member_guest' => 0, 'start' => $start, 'maxindex' => $maxindex));
        $topic_ids = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $topic_ids[] = $row['id_topic'];
        }
    }
    // Grab the appropriate topic information...
    if (!$pre_query || !empty($topic_ids)) {
        // For search engine effectiveness we'll link guests differently.
        $context['pageindex_multiplier'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) && !WIRELESS ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
        $result = $smcFunc['db_query']('substring', '
			SELECT
				t.id_topic, t.num_replies, t.locked, t.num_views, t.is_sticky, t.id_poll, t.id_previous_board,
				' . ($user_info['is_guest'] ? '0' : 'IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1') . ' AS new_from,
				t.id_last_msg, t.approved, t.unapproved_posts, t.id_redirect_topic, ml.poster_time AS last_poster_time,
				ml.id_msg_modified, ml.subject AS last_subject, ml.icon AS last_icon,
				ml.poster_name AS last_member_name, ml.id_member AS last_id_member, ' . (!empty($settings['avatars_on_indexes']) ? 'meml.avatar,' : '') . '
				IFNULL(meml.real_name, ml.poster_name) AS last_display_name, t.id_first_msg,
				mf.poster_time AS first_poster_time, mf.subject AS first_subject, mf.icon AS first_icon,
				mf.poster_name AS first_member_name, mf.id_member AS first_id_member,
				IFNULL(memf.real_name, mf.poster_name) AS first_display_name, ' . (!empty($modSettings['preview_characters']) ? '
				SUBSTRING(ml.body, 1, ' . ($modSettings['preview_characters'] + 256) . ') AS last_body,
				SUBSTRING(mf.body, 1, ' . ($modSettings['preview_characters'] + 256) . ') AS first_body,' : '') . 'ml.smileys_enabled AS last_smileys, mf.smileys_enabled AS first_smileys' . (!empty($settings['avatars_on_indexes']) ? ',
				IFNULL(a.id_attach, 0) AS id_attach, a.filename, a.attachment_type' : '') . '
			FROM {db_prefix}topics AS t
				INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
				INNER JOIN {db_prefix}messages AS mf ON (mf.id_msg = t.id_first_msg)
				LEFT JOIN {db_prefix}members AS meml ON (meml.id_member = ml.id_member)
				LEFT JOIN {db_prefix}members AS memf ON (memf.id_member = mf.id_member)' . ($user_info['is_guest'] ? '' : '
				LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
				LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})') . (!empty($settings['avatars_on_indexes']) ? '
				LEFT JOIN {db_prefix}attachments AS a ON (a.id_member = ml.id_member)' : '') . '
			WHERE ' . ($pre_query ? 't.id_topic IN ({array_int:topic_list})' : 't.id_board = {int:current_board}') . (!$modSettings['postmod_active'] || $context['can_approve_posts'] ? '' : '
				AND (t.approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR t.id_member_started = {int:current_member}') . ')') . '
			ORDER BY ' . ($pre_query ? 'FIND_IN_SET(t.id_topic, {string:find_set_topics})' : (!empty($modSettings['enableStickyTopics']) ? 'is_sticky' . ($fake_ascending ? '' : ' DESC') . ', ' : '') . $_REQUEST['sort'] . ($ascending ? '' : ' DESC')) . '
			LIMIT ' . ($pre_query ? '' : '{int:start}, ') . '{int:maxindex}', array('current_board' => $board, 'current_member' => $user_info['id'], 'topic_list' => $topic_ids, 'is_approved' => 1, 'find_set_topics' => implode(',', $topic_ids), 'start' => $start, 'maxindex' => $maxindex));
        // Begin 'printing' the message index for current board.
        while ($row = $smcFunc['db_fetch_assoc']($result)) {
            if ($row['id_poll'] > 0 && $modSettings['pollMode'] == '0') {
                continue;
            }
            if (!$pre_query) {
                $topic_ids[] = $row['id_topic'];
            }
            // Does the theme support message previews?
            if (!empty($settings['message_index_preview']) && !empty($modSettings['preview_characters'])) {
                // Limit them to $modSettings['preview_characters'] characters
                $row['first_body'] = strip_tags(strtr(parse_bbc($row['first_body'], $row['first_smileys'], $row['id_first_msg']), array('<br />' => '&#10;')));
                if ($smcFunc['strlen']($row['first_body']) > $modSettings['preview_characters']) {
                    $row['first_body'] = $smcFunc['substr']($row['first_body'], 0, $modSettings['preview_characters']) . '...';
                }
                $row['last_body'] = strip_tags(strtr(parse_bbc($row['last_body'], $row['last_smileys'], $row['id_last_msg']), array('<br />' => '&#10;')));
                if ($smcFunc['strlen']($row['last_body']) > $modSettings['preview_characters']) {
                    $row['last_body'] = $smcFunc['substr']($row['last_body'], 0, $modSettings['preview_characters']) . '...';
                }
                // Censor the subject and message preview.
                censorText($row['first_subject']);
                censorText($row['first_body']);
                // Don't censor them twice!
                if ($row['id_first_msg'] == $row['id_last_msg']) {
                    $row['last_subject'] = $row['first_subject'];
                    $row['last_body'] = $row['first_body'];
                } else {
                    censorText($row['last_subject']);
                    censorText($row['last_body']);
                }
            } else {
                $row['first_body'] = '';
                $row['last_body'] = '';
                censorText($row['first_subject']);
                if ($row['id_first_msg'] == $row['id_last_msg']) {
                    $row['last_subject'] = $row['first_subject'];
                } else {
                    censorText($row['last_subject']);
                }
            }
            // Decide how many pages the topic should have.
            if ($row['num_replies'] + 1 > $context['messages_per_page']) {
                $pages = '&#171; ';
                // We can't pass start by reference.
                $start = -1;
                $pages .= constructPageIndex($scripturl . '?topic=' . $row['id_topic'] . '.%1$d', $start, $row['num_replies'] + 1, $context['messages_per_page'], true, false);
                // If we can use all, show all.
                if (!empty($modSettings['enableAllMessages']) && $row['num_replies'] + 1 < $modSettings['enableAllMessages']) {
                    $pages .= ' &nbsp;<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0;all">' . $txt['all'] . '</a>';
                }
                $pages .= ' &#187;';
            } else {
                $pages = '';
            }
            // We need to check the topic icons exist...
            if (!empty($modSettings['messageIconChecks_enable'])) {
                if (!isset($context['icon_sources'][$row['first_icon']])) {
                    $context['icon_sources'][$row['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
                }
                if (!isset($context['icon_sources'][$row['last_icon']])) {
                    $context['icon_sources'][$row['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
                }
            } else {
                if (!isset($context['icon_sources'][$row['first_icon']])) {
                    $context['icon_sources'][$row['first_icon']] = 'images_url';
                }
                if (!isset($context['icon_sources'][$row['last_icon']])) {
                    $context['icon_sources'][$row['last_icon']] = 'images_url';
                }
            }
            if (!empty($settings['avatars_on_indexes'])) {
                // Allow themers to show the latest poster's avatar along with the topic
                if (!empty($row['avatar'])) {
                    if ($modSettings['avatar_action_too_large'] == 'option_html_resize' || $modSettings['avatar_action_too_large'] == 'option_js_resize') {
                        $avatar_width = !empty($modSettings['avatar_max_width_external']) ? ' width="' . $modSettings['avatar_max_width_external'] . '"' : '';
                        $avatar_height = !empty($modSettings['avatar_max_height_external']) ? ' height="' . $modSettings['avatar_max_height_external'] . '"' : '';
                    } else {
                        $avatar_width = '';
                        $avatar_height = '';
                    }
                }
            }
            // 'Print' the topic info.
            $context['topics'][$row['id_topic']] = array('id' => $row['id_topic'], 'first_post' => array('id' => $row['id_first_msg'], 'member' => array('username' => $row['first_member_name'], 'name' => $row['first_display_name'], 'id' => $row['first_id_member'], 'href' => !empty($row['first_id_member']) ? $scripturl . '?action=profile;u=' . $row['first_id_member'] : '', 'link' => !empty($row['first_id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['first_id_member'] . '" title="' . $txt['profile_of'] . ' ' . $row['first_display_name'] . '" class="preview">' . $row['first_display_name'] . '</a>' : $row['first_display_name']), 'time' => timeformat($row['first_poster_time']), 'timestamp' => forum_time(true, $row['first_poster_time']), 'subject' => $row['first_subject'], 'preview' => $row['first_body'], 'icon' => $row['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png', 'href' => $scripturl . '?topic=' . (empty($row['id_redirect_topic']) ? $row['id_topic'] : $row['id_redirect_topic']) . '.0', 'link' => '<a href="' . $scripturl . '?topic=' . (empty($row['id_redirect_topic']) ? $row['id_topic'] : $row['id_redirect_topic']) . '.0">' . $row['first_subject'] . '</a>'), 'last_post' => array('id' => $row['id_last_msg'], 'member' => array('username' => $row['last_member_name'], 'name' => $row['last_display_name'], 'id' => $row['last_id_member'], 'href' => !empty($row['last_id_member']) ? $scripturl . '?action=profile;u=' . $row['last_id_member'] : '', 'link' => !empty($row['last_id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['last_id_member'] . '">' . $row['last_display_name'] . '</a>' : $row['last_display_name']), 'time' => timeformat($row['last_poster_time']), 'timestamp' => forum_time(true, $row['last_poster_time']), 'subject' => $row['last_subject'], 'preview' => $row['last_body'], 'icon' => $row['last_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['last_icon']]] . '/post/' . $row['last_icon'] . '.png', 'href' => $scripturl . '?topic=' . (empty($row['id_redirect_topic']) ? $row['id_topic'] : $row['id_redirect_topic']) . ($user_info['is_guest'] ? '.' . (!empty($options['view_newest_first']) ? 0 : (int) ($row['num_replies'] / $context['pageindex_multiplier']) * $context['pageindex_multiplier']) . '#msg' . $row['id_last_msg'] : ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new'), 'link' => '<a href="' . $scripturl . '?topic=' . (empty($row['id_redirect_topic']) ? $row['id_topic'] : $row['id_redirect_topic']) . ($user_info['is_guest'] ? '.' . (!empty($options['view_newest_first']) ? 0 : (int) ($row['num_replies'] / $context['pageindex_multiplier']) * $context['pageindex_multiplier']) . '#msg' . $row['id_last_msg'] : ($row['num_replies'] == 0 ? '.0' : '.msg' . $row['id_last_msg']) . '#new') . '" ' . ($row['num_replies'] == 0 ? '' : 'rel="nofollow"') . '>' . $row['last_subject'] . '</a>'), 'is_sticky' => !empty($modSettings['enableStickyTopics']) && !empty($row['is_sticky']), 'is_locked' => !empty($row['locked']), 'is_poll' => $modSettings['pollMode'] == '1' && $row['id_poll'] > 0, 'is_hot' => $row['num_replies'] >= $modSettings['hotTopicPosts'], 'is_very_hot' => $row['num_replies'] >= $modSettings['hotTopicVeryPosts'], 'is_posted_in' => false, 'icon' => $row['first_icon'], 'icon_url' => $settings[$context['icon_sources'][$row['first_icon']]] . '/post/' . $row['first_icon'] . '.png', 'subject' => $row['first_subject'], 'new' => $row['new_from'] <= $row['id_msg_modified'], 'new_from' => $row['new_from'], 'newtime' => $row['new_from'], 'new_href' => $scripturl . '?topic=' . (empty($row['id_redirect_topic']) ? $row['id_topic'] : $row['id_redirect_topic']) . '.msg' . $row['new_from'] . '#new', 'pages' => $pages, 'replies' => comma_format($row['num_replies']), 'views' => comma_format($row['num_views']), 'approved' => $row['approved'], 'unapproved_posts' => $row['unapproved_posts']);
            if (!empty($settings['avatars_on_indexes'])) {
                $context['topics'][$row['id_topic']]['last_post']['member']['avatar'] = array('name' => $row['avatar'], 'image' => $row['avatar'] == '' ? $row['id_attach'] > 0 ? '<img class="avatar" src="' . (empty($row['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $row['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $row['filename']) . '" alt="" />' : '' : (stristr($row['avatar'], 'http://') ? '<img class="avatar" src="' . $row['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" />' : '<img class="avatar" src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($row['avatar']) . '" alt="" />'), 'href' => $row['avatar'] == '' ? $row['id_attach'] > 0 ? empty($row['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $row['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $row['filename'] : '' : (stristr($row['avatar'], 'http://') ? $row['avatar'] : $modSettings['avatar_url'] . '/' . $row['avatar']), 'url' => $row['avatar'] == '' ? '' : (stristr($row['avatar'], 'http://') ? $row['avatar'] : $modSettings['avatar_url'] . '/' . $row['avatar']));
            }
            determineTopicClass($context['topics'][$row['id_topic']]);
        }
        $smcFunc['db_free_result']($result);
        // Fix the sequence of topics if they were retrieved in the wrong order. (for speed reasons...)
        if ($fake_ascending) {
            $context['topics'] = array_reverse($context['topics'], true);
        }
        if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest'] && !empty($topic_ids)) {
            $result = $smcFunc['db_query']('', '
				SELECT id_topic
				FROM {db_prefix}messages
				WHERE id_topic IN ({array_int:topic_list})
					AND id_member = {int:current_member}
				GROUP BY id_topic
				LIMIT ' . count($topic_ids), array('current_member' => $user_info['id'], 'topic_list' => $topic_ids));
            while ($row = $smcFunc['db_fetch_assoc']($result)) {
                $context['topics'][$row['id_topic']]['is_posted_in'] = true;
                $context['topics'][$row['id_topic']]['class'] = 'my_' . $context['topics'][$row['id_topic']]['class'];
            }
            $smcFunc['db_free_result']($result);
        }
    }
    $context['jump_to'] = array('label' => addslashes(un_htmlspecialchars($txt['jump_to'])), 'board_name' => htmlspecialchars(strtr(strip_tags($board_info['name']), array('&amp;' => '&'))), 'child_level' => $board_info['child_level']);
    // Is Quick Moderation active/needed?
    if (!empty($options['display_quick_mod']) && !empty($context['topics'])) {
        $context['can_markread'] = $context['user']['is_logged'];
        $context['can_lock'] = allowedTo('lock_any');
        $context['can_sticky'] = allowedTo('make_sticky') && !empty($modSettings['enableStickyTopics']);
        $context['can_move'] = allowedTo('move_any');
        $context['can_remove'] = allowedTo('remove_any');
        $context['can_merge'] = allowedTo('merge_any');
        // Ignore approving own topics as it's unlikely to come up...
        $context['can_approve'] = $modSettings['postmod_active'] && allowedTo('approve_posts') && !empty($board_info['unapproved_topics']);
        // Can we restore topics?
        $context['can_restore'] = allowedTo('move_any') && !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board;
        // Set permissions for all the topics.
        foreach ($context['topics'] as $t => $topic) {
            $started = $topic['first_post']['member']['id'] == $user_info['id'];
            $context['topics'][$t]['quick_mod'] = array('lock' => allowedTo('lock_any') || $started && allowedTo('lock_own'), 'sticky' => allowedTo('make_sticky') && !empty($modSettings['enableStickyTopics']), 'move' => allowedTo('move_any') || $started && allowedTo('move_own'), 'modify' => allowedTo('modify_any') || $started && allowedTo('modify_own'), 'remove' => allowedTo('remove_any') || $started && allowedTo('remove_own'), 'approve' => $context['can_approve'] && $topic['unapproved_posts']);
            $context['can_lock'] |= $started && allowedTo('lock_own');
            $context['can_move'] |= $started && allowedTo('move_own');
            $context['can_remove'] |= $started && allowedTo('remove_own');
        }
        // Find the boards/cateogories they can move their topic to.
        if ($options['display_quick_mod'] == 1 && $context['can_move'] && !empty($context['topics'])) {
            require_once $sourcedir . '/Subs-MessageIndex.php';
            $boardListOptions = array('excluded_boards' => array($board), 'not_redirection' => true, 'use_permissions' => true, 'selected_board' => empty($_SESSION['move_to_topic']) ? null : $_SESSION['move_to_topic']);
            // With no other boards to see, it's useless to move.
            if (empty($context['move_to_boards'])) {
                $context['can_move'] = false;
            }
        }
        // Can we use quick moderation checkboxes?
        if ($options['display_quick_mod'] == 1) {
            $context['can_quick_mod'] = $context['user']['is_logged'] || $context['can_approve'] || $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'] || $context['can_merge'] || $context['can_restore'];
        } else {
            $context['can_quick_mod'] = $context['can_remove'] || $context['can_lock'] || $context['can_sticky'] || $context['can_move'];
        }
    }
    if (!empty($context['can_quick_mod']) && $options['display_quick_mod'] == 1) {
        $context['qmod_actions'] = array('approve', 'remove', 'lock', 'sticky', 'move', 'merge', 'restore', 'markread');
        call_integration_hook('integrate_quick_mod_actions');
    }
    // If there are children, but no topics and no ability to post topics...
    $context['no_topic_listing'] = !empty($context['boards']) && empty($context['topics']) && !$context['can_post_new'];
    // Build the message index button array.
    $context['normal_buttons'] = array('new_topic' => array('test' => 'can_post_new', 'text' => 'new_topic', 'image' => 'new_topic.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0', 'active' => true), 'post_poll' => array('test' => 'can_post_poll', 'text' => 'new_poll', 'image' => 'new_poll.png', 'lang' => true, 'url' => $scripturl . '?action=post;board=' . $context['current_board'] . '.0;poll'), 'notify' => array('test' => 'can_mark_notify', 'text' => $context['is_marked_notify'] ? 'unnotify' : 'notify', 'image' => ($context['is_marked_notify'] ? 'un' : '') . 'notify.png', 'lang' => true, 'custom' => 'onclick="return confirm(\'' . ($context['is_marked_notify'] ? $txt['notification_disable_board'] : $txt['notification_enable_board']) . '\');"', 'url' => $scripturl . '?action=notifyboard;sa=' . ($context['is_marked_notify'] ? 'off' : 'on') . ';board=' . $context['current_board'] . '.' . $context['start'] . ';' . $context['session_var'] . '=' . $context['session_id']), 'markread' => array('text' => 'mark_read_short', 'image' => 'markread.png', 'lang' => true, 'url' => $scripturl . '?action=markasread;sa=board;board=' . $context['current_board'] . '.0;' . $context['session_var'] . '=' . $context['session_id']));
    // Allow adding new buttons easily.
    call_integration_hook('integrate_messageindex_buttons');
}
Example #12
0
/**
 * Allows the user to report a personal message to an administrator.
 *
 * - In the first instance requires that the ID of the message to report is passed through $_GET.
 * - It allows the user to report to either a particular administrator - or the whole admin team.
 * - It will forward on a copy of the original message without allowing the reporter to make changes.
 *
 * @uses report_message sub-template.
 */
function ReportMessage()
{
    global $txt, $context, $scripturl, $sourcedir;
    global $user_info, $language, $modSettings, $smcFunc;
    // Check that this feature is even enabled!
    if (empty($modSettings['enableReportPM']) || empty($_REQUEST['pmsg'])) {
        fatal_lang_error('no_access', false);
    }
    $pmsg = (int) $_REQUEST['pmsg'];
    if (!isAccessiblePM($pmsg, 'inbox')) {
        fatal_lang_error('no_access', false);
    }
    $context['pm_id'] = $pmsg;
    $context['page_title'] = $txt['pm_report_title'];
    // If we're here, just send the user to the template, with a few useful context bits.
    if (!isset($_POST['report'])) {
        $context['sub_template'] = 'report_message';
        // @todo I don't like being able to pick who to send it to.  Favoritism, etc. sucks.
        // Now, get all the administrators.
        $request = $smcFunc['db_query']('', '
			SELECT id_member, real_name
			FROM {db_prefix}members
			WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
			ORDER BY real_name', array('admin_group' => 1));
        $context['admins'] = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['admins'][$row['id_member']] = $row['real_name'];
        }
        $smcFunc['db_free_result']($request);
        // How many admins in total?
        $context['admin_count'] = count($context['admins']);
    } else {
        // Check the session before proceeding any further!
        checkSession('post');
        // First, pull out the message contents, and verify it actually went to them!
        $request = $smcFunc['db_query']('', '
			SELECT pm.subject, pm.body, pm.msgtime, pm.id_member_from, IFNULL(m.real_name, pm.from_name) AS sender_name
			FROM {db_prefix}personal_messages AS pm
				INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
				LEFT JOIN {db_prefix}members AS m ON (m.id_member = pm.id_member_from)
			WHERE pm.id_pm = {int:id_pm}
				AND pmr.id_member = {int:current_member}
				AND pmr.deleted = {int:not_deleted}
			LIMIT 1', array('current_member' => $user_info['id'], 'id_pm' => $context['pm_id'], 'not_deleted' => 0));
        // Can only be a hacker here!
        if ($smcFunc['db_num_rows']($request) == 0) {
            fatal_lang_error('no_access', false);
        }
        list($subject, $body, $time, $memberFromID, $memberFromName) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        // Remove the line breaks...
        $body = preg_replace('~<br ?/?' . '>~i', "\n", $body);
        // Get any other recipients of the email.
        $request = $smcFunc['db_query']('', '
			SELECT mem_to.id_member AS id_member_to, mem_to.real_name AS to_name, pmr.bcc
			FROM {db_prefix}pm_recipients AS pmr
				LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
			WHERE pmr.id_pm = {int:id_pm}
				AND pmr.id_member != {int:current_member}', array('current_member' => $user_info['id'], 'id_pm' => $context['pm_id']));
        $recipients = array();
        $hidden_recipients = 0;
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // If it's hidden still don't reveal their names - privacy after all ;)
            if ($row['bcc']) {
                $hidden_recipients++;
            } else {
                $recipients[] = '[url=' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . ']' . $row['to_name'] . '[/url]';
            }
        }
        $smcFunc['db_free_result']($request);
        if ($hidden_recipients) {
            $recipients[] = sprintf($txt['pm_report_pm_hidden'], $hidden_recipients);
        }
        // Now let's get out and loop through the admins.
        $request = $smcFunc['db_query']('', '
			SELECT id_member, real_name, lngfile
			FROM {db_prefix}members
			WHERE (id_group = {int:admin_id} OR FIND_IN_SET({int:admin_id}, additional_groups) != 0)
				' . (empty($_POST['id_admin']) ? '' : 'AND id_member = {int:specific_admin}') . '
			ORDER BY lngfile', array('admin_id' => 1, 'specific_admin' => isset($_POST['id_admin']) ? (int) $_POST['id_admin'] : 0));
        // Maybe we shouldn't advertise this?
        if ($smcFunc['db_num_rows']($request) == 0) {
            fatal_lang_error('no_access', false);
        }
        $memberFromName = un_htmlspecialchars($memberFromName);
        // Prepare the message storage array.
        $messagesToSend = array();
        // Loop through each admin, and add them to the right language pile...
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // Need to send in the correct language!
            $cur_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
            if (!isset($messagesToSend[$cur_language])) {
                loadLanguage('PersonalMessage', $cur_language, false);
                // Make the body.
                $report_body = str_replace(array('{REPORTER}', '{SENDER}'), array(un_htmlspecialchars($user_info['name']), $memberFromName), $txt['pm_report_pm_user_sent']);
                $report_body .= "\n" . '[b]' . $_POST['reason'] . '[/b]' . "\n\n";
                if (!empty($recipients)) {
                    $report_body .= $txt['pm_report_pm_other_recipients'] . ' ' . implode(', ', $recipients) . "\n\n";
                }
                $report_body .= $txt['pm_report_pm_unedited_below'] . "\n" . '[quote author=' . (empty($memberFromID) ? '&quot;' . $memberFromName . '&quot;' : $memberFromName . ' link=action=profile;u=' . $memberFromID . ' date=' . $time) . ']' . "\n" . un_htmlspecialchars($body) . '[/quote]';
                // Plonk it in the array ;)
                $messagesToSend[$cur_language] = array('subject' => ($smcFunc['strpos']($subject, $txt['pm_report_pm_subject']) === false ? $txt['pm_report_pm_subject'] : '') . un_htmlspecialchars($subject), 'body' => $report_body, 'recipients' => array('to' => array(), 'bcc' => array()));
            }
            // Add them to the list.
            $messagesToSend[$cur_language]['recipients']['to'][$row['id_member']] = $row['id_member'];
        }
        $smcFunc['db_free_result']($request);
        // Send a different email for each language.
        foreach ($messagesToSend as $lang => $message) {
            sendpm($message['recipients'], $message['subject'], $message['body']);
        }
        // Give the user their own language back!
        if (!empty($modSettings['userLanguage'])) {
            loadLanguage('PersonalMessage', '', false);
        }
        // Leave them with a template.
        $context['sub_template'] = 'report_message_complete';
    }
}
Example #13
0
function Login2()
{
    global $txt, $scripturl, $user_info, $user_settings, $smcFunc;
    global $cookiename, $maintenance, $modSettings, $context, $sc, $sourcedir;
    // Load cookie authentication stuff.
    require_once $sourcedir . '/Subs-Auth.php';
    if (isset($_GET['sa']) && $_GET['sa'] == 'salt' && !$user_info['is_guest']) {
        if (isset($_COOKIE[$cookiename]) && preg_match('~^a:[34]:\\{i:0;(i:\\d{1,6}|s:[1-8]:"\\d{1,8}");i:1;s:(0|40):"([a-fA-F0-9]{40})?";i:2;[id]:\\d{1,14};(i:3;i:\\d;)?\\}$~', $_COOKIE[$cookiename]) === 1) {
            list(, , $timeout) = @unserialize($_COOKIE[$cookiename]);
        } elseif (isset($_SESSION['login_' . $cookiename])) {
            list(, , $timeout) = @unserialize($_SESSION['login_' . $cookiename]);
        } else {
            trigger_error('Login2(): Cannot be logged in without a session or cookie', E_USER_ERROR);
        }
        $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
        updateMemberData($user_info['id'], array('password_salt' => $user_settings['password_salt']));
        setLoginCookie($timeout - time(), $user_info['id'], sha1($user_settings['passwd'] . $user_settings['password_salt']));
        redirectexit('action=login2;sa=check;member=' . $user_info['id'], $context['server']['needs_login_fix']);
    } elseif (isset($_GET['sa']) && $_GET['sa'] == 'check') {
        // Strike!  You're outta there!
        if ($_GET['member'] != $user_info['id']) {
            fatal_lang_error('login_cookie_error', false);
        }
        // Some whitelisting for login_url...
        if (empty($_SESSION['login_url'])) {
            redirectexit();
        } else {
            // Best not to clutter the session data too much...
            $temp = $_SESSION['login_url'];
            unset($_SESSION['login_url']);
            redirectexit($temp);
        }
    }
    // Beyond this point you are assumed to be a guest trying to login.
    if (!$user_info['is_guest']) {
        redirectexit();
    }
    // Set the login_url if it's not already set (but careful not to send us to an attachment).
    if (empty($_SESSION['login_url']) && isset($_SESSION['old_url']) && strpos($_SESSION['old_url'], 'dlattach') === false && preg_match('~(board|topic)[=,]~', $_SESSION['old_url']) != 0) {
        $_SESSION['login_url'] = $_SESSION['old_url'];
    }
    // Are you guessing with a script that doesn't keep the session id?
    spamProtection('login');
    // Been guessing a lot, haven't we?
    if (isset($_SESSION['failed_login']) && $_SESSION['failed_login'] >= $modSettings['failed_login_threshold'] * 3) {
        fatal_lang_error('login_threshold_fail', 'critical');
    }
    // Set up the cookie length.  (if it's invalid, just fall through and use the default.)
    if (isset($_POST['cookieneverexp']) || !empty($_POST['cookielength']) && $_POST['cookielength'] == -1) {
        $modSettings['cookieTime'] = 3153600;
    } elseif (!empty($_POST['cookielength']) && ($_POST['cookielength'] >= 1 || $_POST['cookielength'] <= 525600)) {
        $modSettings['cookieTime'] = (int) $_POST['cookielength'];
    }
    loadLanguage('Login');
    // Load the template stuff - wireless or normal.
    if (WIRELESS) {
        $context['sub_template'] = WIRELESS_PROTOCOL . '_login';
    } else {
        loadTemplate('Login');
        $context['sub_template'] = 'login';
    }
    // Set up the default/fallback stuff.
    $context['default_username'] = isset($_REQUEST['user']) ? preg_replace('~&amp;#(\\d{1,7}|x[0-9a-fA-F]{1,6});~', '&#\\1;', htmlspecialchars($_REQUEST['user'])) : '';
    $context['default_password'] = '';
    $context['never_expire'] = $modSettings['cookieTime'] == 525600 || $modSettings['cookieTime'] == 3153600;
    $context['login_errors'] = array($txt['error_occured']);
    $context['page_title'] = $txt['login'];
    // Add the login chain to the link tree.
    $context['linktree'][] = array('url' => $scripturl . '?action=login', 'name' => $txt['login']);
    if (!empty($_REQUEST['openid_identifier']) && !empty($modSettings['enableOpenID'])) {
        require_once $sourcedir . '/Subs-OpenID.php';
        return smf_openID_validate($_REQUEST['openid_identifier']);
    }
    // You forgot to type your username, dummy!
    if (!isset($_REQUEST['user']) || $_REQUEST['user'] == '') {
        $context['login_errors'] = array($txt['need_username']);
        return;
    }
    // Hmm... maybe 'admin' will login with no password. Uhh... NO!
    if ((!isset($_POST['passwrd']) || $_POST['passwrd'] == '') && (!isset($_REQUEST['hash_passwrd']) || strlen($_REQUEST['hash_passwrd']) != 40)) {
        $context['login_errors'] = array($txt['no_password']);
        return;
    }
    // No funky symbols either.
    if (preg_match('~[<>&"\'=\\\\]~', preg_replace('~(&#(\\d{1,7}|x[0-9a-fA-F]{1,6});)~', '', $_REQUEST['user'])) != 0) {
        $context['login_errors'] = array($txt['error_invalid_characters_username']);
        return;
    }
    // Are we using any sort of integration to validate the login?
    if (isset($modSettings['integrate_validate_login']) && is_callable($modSettings['integrate_validate_login'])) {
        if (call_user_func(strpos($modSettings['integrate_validate_login'], '::') === false ? $modSettings['integrate_validate_login'] : explode('::', $modSettings['integrate_validate_login']), $_REQUEST['user'], isset($_REQUEST['hash_passwrd']) && strlen($_REQUEST['hash_passwrd']) == 40 ? $_REQUEST['hash_passwrd'] : null, $modSettings['cookieTime']) == 'retry') {
            $context['login_errors'] = array($txt['login_hash_error']);
            $context['disable_login_hashing'] = true;
            return;
        }
    }
    // Load the data up!
    $request = $smcFunc['db_query']('', '
		SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt,
			openid_uri, passwd_flood
		FROM {db_prefix}members
		WHERE ' . ($smcFunc['db_case_sensitive'] ? 'LOWER(member_name) = LOWER({string:user_name})' : 'member_name = {string:user_name}') . '
		LIMIT 1', array('user_name' => $smcFunc['db_case_sensitive'] ? strtolower($_REQUEST['user']) : $_REQUEST['user']));
    // Probably mistyped or their email, try it as an email address. (member_name first, though!)
    if ($smcFunc['db_num_rows']($request) == 0) {
        $smcFunc['db_free_result']($request);
        $request = $smcFunc['db_query']('', '
			SELECT passwd, id_member, id_group, lngfile, is_activated, email_address, additional_groups, member_name, password_salt, openid_uri,
			passwd_flood
			FROM {db_prefix}members
			WHERE email_address = {string:user_name}
			LIMIT 1', array('user_name' => $_REQUEST['user']));
        // Let them try again, it didn't match anything...
        if ($smcFunc['db_num_rows']($request) == 0) {
            $context['login_errors'] = array($txt['username_no_exist']);
            return;
        }
    }
    $user_settings = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);
    // Figure out the password using SMF's encryption - if what they typed is right.
    if (isset($_REQUEST['hash_passwrd']) && strlen($_REQUEST['hash_passwrd']) == 40) {
        // Needs upgrading?
        if (strlen($user_settings['passwd']) != 40) {
            $context['login_errors'] = array($txt['login_hash_error']);
            $context['disable_login_hashing'] = true;
            unset($user_settings);
            return;
        } elseif ($_REQUEST['hash_passwrd'] == sha1($user_settings['passwd'] . $sc)) {
            $sha_passwd = $user_settings['passwd'];
        } else {
            // Don't allow this!
            validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
            $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
            if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold']) {
                redirectexit('action=reminder');
            } else {
                log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
                $context['disable_login_hashing'] = true;
                $context['login_errors'] = array($txt['incorrect_password']);
                unset($user_settings);
                return;
            }
        }
    } else {
        $sha_passwd = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
    }
    // Bad password!  Thought you could fool the database?!
    if ($user_settings['passwd'] != $sha_passwd) {
        // Let's be cautious, no hacking please. thanx.
        validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood']);
        // Maybe we were too hasty... let's try some other authentication methods.
        $other_passwords = array();
        // None of the below cases will be used most of the time (because the salt is normally set.)
        if ($user_settings['password_salt'] == '') {
            // YaBB SE, Discus, MD5 (used a lot), SHA-1 (used some), SMF 1.0.x, IkonBoard, and none at all.
            $other_passwords[] = crypt($_POST['passwrd'], substr($_POST['passwrd'], 0, 2));
            $other_passwords[] = crypt($_POST['passwrd'], substr($user_settings['passwd'], 0, 2));
            $other_passwords[] = md5($_POST['passwrd']);
            $other_passwords[] = sha1($_POST['passwrd']);
            $other_passwords[] = md5_hmac($_POST['passwrd'], strtolower($user_settings['member_name']));
            $other_passwords[] = md5($_POST['passwrd'] . strtolower($user_settings['member_name']));
            $other_passwords[] = $_POST['passwrd'];
            // This one is a strange one... MyPHP, crypt() on the MD5 hash.
            $other_passwords[] = crypt(md5($_POST['passwrd']), md5($_POST['passwrd']));
            // Snitz style - SHA-256.  Technically, this is a downgrade, but most PHP configurations don't support sha256 anyway.
            if (strlen($user_settings['passwd']) == 64 && function_exists('mhash') && defined('MHASH_SHA256')) {
                $other_passwords[] = bin2hex(mhash(MHASH_SHA256, $_POST['passwrd']));
            }
            // phpBB3 users new hashing.  We now support it as well ;).
            $other_passwords[] = phpBB3_password_check($_POST['passwrd'], $user_settings['passwd']);
            // APBoard 2 Login Method.
            $other_passwords[] = md5(crypt($_REQUEST['passwrd'], 'CRYPT_MD5'));
        } elseif (strlen($user_settings['passwd']) == 32) {
            // vBulletin 3 style hashing?  Let's welcome them with open arms \o/.
            $other_passwords[] = md5(md5($_POST['passwrd']) . $user_settings['password_salt']);
            // Hmm.. p'raps it's Invision 2 style?
            $other_passwords[] = md5(md5($user_settings['password_salt']) . md5($_POST['passwrd']));
            // Some common md5 ones.
            $other_passwords[] = md5($user_settings['password_salt'] . $_POST['passwrd']);
            $other_passwords[] = md5($_POST['passwrd'] . $user_settings['password_salt']);
            $other_passwords[] = md5($_POST['passwrd']);
            $other_passwords[] = md5(md5($_POST['passwrd']));
        } elseif (strlen($user_settings['passwd']) == 40) {
            // Maybe they are using a hash from before the password fix.
            $other_passwords[] = sha1(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
            // BurningBoard3 style of hashing.
            $other_passwords[] = sha1($user_settings['password_salt'] . sha1($user_settings['password_salt'] . sha1($_REQUEST['passwrd'])));
            // Perhaps we converted to UTF-8 and have a valid password being hashed differently.
            if ($context['character_set'] == 'utf8' && !empty($modSettings['previousCharacterSet']) && $modSettings['previousCharacterSet'] != 'utf8') {
                // Try iconv first, for no particular reason.
                if (function_exists('iconv')) {
                    $other_passwords['iconv'] = sha1(strtolower(iconv('UTF-8', $modSettings['previousCharacterSet'], $user_settings['member_name'])) . un_htmlspecialchars(iconv('UTF-8', $modSettings['previousCharacterSet'], $_POST['passwrd'])));
                }
                // Say it aint so, iconv failed!
                if (empty($other_passwords['iconv']) && function_exists('mb_convert_encoding')) {
                    $other_passwords[] = sha1(strtolower(mb_convert_encoding($user_settings['member_name'], 'UTF-8', $modSettings['previousCharacterSet'])) . un_htmlspecialchars(mb_convert_encoding($_POST['passwrd'], 'UTF-8', $modSettings['previousCharacterSet'])));
                }
            }
        }
        // SMF's sha1 function can give a funny result on Linux (Not our fault!). If we've now got the real one let the old one be valid!
        if (strpos(strtolower(PHP_OS), 'win') !== 0) {
            require_once $sourcedir . '/Subs-Compat.php';
            $other_passwords[] = sha1_smf(strtolower($user_settings['member_name']) . un_htmlspecialchars($_POST['passwrd']));
        }
        // Whichever encryption it was using, let's make it use SMF's now ;).
        if (in_array($user_settings['passwd'], $other_passwords)) {
            $user_settings['passwd'] = $sha_passwd;
            $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
            // Update the password and set up the hash.
            updateMemberData($user_settings['id_member'], array('passwd' => $user_settings['passwd'], 'password_salt' => $user_settings['password_salt']));
        } else {
            // They've messed up again - keep a count to see if they need a hand.
            $_SESSION['failed_login'] = @$_SESSION['failed_login'] + 1;
            // Hmm... don't remember it, do you?  Here, try the password reminder ;).
            if ($_SESSION['failed_login'] >= $modSettings['failed_login_threshold']) {
                redirectexit('action=reminder');
            } else {
                // Log an error so we know that it didn't go well in the error log.
                log_error($txt['incorrect_password'] . ' - <span class="remove">' . $user_settings['member_name'] . '</span>', 'user');
                $context['login_errors'] = array($txt['incorrect_password']);
                return;
            }
        }
    } elseif (!empty($user_settings['passwd_flood'])) {
        // Let's be sure they wern't a little hacker.
        validatePasswordFlood($user_settings['id_member'], $user_settings['passwd_flood'], true);
        // If we got here then we can reset the flood counter.
        updateMemberData($user_settings['id_member'], array('passwd_flood' => ''));
    }
    // Correct password, but they've got no salt; fix it!
    if ($user_settings['password_salt'] == '') {
        $user_settings['password_salt'] = substr(md5(mt_rand()), 0, 4);
        updateMemberData($user_settings['id_member'], array('password_salt' => $user_settings['password_salt']));
    }
    // Check their activation status.
    if (!checkActivation()) {
        return;
    }
    DoLogin();
}
Example #14
0
function scheduled_daily_digest()
{
    global $is_weekly, $txt, $mbname, $scripturl, $sourcedir, $context, $modSettings;
    // We'll want this...
    require_once $sourcedir . '/lib/Subs-Post.php';
    loadEssentialThemeData();
    $is_weekly = !empty($is_weekly) ? 1 : 0;
    // Right - get all the notification data FIRST.
    $request = smf_db_query('
		SELECT ln.id_topic, COALESCE(t.id_board, ln.id_board) AS id_board, mem.email_address, mem.member_name, mem.notify_types,
			mem.lngfile, mem.id_member
		FROM {db_prefix}log_notify AS ln
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
			LEFT JOIN {db_prefix}topics AS t ON (ln.id_topic != {int:empty_topic} AND t.id_topic = ln.id_topic)
		WHERE mem.notify_regularity = {int:notify_regularity}
			AND mem.is_activated = {int:is_activated}', array('empty_topic' => 0, 'notify_regularity' => $is_weekly ? '3' : '2', 'is_activated' => 1));
    $members = array();
    $langs = array();
    $notify = array();
    while ($row = mysql_fetch_assoc($request)) {
        if (!isset($members[$row['id_member']])) {
            $members[$row['id_member']] = array('email' => $row['email_address'], 'name' => $row['member_name'], 'id' => $row['id_member'], 'notifyMod' => $row['notify_types'] < 3 ? true : false, 'lang' => $row['lngfile']);
            $langs[$row['lngfile']] = $row['lngfile'];
        }
        // Store this useful data!
        $boards[$row['id_board']] = $row['id_board'];
        if ($row['id_topic']) {
            $notify['topics'][$row['id_topic']][] = $row['id_member'];
        } else {
            $notify['boards'][$row['id_board']][] = $row['id_member'];
        }
    }
    mysql_free_result($request);
    if (empty($boards)) {
        return true;
    }
    // Just get the board names.
    $request = smf_db_query('
		SELECT id_board, name
		FROM {db_prefix}boards
		WHERE id_board IN ({array_int:board_list})', array('board_list' => $boards));
    $boards = array();
    while ($row = mysql_fetch_assoc($request)) {
        $boards[$row['id_board']] = $row['name'];
    }
    mysql_free_result($request);
    if (empty($boards)) {
        return true;
    }
    // Get the actual topics...
    $request = smf_db_query('
		SELECT ld.note_type, t.id_topic, t.id_board, t.id_member_started, m.id_msg, m.subject,
			b.name AS board_name
		FROM {db_prefix}log_digest AS ld
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ld.id_topic
				AND t.id_board IN ({array_int:board_list}))
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
		WHERE ' . ($is_weekly ? 'ld.daily != {int:daily_value}' : 'ld.daily IN (0, 2)'), array('board_list' => array_keys($boards), 'daily_value' => 2));
    $types = array();
    while ($row = mysql_fetch_assoc($request)) {
        if (!isset($types[$row['note_type']][$row['id_board']])) {
            $types[$row['note_type']][$row['id_board']] = array('lines' => array(), 'name' => $row['board_name'], 'id' => $row['id_board']);
        }
        if ($row['note_type'] == 'reply') {
            if (isset($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']])) {
                $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['count']++;
            } else {
                $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']] = array('id' => $row['id_topic'], 'subject' => un_htmlspecialchars($row['subject']), 'count' => 1);
            }
        } elseif ($row['note_type'] == 'topic') {
            if (!isset($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']])) {
                $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']] = array('id' => $row['id_topic'], 'subject' => un_htmlspecialchars($row['subject']));
            }
        } else {
            if (!isset($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']])) {
                $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']] = array('id' => $row['id_topic'], 'subject' => un_htmlspecialchars($row['subject']), 'starter' => $row['id_member_started']);
            }
        }
        $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'] = array();
        if (!empty($notify['topics'][$row['id_topic']])) {
            $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'] = array_merge($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'], $notify['topics'][$row['id_topic']]);
        }
        if (!empty($notify['boards'][$row['id_board']])) {
            $types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'] = array_merge($types[$row['note_type']][$row['id_board']]['lines'][$row['id_topic']]['members'], $notify['boards'][$row['id_board']]);
        }
    }
    mysql_free_result($request);
    if (empty($types)) {
        return true;
    }
    // Let's load all the languages into a cache thingy.
    $langtxt = array();
    foreach ($langs as $lang) {
        loadLanguage('Post', $lang);
        loadLanguage('index', $lang);
        loadLanguage('EmailTemplates', $lang);
        $langtxt[$lang] = array('subject' => $txt['digest_subject_' . ($is_weekly ? 'weekly' : 'daily')], 'char_set' => $txt['lang_character_set'], 'intro' => sprintf($txt['digest_intro_' . ($is_weekly ? 'weekly' : 'daily')], $mbname), 'new_topics' => $txt['digest_new_topics'], 'topic_lines' => $txt['digest_new_topics_line'], 'new_replies' => $txt['digest_new_replies'], 'mod_actions' => $txt['digest_mod_actions'], 'replies_one' => $txt['digest_new_replies_one'], 'replies_many' => $txt['digest_new_replies_many'], 'sticky' => $txt['digest_mod_act_sticky'], 'lock' => $txt['digest_mod_act_lock'], 'unlock' => $txt['digest_mod_act_unlock'], 'remove' => $txt['digest_mod_act_remove'], 'move' => $txt['digest_mod_act_move'], 'merge' => $txt['digest_mod_act_merge'], 'split' => $txt['digest_mod_act_split'], 'bye' => $txt['regards_team']);
    }
    // Right - send out the silly things - this will take quite some space!
    $emails = array();
    foreach ($members as $mid => $member) {
        // Right character set!
        $context['character_set'] = 'UTF-8';
        // Do the start stuff!
        $email = array('subject' => $mbname . ' - ' . $langtxt[$lang]['subject'], 'body' => $member['name'] . ',' . "\n\n" . $langtxt[$lang]['intro'] . "\n" . $scripturl . '?action=profile;area=notification;u=' . $member['id'] . "\n", 'email' => $member['email']);
        // All new topics?
        if (isset($types['topic'])) {
            $titled = false;
            foreach ($types['topic'] as $id => $board) {
                foreach ($board['lines'] as $topic) {
                    if (in_array($mid, $topic['members'])) {
                        if (!$titled) {
                            $email['body'] .= "\n" . $langtxt[$lang]['new_topics'] . ':' . "\n" . '-----------------------------------------------';
                            $titled = true;
                        }
                        $email['body'] .= "\n" . sprintf($langtxt[$lang]['topic_lines'], $topic['subject'], $board['name']);
                    }
                }
            }
            if ($titled) {
                $email['body'] .= "\n";
            }
        }
        // What about replies?
        if (isset($types['reply'])) {
            $titled = false;
            foreach ($types['reply'] as $id => $board) {
                foreach ($board['lines'] as $topic) {
                    if (in_array($mid, $topic['members'])) {
                        if (!$titled) {
                            $email['body'] .= "\n" . $langtxt[$lang]['new_replies'] . ':' . "\n" . '-----------------------------------------------';
                            $titled = true;
                        }
                        $email['body'] .= "\n" . ($topic['count'] == 1 ? sprintf($langtxt[$lang]['replies_one'], $topic['subject']) : sprintf($langtxt[$lang]['replies_many'], $topic['count'], $topic['subject']));
                    }
                }
            }
            if ($titled) {
                $email['body'] .= "\n";
            }
        }
        // Finally, moderation actions!
        $titled = false;
        foreach ($types as $note_type => $type) {
            if ($note_type == 'topic' || $note_type == 'reply') {
                continue;
            }
            foreach ($type as $id => $board) {
                foreach ($board['lines'] as $topic) {
                    if (in_array($mid, $topic['members'])) {
                        if (!$titled) {
                            $email['body'] .= "\n" . $langtxt[$lang]['mod_actions'] . ':' . "\n" . '-----------------------------------------------';
                            $titled = true;
                        }
                        $email['body'] .= "\n" . sprintf($langtxt[$lang][$note_type], $topic['subject']);
                    }
                }
            }
        }
        if ($titled) {
            $email['body'] .= "\n";
        }
        // Then just say our goodbyes!
        $email['body'] .= "\n\n" . $txt['regards_team'];
        // Send it - low priority!
        sendmail($email['email'], $email['subject'], $email['body'], null, null, false, 4);
    }
    // Clean up...
    if ($is_weekly) {
        smf_db_query('
			DELETE FROM {db_prefix}log_digest
			WHERE daily != {int:not_daily}', array('not_daily' => 0));
        smf_db_query('
			UPDATE {db_prefix}log_digest
			SET daily = {int:daily_value}
			WHERE daily = {int:not_daily}', array('daily_value' => 2, 'not_daily' => 0));
    } else {
        // Clear any only weekly ones, and stop us from sending daily again.
        smf_db_query('
			DELETE FROM {db_prefix}log_digest
			WHERE daily = {int:daily_value}', array('daily_value' => 2));
        smf_db_query('
			UPDATE {db_prefix}log_digest
			SET daily = {int:both_value}
			WHERE daily = {int:no_value}', array('both_value' => 1, 'no_value' => 0));
    }
    // Just in case the member changes their settings mark this as sent.
    $members = array_keys($members);
    smf_db_query('
		UPDATE {db_prefix}log_notify
		SET sent = {int:is_sent}
		WHERE id_member IN ({array_int:member_list})', array('member_list' => $members, 'is_sent' => 1));
    // Log we've done it...
    return true;
}
Example #15
0
function EditSmileys()
{
    global $modSettings, $context, $settings, $db_prefix, $txt, $boarddir;
    // Force the correct tab to be displayed.
    $context['admin_tabs']['tabs']['editsmileys']['is_selected'] = true;
    // Submitting a form?
    if (isset($_POST['sc'])) {
        checkSession();
        // Changing the selected smileys?
        if (isset($_POST['smiley_action']) && !empty($_POST['checked_smileys'])) {
            foreach ($_POST['checked_smileys'] as $id => $smiley_id) {
                $_POST['checked_smileys'][$id] = (int) $smiley_id;
            }
            if ($_POST['smiley_action'] == 'delete') {
                db_query("\n\t\t\t\t\tDELETE FROM {$db_prefix}smileys\n\t\t\t\t\tWHERE ID_SMILEY IN (" . implode(', ', $_POST['checked_smileys']) . ')', __FILE__, __LINE__);
            } else {
                // Check it's a valid type.
                $displayTypes = array('post' => 0, 'hidden' => 1, 'popup' => 2);
                if (isset($displayTypes[$_POST['smiley_action']])) {
                    db_query("\n\t\t\t\t\t\tUPDATE {$db_prefix}smileys\n\t\t\t\t\t\tSET hidden = " . $displayTypes[$_POST['smiley_action']] . "\n\t\t\t\t\t\tWHERE ID_SMILEY IN (" . implode(', ', $_POST['checked_smileys']) . ')', __FILE__, __LINE__);
                }
            }
        } elseif (isset($_POST['smiley'])) {
            $_POST['smiley'] = (int) $_POST['smiley'];
            $_POST['smiley_code'] = htmltrim__recursive($_POST['smiley_code']);
            $_POST['smiley_filename'] = htmltrim__recursive($_POST['smiley_filename']);
            $_POST['smiley_location'] = empty($_POST['smiley_location']) || $_POST['smiley_location'] > 2 || $_POST['smiley_location'] < 0 ? 0 : (int) $_POST['smiley_location'];
            // Make sure some code was entered.
            if (empty($_POST['smiley_code'])) {
                fatal_lang_error('smiley_has_no_code');
            }
            // Also make sure a filename was given.
            if (empty($_POST['smiley_filename'])) {
                fatal_lang_error('smiley_has_no_filename');
            }
            // Check whether the new code has duplicates. It should be unique.
            $request = db_query("\n\t\t\t\tSELECT ID_SMILEY\n\t\t\t\tFROM {$db_prefix}smileys\n\t\t\t\tWHERE code = BINARY '{$_POST['smiley_code']}'" . (empty($_POST['smiley']) ? '' : "\n\t\t\t\t\tAND ID_SMILEY != {$_POST['smiley']}"), __FILE__, __LINE__);
            if (mysql_num_rows($request) > 0) {
                fatal_lang_error('smiley_not_unique');
            }
            mysql_free_result($request);
            db_query("\n\t\t\t\tUPDATE {$db_prefix}smileys\n\t\t\t\tSET\n\t\t\t\t\tcode = '{$_POST['smiley_code']}',\n\t\t\t\t\tfilename = '{$_POST['smiley_filename']}',\n\t\t\t\t\tdescription = '{$_POST['smiley_description']}',\n\t\t\t\t\thidden = {$_POST['smiley_location']}\n\t\t\t\tWHERE ID_SMILEY = {$_POST['smiley']}", __FILE__, __LINE__);
            // Sort all smiley codes for more accurate parsing (longest code first).
            db_query("\n\t\t\t\tALTER TABLE {$db_prefix}smileys\n\t\t\t\tORDER BY LENGTH(code) DESC", __FILE__, __LINE__);
        }
        cache_put_data('parsing_smileys', null, 480);
        cache_put_data('posting_smileys', null, 480);
    }
    // Load all known smiley sets.
    $context['smiley_sets'] = explode(',', $modSettings['smiley_sets_known']);
    $set_names = explode("\n", $modSettings['smiley_sets_names']);
    foreach ($context['smiley_sets'] as $i => $set) {
        $context['smiley_sets'][$i] = array('id' => $i, 'path' => htmlspecialchars($set), 'name' => htmlspecialchars($set_names[$i]), 'selected' => $set == $modSettings['smiley_sets_default']);
    }
    // Prepare overview of all (custom) smileys.
    if ($context['sub_action'] == 'editsmileys') {
        $sortColumns = array('code', 'filename', 'description', 'hidden');
        // Default to 'order by filename'.
        $context['sort'] = empty($_REQUEST['sort']) || !in_array($_REQUEST['sort'], $sortColumns) ? 'filename' : $_REQUEST['sort'];
        $request = db_query("\n\t\t\tSELECT ID_SMILEY, code, filename, description, smileyRow, smileyOrder, hidden\n\t\t\tFROM {$db_prefix}smileys\n\t\t\tORDER BY {$context['sort']}", __FILE__, __LINE__);
        $context['smileys'] = array();
        while ($row = mysql_fetch_assoc($request)) {
            $context['smileys'][] = array('id' => $row['ID_SMILEY'], 'code' => htmlspecialchars($row['code']), 'filename' => htmlspecialchars($row['filename']), 'description' => htmlspecialchars($row['description']), 'row' => $row['smileyRow'], 'order' => $row['smileyOrder'], 'location' => empty($row['hidden']) ? $txt['smileys_location_form'] : ($row['hidden'] == 1 ? $txt['smileys_location_hidden'] : $txt['smileys_location_popup']), 'sets_not_found' => array());
        }
        mysql_free_result($request);
        if (!empty($modSettings['smileys_dir']) && is_dir($modSettings['smileys_dir'])) {
            foreach ($context['smiley_sets'] as $smiley_set) {
                foreach ($context['smileys'] as $smiley_id => $smiley) {
                    if (!file_exists($modSettings['smileys_dir'] . '/' . un_htmlspecialchars($smiley_set['path']) . '/' . $smiley['filename'])) {
                        $context['smileys'][$smiley_id]['sets_not_found'][] = $smiley_set['path'];
                    }
                }
            }
        }
        $context['selected_set'] = $modSettings['smiley_sets_default'];
    } elseif ($context['sub_action'] == 'modifysmiley') {
        // Get a list of all known smiley sets.
        $context['smileys_dir'] = empty($modSettings['smileys_dir']) ? $boarddir . '/Smileys' : $modSettings['smileys_dir'];
        $context['smileys_dir_found'] = is_dir($context['smileys_dir']);
        $context['smiley_sets'] = explode(',', $modSettings['smiley_sets_known']);
        $set_names = explode("\n", $modSettings['smiley_sets_names']);
        foreach ($context['smiley_sets'] as $i => $set) {
            $context['smiley_sets'][$i] = array('id' => $i, 'path' => htmlspecialchars($set), 'name' => htmlspecialchars($set_names[$i]), 'selected' => $set == $modSettings['smiley_sets_default']);
        }
        $context['selected_set'] = $modSettings['smiley_sets_default'];
        // Get all possible filenames for the smileys.
        $context['filenames'] = array();
        if ($context['smileys_dir_found']) {
            foreach ($context['smiley_sets'] as $smiley_set) {
                if (!file_exists($context['smileys_dir'] . '/' . un_htmlspecialchars($smiley_set['path']))) {
                    continue;
                }
                $dir = dir($context['smileys_dir'] . '/' . un_htmlspecialchars($smiley_set['path']));
                while ($entry = $dir->read()) {
                    if (!in_array($entry, $context['filenames']) && in_array(strrchr($entry, '.'), array('.jpg', '.gif', '.jpeg', '.png'))) {
                        $context['filenames'][strtolower($entry)] = array('id' => htmlspecialchars($entry), 'selected' => false);
                    }
                }
                $dir->close();
            }
            ksort($context['filenames']);
        }
        $request = db_query("\n\t\t\tSELECT ID_SMILEY AS id, code, filename, description, hidden AS location, 0 AS is_new\n\t\t\tFROM {$db_prefix}smileys\n\t\t\tWHERE ID_SMILEY = " . (int) $_REQUEST['smiley'], __FILE__, __LINE__);
        if (mysql_num_rows($request) != 1) {
            fatal_lang_error('smiley_not_found');
        }
        $context['current_smiley'] = mysql_fetch_assoc($request);
        mysql_free_result($request);
        $context['current_smiley']['code'] = htmlspecialchars($context['current_smiley']['code']);
        $context['current_smiley']['filename'] = htmlspecialchars($context['current_smiley']['filename']);
        $context['current_smiley']['description'] = htmlspecialchars($context['current_smiley']['description']);
        if (isset($context['filenames'][strtolower($context['current_smiley']['filename'])])) {
            $context['filenames'][strtolower($context['current_smiley']['filename'])]['selected'] = true;
        }
    }
}
function do_postchecks()
{
    global $context, $txt, $settings, $boarddir, $smcFunc, $sourcedir;
    // If we have any setting changes add them to this array
    $updateArray = array();
    // which screen do we come frm?
    if (!empty($_POST['tpadmin_form'])) {
        // get it
        $from = $_POST['tpadmin_form'];
        //news
        if ($from == 'news') {
            return 'news';
        } elseif ($from == 'blockoverview') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $block = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 5, 7) == 'tpblock') {
                    // get the id
                    $bid = substr($what, 12);
                    if (!isset($block[$bid])) {
                        $block[$bid] = array();
                    }
                    if ($value != 'control' && !in_array($value, $block[$bid])) {
                        $block[$bid][] = $value;
                    }
                }
            }
            foreach ($block as $bl => $blo) {
                $request = $smcFunc['db_query']('', '
					SELECT access FROM {db_prefix}tp_blocks 
					WHERE id = {int:blockid}', array('blockid' => $bl));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $smcFunc['db_free_result']($request);
                    $request = $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET access = {string:access} WHERE id = {int:blockid}', array('access' => implode(',', $blo), 'blockid' => $bl));
                }
            }
            return 'blocks;overview';
        } elseif (in_array($from, array('settings', 'frontpage', 'artsettings', 'panels'))) {
            checkSession('post');
            isAllowedTo('tp_settings');
            $w = array();
            $ssi = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'tp_') {
                    $where = substr($what, 3);
                    $clean = $value;
                    // for frontpage, do some extra
                    if ($from == 'frontpage') {
                        if (substr($what, 0, 20) == 'tp_frontpage_visual_') {
                            $w[] = substr($what, 20);
                            unset($clean);
                        } elseif (substr($what, 0, 21) == 'tp_frontpage_usorting') {
                            $w[] = 'sort_' . $value;
                            unset($clean);
                        } elseif (substr($what, 0, 26) == 'tp_frontpage_sorting_order') {
                            $w[] = 'sortorder_' . $value;
                            unset($clean);
                        } elseif (substr($what, 0, 11) == 'tp_ssiboard') {
                            if ($value != 0) {
                                $ssi[$value] = $value;
                            }
                        }
                    }
                    if ($from == 'settings' && $what == 'tp_frontpage_title') {
                        $updateArray['frontpage_title'] = $clean;
                    } else {
                        if (isset($clean)) {
                            $updateArray[$where] = $clean;
                        }
                    }
                }
            }
            // check the frontpage visual setting..
            if ($from == 'frontpage') {
                $updateArray['frontpage_visual'] = implode(',', $w);
                $updateArray['SSI_board'] = implode(',', $ssi);
            }
            updateTPSettings($updateArray);
            return $from;
        } elseif ($from == 'categories') {
            checkSession('post');
            isAllowedTo('tp_articles');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'tp_') {
                    // for frontpage, do some extra
                    if ($from == 'categories') {
                        if (substr($what, 0, 19) == 'tp_category_value2_') {
                            $where = tp_sanitize(substr($what, 19));
                            //make sure parent are not its own parent
                            $request = $smcFunc['db_query']('', '
								SELECT value2 FROM {db_prefix}tp_variables 
								WHERE id = {string:varid} LIMIT 1', array('varid' => $value));
                            $row = $smcFunc['db_fetch_assoc']($request);
                            $smcFunc['db_free_result']($request);
                            if ($row['value2'] == $where) {
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_variables 
									SET value2 = {string:val2}
									WHERE id = {string:varid} LIMIT 1', array('val2' => '0', 'varid' => $value));
                            }
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}tp_variables 
								SET value2 = {string:val2}
								WHERE id = {string:varid} LIMIT 1', array('val2' => $value, 'varid' => $where));
                        }
                    }
                }
            }
            return $from;
        } elseif ($from == 'articles') {
            checkSession('post');
            isAllowedTo('tp_articles');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 14) == 'tp_article_pos') {
                    $where = tp_sanitize(substr($what, 14));
                    $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET parse = {int:parse} 
							WHERE id = {int:artid} LIMIT 1', array('parse' => $value, 'artid' => $where));
                }
            }
            if (isset($_POST['tpadmin_form_category']) && is_numeric($_POST['tpadmin_form_category'])) {
                return $from . ';cu=' . $_POST['tpadmin_form_category'];
            } else {
                return $from;
            }
        } elseif ($from == 'modules') {
            checkSession('post');
            isAllowedTo('tp_settings');
            foreach ($_POST as $what => $value) {
                if ($what == 'tp_show_download') {
                    $updateArray['show_download'] = $value;
                } elseif (substr($what, 0, 14) == 'tpmodule_state') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_modules 
						SET active = {int:active} 
						WHERE id = {int:modid}', array('active' => $value, 'modid' => substr($what, 14)));
                }
            }
            updateTPSettings($updateArray);
            return $from;
        } elseif ($from == 'menuitems') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $all = explode(',', $context['TPortal']['sitemap_items']);
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 8) == 'menu_pos') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET subtype = {string:subtype} 
						WHERE id = {int:varid}', array('subtype' => tp_sanitize($value), 'varid' => substr($what, 8)));
                } elseif (substr($what, 0, 8) == 'menu_sub') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value4 = {string:val4} 
						WHERE id = {int:varid}', array('val4' => tp_sanitize($value), 'varid' => substr($what, 8)));
                } elseif (substr($what, 0, 15) == 'tp_menu_sitemap') {
                    $new = substr($what, 15);
                    if ($value == 0 && in_array($new, $all)) {
                        foreach ($all as $key => $value) {
                            if ($all[$key] == $new) {
                                unset($all[$key]);
                            }
                        }
                    } elseif ($value == 1 && !in_array($new, $all)) {
                        $all[] = $new;
                    }
                    $updateArray['sitemap_items'] = implode(',', $all);
                }
            }
            updateTPSettings($updateArray);
            redirectexit('action=tpadmin;sa=menubox;mid=' . $_POST['tp_menuid']);
        } elseif ($from == 'menus') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 12) == 'tp_menu_name') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value1 = {string:val1} 
						WHERE id = {int:varid}', array('val1' => tp_sanitize($value), 'varid' => substr($what, 12)));
                }
            }
            redirectexit('action=tpadmin;sa=menubox');
        } elseif ($from == 'singlemenuedit') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $where = isset($_POST['tpadmin_form_id']) ? $_POST['tpadmin_form_id'] : 0;
            foreach ($_POST as $what => $value) {
                if ($what == 'tp_menu_name') {
                    // make sure special charachters can't be done
                    $value = preg_replace('~&#\\d+$~', '', $value);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value1 = {string:val1} 
						WHERE id = {int:varid}', array('val1' => $value, 'varid' => $where));
                } elseif ($what == 'tp_menu_newlink') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value2 = {string:var2} 
						WHERE id = {int:varid}', array('var2' => $value, 'varid' => $where));
                } elseif ($what == 'tp_menu_menuid') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET subtype2 = {int:subtype2} 
						WHERE id = {int:varid}', array('subtype2' => $value, 'varid' => $where));
                } elseif ($what == 'tp_menu_type') {
                    if ($value == 'cats') {
                        $idtype = 'cats' . $_POST['tp_menu_category'];
                    } elseif ($value == 'arti') {
                        $idtype = 'arti' . $_POST['tp_menu_article'];
                    } elseif ($value == 'link') {
                        $idtype = $_POST['tp_menu_link'];
                    } elseif ($value == 'head') {
                        $idtype = 'head';
                    } elseif ($value == 'spac') {
                        $idtype = 'spac';
                    }
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value3 = {string:val3} 
						WHERE id = {int:varid}', array('val3' => $idtype, 'varid' => $where));
                } elseif ($what == 'tp_menu_sub') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables
						SET value4 = {string:val4}
						WHERE id = {int:varid}', array('val4' => $value, 'varid' => $where));
                } elseif (substr($what, 0, 15) == 'tp_menu_newlink') {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_variables 
						SET value2 =  
						WHERE id = {int:varid}', array('val2' => $value, 'varid' => $where));
                }
            }
            redirectexit('action=tpadmin;linkedit=' . $where . ';' . $context['session_var'] . '=' . $context['session_id']);
        } elseif ($from == 'addcategory') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $name = !empty($_POST['tp_cat_name']) ? $_POST['tp_cat_name'] : $txt['tp-noname'];
            $parent = !empty($_POST['tp_cat_parent']) ? $_POST['tp_cat_parent'] : '0';
            $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array(strip_tags($name), $parent, '', 'category', '', 0, '', 'catlayout=1|layout=1', 0, 0), array('id'));
            $go = $smcFunc['db_insert_id']('{db_prefix}tp_variables', 'id');
            redirectexit('action=tpadmin;sa=categories;cu=' . $go);
        } elseif ($from == 'clist') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $cats = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 8) == 'tp_clist') {
                    $cats[] = $value;
                }
            }
            if (sizeof($cats) > 0) {
                $catnames = implode(',', $cats);
            } else {
                $catnames = '';
            }
            $updateArray['cat_list'] = $catnames;
            updateTPSettings($updateArray);
            return $from;
        } elseif ($from == 'editcategory') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $options = array();
            $groups = array();
            $where = $_POST['tpadmin_form_id'];
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'tp_') {
                    $clean = tp_sanitize($value);
                    $param = substr($what, 12);
                    if (in_array($param, array('value5', 'value6', 'value8'))) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET ' . $param . ' = {string:val} 
							WHERE id = {int:varid} LIMIT 1', array('val' => $value, 'varid' => $where));
                    } elseif ($param == 'value2') {
                        //make sure parent are not its own parent
                        $request = $smcFunc['db_query']('', '
							SELECT value2 FROM {db_prefix}tp_variables 
							WHERE id = {int:varid} LIMIT 1', array('varid' => $value));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                        if ($row['value2'] == $where) {
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}tp_variables 
								SET value2 = {string:val2} 
								WHERE id = {int:varid} LIMIT 1', array('val2' => '0', 'varid' => $value));
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value2 = {string:val2} 
							WHERE id = {int:varid} LIMIT 1', array('val2' => $value, 'varid' => $where));
                    } elseif ($param == 'value1') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value1 = {string:val1} 
							WHERE id = {int:varid} LIMIT 1', array('val1' => strip_tags($value), 'varid' => $where));
                    } elseif ($param == 'value4') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value4 = {string:val4} 
							WHERE id = {int:varid} LIMIT 1', array('val4' => $value, 'varid' => $where));
                    } elseif ($param == 'value9') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_variables 
							SET value9 = {string:val9} 
							WHERE id = {int:varid} LIMIT 1', array('val9' => $value, 'varid' => $where));
                    } elseif (substr($param, 0, 6) == 'group_') {
                        $groups[] = substr($param, 6);
                    } else {
                        $options[] = $param . '=' . $value;
                    }
                }
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_variables 
				SET value3 = {string:val3}, value7 = {string:val7} 
				WHERE id = {int:varid} LIMIT 1', array('val3' => implode(',', $groups), 'val7' => implode('|', $options), 'varid' => $where));
            $from = 'categories;cu=' . $where;
            return $from;
        } elseif ($from == 'strays') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $ccats = array();
            // check if we have some values
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 16) == 'tp_article_stray') {
                    $ccats[] = substr($what, 16);
                } elseif ($what == 'tp_article_cat') {
                    $straycat = $value;
                } elseif ($what == 'tp_article_new') {
                    $straynewcat = $value;
                }
            }
            // update
            if (isset($straycat) && sizeof($ccats) > 0) {
                $category = $straycat;
                if ($category == 0 && !empty($straynewcat)) {
                    $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'type' => 'string'), array(strip_tags($straynewcat), '0', 'category'), array('id'));
                    $newcategory = $smcFunc['db_insert_id']('{db_prefix}tp_variables', 'id');
                    $smcFunc['db_free_result']($request);
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET category = {int:cat} 
					WHERE id IN ({array_int:artid})', array('cat' => !empty($newcategory) ? $newcategory : $category, 'artid' => $ccats));
            }
            return $from;
        } elseif ($from == 'articons') {
            checkSession('post');
            isAllowedTo('tp_articles');
            // any icons sent?
            if (file_exists($_FILES['tp_article_newicon']['tmp_name'])) {
                TPuploadpicture('tp_article_newicon', '', '300', 'jpg,gif,png', 'tp-files/tp-articles/icons');
            }
            if (file_exists($_FILES['tp_article_newillustration']['tmp_name'])) {
                $name = TPuploadpicture('tp_article_newillustration', '', '500', 'jpg,gif,png', 'tp-files/tp-articles/illustrations');
                tp_createthumb('tp-files/tp-articles/illustrations/' . $name, 128, 128, 'tp-files/tp-articles/illustrations/s_' . $name);
                unlink('tp-files/tp-articles/illustrations/' . $name);
            }
            // how about deleted?
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 7) == 'articon') {
                    unlink($boarddir . '/tp-files/tp-articles/icons/' . $value);
                } elseif (substr($what, 0, 15) == 'artillustration') {
                    unlink($boarddir . '/tp-files/tp-articles/illustrations/' . $value);
                }
            }
            return $from;
        } elseif ($from == 'menuadd') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            if (!empty($_POST['tp_menu_title'])) {
                $mtitle = strip_tags($_POST['tp_menu_title']);
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'type' => 'string'), array($mtitle, 'menus'), array('id'));
                redirectexit('action=tpadmin;sa=menubox');
            }
        } elseif ($from == 'menuaddsingle') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $mid = $_POST['tp_menu_menuid'];
            $mtitle = strip_tags($_POST['tp_menu_title']);
            if ($mtitle == '') {
                $mtitle = $txt['tp-no_title'];
            }
            $mtype = $_POST['tp_menu_type'];
            $mcat = isset($_POST['tp_menu_category']) ? $_POST['tp_menu_category'] : '';
            $mart = isset($_POST['tp_menu_article']) ? $_POST['tp_menu_article'] : '';
            $mlink = isset($_POST['tp_menu_link']) ? $_POST['tp_menu_link'] : '';
            $mhead = isset($_POST['tp_menu_head']) ? $_POST['tp_menu_head'] : '';
            $mnewlink = isset($_POST['tp_menu_newlink']) ? $_POST['tp_menu_newlink'] : '0';
            if ($mtype == 'cats') {
                $mtype = 'cats' . $mcat;
            } elseif ($mtype == 'arti') {
                $mtype = 'arti' . $mart;
            } elseif ($mtype == 'head') {
                $mtype = 'head' . $mhead;
            } elseif ($mtype == 'spac') {
                $mtype = 'spac';
            } else {
                $mtype = $mlink;
            }
            $msub = $_POST['tp_menu_sub'];
            $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype2' => 'int'), array($mtitle, $mnewlink, $mtype, 'menubox', $msub, -1, $mid), array('id'));
            redirectexit('action=tpadmin;sa=menubox;mid=' . $mid);
        } elseif ($from == 'submission') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $ccats = array();
            // check if we have some values
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 21) == 'tp_article_submission') {
                    $ccats[] = substr($what, 21);
                } elseif ($what == 'tp_article_cat') {
                    $straycat = $value;
                } elseif ($what == 'tp_article_new') {
                    $straynewcat = $value;
                }
            }
            // update
            if (isset($straycat) && sizeof($ccats) > 0) {
                $category = $straycat;
                if ($category == 0 && !empty($straynewcat)) {
                    $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'type' => 'string'), array($straynewcat, '0', 'category'), array('id'));
                    $newcategory = $smcFunc['db_insert_id']('{db_prefix}tp_variables', 'id');
                    $smcFunc['db_free_result']($request);
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET approved = {int:approved}, category = {int:cat} 
					WHERE id IN ({array_int:artid})', array('approved' => 1, 'cat' => !empty($newcategory) ? $newcategory : $category, 'artid' => $ccats));
                $smcFunc['db_query']('', '
					DELETE FROM {db_prefix}tp_variables 
					WHERE type = {string:type} 
					AND value5 IN ({array_int:val5})', array('type' => 'art_not_approved', 'val5' => $ccats));
            }
            return $from;
        } elseif ($from == 'blocks') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 3) == 'pos') {
                    $where = substr($what, 3);
                    if (is_numeric($where)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET pos = {int:pos} 
							WHERE id = {int:blockid}', array('pos' => $value, 'blockid' => $where));
                    }
                } elseif (substr($what, 0, 6) == 'addpos') {
                    $where = substr($what, 6);
                    if (is_numeric($where)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET pos = (pos + 11) 
							WHERE id = {int:blockid}', array('blockid' => $where));
                    }
                } elseif (substr($what, 0, 6) == 'subpos') {
                    $where = substr($what, 6);
                    if (is_numeric($where)) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks SET pos = (pos - 11) 
							WHERE id = {int:blockid}', array('blockid' => $where));
                    }
                } elseif (substr($what, 0, 4) == 'type') {
                    $where = substr($what, 4);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET type = {int:type} 
						WHERE id = {int:blockid}', array('type' => $value, 'blockid' => $where));
                } elseif (substr($what, 0, 5) == 'title') {
                    $where = strip_tags(substr($what, 5));
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET title = {string:title} 
						WHERE id = {int:blockid}', array('title' => $value, 'blockid' => $where));
                } elseif (substr($what, 0, 9) == 'blockbody') {
                    $where = tp_sanitize(substr($what, 9));
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_blocks 
						SET body = {string:body} 
						WHERE id = {int:blockid}', array('body' => $value, 'blockid' => $where));
                }
            }
            redirectexit('action=tpadmin;sa=blocks');
        } elseif ($from == 'addblock') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $title = empty($_POST['tp_addblocktitle']) ? '-no title-' : $_POST['tp_addblocktitle'];
            $panel = $_POST['tp_addblockpanel'];
            $type = $_POST['tp_addblock'];
            if (!is_numeric($type)) {
                if (substr($type, 0, 3) == 'mb_') {
                    $request = $smcFunc['db_query']('', '
						SELECT * FROM {db_prefix}tp_blocks 
						WHERE id = {int:blockid}', array('blockid' => substr($type, 3)));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        $cp = $smcFunc['db_fetch_assoc']($request);
                        $smcFunc['db_free_result']($request);
                    }
                } else {
                    $od = TPparseModfile(file_get_contents($boarddir . '/tp-files/tp-blockcodes/' . $type . '.blockcode'), array('code'));
                }
            }
            if (isset($od['code'])) {
                $body = tp_convertphp($od['code']);
                $type = 10;
            } else {
                $body = '';
            }
            if (isset($cp)) {
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_blocks', array('type' => 'int', 'frame' => 'string', 'title' => 'string', 'body' => 'string', 'access' => 'string', 'bar' => 'int', 'pos' => 'int', 'off' => 'int', 'visible' => 'string', 'var1' => 'int', 'var2' => 'int', 'lang' => 'string', 'access2' => 'string', 'editgroups' => 'string'), array($cp['type'], $cp['frame'], $title, $cp['body'], $cp['access'], $panel, 0, 1, 1, $cp['var1'], $cp['var2'], $cp['lang'], $cp['access2'], $cp['editgroups']), array('id'));
            } else {
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_blocks', array('type' => 'int', 'frame' => 'string', 'title' => 'string', 'body' => 'string', 'access' => 'string', 'bar' => 'int', 'pos' => 'int', 'off' => 'int', 'visible' => 'string', 'var1' => 'int', 'var2' => 'int', 'lang' => 'string', 'access2' => 'string', 'editgroups' => 'string'), array($type, 'theme', $title, $body, '-1,0,1', $panel, 0, 1, 1, 0, 0, '', 'actio=allpages', ''), array('id'));
            }
            $where = $smcFunc['db_insert_id']('{db_prefix}tp_blocks', 'id');
            if (!empty($where)) {
                redirectexit('action=tpadmin;blockedit=' . $where . ';sesc=' . $context['session_id']);
            } else {
                redirectexit('action=tpadmin;sa=blocks');
            }
        } elseif ($from == 'blockedit') {
            checkSession('post');
            isAllowedTo('tp_blocks');
            $where = is_numeric($_POST['tpadmin_form_id']) ? $_POST['tpadmin_form_id'] : 0;
            $tpgroups = array();
            $editgroups = array();
            $access = array();
            $lang = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 9) == 'tp_block_') {
                    $setting = substr($what, 9);
                    if ($setting == 'body') {
                        // If we came from WYSIWYG then turn it back into BBC regardless.
                        if (!empty($_REQUEST['tp_block_body_mode']) && isset($_REQUEST['tp_block_body'])) {
                            require_once $sourcedir . '/Subs-Editor.php';
                            $_REQUEST['tp_block_body'] = html_to_bbc($_REQUEST['tp_block_body']);
                            // We need to unhtml it now as it gets done shortly.
                            $_REQUEST['tp_block_body'] = un_htmlspecialchars($_REQUEST['tp_block_body']);
                            // We need this for everything else.
                            $value = $_POST['tp_block_body'] = $_REQUEST['tp_block_body'];
                        }
                        // PHP block?
                        if ($_POST['tp_block_type'] == 10) {
                            $value = tp_convertphp($value);
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET ' . $setting . ' = {string:value} 
							WHERE id = {int:blockid}', array('value' => $value, 'blockid' => $where));
                    } elseif ($setting == 'title') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET title = {string:title} 
							WHERE id = {int:blockid}', array('title' => $value, 'blockid' => $where));
                    } elseif ($setting == 'body_mode' || $setting == 'body_choice' || $setting == 'body_pure') {
                        $go = '';
                    } elseif ($setting == 'frame') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET frame = {string:val}
							WHERE id = {int:blockid}', array('val' => $value, 'blockid' => $where));
                    } else {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_blocks 
							SET ' . $setting . ' = {raw:val}
							WHERE id = {int:blockid}', array('val' => $value, 'blockid' => $where));
                    }
                } elseif (substr($what, 0, 8) == 'tp_group') {
                    $tpgroups[] = substr($what, 8);
                } elseif (substr($what, 0, 12) == 'tp_editgroup') {
                    $editgroups[] = substr($what, 12);
                } elseif (substr($what, 0, 10) == 'actiontype') {
                    $access[] = 'actio=' . $value;
                } elseif (substr($what, 0, 9) == 'boardtype') {
                    $access[] = 'board=' . $value;
                } elseif (substr($what, 0, 11) == 'articletype') {
                    $access[] = 'tpage=' . $value;
                } elseif (substr($what, 0, 12) == 'categorytype') {
                    $access[] = 'tpcat=' . $value;
                } elseif (substr($what, 0, 8) == 'langtype') {
                    $access[] = 'tlang=' . $value;
                } elseif (substr($what, 0, 9) == 'dlcattype') {
                    $access[] = 'dlcat=' . $value;
                } elseif (substr($what, 0, 9) == 'tpmodtype') {
                    $access[] = 'tpmod=' . $value;
                } elseif (substr($what, 0, 9) == 'custotype' && !empty($value)) {
                    $items = explode(',', $value);
                    foreach ($items as $iti => $it) {
                        $access[] = 'actio=' . $it;
                    }
                } elseif (substr($what, 0, 8) == 'tp_lang_') {
                    if (substr($what, 8) != '') {
                        $lang[] = substr($what, 8) . '|' . $value;
                    }
                } elseif (substr($what, 0, 18) == 'tp_userbox_options') {
                    if (!isset($userbox)) {
                        $userbox = array();
                    }
                    $userbox[] = $value;
                } elseif (substr($what, 0, 8) == 'tp_theme') {
                    $theme = substr($what, 8);
                    if (!isset($themebox)) {
                        $themebox = array();
                    }
                    // get the path too
                    if (isset($_POST['tp_path' . $theme])) {
                        $tpath = $_POST['tp_path' . $theme];
                    } else {
                        $tpath = '';
                    }
                    $themebox[] = $theme . '|' . $value . '|' . $tpath;
                }
            }
            // construct the access++
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_blocks 
				SET	access2 = {string:acc2},
					access = {string:acc},
					lang = {string:lang},
					editgroups = {string:editgrp}
				WHERE id = {int:blockid}', array('acc2' => implode(',', $access), 'acc' => implode(',', $tpgroups), 'lang' => implode('|', $lang), 'editgrp' => implode(',', $editgroups), 'blockid' => $where));
            if (isset($userbox)) {
                $updateArray['userbox_options'] = implode(',', $userbox);
            }
            if (isset($themebox)) {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_blocks 
					SET body = {string:body}
					WHERE id = {int:blockid}', array('body' => implode(',', $themebox), 'blockid' => $where));
            }
            // anything from PHP block?
            if (isset($_POST['blockcode_overwrite'])) {
                // get the blockcode
                $newval = TPparseModfile(file_get_contents($boarddir . '/tp-files/tp-blockcodes/' . $_POST['tp_blockcode'] . '.blockcode'), array('code'));
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_blocks 
					SET body = {string:body}
					WHERE id = {int:blockid}', array('body' => $newval['code'], 'blockid' => $where));
            }
            // check if uploadad picture
            if (isset($_FILES['qup_blockbody']) && file_exists($_FILES['qup_blockbody']['tmp_name'])) {
                $name = TPuploadpicture('qup_blockbody', $context['user']['id'] . 'uid');
                tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
            }
            updateTPSettings($updateArray);
            redirectexit('action=tpadmin;blockedit=' . $where . ';' . $context['session_var'] . '=' . $context['session_id']);
        } elseif (substr($from, 0, 11) == 'editarticle') {
            checkSession('post');
            isAllowedTo('tp_articles');
            $new = false;
            $where = substr($from, 11);
            if (empty($where)) {
                // we need to create one first
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_articles', array('date' => 'int'), array(time()), array('id'));
                $where = $smcFunc['db_insert_id']('{db_prefix}tp_articles', 'id');
                $new = true;
                $from = 'editarticle' . $where;
            }
            // check if uploads are there
            if (file_exists($_FILES['tp_article_illupload']['tmp_name'])) {
                $name = TPuploadpicture('tp_article_illupload', '', '180', 'jpg,gif,png', 'tp-files/tp-articles/illustrations');
                tp_createthumb('tp-files/tp-articles/illustrations/' . $name, 128, 128, 'tp-files/tp-articles/illustrations/s_' . $name);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_articles 
					SET illustration = {string:ill} 
					WHERE id = {int:artid} LIMIT 1', array('ill' => 's_' . $name, 'artid' => $where));
            }
            // check if uploadad picture
            if (isset($_FILES['qup_tp_article_body']) && file_exists($_FILES['qup_tp_article_body']['tmp_name'])) {
                $name = TPuploadpicture('qup_tp_article_body', $context['user']['id'] . 'uid');
                tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
            }
            $options = array();
            foreach ($_POST as $what => $value) {
                if (substr($what, 0, 11) == 'tp_article_' && !empty($where)) {
                    $setting = substr($what, 11);
                    if ($setting == 'authorid') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET author_id = {int:auth} 
							WHERE id = {int:artid} LIMIT 1', array('auth' => $value, 'artid' => $where));
                    } elseif ($setting == 'idtheme') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET id_theme = {int:id_theme} 
							WHERE id = {int:artid} LIMIT 1', array('id_theme' => $value, 'artid' => $where));
                    } elseif ($setting == 'subject') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET subject = {string:subject} 
							WHERE id = {int:artid} LIMIT 1', array('subject' => $value, 'artid' => $where));
                    } elseif ($setting == 'shortname') {
                        $value = htmlspecialchars(str_replace(' ', '-', $value), ENT_QUOTES);
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET shortname = {string:shortname} 
							WHERE id = {int:artid} LIMIT 1', array('shortname' => $value, 'artid' => $where));
                    } elseif ($setting == 'category') {
                        // for the event, get the allowed
                        $request = $smcFunc['db_query']('', '
							SELECT value3 FROM {db_prefix}tp_variables 
							WHERE id = {int:varid} LIMIT 1', array('varid' => $value));
                        if ($smcFunc['db_num_rows']($request) > 0) {
                            $row = $smcFunc['db_fetch_assoc']($request);
                            $allowed = $row['value3'];
                            $smcFunc['db_free_result']($request);
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET category = {int:cat} 
							WHERE id = {int:artid} LIMIT 1', array('cat' => $value, 'artid' => $where));
                    } elseif (in_array($setting, array('body', 'intro'))) {
                        // If we came from WYSIWYG then turn it back into BBC regardless.
                        if (!empty($_REQUEST['tp_article_body_mode']) && isset($_REQUEST['tp_article_body'])) {
                            require_once $sourcedir . '/Subs-Editor.php';
                            $_REQUEST['tp_article_body'] = html_to_bbc($_REQUEST['tp_article_body']);
                            // We need to unhtml it now as it gets done shortly.
                            $_REQUEST['tp_article_body'] = un_htmlspecialchars($_REQUEST['tp_article_body']);
                            // We need this for everything else.
                            if ($setting == 'body') {
                                $value = $_POST['tp_article_body'] = $_REQUEST['tp_article_body'];
                            } elseif ($settings == 'intro') {
                                $value = $_POST['tp_article_intro'] = $_REQUEST['tp_article_intro'];
                            }
                        }
                        // in case of HTML article we need to check it
                        if (isset($_POST['tp_article_body_pure']) && isset($_POST['tp_article_body_choice'])) {
                            if ($_POST['tp_article_body_choice'] == 0) {
                                if ($setting == 'body') {
                                    $value = $_POST['tp_article_body_pure'];
                                } elseif ($setting == 'intro') {
                                    $value = $_POST['tp_article_intro'];
                                }
                            }
                            // save the choice too
                            $request = $smcFunc['db_query']('', '
								SELECT id FROM {db_prefix}tp_variables 
								WHERE subtype2 = {int:sub2}  
								AND type = {string:type} LIMIT 1', array('sub2' => $where, 'type' => 'editorchoice'));
                            if ($smcFunc['db_num_rows']($request) > 0) {
                                $row = $smcFunc['db_fetch_assoc']($request);
                                $smcFunc['db_free_result']($request);
                                $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_variables 
									SET value1 = {string:val1}
									WHERE subtype2 = {int:sub2} 
									AND type = {string:type}', array('val1' => $_POST['tp_article_body_choice'], 'sub2' => $where, 'type' => 'editorchoice'));
                            } else {
                                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'type' => 'string', 'subtype2' => 'int'), array($_POST['tp_article_body_choice'], 'editorchoice', $where), array('id'));
                            }
                        }
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET ' . $setting . ' = {string:val} 
							WHERE id = {int:artid} LIMIT 1', array('val' => $value, 'artid' => $where));
                    } elseif (in_array($setting, array('day', 'month', 'year', 'minute', 'hour', 'timestamp'))) {
                        $timestamp = mktime($_POST['tp_article_hour'], $_POST['tp_article_minute'], 0, $_POST['tp_article_month'], $_POST['tp_article_day'], $_POST['tp_article_year']);
                        if (!isset($savedtime)) {
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}tp_articles 
								SET date = {int:date} 
								WHERE id = {int:artid} LIMIT 1', array('date' => $timestamp, 'artid' => $where));
                        }
                        $savedtime = 1;
                    } elseif (in_array($setting, array('pubstartday', 'pubstartmonth', 'pubstartyear', 'pubstartminute', 'pubstarthour', 'pub_start'))) {
                        // are all zero? then skip
                        if (empty($_POST['tp_article_pubstarthour']) && empty($_POST['tp_article_pubstartminute']) && empty($_POST['tp_article_pubstartmonth']) && empty($_POST['tp_article_pubstartday']) && empty($_POST['tp_article_pubstartyear'])) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_start = {int:start}
									WHERE id = {int:artid} LIMIT 1', array('start' => 0, 'artid' => $where));
                        } else {
                            $timestamp = mktime($_POST['tp_article_pubstarthour'], $_POST['tp_article_pubstartminute'], 0, $_POST['tp_article_pubstartmonth'], $_POST['tp_article_pubstartday'], $_POST['tp_article_pubstartyear']);
                        }
                        if (!isset($pubstart)) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_start = {int:start} 
									WHERE id = {int:artid} LIMIT 1', array('start' => $timestamp, 'artid' => $where));
                        }
                        $pubstart = 1;
                    } elseif (in_array($setting, array('pubendday', 'pubendmonth', 'pubendyear', 'pubendminute', 'pubendhour', 'pub_start'))) {
                        // are all zero? then skip
                        if (empty($_POST['tp_article_pubendhour']) && empty($_POST['tp_article_pubendminute']) && empty($_POST['tp_article_pubendmonth']) && empty($_POST['tp_article_pubendday']) && empty($_POST['tp_article_pubendyear'])) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_end = {int:end}
									WHERE id = {int:artid} LIMIT 1', array('end' => 0, 'artid' => $where));
                        } else {
                            $timestamp = mktime($_POST['tp_article_pubendhour'], $_POST['tp_article_pubendminute'], 0, $_POST['tp_article_pubendmonth'], $_POST['tp_article_pubendday'], $_POST['tp_article_pubendyear']);
                        }
                        if (!isset($pubend)) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_articles 
									SET pub_end = {int:end}
									WHERE id = {int:artid} LIMIT 1', array('end' => $timestamp, 'artid' => $where));
                        }
                        $pubend = 1;
                    } elseif (substr($setting, 0, 8) == 'options_') {
                        if (substr($setting, 0, 19) == 'options_lblockwidth' || substr($setting, 0, 19) == 'options_rblockwidth') {
                            $options[] = substr($setting, 8) . $value;
                        } else {
                            $options[] = substr($setting, 8);
                        }
                    } elseif (in_array($setting, array('body_mode', 'intro_mode', 'illupload', 'body_pure', 'body_choice'))) {
                        // ignore it
                        continue;
                    } elseif ($setting == 'approved') {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET approved = {int:approved} 
							WHERE id = {int:artid} LIMIT 1', array('approved' => $value, 'artid' => $where));
                        if ($value == 1) {
                            $smcFunc['db_query']('', '
								DELETE FROM {db_prefix}tp_variables 
								WHERE type = {string:type} 
								AND value5 = {int:val5}', array('type' => 'art_not_approved', 'val5' => $where));
                        } elseif ($new) {
                            $smcFunc['db_insert']('replace', '{db_prefix}tp_variables', array('type' => 'string', 'value5' => 'int'), array('art_not_approved', $where), array('id'));
                        }
                    } else {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}tp_articles 
							SET ' . $setting . ' = {string:val}
							WHERE id = {int:artid} LIMIT 1', array('val' => $value, 'artid' => $where));
                    }
                }
            }
            // if this was a new article
            if ($_POST['tp_article_approved'] == 1 && $_POST['tp_article_off'] == 0) {
                tp_recordevent($timestamp, $_POST['tp_article_authorid'], 'tp-createdarticle', 'page=' . $where, 'Creation of new article.', isset($allowed) ? $allowed : 0, $where);
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET options = {string:opt} 
				WHERE id = {int:artid} LIMIT 1', array('opt' => implode(',', $options), 'artid' => $where));
        }
    } else {
        return;
    }
}
Example #17
0
function EditSmileys()
{
    global $modSettings, $context, $settings, $txt, $boarddir;
    global $smcFunc, $scripturl, $sourcedir;
    // Force the correct tab to be displayed.
    $context[$context['admin_menu_name']]['current_subsection'] = 'editsmileys';
    // Submitting a form?
    if (isset($_POST[$context['session_var']])) {
        checkSession();
        // Changing the selected smileys?
        if (isset($_POST['smiley_action']) && !empty($_POST['checked_smileys'])) {
            foreach ($_POST['checked_smileys'] as $id => $smiley_id) {
                $_POST['checked_smileys'][$id] = (int) $smiley_id;
            }
            if ($_POST['smiley_action'] == 'delete') {
                $smcFunc['db_query']('', '
					DELETE FROM {db_prefix}smileys
					WHERE id_smiley IN ({array_int:checked_smileys})', array('checked_smileys' => $_POST['checked_smileys']));
            } else {
                // Check it's a valid type.
                $displayTypes = array('post' => 0, 'hidden' => 1, 'popup' => 2);
                if (isset($displayTypes[$_POST['smiley_action']])) {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}smileys
						SET hidden = {int:display_type}
						WHERE id_smiley IN ({array_int:checked_smileys})', array('checked_smileys' => $_POST['checked_smileys'], 'display_type' => $displayTypes[$_POST['smiley_action']]));
                }
            }
        } elseif (isset($_POST['smiley'])) {
            // Is it a delete?
            if (!empty($_POST['deletesmiley'])) {
                $smcFunc['db_query']('', '
					DELETE FROM {db_prefix}smileys
					WHERE id_smiley = {int:current_smiley}', array('current_smiley' => $_POST['smiley']));
            } else {
                $_POST['smiley'] = (int) $_POST['smiley'];
                $_POST['smiley_code'] = htmltrim__recursive($_POST['smiley_code']);
                $_POST['smiley_filename'] = htmltrim__recursive($_POST['smiley_filename']);
                $_POST['smiley_location'] = empty($_POST['smiley_location']) || $_POST['smiley_location'] > 2 || $_POST['smiley_location'] < 0 ? 0 : (int) $_POST['smiley_location'];
                // Make sure some code was entered.
                if (empty($_POST['smiley_code'])) {
                    fatal_lang_error('smiley_has_no_code');
                }
                // Also make sure a filename was given.
                if (empty($_POST['smiley_filename'])) {
                    fatal_lang_error('smiley_has_no_filename');
                }
                // Check whether the new code has duplicates. It should be unique.
                $request = $smcFunc['db_query']('', '
					SELECT id_smiley
					FROM {db_prefix}smileys
					WHERE code = {raw:mysql_binary_type} {string:smiley_code}' . (empty($_POST['smiley']) ? '' : '
						AND id_smiley != {int:current_smiley}'), array('current_smiley' => $_POST['smiley'], 'mysql_binary_type' => $smcFunc['db_title'] == 'MySQL' ? 'BINARY' : '', 'smiley_code' => $_POST['smiley_code']));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    fatal_lang_error('smiley_not_unique');
                }
                $smcFunc['db_free_result']($request);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}smileys
					SET
						code = {string:smiley_code},
						filename = {string:smiley_filename},
						description = {string:smiley_description},
						hidden = {int:smiley_location}
					WHERE id_smiley = {int:current_smiley}', array('smiley_location' => $_POST['smiley_location'], 'current_smiley' => $_POST['smiley'], 'smiley_code' => $_POST['smiley_code'], 'smiley_filename' => $_POST['smiley_filename'], 'smiley_description' => $_POST['smiley_description']));
            }
            // Sort all smiley codes for more accurate parsing (longest code first).
            sortSmileyTable();
        }
        cache_put_data('parsing_smileys', null, 480);
        cache_put_data('posting_smileys', null, 480);
    }
    // Load all known smiley sets.
    $context['smiley_sets'] = explode(',', $modSettings['smiley_sets_known']);
    $set_names = explode("\n", $modSettings['smiley_sets_names']);
    foreach ($context['smiley_sets'] as $i => $set) {
        $context['smiley_sets'][$i] = array('id' => $i, 'path' => htmlspecialchars($set), 'name' => htmlspecialchars($set_names[$i]), 'selected' => $set == $modSettings['smiley_sets_default']);
    }
    // Prepare overview of all (custom) smileys.
    if ($context['sub_action'] == 'editsmileys') {
        // Determine the language specific sort order of smiley locations.
        $smiley_locations = array($txt['smileys_location_form'], $txt['smileys_location_hidden'], $txt['smileys_location_popup']);
        asort($smiley_locations);
        // Create a list of options for selecting smiley sets.
        $smileyset_option_list = '
			<select name="set" onchange="changeSet(this.options[this.selectedIndex].value);">';
        foreach ($context['smiley_sets'] as $smiley_set) {
            $smileyset_option_list .= '
				<option value="' . $smiley_set['path'] . '"' . ($modSettings['smiley_sets_default'] == $smiley_set['path'] ? ' selected="selected"' : '') . '>' . $smiley_set['name'] . '</option>';
        }
        $smileyset_option_list .= '
			</select>';
        $listOptions = array('id' => 'smiley_list', 'items_per_page' => 40, 'base_href' => $scripturl . '?action=admin;area=smileys;sa=editsmileys', 'default_sort_col' => 'filename', 'get_items' => array('function' => 'list_getSmileys'), 'get_count' => array('function' => 'list_getNumSmileys'), 'no_items_label' => $txt['smileys_no_entries'], 'columns' => array('picture' => array('data' => array('sprintf' => array('format' => '<a href="' . $scripturl . '?action=admin;area=smileys;sa=modifysmiley;smiley=%1$d"><img src="' . $modSettings['smileys_url'] . '/' . $modSettings['smiley_sets_default'] . '/%2$s" alt="%3$s" style="padding: 2px;" id="smiley%1$d" /><input type="hidden" name="smileys[%1$d][filename]" value="%2$s" /></a>', 'params' => array('id_smiley' => false, 'filename' => true, 'description' => true)), 'style' => 'text-align: center;')), 'code' => array('header' => array('value' => $txt['smileys_code']), 'data' => array('db_htmlsafe' => 'code'), 'sort' => array('default' => 'code', 'reverse' => 'code DESC')), 'filename' => array('header' => array('value' => $txt['smileys_filename']), 'data' => array('db_htmlsafe' => 'filename', 'class' => 'windowbg'), 'sort' => array('default' => 'filename', 'reverse' => 'filename DESC')), 'location' => array('header' => array('value' => $txt['smileys_location']), 'data' => array('function' => create_function('$rowData', '
							global $txt;

							if (empty($rowData[\'hidden\']))
								return $txt[\'smileys_location_form\'];
							elseif ($rowData[\'hidden\'] == 1)
								return $txt[\'smileys_location_hidden\'];
							else
								return $txt[\'smileys_location_popup\'];
						'), 'class' => 'windowbg'), 'sort' => array('default' => 'FIND_IN_SET(hidden, \'' . implode(',', array_keys($smiley_locations)) . '\')', 'reverse' => 'FIND_IN_SET(hidden, \'' . implode(',', array_keys($smiley_locations)) . '\') DESC')), 'tooltip' => array('header' => array('value' => $txt['smileys_description']), 'data' => array('function' => create_function('$rowData', empty($modSettings['smileys_dir']) || !is_dir($modSettings['smileys_dir']) ? '
							return htmlspecialchars($rowData[\'description\']);
						' : '
							global $context, $txt, $modSettings;

							// Check if there are smileys missing in some sets.
							$missing_sets = array();
							foreach ($context[\'smiley_sets\'] as $smiley_set)
								if (!file_exists(sprintf(\'%1$s/%2$s/%3$s\', $modSettings[\'smileys_dir\'], $smiley_set[\'path\'], $rowData[\'filename\'])))
									$missing_sets[] = $smiley_set[\'path\'];

							$description = htmlspecialchars($rowData[\'description\']);

							if (!empty($missing_sets))
								$description .= sprintf(\'<br /><span class="smalltext"><strong>%1$s:</strong> %2$s</span>\', $txt[\'smileys_not_found_in_set\'], implode(\', \', $missing_sets));

							return $description;
						'), 'class' => 'windowbg'), 'sort' => array('default' => 'description', 'reverse' => 'description DESC')), 'modify' => array('header' => array('value' => $txt['smileys_modify']), 'data' => array('sprintf' => array('format' => '<a href="' . $scripturl . '?action=admin;area=smileys;sa=modifysmiley;smiley=%1$d">' . $txt['smileys_modify'] . '</a>', 'params' => array('id_smiley' => false)), 'style' => 'text-align: center;')), 'check' => array('header' => array('value' => '<input type="checkbox" onclick="invertAll(this, this.form);" class="input_check" />'), 'data' => array('sprintf' => array('format' => '<input type="checkbox" name="checked_smileys[]" value="%1$d" class="input_check" />', 'params' => array('id_smiley' => false)), 'style' => 'text-align: center'))), 'form' => array('href' => $scripturl . '?action=admin;area=smileys;sa=editsmileys', 'name' => 'smileyForm'), 'additional_rows' => array(array('position' => 'above_column_headers', 'value' => $smileyset_option_list, 'style' => 'text-align: right;'), array('position' => 'below_table_data', 'value' => '
						<select name="smiley_action" onchange="makeChanges(this.value);">
							<option value="-1">' . $txt['smileys_with_selected'] . ':</option>
							<option value="-1">--------------</option>
							<option value="hidden">' . $txt['smileys_make_hidden'] . '</option>
							<option value="post">' . $txt['smileys_show_on_post'] . '</option>
							<option value="popup">' . $txt['smileys_show_on_popup'] . '</option>
							<option value="delete">' . $txt['smileys_remove'] . '</option>
						</select>
						<noscript><input type="submit" name="perform_action" value="' . $txt['go'] . '" class="button_submit" /></noscript>', 'style' => 'text-align: right;')), 'javascript' => '
				function makeChanges(action)
				{
					if (action == \'-1\')
						return false;
					else if (action == \'delete\')
					{
						if (confirm(\'' . $txt['smileys_confirm'] . '\'))
							document.forms.smileyForm.submit();
					}
					else
						document.forms.smileyForm.submit();
					return true;
				}
				function changeSet(newSet)
				{
					var currentImage, i, knownSmileys = [];

					if (knownSmileys.length == 0)
					{
						for (var i = 0, n = document.images.length; i < n; i++)
							if (document.images[i].id.substr(0, 6) == \'smiley\')
								knownSmileys[knownSmileys.length] = document.images[i].id.substr(6);
					}

					for (i = 0; i < knownSmileys.length; i++)
					{
						currentImage = document.getElementById("smiley" + knownSmileys[i]);
						currentImage.src = "' . $modSettings['smileys_url'] . '/" + newSet + "/" + document.forms.smileyForm["smileys[" + knownSmileys[i] + "][filename]"].value;
					}
				}');
        require_once $sourcedir . '/Subs-List.php';
        createList($listOptions);
        // The list is the only thing to show, so make it the main template.
        $context['default_list'] = 'smiley_list';
        $context['sub_template'] = 'show_list';
    } elseif ($context['sub_action'] == 'modifysmiley') {
        // Get a list of all known smiley sets.
        $context['smileys_dir'] = empty($modSettings['smileys_dir']) ? $boarddir . '/Smileys' : $modSettings['smileys_dir'];
        $context['smileys_dir_found'] = is_dir($context['smileys_dir']);
        $context['smiley_sets'] = explode(',', $modSettings['smiley_sets_known']);
        $set_names = explode("\n", $modSettings['smiley_sets_names']);
        foreach ($context['smiley_sets'] as $i => $set) {
            $context['smiley_sets'][$i] = array('id' => $i, 'path' => htmlspecialchars($set), 'name' => htmlspecialchars($set_names[$i]), 'selected' => $set == $modSettings['smiley_sets_default']);
        }
        $context['selected_set'] = $modSettings['smiley_sets_default'];
        // Get all possible filenames for the smileys.
        $context['filenames'] = array();
        if ($context['smileys_dir_found']) {
            foreach ($context['smiley_sets'] as $smiley_set) {
                if (!file_exists($context['smileys_dir'] . '/' . un_htmlspecialchars($smiley_set['path']))) {
                    continue;
                }
                $dir = dir($context['smileys_dir'] . '/' . un_htmlspecialchars($smiley_set['path']));
                while ($entry = $dir->read()) {
                    if (!in_array($entry, $context['filenames']) && in_array(strrchr($entry, '.'), array('.jpg', '.gif', '.jpeg', '.png'))) {
                        $context['filenames'][strtolower($entry)] = array('id' => htmlspecialchars($entry), 'selected' => false);
                    }
                }
                $dir->close();
            }
            ksort($context['filenames']);
        }
        $request = $smcFunc['db_query']('', '
			SELECT id_smiley AS id, code, filename, description, hidden AS location, 0 AS is_new
			FROM {db_prefix}smileys
			WHERE id_smiley = {int:current_smiley}', array('current_smiley' => (int) $_REQUEST['smiley']));
        if ($smcFunc['db_num_rows']($request) != 1) {
            fatal_lang_error('smiley_not_found');
        }
        $context['current_smiley'] = $smcFunc['db_fetch_assoc']($request);
        $smcFunc['db_free_result']($request);
        $context['current_smiley']['code'] = htmlspecialchars($context['current_smiley']['code']);
        $context['current_smiley']['filename'] = htmlspecialchars($context['current_smiley']['filename']);
        $context['current_smiley']['description'] = htmlspecialchars($context['current_smiley']['description']);
        if (isset($context['filenames'][strtolower($context['current_smiley']['filename'])])) {
            $context['filenames'][strtolower($context['current_smiley']['filename'])]['selected'] = true;
        }
    }
}
Example #18
0
/**
 * Updates BBC img tags in a message so that the width / height respect the forum settings.
 *
 * - Will add the width/height attrib if needed, or update existing ones if they break the rules
 *
 * @package Posts
 * @param string $message
 */
function resizeBBCImages(&$message)
{
    global $modSettings;
    // We'll need this for image processing
    require_once SUBSDIR . '/Attachments.subs.php';
    // Find all the img tags - with or without width and height.
    preg_match_all('~\\[img(\\s+width=\\d+)?(\\s+height=\\d+)?(\\s+width=\\d+)?\\](.+?)\\[/img\\]~is', $message, $matches, PREG_PATTERN_ORDER);
    $replaces = array();
    foreach ($matches[0] as $match => $dummy) {
        // If the width was after the height, handle it.
        $matches[1][$match] = !empty($matches[3][$match]) ? $matches[3][$match] : $matches[1][$match];
        // Now figure out if they had a desired height or width...
        $desired_width = !empty($matches[1][$match]) ? (int) substr(trim($matches[1][$match]), 6) : 0;
        $desired_height = !empty($matches[2][$match]) ? (int) substr(trim($matches[2][$match]), 7) : 0;
        // One was omitted, or both.  We'll have to find its real size...
        if (empty($desired_width) || empty($desired_height)) {
            list($width, $height) = url_image_size(un_htmlspecialchars($matches[4][$match]));
            // They don't have any desired width or height!
            if (empty($desired_width) && empty($desired_height)) {
                $desired_width = $width;
                $desired_height = $height;
            } elseif (empty($desired_width) && !empty($height)) {
                $desired_width = (int) ($desired_height * $width / $height);
            } elseif (!empty($width)) {
                $desired_height = (int) ($desired_width * $height / $width);
            }
        }
        // If the width and height are fine, just continue along...
        if ($desired_width <= $modSettings['max_image_width'] && $desired_height <= $modSettings['max_image_height']) {
            continue;
        }
        // Too bad, it's too wide.  Make it as wide as the maximum.
        if ($desired_width > $modSettings['max_image_width'] && !empty($modSettings['max_image_width'])) {
            $desired_height = (int) ($modSettings['max_image_width'] * $desired_height / $desired_width);
            $desired_width = $modSettings['max_image_width'];
        }
        // Now check the height, as well.  Might have to scale twice, even...
        if ($desired_height > $modSettings['max_image_height'] && !empty($modSettings['max_image_height'])) {
            $desired_width = (int) ($modSettings['max_image_height'] * $desired_width / $desired_height);
            $desired_height = $modSettings['max_image_height'];
        }
        $replaces[$matches[0][$match]] = '[img' . (!empty($desired_width) ? ' width=' . $desired_width : '') . (!empty($desired_height) ? ' height=' . $desired_height : '') . ']' . $matches[4][$match] . '[/img]';
    }
    // If any img tags were actually changed...
    if (!empty($replaces)) {
        $message = strtr($message, $replaces);
    }
}
function cleanLangString($string, $to_display = true)
{
    global $smcFunc;
    // If going to display we make sure it doesn't have any HTML in it - etc.
    $new_string = '';
    if ($to_display) {
        // Are we in a string (0 = no, 1 = single quote, 2 = parsed)
        $in_string = 0;
        $is_escape = false;
        for ($i = 0; $i < strlen($string); $i++) {
            // Handle ecapes first.
            if ($string[$i] == '\\') {
                // Toggle the escape.
                $is_escape = !$is_escape;
                // If we're now escaped don't add this string.
                if ($is_escape) {
                    continue;
                }
            } elseif (($string[$i] == 'n' || $string[$i] == 't') && $in_string == 2 && $is_escape) {
                // Put the escape back...
                $new_string .= $string[$i] == 'n' ? "\n" : "\t";
                $is_escape = false;
                continue;
            } elseif ($string[$i] == '\'') {
                // Already in a parsed string, or escaped in a linear string, means we print it - otherwise something special.
                if ($in_string != 2 && ($in_string != 1 || !$is_escape)) {
                    // Is it the end of a single quote string?
                    if ($in_string == 1) {
                        $in_string = 0;
                    } else {
                        $in_string = 1;
                    }
                    // Don't actually include this character!
                    continue;
                }
            } elseif ($string[$i] == '"') {
                // Already in a single quote string, or escaped in a parsed string, means we print it - otherwise something special.
                if ($in_string != 1 && ($in_string != 2 || !$is_escape)) {
                    // Is it the end of a double quote string?
                    if ($in_string == 2) {
                        $in_string = 0;
                    } else {
                        $in_string = 2;
                    }
                    // Don't actually include this character!
                    continue;
                }
            } elseif ($in_string == 0 && (empty($string[$i]) || $string[$i] == '.')) {
                continue;
            } elseif ($in_string == 0 && $string[$i] == '$') {
                // Find the whole of it!
                preg_match('~([\\$A-Za-z0-9\'\\[\\]_-]+)~', substr($string, $i), $matches);
                if (!empty($matches[1])) {
                    // Come up with some pseudo thing to indicate this is a var.
                    //!!! Do better than this, please!
                    $new_string .= '{%' . $matches[1] . '%}';
                    // We're not going to reparse this.
                    $i += strlen($matches[1]) - 1;
                }
                continue;
            } elseif ($in_string == 0) {
                continue;
            }
            // Actually add the character to the string!
            $new_string .= $string[$i];
            // If anything was escaped it ain't any longer!
            $is_escape = false;
        }
        // Unhtml then rehtml the whole thing!
        $new_string = htmlspecialchars(un_htmlspecialchars($new_string));
    } else {
        // Keep track of what we're doing...
        $in_string = 0;
        // This is for deciding whether to HTML a quote.
        $in_html = false;
        for ($i = 0; $i < strlen($string); $i++) {
            // Handle line breaks!
            if ($string[$i] == "\n" || $string[$i] == "\t") {
                // Are we in a string? Is it the right type?
                if ($in_string == 1) {
                    // Change type!
                    $new_string .= '\' . "\\' . ($string[$i] == "\n" ? 'n' : 't');
                    $in_string = 2;
                } elseif ($in_string == 2) {
                    $new_string .= '\\' . ($string[$i] == "\n" ? 'n' : 't');
                } else {
                    $new_string .= ($new_string ? ' . ' : '') . '"\\' . ($string[$i] == "\n" ? 'n' : 't');
                }
                continue;
            } elseif ($in_string == 2) {
                $in_string = 0;
                $new_string .= '"';
            }
            // Not in a string yet?
            if ($in_string != 1) {
                $in_string = 1;
                $new_string .= ($new_string ? ' . ' : '') . '\'';
            }
            // Is this a variable?
            if ($string[$i] == '{' && $string[$i + 1] == '%' && $string[$i + 2] == '$') {
                // Grab the variable.
                preg_match('~\\{%([\\$A-Za-z0-9\'\\[\\]_-]+)%\\}~', substr($string, $i), $matches);
                if (!empty($matches[1])) {
                    if ($in_string == 1) {
                        $new_string .= '\' . ';
                    } elseif ($new_string) {
                        $new_string .= ' . ';
                    }
                    $new_string .= $matches[1];
                    $i += strlen($matches[1]) + 3;
                    $in_string = 0;
                }
                continue;
            } elseif ($string[$i] == '<') {
                // Probably HTML?
                if ($string[$i + 1] != ' ') {
                    $in_html = true;
                } else {
                    $new_string .= '&lt;';
                    continue;
                }
            } elseif ($string[$i] == '>') {
                // Will it be HTML?
                if ($in_html) {
                    $in_html = false;
                } else {
                    $new_string .= '&gt;';
                    continue;
                }
            }
            // Is it a slash? If so escape it...
            if ($string[$i] == '\\') {
                $new_string .= '\\';
            } elseif ($string[$i] == '"') {
                // If we're in HTML we leave it as a quote - otherwise we entity it.
                if (!$in_html) {
                    $new_string .= '&quot;';
                    continue;
                }
            } elseif ($string[$i] == '\'') {
                // Must be in a string so escape it.
                $new_string .= '\\';
            }
            // Finally add the character to the string!
            $new_string .= $string[$i];
        }
        // If we ended as a string then close it off.
        if ($in_string == 1) {
            $new_string .= '\'';
        } elseif ($in_string == 2) {
            $new_string .= '"';
        }
    }
    return $new_string;
}
Example #20
0
/**
 * A special function for handling the hell which is sending approval notifications.
 *
 * @param mixed[] $topicData
 */
function sendApprovalNotifications(&$topicData)
{
    global $scripturl, $language, $user_info, $modSettings;
    $db = database();
    // Clean up the data...
    if (!is_array($topicData) || empty($topicData)) {
        return;
    }
    // Email ahoy
    require_once SUBSDIR . '/Mail.subs.php';
    require_once SUBSDIR . '/Emailpost.subs.php';
    $topics = array();
    $digest_insert = array();
    foreach ($topicData as $topic => $msgs) {
        foreach ($msgs as $msgKey => $msg) {
            // Convert it to markdown for sending, censor is done as well
            pbe_prepare_text($topicData[$topic][$msgKey]['body'], $topicData[$topic][$msgKey]['subject']);
            $topics[] = $msg['id'];
            $digest_insert[] = array($msg['topic'], $msg['id'], 'reply', $user_info['id']);
        }
    }
    // These need to go into the digest too...
    $db->insert('', '{db_prefix}log_digest', array('id_topic' => 'int', 'id_msg' => 'int', 'note_type' => 'string', 'exclude' => 'int'), $digest_insert, array());
    // Find everyone who needs to know about this.
    $members = $db->query('', '
		SELECT
			mem.id_member, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile,
			ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started,
			ln.id_topic
		FROM {db_prefix}log_notify AS ln
			INNER JOIN {db_prefix}members AS mem ON (mem.id_member = ln.id_member)
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = ln.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
		WHERE ln.id_topic IN ({array_int:topic_list})
			AND mem.is_activated = {int:is_activated}
			AND mem.notify_types < {int:notify_types}
			AND mem.notify_regularity < {int:notify_regularity}
		GROUP BY mem.id_member, ln.id_topic, mem.email_address, mem.notify_regularity, mem.notify_types, mem.notify_send_body, mem.lngfile, ln.sent, mem.id_group, mem.additional_groups, b.member_groups, mem.id_post_group, t.id_member_started
		ORDER BY mem.lngfile', array('topic_list' => $topics, 'is_activated' => 1, 'notify_types' => 4, 'notify_regularity' => 2));
    $sent = 0;
    $current_language = $user_info['language'];
    while ($row = $db->fetch_assoc($members)) {
        if ($row['id_group'] != 1) {
            $allowed = explode(',', $row['member_groups']);
            $row['additional_groups'] = explode(',', $row['additional_groups']);
            $row['additional_groups'][] = $row['id_group'];
            $row['additional_groups'][] = $row['id_post_group'];
            if (count(array_intersect($allowed, $row['additional_groups'])) == 0) {
                continue;
            }
        }
        $needed_language = empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile'];
        if (empty($current_language) || $current_language != $needed_language) {
            $current_language = loadLanguage('Post', $needed_language, false);
        }
        $sent_this_time = false;
        $replacements = array('TOPICLINK' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new', 'UNSUBSCRIBELINK' => $scripturl . '?action=notify;topic=' . $row['id_topic'] . '.0');
        // Now loop through all the messages to send.
        foreach ($topicData[$row['id_topic']] as $msg) {
            $replacements += array('TOPICSUBJECT' => $msg['subject'], 'POSTERNAME' => un_htmlspecialchars($msg['name']));
            $message_type = 'notification_reply';
            // Do they want the body of the message sent too?
            if (!empty($row['notify_send_body']) && empty($modSettings['disallow_sendBody'])) {
                $message_type .= '_body';
                $replacements['MESSAGE'] = $msg['body'];
            }
            if (!empty($row['notify_regularity'])) {
                $message_type .= '_once';
            }
            // Send only if once is off or it's on and it hasn't been sent.
            if (empty($row['notify_regularity']) || empty($row['sent']) && !$sent_this_time) {
                $emaildata = loadEmailTemplate($message_type, $replacements, $needed_language);
                sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], null, 'm' . $msg['last_id']);
                $sent++;
            }
            $sent_this_time = true;
        }
    }
    $db->free_result($members);
    if (isset($current_language) && $current_language != $user_info['language']) {
        loadLanguage('Post');
    }
    // Sent!
    if (!empty($sent)) {
        $db->query('', '
			UPDATE {db_prefix}log_notify
			SET sent = {int:is_sent}
			WHERE id_topic IN ({array_int:topic_list})
				AND id_member != {int:current_member}', array('current_member' => $user_info['id'], 'topic_list' => $topics, 'is_sent' => 1));
    }
}
Example #21
0
    }
    echo "</td>\n</tr>\n";
}
show_admin_header();
if ($action == "loadtemplate") {
    $content = implode("", file(ROOT_PATH . TEMPLATE_DIR . "/" . $template_folder . "/" . $template_file_name));
    $action = "modifytemplates";
}
if ($action == "savetemplate") {
    if (isset($HTTP_POST_VARS['content'])) {
        $content = trim($HTTP_POST_VARS['content']);
    } else {
        $content = "";
    }
    if ($template_file_name != "" && $content != "") {
        $content = un_htmlspecialchars($content);
        $content = stripslashes($content);
        $fp = @fopen(ROOT_PATH . TEMPLATE_DIR . "/" . $template_folder . "/" . $template_file_name, "w+");
        if (@fwrite($fp, $content)) {
            $msg = $lang['template_edit_success'];
        } else {
            $msg = sprintf("<span class=\"marktext\">%s</span>", $lang['template_edit_error']);
        }
    }
    $action = "modifytemplates";
}
if ($action == "modifytemplates") {
    if ($msg != "") {
        printf("<p><b>%s</b></p>\n", $msg);
    }
    show_table_header($lang['edit_templates'], 2);
 /**
  * Allows the admin to choose from predefined and custom templates
  *
  * - Uses the selected template to send a bounce notification with
  * details as specified by the template
  * - Accessd by ?action=admin;area=maillist;sa=bounce;item=?'
  * - Redirects to action=admin;area=maillist;sa=bounced
  *
  * @uses bounce_email sub-template
  */
 public function action_bounce_email()
 {
     global $context, $txt, $modSettings, $scripturl, $mbname;
     if (!isset($_REQUEST['bounce'])) {
         checkSession('get');
         validateToken('admin-ml', 'get');
     }
     require_once SUBSDIR . '/Mail.subs.php';
     // We should have been sent an email ID
     if (isset($_REQUEST['item'])) {
         // Needs to be an int!
         $id = (int) $_REQUEST['item'];
         // Load up the email details, no funny biz yall ;)
         $temp_email = list_maillist_unapproved($id);
         if (!empty($temp_email)) {
             // Set the options
             $_POST['item'] = (int) $temp_email[0]['id_email'];
             $fullerrortext = $txt[$temp_email[0]['error_code']];
             // Build the template selection area, first the standard ones
             $bounce = array('bounce', 'inform');
             foreach ($bounce as $k => $type) {
                 $context['bounce_templates'][$k]['body'] = $txt['ml_' . $type . '_body'];
                 $context['bounce_templates'][$k]['subject'] = $txt['ml_' . $type . '_subject'];
                 $context['bounce_templates'][$k]['title'] = $txt['ml_' . $type . '_title'];
             }
             // And now any custom ones available for this moderator
             $context['bounce_templates'] += array_merge($context['bounce_templates'], maillist_templates('bnctpl', $txt['ml_bounce_template_subject_default']));
             // Replace all the variables in the templates
             foreach ($context['bounce_templates'] as $k => $name) {
                 $context['bounce_templates'][$k]['body'] = strtr($name['body'], array('{MEMBER}' => un_htmlspecialchars($temp_email[0]['name']), '{SCRIPTURL}' => $scripturl, '{FORUMNAME}' => $mbname, '{REGARDS}' => replaceBasicActionUrl($txt['regards_team']), '{SUBJECT}' => $temp_email[0]['subject'], '{ERROR}' => $fullerrortext, '{FORUMNAME}' => $mbname, '{FORUMNAMESHORT}' => !empty($modSettings['maillist_sitename']) ? $modSettings['maillist_sitename'] : $mbname, '{EMAILREGARDS}' => !empty($modSettings['maillist_sitename_regards']) ? $modSettings['maillist_sitename_regards'] : ''));
             }
         } else {
             $context['settings_message'] = $txt['badid'];
         }
     } else {
         $context['settings_message'] = $txt['badid'];
     }
     // Check if they are sending the notice
     if (isset($_REQUEST['bounce']) && isset($temp_email)) {
         checkSession('post');
         validateToken('admin-ml');
         // They did check the box, how else could they have posted
         if (isset($_POST['warn_notify'])) {
             // lets make sure we have the items to send it
             $check_emails = explode('=>', $temp_email[0]['from']);
             $to = trim($check_emails[0]);
             $subject = trim($_POST['warn_sub']);
             $body = trim($_POST['warn_body']);
             if (empty($body) || empty($subject)) {
                 $context['settings_message'] = $txt['bad_bounce'];
             } else {
                 // Time for someone to get a we're so sorry message!
                 sendmail($to, $subject, $body, null, null, false, 5);
                 redirectexit('action=admin;area=maillist;bounced');
             }
         }
     }
     // Prepare and show the template
     createToken('admin-ml');
     $context['warning_data'] = array('notify' => '', 'notify_subject' => '', 'notify_body' => '');
     $context['body'] = isset($fullerrortext) ? parse_bbc($fullerrortext) : '';
     $context['item'] = isset($_POST['item']) ? $_POST['item'] : '';
     $context['notice_to'] = $txt['to'] . ' ' . isset($temp_email[0]['from']) ? $temp_email[0]['from'] : '';
     $context['page_title'] = $txt['bounce_title'];
     $context['sub_template'] = 'bounce_email';
 }
Example #23
0
     $image_keywords_arr = explode(',', $image_keywords);
     array_walk($image_keywords_arr, 'trim_value');
     $image_keywords = implode(',', array_unique(array_filter($image_keywords_arr)));
 } else {
     $image_keywords = "";
 }
 $image_active = intval($HTTP_POST_VARS['image_active_' . $i]);
 $image_allow_comments = intval($HTTP_POST_VARS['image_allow_comments_' . $i]);
 $additional_field_sql = "";
 $additional_value_sql = "";
 if (!empty($additional_image_fields)) {
     $table_fields = $site_db->get_table_fields(IMAGES_TABLE);
     foreach ($additional_image_fields as $key => $val) {
         if (isset($HTTP_POST_VARS[$key . '_' . $i]) && isset($table_fields[$key])) {
             $additional_field_sql .= ", {$key}";
             $additional_value_sql .= ", '" . un_htmlspecialchars(trim($HTTP_POST_VARS[$key . '_' . $i])) . "'";
         }
     }
 }
 $file = MEDIA_PATH . ($old_cat_id != 0 ? "/" . $old_cat_id : "") . "/" . $image_media_file;
 $big_dir = MEDIA_PATH . "/" . $old_cat_id . "/" . $big_folder;
 $big_file = "";
 $log[] = str_replace("{file}", str_replace(ROOT_PATH, "", $file), $lang['cni_working']);
 if (file_exists($file)) {
     $image_media_file_backup = $image_media_file;
     if ($cat_id != $old_cat_id) {
         $image_media_file = copy_media($image_media_file, $old_cat_id, $cat_id);
         if ($image_media_file && file_exists(MEDIA_PATH . "/" . $cat_id . "/" . $image_media_file)) {
             $log[] = str_replace("{name}", MEDIA_DIR . "/" . $cat_id, $lang['cni_copy_success']);
         } else {
             $log[] = str_replace("{name}", MEDIA_DIR . "/" . $cat_id, $lang['cni_copy_error']);
Example #24
0
 /**
  * Handles the sending of the forum mailing in batches.
  *
  * What it does:
  * - Called by ?action=admin;area=news;sa=mailingsend
  * - Requires the send_mail permission.
  * - Redirects to itself when more batches need to be sent.
  * - Redirects to ?action=admin after everything has been sent.
  *
  * @uses the ManageNews template and email_members_send sub template.
  * @param bool $clean_only = false; if set, it will only clean the variables, put them in context, then return.
  */
 public function action_mailingsend($clean_only = false)
 {
     global $txt, $context, $scripturl, $modSettings, $user_info;
     // A nice successful screen if you did it
     if (isset($_REQUEST['success'])) {
         $context['sub_template'] = 'email_members_succeeded';
         loadTemplate('ManageNews');
         return;
     }
     // If just previewing we prepare a message and return it for viewing
     if (isset($_POST['preview'])) {
         $context['preview'] = true;
         return $this->action_mailingcompose();
     }
     // How many to send at once? Quantity depends on whether we are queueing or not.
     // @todo Might need an interface? (used in Post.controller.php too with different limits)
     $num_at_once = empty($modSettings['mail_queue']) ? 60 : 1000;
     // If by PM's I suggest we half the above number.
     if (!empty($_POST['send_pm'])) {
         $num_at_once /= 2;
     }
     checkSession();
     // Where are we actually to?
     $context['start'] = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
     $context['email_force'] = !empty($_POST['email_force']) ? 1 : 0;
     $context['send_pm'] = !empty($_POST['send_pm']) ? 1 : 0;
     $context['total_emails'] = !empty($_POST['total_emails']) ? (int) $_POST['total_emails'] : 0;
     $context['max_id_member'] = !empty($_POST['max_id_member']) ? (int) $_POST['max_id_member'] : 0;
     $context['send_html'] = !empty($_POST['send_html']) ? 1 : 0;
     $context['parse_html'] = !empty($_POST['parse_html']) ? 1 : 0;
     // Create our main context.
     $context['recipients'] = array('groups' => array(), 'exclude_groups' => array(), 'members' => array(), 'exclude_members' => array(), 'emails' => array());
     // Have we any excluded members?
     if (!empty($_POST['exclude_members'])) {
         $members = explode(',', $_POST['exclude_members']);
         foreach ($members as $member) {
             if ($member >= $context['start']) {
                 $context['recipients']['exclude_members'][] = (int) $member;
             }
         }
     }
     // What about members we *must* do?
     if (!empty($_POST['members'])) {
         $members = explode(',', $_POST['members']);
         foreach ($members as $member) {
             if ($member >= $context['start']) {
                 $context['recipients']['members'][] = (int) $member;
             }
         }
     }
     // Cleaning groups is simple - although deal with both checkbox and commas.
     if (isset($_POST['groups'])) {
         if (is_array($_POST['groups'])) {
             foreach ($_POST['groups'] as $group => $dummy) {
                 $context['recipients']['groups'][] = (int) $group;
             }
         } elseif (trim($_POST['groups']) != '') {
             $groups = explode(',', $_POST['groups']);
             foreach ($groups as $group) {
                 $context['recipients']['groups'][] = (int) $group;
             }
         }
     }
     // Same for excluded groups
     if (isset($_POST['exclude_groups'])) {
         if (is_array($_POST['exclude_groups'])) {
             foreach ($_POST['exclude_groups'] as $group => $dummy) {
                 $context['recipients']['exclude_groups'][] = (int) $group;
             }
         } elseif (trim($_POST['exclude_groups']) != '') {
             $groups = explode(',', $_POST['exclude_groups']);
             foreach ($groups as $group) {
                 $context['recipients']['exclude_groups'][] = (int) $group;
             }
         }
     }
     // Finally - emails!
     if (!empty($_POST['emails'])) {
         $addressed = array_unique(explode(';', strtr($_POST['emails'], array("\n" => ';', "\r" => ';', ',' => ';'))));
         foreach ($addressed as $curmem) {
             $curmem = trim($curmem);
             if ($curmem != '') {
                 $context['recipients']['emails'][$curmem] = $curmem;
             }
         }
     }
     // If we're only cleaning drop out here.
     if ($clean_only) {
         return;
     }
     // Some functions we will need
     require_once SUBSDIR . '/Mail.subs.php';
     if ($context['send_pm']) {
         require_once SUBSDIR . '/PersonalMessage.subs.php';
     }
     // We are relying too much on writing to superglobals...
     $base_subject = !empty($_POST['subject']) ? $_POST['subject'] : '';
     $base_message = !empty($_POST['message']) ? $_POST['message'] : '';
     // Save the message and its subject in $context
     $context['subject'] = htmlspecialchars($base_subject, ENT_COMPAT, 'UTF-8');
     $context['message'] = htmlspecialchars($base_message, ENT_COMPAT, 'UTF-8');
     // Prepare the message for sending it as HTML
     if (!$context['send_pm'] && !empty($_POST['send_html'])) {
         // Prepare the message for HTML.
         if (!empty($_POST['parse_html'])) {
             $base_message = str_replace(array("\n", '  '), array('<br />' . "\n", '&nbsp; '), $base_message);
         }
         // This is here to prevent spam filters from tagging this as spam.
         if (preg_match('~\\<html~i', $base_message) == 0) {
             if (preg_match('~\\<body~i', $base_message) == 0) {
                 $base_message = '<html><head><title>' . $base_subject . '</title></head>' . "\n" . '<body>' . $base_message . '</body></html>';
             } else {
                 $base_message = '<html>' . $base_message . '</html>';
             }
         }
     }
     if (empty($base_message) || empty($base_subject)) {
         $context['preview'] = true;
         return $this->action_mailingcompose();
     }
     // Use the default time format.
     $user_info['time_format'] = $modSettings['time_format'];
     $variables = array('{$board_url}', '{$current_time}', '{$latest_member.link}', '{$latest_member.id}', '{$latest_member.name}');
     // We might need this in a bit
     $cleanLatestMember = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($modSettings['latestRealName']) : $modSettings['latestRealName'];
     // Replace in all the standard things.
     $base_message = str_replace($variables, array(!empty($_POST['send_html']) ? '<a href="' . $scripturl . '">' . $scripturl . '</a>' : $scripturl, standardTime(forum_time(), false), !empty($_POST['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . '">' . $cleanLatestMember . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $modSettings['latestMember'] . ']' . $cleanLatestMember . '[/url]' : $cleanLatestMember), $modSettings['latestMember'], $cleanLatestMember), $base_message);
     $base_subject = str_replace($variables, array($scripturl, standardTime(forum_time(), false), $modSettings['latestRealName'], $modSettings['latestMember'], $modSettings['latestRealName']), $base_subject);
     $from_member = array('{$member.email}', '{$member.link}', '{$member.id}', '{$member.name}');
     // If we still have emails, do them first!
     $i = 0;
     foreach ($context['recipients']['emails'] as $k => $email) {
         // Done as many as we can?
         if ($i >= $num_at_once) {
             break;
         }
         // Don't sent it twice!
         unset($context['recipients']['emails'][$k]);
         // Dammit - can't PM emails!
         if ($context['send_pm']) {
             continue;
         }
         $to_member = array($email, !empty($_POST['send_html']) ? '<a href="mailto:' . $email . '">' . $email . '</a>' : $email, '??', $email);
         sendmail($email, str_replace($from_member, $to_member, $base_subject), str_replace($from_member, $to_member, $base_message), null, null, !empty($_POST['send_html']), 5);
         // Done another...
         $i++;
     }
     // Got some more to send this batch?
     $last_id_member = 0;
     if ($i < $num_at_once) {
         // Need to build quite a query!
         $sendQuery = '(';
         $sendParams = array();
         if (!empty($context['recipients']['groups'])) {
             // Take the long route...
             $queryBuild = array();
             foreach ($context['recipients']['groups'] as $group) {
                 $sendParams['group_' . $group] = $group;
                 $queryBuild[] = 'mem.id_group = {int:group_' . $group . '}';
                 if (!empty($group)) {
                     $queryBuild[] = 'FIND_IN_SET({int:group_' . $group . '}, mem.additional_groups) != 0';
                     $queryBuild[] = 'mem.id_post_group = {int:group_' . $group . '}';
                 }
             }
             if (!empty($queryBuild)) {
                 $sendQuery .= implode(' OR ', $queryBuild);
             }
         }
         if (!empty($context['recipients']['members'])) {
             $sendQuery .= ($sendQuery == '(' ? '' : ' OR ') . 'mem.id_member IN ({array_int:members})';
             $sendParams['members'] = $context['recipients']['members'];
         }
         $sendQuery .= ')';
         // If we've not got a query then we must be done!
         if ($sendQuery == '()') {
             redirectexit('action=admin');
         }
         // Anything to exclude?
         if (!empty($context['recipients']['exclude_groups']) && in_array(0, $context['recipients']['exclude_groups'])) {
             $sendQuery .= ' AND mem.id_group != {int:regular_group}';
         }
         if (!empty($context['recipients']['exclude_members'])) {
             $sendQuery .= ' AND mem.id_member NOT IN ({array_int:exclude_members})';
             $sendParams['exclude_members'] = $context['recipients']['exclude_members'];
         }
         // Force them to have it?
         if (empty($context['email_force'])) {
             $sendQuery .= ' AND mem.notify_announcements = {int:notify_announcements}';
         }
         require_once SUBSDIR . '/News.subs.php';
         // Get the smelly people - note we respect the id_member range as it gives us a quicker query.
         $recipients = getNewsletterRecipients($sendQuery, $sendParams, $context['start'], $num_at_once, $i);
         foreach ($recipients as $row) {
             $last_id_member = $row['id_member'];
             // What groups are we looking at here?
             if (empty($row['additional_groups'])) {
                 $groups = array($row['id_group'], $row['id_post_group']);
             } else {
                 $groups = array_merge(array($row['id_group'], $row['id_post_group']), explode(',', $row['additional_groups']));
             }
             // Excluded groups?
             if (array_intersect($groups, $context['recipients']['exclude_groups'])) {
                 continue;
             }
             // We might need this
             $cleanMemberName = empty($_POST['send_html']) || $context['send_pm'] ? un_htmlspecialchars($row['real_name']) : $row['real_name'];
             // Replace the member-dependant variables
             $message = str_replace($from_member, array($row['email_address'], !empty($_POST['send_html']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $cleanMemberName . '</a>' : ($context['send_pm'] ? '[url=' . $scripturl . '?action=profile;u=' . $row['id_member'] . ']' . $cleanMemberName . '[/url]' : $cleanMemberName), $row['id_member'], $cleanMemberName), $base_message);
             $subject = str_replace($from_member, array($row['email_address'], $row['real_name'], $row['id_member'], $row['real_name']), $base_subject);
             // Send the actual email - or a PM!
             if (!$context['send_pm']) {
                 sendmail($row['email_address'], $subject, $message, null, null, !empty($_POST['send_html']), 5);
             } else {
                 sendpm(array('to' => array($row['id_member']), 'bcc' => array()), $subject, $message);
             }
         }
     }
     // If used our batch assume we still have a member.
     if ($i >= $num_at_once) {
         $last_id_member = $context['start'];
     } elseif (empty($last_id_member) && $context['start'] + $num_at_once < $context['max_id_member']) {
         $last_id_member = $context['start'] + $num_at_once;
     } elseif (empty($last_id_member) && empty($context['recipients']['emails'])) {
         // Log this into the admin log.
         logAction('newsletter', array(), 'admin');
         redirectexit('action=admin;area=news;sa=mailingsend;success');
     }
     $context['start'] = $last_id_member;
     // Working out progress is a black art of sorts.
     $percentEmails = $context['total_emails'] == 0 ? 0 : count($context['recipients']['emails']) / $context['total_emails'] * ($context['total_emails'] / ($context['total_emails'] + $context['max_id_member']));
     $percentMembers = $context['start'] / $context['max_id_member'] * ($context['max_id_member'] / ($context['total_emails'] + $context['max_id_member']));
     $context['percentage_done'] = round(($percentEmails + $percentMembers) * 100, 2);
     $context['page_title'] = $txt['admin_newsletters'];
     $context['sub_template'] = 'email_members_send';
 }
function Display()
{
    global $scripturl, $txt, $modSettings, $context, $settings;
    global $options, $sourcedir, $user_info, $board_info, $topic, $board;
    global $attachments, $messages_request, $topicinfo, $language, $smcFunc;
    // What are you gonna display if these are empty?!
    if (empty($topic)) {
        fatal_lang_error('no_board', false);
    }
    // Load the proper template and/or sub template.
    if (WIRELESS) {
        $context['sub_template'] = WIRELESS_PROTOCOL . '_display';
    } else {
        loadTemplate('Display');
    }
    // Not only does a prefetch make things slower for the server, but it makes it impossible to know if they read it.
    if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch') {
        ob_end_clean();
        header('HTTP/1.1 403 Prefetch Forbidden');
        die;
    }
    // How much are we sticking on each page?
    $context['messages_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['messages_per_page']) && !WIRELESS ? $options['messages_per_page'] : $modSettings['defaultMaxMessages'];
    // Let's do some work on what to search index.
    if (count($_GET) > 2) {
        foreach ($_GET as $k => $v) {
            if (!in_array($k, array('topic', 'board', 'start', session_name()))) {
                $context['robot_no_index'] = true;
            }
        }
    }
    if (!empty($_REQUEST['start']) && (!is_numeric($_REQUEST['start']) || $_REQUEST['start'] % $context['messages_per_page'] != 0)) {
        $context['robot_no_index'] = true;
    }
    // Find the previous or next topic.  Make a fuss if there are no more.
    if (isset($_REQUEST['prev_next']) && ($_REQUEST['prev_next'] == 'prev' || $_REQUEST['prev_next'] == 'next')) {
        // No use in calculating the next topic if there's only one.
        if ($board_info['num_topics'] > 1) {
            // Just prepare some variables that are used in the query.
            $gt_lt = $_REQUEST['prev_next'] == 'prev' ? '>' : '<';
            $order = $_REQUEST['prev_next'] == 'prev' ? '' : ' DESC';
            $request = $smcFunc['db_query']('', '
				SELECT t2.id_topic
				FROM {db_prefix}topics AS t
					INNER JOIN {db_prefix}topics AS t2 ON (' . (empty($modSettings['enableStickyTopics']) ? '
					t2.id_last_msg ' . $gt_lt . ' t.id_last_msg' : '
					(t2.id_last_msg ' . $gt_lt . ' t.id_last_msg AND t2.is_sticky ' . $gt_lt . '= t.is_sticky) OR t2.is_sticky ' . $gt_lt . ' t.is_sticky') . ')
				WHERE t.id_topic = {int:current_topic}
					AND t2.id_board = {int:current_board}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
					AND (t2.approved = {int:is_approved} OR (t2.id_member_started != {int:id_member_started} AND t2.id_member_started = {int:current_member}))') . '
				ORDER BY' . (empty($modSettings['enableStickyTopics']) ? '' : ' t2.is_sticky' . $order . ',') . ' t2.id_last_msg' . $order . '
				LIMIT 1', array('current_board' => $board, 'current_member' => $user_info['id'], 'current_topic' => $topic, 'is_approved' => 1, 'id_member_started' => 0));
            // No more left.
            if ($smcFunc['db_num_rows']($request) == 0) {
                $smcFunc['db_free_result']($request);
                // Roll over - if we're going prev, get the last - otherwise the first.
                $request = $smcFunc['db_query']('', '
					SELECT id_topic
					FROM {db_prefix}topics
					WHERE id_board = {int:current_board}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : '
						AND (approved = {int:is_approved} OR (id_member_started != {int:id_member_started} AND id_member_started = {int:current_member}))') . '
					ORDER BY' . (empty($modSettings['enableStickyTopics']) ? '' : ' is_sticky' . $order . ',') . ' id_last_msg' . $order . '
					LIMIT 1', array('current_board' => $board, 'current_member' => $user_info['id'], 'is_approved' => 1, 'id_member_started' => 0));
            }
            // Now you can be sure $topic is the id_topic to view.
            list($topic) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
            $context['current_topic'] = $topic;
        }
        // Go to the newest message on this topic.
        $_REQUEST['start'] = 'new';
    }
    // Add 1 to the number of views of this topic.
    if (empty($_SESSION['last_read_topic']) || $_SESSION['last_read_topic'] != $topic) {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}topics
			SET num_views = num_views + 1
			WHERE id_topic = {int:current_topic}', array('current_topic' => $topic));
        $_SESSION['last_read_topic'] = $topic;
    }
    // Get all the important topic info.
    $request = $smcFunc['db_query']('', '
		SELECT
			t.num_replies, t.num_views, t.locked, ms.subject, t.is_sticky, t.id_poll,
			t.id_member_started, t.id_first_msg, t.id_last_msg, t.approved, t.unapproved_posts,
			' . ($user_info['is_guest'] ? 't.id_last_msg + 1' : 'IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1') . ' AS new_from
			' . (!empty($modSettings['recycle_board']) && $modSettings['recycle_board'] == $board ? ', id_previous_board, id_previous_topic' : '') . '
		FROM {db_prefix}topics AS t
			INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)' . ($user_info['is_guest'] ? '' : '
			LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
			LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})') . '
		WHERE t.id_topic = {int:current_topic}
		LIMIT 1', array('current_member' => $user_info['id'], 'current_topic' => $topic, 'current_board' => $board));
    if ($smcFunc['db_num_rows']($request) == 0) {
        fatal_lang_error('not_a_topic', false);
    }
    $topicinfo = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);
    $context['real_num_replies'] = $context['num_replies'] = $topicinfo['num_replies'];
    $context['topic_first_message'] = $topicinfo['id_first_msg'];
    $context['topic_last_message'] = $topicinfo['id_last_msg'];
    // Add up unapproved replies to get real number of replies...
    if ($modSettings['postmod_active'] && allowedTo('approve_posts')) {
        $context['real_num_replies'] += $topicinfo['unapproved_posts'] - ($topicinfo['approved'] ? 0 : 1);
    }
    // If this topic has unapproved posts, we need to work out how many posts the user can see, for page indexing.
    if ($modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !$user_info['is_guest'] && !allowedTo('approve_posts')) {
        $request = $smcFunc['db_query']('', '
			SELECT COUNT(id_member) AS my_unapproved_posts
			FROM {db_prefix}messages
			WHERE id_topic = {int:current_topic}
				AND id_member = {int:current_member}
				AND approved = 0', array('current_topic' => $topic, 'current_member' => $user_info['id']));
        list($myUnapprovedPosts) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        $context['total_visible_posts'] = $context['num_replies'] + $myUnapprovedPosts + ($topicinfo['approved'] ? 1 : 0);
    } else {
        $context['total_visible_posts'] = $context['num_replies'] + $topicinfo['unapproved_posts'] + ($topicinfo['approved'] ? 1 : 0);
    }
    // When was the last time this topic was replied to?  Should we warn them about it?
    $request = $smcFunc['db_query']('', '
		SELECT poster_time
		FROM {db_prefix}messages
		WHERE id_msg = {int:id_last_msg}
		LIMIT 1', array('id_last_msg' => $topicinfo['id_last_msg']));
    list($lastPostTime) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    $context['oldTopicError'] = !empty($modSettings['oldTopicDays']) && $lastPostTime + $modSettings['oldTopicDays'] * 86400 < time() && empty($sticky);
    // The start isn't a number; it's information about what to do, where to go.
    if (!is_numeric($_REQUEST['start'])) {
        // Redirect to the page and post with new messages, originally by Omar Bazavilvazo.
        if ($_REQUEST['start'] == 'new') {
            // Guests automatically go to the last post.
            if ($user_info['is_guest']) {
                $context['start_from'] = $context['total_visible_posts'] - 1;
                $_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : 0;
            } else {
                // Find the earliest unread message in the topic. (the use of topics here is just for both tables.)
                $request = $smcFunc['db_query']('', '
					SELECT IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from
					FROM {db_prefix}topics AS t
						LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = {int:current_topic} AND lt.id_member = {int:current_member})
						LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = {int:current_board} AND lmr.id_member = {int:current_member})
					WHERE t.id_topic = {int:current_topic}
					LIMIT 1', array('current_board' => $board, 'current_member' => $user_info['id'], 'current_topic' => $topic));
                list($new_from) = $smcFunc['db_fetch_row']($request);
                $smcFunc['db_free_result']($request);
                // Fall through to the next if statement.
                $_REQUEST['start'] = 'msg' . $new_from;
            }
        }
        // Start from a certain time index, not a message.
        if (substr($_REQUEST['start'], 0, 4) == 'from') {
            $timestamp = (int) substr($_REQUEST['start'], 4);
            if ($timestamp === 0) {
                $_REQUEST['start'] = 0;
            } else {
                // Find the number of messages posted before said time...
                $request = $smcFunc['db_query']('', '
					SELECT COUNT(*)
					FROM {db_prefix}messages
					WHERE poster_time < {int:timestamp}
						AND id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !allowedTo('approve_posts') ? '
						AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')' : ''), array('current_topic' => $topic, 'current_member' => $user_info['id'], 'is_approved' => 1, 'timestamp' => $timestamp));
                list($context['start_from']) = $smcFunc['db_fetch_row']($request);
                $smcFunc['db_free_result']($request);
                // Handle view_newest_first options, and get the correct start value.
                $_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : $context['total_visible_posts'] - $context['start_from'] - 1;
            }
        } elseif (substr($_REQUEST['start'], 0, 3) == 'msg') {
            $virtual_msg = (int) substr($_REQUEST['start'], 3);
            if (!$topicinfo['unapproved_posts'] && $virtual_msg >= $topicinfo['id_last_msg']) {
                $context['start_from'] = $context['total_visible_posts'] - 1;
            } elseif (!$topicinfo['unapproved_posts'] && $virtual_msg <= $topicinfo['id_first_msg']) {
                $context['start_from'] = 0;
            } else {
                // Find the start value for that message......
                $request = $smcFunc['db_query']('', '
					SELECT COUNT(*)
					FROM {db_prefix}messages
					WHERE id_msg < {int:virtual_msg}
						AND id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && $topicinfo['unapproved_posts'] && !allowedTo('approve_posts') ? '
						AND (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')' : ''), array('current_member' => $user_info['id'], 'current_topic' => $topic, 'virtual_msg' => $virtual_msg, 'is_approved' => 1, 'no_member' => 0));
                list($context['start_from']) = $smcFunc['db_fetch_row']($request);
                $smcFunc['db_free_result']($request);
            }
            // We need to reverse the start as well in this case.
            $_REQUEST['start'] = empty($options['view_newest_first']) ? $context['start_from'] : $context['total_visible_posts'] - $context['start_from'] - 1;
        }
    }
    // Create a previous next string if the selected theme has it as a selected option.
    $context['previous_next'] = $modSettings['enablePreviousNext'] ? '<a href="' . $scripturl . '?topic=' . $topic . '.0;prev_next=prev#new">' . $txt['previous_next_back'] . '</a> <a href="' . $scripturl . '?topic=' . $topic . '.0;prev_next=next#new">' . $txt['previous_next_forward'] . '</a>' : '';
    // Check if spellchecking is both enabled and actually working. (for quick reply.)
    $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
    // Do we need to show the visual verification image?
    $context['require_verification'] = !$user_info['is_mod'] && !$user_info['is_admin'] && !empty($modSettings['posts_require_captcha']) && ($user_info['posts'] < $modSettings['posts_require_captcha'] || $user_info['is_guest'] && $modSettings['posts_require_captcha'] == -1);
    if ($context['require_verification']) {
        require_once $sourcedir . '/Subs-Editor.php';
        $verificationOptions = array('id' => 'post');
        $context['require_verification'] = create_control_verification($verificationOptions);
        $context['visual_verification_id'] = $verificationOptions['id'];
    }
    // Are we showing signatures - or disabled fields?
    $context['signature_enabled'] = substr($modSettings['signature_settings'], 0, 1) == 1;
    $context['disabled_fields'] = isset($modSettings['disabled_profile_fields']) ? array_flip(explode(',', $modSettings['disabled_profile_fields'])) : array();
    // Censor the title...
    censorText($topicinfo['subject']);
    $context['page_title'] = $topicinfo['subject'];
    // Is this already an article?
    $request = $smcFunc['db_query']('', '
		SELECT id_message
		FROM {db_prefix}sp_articles
		WHERE id_message = {int:message}', array('message' => $context['topic_first_message']));
    list($context['topic_is_article']) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    // Is this topic sticky, or can it even be?
    $topicinfo['is_sticky'] = empty($modSettings['enableStickyTopics']) ? '0' : $topicinfo['is_sticky'];
    // Default this topic to not marked for notifications... of course...
    $context['is_marked_notify'] = false;
    // Did we report a post to a moderator just now?
    $context['report_sent'] = isset($_GET['reportsent']);
    // Let's get nosey, who is viewing this topic?
    if (!empty($settings['display_who_viewing'])) {
        // Start out with no one at all viewing it.
        $context['view_members'] = array();
        $context['view_members_list'] = array();
        $context['view_num_hidden'] = 0;
        // Search for members who have this topic set in their GET data.
        $request = $smcFunc['db_query']('', '
			SELECT
				lo.id_member, lo.log_time, mem.real_name, mem.member_name, mem.show_online,
				mg.online_color, mg.id_group, mg.group_name
			FROM {db_prefix}log_online AS lo
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = lo.id_member)
				LEFT JOIN {db_prefix}membergroups AS mg ON (mg.id_group = CASE WHEN mem.id_group = {int:reg_id_group} THEN mem.id_post_group ELSE mem.id_group END)
			WHERE INSTR(lo.url, {string:in_url_string}) > 0 OR lo.session = {string:session}', array('reg_id_group' => 0, 'in_url_string' => 's:5:"topic";i:' . $topic . ';', 'session' => $user_info['is_guest'] ? 'ip' . $user_info['ip'] : session_id()));
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            if (empty($row['id_member'])) {
                continue;
            }
            if (!empty($row['online_color'])) {
                $link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" style="color: ' . $row['online_color'] . ';">' . $row['real_name'] . '</a>';
            } else {
                $link = '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>';
            }
            $is_buddy = in_array($row['id_member'], $user_info['buddies']);
            if ($is_buddy) {
                $link = '<strong>' . $link . '</strong>';
            }
            // Add them both to the list and to the more detailed list.
            if (!empty($row['show_online']) || allowedTo('moderate_forum')) {
                $context['view_members_list'][$row['log_time'] . $row['member_name']] = empty($row['show_online']) ? '<em>' . $link . '</em>' : $link;
            }
            $context['view_members'][$row['log_time'] . $row['member_name']] = array('id' => $row['id_member'], 'username' => $row['member_name'], 'name' => $row['real_name'], 'group' => $row['id_group'], 'href' => $scripturl . '?action=profile;u=' . $row['id_member'], 'link' => $link, 'is_buddy' => $is_buddy, 'hidden' => empty($row['show_online']));
            if (empty($row['show_online'])) {
                $context['view_num_hidden']++;
            }
        }
        // The number of guests is equal to the rows minus the ones we actually used ;).
        $context['view_num_guests'] = $smcFunc['db_num_rows']($request) - count($context['view_members']);
        $smcFunc['db_free_result']($request);
        // Sort the list.
        krsort($context['view_members']);
        krsort($context['view_members_list']);
    }
    // If all is set, but not allowed... just unset it.
    $can_show_all = !empty($modSettings['enableAllMessages']) && $context['total_visible_posts'] > $context['messages_per_page'] && $context['total_visible_posts'] < $modSettings['enableAllMessages'];
    if (isset($_REQUEST['all']) && !$can_show_all) {
        unset($_REQUEST['all']);
    } elseif (isset($_REQUEST['all'])) {
        $_REQUEST['start'] = -1;
    }
    // Construct the page index, allowing for the .START method...
    $context['page_index'] = constructPageIndex($scripturl . '?topic=' . $topic . '.%1$d', $_REQUEST['start'], $context['total_visible_posts'], $context['messages_per_page'], true);
    $context['start'] = $_REQUEST['start'];
    // This is information about which page is current, and which page we're on - in case you don't like the constructed page index. (again, wireles..)
    $context['page_info'] = array('current_page' => $_REQUEST['start'] / $context['messages_per_page'] + 1, 'num_pages' => floor(($context['total_visible_posts'] - 1) / $context['messages_per_page']) + 1);
    // Figure out all the link to the next/prev/first/last/etc. for wireless mainly.
    $context['links'] = array('first' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.0' : '', 'prev' => $_REQUEST['start'] >= $context['messages_per_page'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] - $context['messages_per_page']) : '', 'next' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic . '.' . ($_REQUEST['start'] + $context['messages_per_page']) : '', 'last' => $_REQUEST['start'] + $context['messages_per_page'] < $context['total_visible_posts'] ? $scripturl . '?topic=' . $topic . '.' . floor($context['total_visible_posts'] / $context['messages_per_page']) * $context['messages_per_page'] : '', 'up' => $scripturl . '?board=' . $board . '.0');
    // If they are viewing all the posts, show all the posts, otherwise limit the number.
    if ($can_show_all) {
        if (isset($_REQUEST['all'])) {
            // No limit! (actually, there is a limit, but...)
            $context['messages_per_page'] = -1;
            $context['page_index'] .= empty($modSettings['compactTopicPagesEnable']) ? '<strong>' . $txt['all'] . '</strong> ' : '[<strong>' . $txt['all'] . '</strong>] ';
            // Set start back to 0...
            $_REQUEST['start'] = 0;
        } else {
            $context['page_index'] .= '&nbsp;<a href="' . $scripturl . '?topic=' . $topic . '.0;all">' . $txt['all'] . '</a> ';
        }
    }
    // Build the link tree.
    $context['linktree'][] = array('url' => $scripturl . '?topic=' . $topic . '.0', 'name' => $topicinfo['subject'], 'extra_before' => $settings['linktree_inline'] ? $txt['topic'] . ': ' : '');
    // Build a list of this board's moderators.
    $context['moderators'] =& $board_info['moderators'];
    $context['link_moderators'] = array();
    if (!empty($board_info['moderators'])) {
        // Add a link for each moderator...
        foreach ($board_info['moderators'] as $mod) {
            $context['link_moderators'][] = '<a href="' . $scripturl . '?action=profile;u=' . $mod['id'] . '" title="' . $txt['board_moderator'] . '">' . $mod['name'] . '</a>';
        }
        // And show it after the board's name.
        $context['linktree'][count($context['linktree']) - 2]['extra_after'] = ' (' . (count($context['link_moderators']) == 1 ? $txt['moderator'] : $txt['moderators']) . ': ' . implode(', ', $context['link_moderators']) . ')';
    }
    // Information about the current topic...
    $context['is_locked'] = $topicinfo['locked'];
    $context['is_sticky'] = $topicinfo['is_sticky'];
    $context['is_very_hot'] = $topicinfo['num_replies'] >= $modSettings['hotTopicVeryPosts'];
    $context['is_hot'] = $topicinfo['num_replies'] >= $modSettings['hotTopicPosts'];
    $context['is_approved'] = $topicinfo['approved'];
    // We don't want to show the poll icon in the topic class here, so pretend it's not one.
    $context['is_poll'] = false;
    determineTopicClass($context);
    $context['is_poll'] = $topicinfo['id_poll'] > 0 && $modSettings['pollMode'] == '1' && allowedTo('poll_view');
    // Did this user start the topic or not?
    $context['user']['started'] = $user_info['id'] == $topicinfo['id_member_started'] && !$user_info['is_guest'];
    $context['topic_starter_id'] = $topicinfo['id_member_started'];
    // Set the topic's information for the template.
    $context['subject'] = $topicinfo['subject'];
    $context['num_views'] = $topicinfo['num_views'];
    $context['mark_unread_time'] = $topicinfo['new_from'];
    // Set a canonical URL for this page.
    $context['canonical_url'] = $scripturl . '?topic=' . $topic . '.' . $context['start'];
    // For quick reply we need a response prefix in the default forum language.
    if (!isset($context['response_prefix']) && !($context['response_prefix'] = cache_get_data('response_prefix', 600))) {
        if ($language === $user_info['language']) {
            $context['response_prefix'] = $txt['response_prefix'];
        } else {
            loadLanguage('index', $language, false);
            $context['response_prefix'] = $txt['response_prefix'];
            loadLanguage('index');
        }
        cache_put_data('response_prefix', $context['response_prefix'], 600);
    }
    // If we want to show event information in the topic, prepare the data.
    if (allowedTo('calendar_view') && !empty($modSettings['cal_showInTopic']) && !empty($modSettings['cal_enabled'])) {
        // First, try create a better time format, ignoring the "time" elements.
        if (preg_match('~%[AaBbCcDdeGghjmuYy](?:[^%]*%[AaBbCcDdeGghjmuYy])*~', $user_info['time_format'], $matches) == 0 || empty($matches[0])) {
            $date_string = $user_info['time_format'];
        } else {
            $date_string = $matches[0];
        }
        // Any calendar information for this topic?
        $request = $smcFunc['db_query']('', '
			SELECT cal.id_event, cal.start_date, cal.end_date, cal.title, cal.id_member, mem.real_name
			FROM {db_prefix}calendar AS cal
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = cal.id_member)
			WHERE cal.id_topic = {int:current_topic}
			ORDER BY start_date', array('current_topic' => $topic));
        $context['linked_calendar_events'] = array();
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // Prepare the dates for being formatted.
            $start_date = sscanf($row['start_date'], '%04d-%02d-%02d');
            $start_date = mktime(12, 0, 0, $start_date[1], $start_date[2], $start_date[0]);
            $end_date = sscanf($row['end_date'], '%04d-%02d-%02d');
            $end_date = mktime(12, 0, 0, $end_date[1], $end_date[2], $end_date[0]);
            $context['linked_calendar_events'][] = array('id' => $row['id_event'], 'title' => $row['title'], 'can_edit' => allowedTo('calendar_edit_any') || $row['id_member'] == $user_info['id'] && allowedTo('calendar_edit_own'), 'modify_href' => $scripturl . '?action=post;msg=' . $topicinfo['id_first_msg'] . ';topic=' . $topic . '.0;calendar;eventid=' . $row['id_event'] . ';' . $context['session_var'] . '=' . $context['session_id'], 'start_date' => timeformat($start_date, $date_string, 'none'), 'start_timestamp' => $start_date, 'end_date' => timeformat($end_date, $date_string, 'none'), 'end_timestamp' => $end_date, 'is_last' => false);
        }
        $smcFunc['db_free_result']($request);
        if (!empty($context['linked_calendar_events'])) {
            $context['linked_calendar_events'][count($context['linked_calendar_events']) - 1]['is_last'] = true;
        }
    }
    // Create the poll info if it exists.
    if ($context['is_poll']) {
        // Get the question and if it's locked.
        $request = $smcFunc['db_query']('', '
			SELECT
				p.question, p.voting_locked, p.hide_results, p.expire_time, p.max_votes, p.change_vote,
				p.guest_vote, p.id_member, IFNULL(mem.real_name, p.poster_name) AS poster_name, p.num_guest_voters, p.reset_poll
			FROM {db_prefix}polls AS p
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = p.id_member)
			WHERE p.id_poll = {int:id_poll}
			LIMIT 1', array('id_poll' => $topicinfo['id_poll']));
        $pollinfo = $smcFunc['db_fetch_assoc']($request);
        $smcFunc['db_free_result']($request);
        $request = $smcFunc['db_query']('', '
			SELECT COUNT(DISTINCT id_member) AS total
			FROM {db_prefix}log_polls
			WHERE id_poll = {int:id_poll}
				AND id_member != {int:not_guest}', array('id_poll' => $topicinfo['id_poll'], 'not_guest' => 0));
        list($pollinfo['total']) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        // Total voters needs to include guest voters
        $pollinfo['total'] += $pollinfo['num_guest_voters'];
        // Get all the options, and calculate the total votes.
        $request = $smcFunc['db_query']('', '
			SELECT pc.id_choice, pc.label, pc.votes, IFNULL(lp.id_choice, -1) AS voted_this
			FROM {db_prefix}poll_choices AS pc
				LEFT JOIN {db_prefix}log_polls AS lp ON (lp.id_choice = pc.id_choice AND lp.id_poll = {int:id_poll} AND lp.id_member = {int:current_member} AND lp.id_member != {int:not_guest})
			WHERE pc.id_poll = {int:id_poll}', array('current_member' => $user_info['id'], 'id_poll' => $topicinfo['id_poll'], 'not_guest' => 0));
        $pollOptions = array();
        $realtotal = 0;
        $pollinfo['has_voted'] = false;
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            censorText($row['label']);
            $pollOptions[$row['id_choice']] = $row;
            $realtotal += $row['votes'];
            $pollinfo['has_voted'] |= $row['voted_this'] != -1;
        }
        $smcFunc['db_free_result']($request);
        // If this is a guest we need to do our best to work out if they have voted, and what they voted for.
        if ($user_info['is_guest'] && $pollinfo['guest_vote'] && allowedTo('poll_vote')) {
            if (!empty($_COOKIE['guest_poll_vote']) && preg_match('~^[0-9,;]+$~', $_COOKIE['guest_poll_vote']) && strpos($_COOKIE['guest_poll_vote'], ';' . $topicinfo['id_poll'] . ',') !== false) {
                // ;id,timestamp,[vote,vote...]; etc
                $guestinfo = explode(';', $_COOKIE['guest_poll_vote']);
                // Find the poll we're after.
                foreach ($guestinfo as $i => $guestvoted) {
                    $guestvoted = explode(',', $guestvoted);
                    if ($guestvoted[0] == $topicinfo['id_poll']) {
                        break;
                    }
                }
                // Has the poll been reset since guest voted?
                if ($pollinfo['reset_poll'] > $guestvoted[1]) {
                    // Remove the poll info from the cookie to allow guest to vote again
                    unset($guestinfo[$i]);
                    if (!empty($guestinfo)) {
                        $_COOKIE['guest_poll_vote'] = ';' . implode(';', $guestinfo);
                    } else {
                        unset($_COOKIE['guest_poll_vote']);
                    }
                } else {
                    // What did they vote for?
                    unset($guestvoted[0], $guestvoted[1]);
                    foreach ($pollOptions as $choice => $details) {
                        $pollOptions[$choice]['voted_this'] = in_array($choice, $guestvoted) ? 1 : -1;
                        $pollinfo['has_voted'] |= $pollOptions[$choice]['voted_this'] != -1;
                    }
                    unset($choice, $details, $guestvoted);
                }
                unset($guestinfo, $guestvoted, $i);
            }
        }
        // Set up the basic poll information.
        $context['poll'] = array('id' => $topicinfo['id_poll'], 'image' => 'normal_' . (empty($pollinfo['voting_locked']) ? 'poll' : 'locked_poll'), 'question' => parse_bbc($pollinfo['question']), 'total_votes' => $pollinfo['total'], 'change_vote' => !empty($pollinfo['change_vote']), 'is_locked' => !empty($pollinfo['voting_locked']), 'options' => array(), 'lock' => allowedTo('poll_lock_any') || $context['user']['started'] && allowedTo('poll_lock_own'), 'edit' => allowedTo('poll_edit_any') || $context['user']['started'] && allowedTo('poll_edit_own'), 'allowed_warning' => $pollinfo['max_votes'] > 1 ? sprintf($txt['poll_options6'], min(count($pollOptions), $pollinfo['max_votes'])) : '', 'is_expired' => !empty($pollinfo['expire_time']) && $pollinfo['expire_time'] < time(), 'expire_time' => !empty($pollinfo['expire_time']) ? timeformat($pollinfo['expire_time']) : 0, 'has_voted' => !empty($pollinfo['has_voted']), 'starter' => array('id' => $pollinfo['id_member'], 'name' => $row['poster_name'], 'href' => $pollinfo['id_member'] == 0 ? '' : $scripturl . '?action=profile;u=' . $pollinfo['id_member'], 'link' => $pollinfo['id_member'] == 0 ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $pollinfo['id_member'] . '">' . $row['poster_name'] . '</a>'));
        // Make the lock and edit permissions defined above more directly accessible.
        $context['allow_lock_poll'] = $context['poll']['lock'];
        $context['allow_edit_poll'] = $context['poll']['edit'];
        // You're allowed to vote if:
        // 1. the poll did not expire, and
        // 2. you're either not a guest OR guest voting is enabled... and
        // 3. you're not trying to view the results, and
        // 4. the poll is not locked, and
        // 5. you have the proper permissions, and
        // 6. you haven't already voted before.
        $context['allow_vote'] = !$context['poll']['is_expired'] && (!$user_info['is_guest'] || $pollinfo['guest_vote'] && allowedTo('poll_vote')) && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && !$context['poll']['has_voted'];
        // You're allowed to view the results if:
        // 1. you're just a super-nice-guy, or
        // 2. anyone can see them (hide_results == 0), or
        // 3. you can see them after you voted (hide_results == 1), or
        // 4. you've waited long enough for the poll to expire. (whether hide_results is 1 or 2.)
        $context['allow_poll_view'] = allowedTo('moderate_board') || $pollinfo['hide_results'] == 0 || $pollinfo['hide_results'] == 1 && $context['poll']['has_voted'] || $context['poll']['is_expired'];
        $context['poll']['show_results'] = $context['allow_poll_view'] && (isset($_REQUEST['viewresults']) || isset($_REQUEST['viewResults']));
        $context['show_view_results_button'] = $context['allow_vote'] && (!$context['allow_poll_view'] || !$context['poll']['show_results'] || !$context['poll']['has_voted']);
        // You're allowed to change your vote if:
        // 1. the poll did not expire, and
        // 2. you're not a guest... and
        // 3. the poll is not locked, and
        // 4. you have the proper permissions, and
        // 5. you have already voted, and
        // 6. the poll creator has said you can!
        $context['allow_change_vote'] = !$context['poll']['is_expired'] && !$user_info['is_guest'] && empty($pollinfo['voting_locked']) && allowedTo('poll_vote') && $context['poll']['has_voted'] && $context['poll']['change_vote'];
        // You're allowed to return to voting options if:
        // 1. you are (still) allowed to vote.
        // 2. you are currently seeing the results.
        $context['allow_return_vote'] = $context['allow_vote'] && $context['poll']['show_results'];
        // Calculate the percentages and bar lengths...
        $divisor = $realtotal == 0 ? 1 : $realtotal;
        // Determine if a decimal point is needed in order for the options to add to 100%.
        $precision = $realtotal == 100 ? 0 : 1;
        // Now look through each option, and...
        foreach ($pollOptions as $i => $option) {
            // First calculate the percentage, and then the width of the bar...
            $bar = round($option['votes'] * 100 / $divisor, $precision);
            $barWide = $bar == 0 ? 1 : floor($bar * 8 / 3);
            // Now add it to the poll's contextual theme data.
            $context['poll']['options'][$i] = array('id' => 'options-' . $i, 'percent' => $bar, 'votes' => $option['votes'], 'voted_this' => $option['voted_this'] != -1, 'bar' => '<span style="white-space: nowrap;"><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'right' : 'left') . '.gif" alt="" /><img src="' . $settings['images_url'] . '/poll_middle.gif" width="' . $barWide . '" height="12" alt="-" /><img src="' . $settings['images_url'] . '/poll_' . ($context['right_to_left'] ? 'left' : 'right') . '.gif" alt="" /></span>', 'bar_ndt' => $bar > 0 ? '<div class="bar" style="width: ' . ($bar * 3.5 + 4) . 'px;"><div style="width: ' . $bar * 3.5 . 'px;"></div></div>' : '', 'bar_width' => $barWide, 'option' => parse_bbc($option['label']), 'vote_button' => '<input type="' . ($pollinfo['max_votes'] > 1 ? 'checkbox' : 'radio') . '" name="options[]" id="options-' . $i . '" value="' . $i . '" class="input_' . ($pollinfo['max_votes'] > 1 ? 'check' : 'radio') . '" />');
        }
    }
    // Calculate the fastest way to get the messages!
    $ascending = empty($options['view_newest_first']);
    $start = $_REQUEST['start'];
    $limit = $context['messages_per_page'];
    $firstIndex = 0;
    if ($start >= $context['total_visible_posts'] / 2 && $context['messages_per_page'] != -1) {
        $ascending = !$ascending;
        $limit = $context['total_visible_posts'] <= $start + $limit ? $context['total_visible_posts'] - $start : $limit;
        $start = $context['total_visible_posts'] <= $start + $limit ? 0 : $context['total_visible_posts'] - $start - $limit;
        $firstIndex = $limit - 1;
    }
    // Get each post and poster in this topic.
    $request = $smcFunc['db_query']('display_get_post_poster', '
		SELECT id_msg, id_member, approved
		FROM {db_prefix}messages
		WHERE id_topic = {int:current_topic}' . (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : (!empty($modSettings['db_mysql_group_by_fix']) ? '' : '
		GROUP BY id_msg') . '
		HAVING (approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR id_member = {int:current_member}') . ')') . '
		ORDER BY id_msg ' . ($ascending ? '' : 'DESC') . ($context['messages_per_page'] == -1 ? '' : '
		LIMIT ' . $start . ', ' . $limit), array('current_member' => $user_info['id'], 'current_topic' => $topic, 'is_approved' => 1, 'blank_id_member' => 0));
    $messages = array();
    $all_posters = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        if (!empty($row['id_member'])) {
            $all_posters[$row['id_msg']] = $row['id_member'];
        }
        $messages[] = $row['id_msg'];
    }
    $smcFunc['db_free_result']($request);
    $posters = array_unique($all_posters);
    // Guests can't mark topics read or for notifications, just can't sorry.
    if (!$user_info['is_guest']) {
        $mark_at_msg = max($messages);
        if ($mark_at_msg >= $topicinfo['id_last_msg']) {
            $mark_at_msg = $modSettings['maxMsgID'];
        }
        if ($mark_at_msg >= $topicinfo['new_from']) {
            $smcFunc['db_insert']($topicinfo['new_from'] == 0 ? 'ignore' : 'replace', '{db_prefix}log_topics', array('id_member' => 'int', 'id_topic' => 'int', 'id_msg' => 'int'), array($user_info['id'], $topic, $mark_at_msg), array('id_member', 'id_topic'));
        }
        // Check for notifications on this topic OR board.
        $request = $smcFunc['db_query']('', '
			SELECT sent, id_topic
			FROM {db_prefix}log_notify
			WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
				AND id_member = {int:current_member}
			LIMIT 2', array('current_board' => $board, 'current_member' => $user_info['id'], 'current_topic' => $topic));
        $do_once = true;
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // Find if this topic is marked for notification...
            if (!empty($row['id_topic'])) {
                $context['is_marked_notify'] = true;
            }
            // Only do this once, but mark the notifications as "not sent yet" for next time.
            if (!empty($row['sent']) && $do_once) {
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}log_notify
					SET sent = {int:is_not_sent}
					WHERE (id_topic = {int:current_topic} OR id_board = {int:current_board})
						AND id_member = {int:current_member}', array('current_board' => $board, 'current_member' => $user_info['id'], 'current_topic' => $topic, 'is_not_sent' => 0));
                $do_once = false;
            }
        }
        // Have we recently cached the number of new topics in this board, and it's still a lot?
        if (isset($_REQUEST['topicseen']) && isset($_SESSION['topicseen_cache'][$board]) && $_SESSION['topicseen_cache'][$board] > 5) {
            $_SESSION['topicseen_cache'][$board]--;
        } elseif (isset($_REQUEST['topicseen'])) {
            // Use the mark read tables... and the last visit to figure out if this should be read or not.
            $request = $smcFunc['db_query']('', '
				SELECT COUNT(*)
				FROM {db_prefix}topics AS t
					LEFT JOIN {db_prefix}log_boards AS lb ON (lb.id_board = {int:current_board} AND lb.id_member = {int:current_member})
					LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
				WHERE t.id_board = {int:current_board}
					AND t.id_last_msg > IFNULL(lb.id_msg, 0)
					AND t.id_last_msg > IFNULL(lt.id_msg, 0)' . (empty($_SESSION['id_msg_last_visit']) ? '' : '
					AND t.id_last_msg > {int:id_msg_last_visit}'), array('current_board' => $board, 'current_member' => $user_info['id'], 'id_msg_last_visit' => (int) $_SESSION['id_msg_last_visit']));
            list($numNewTopics) = $smcFunc['db_fetch_row']($request);
            $smcFunc['db_free_result']($request);
            // If there're no real new topics in this board, mark the board as seen.
            if (empty($numNewTopics)) {
                $_REQUEST['boardseen'] = true;
            } else {
                $_SESSION['topicseen_cache'][$board] = $numNewTopics;
            }
        } elseif (isset($_SESSION['topicseen_cache'][$board])) {
            $_SESSION['topicseen_cache'][$board]--;
        }
        // Mark board as seen if we came using last post link from BoardIndex. (or other places...)
        if (isset($_REQUEST['boardseen'])) {
            $smcFunc['db_insert']('replace', '{db_prefix}log_boards', array('id_msg' => 'int', 'id_member' => 'int', 'id_board' => 'int'), array($modSettings['maxMsgID'], $user_info['id'], $board), array('id_member', 'id_board'));
        }
    }
    $attachments = array();
    // If there _are_ messages here... (probably an error otherwise :!)
    if (!empty($messages)) {
        // Fetch attachments.
        if (!empty($modSettings['attachmentEnable']) && allowedTo('view_attachments')) {
            $request = $smcFunc['db_query']('', '
				SELECT
					a.id_attach, a.id_folder, a.id_msg, a.filename, a.file_hash, IFNULL(a.size, 0) AS filesize, a.downloads, a.approved,
					a.width, a.height' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : ',
					IFNULL(thumb.id_attach, 0) AS id_thumb, thumb.width AS thumb_width, thumb.height AS thumb_height') . '
				FROM {db_prefix}attachments AS a' . (empty($modSettings['attachmentShowImages']) || empty($modSettings['attachmentThumbnails']) ? '' : '
					LEFT JOIN {db_prefix}attachments AS thumb ON (thumb.id_attach = a.id_thumb)') . '
				WHERE a.id_msg IN ({array_int:message_list})
					AND a.attachment_type = {int:attachment_type}', array('message_list' => $messages, 'attachment_type' => 0, 'is_approved' => 1));
            $temp = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if (!$row['approved'] && $modSettings['postmod_active'] && !allowedTo('approve_posts') && (!isset($all_posters[$row['id_msg']]) || $all_posters[$row['id_msg']] != $user_info['id'])) {
                    continue;
                }
                $temp[$row['id_attach']] = $row;
                if (!isset($attachments[$row['id_msg']])) {
                    $attachments[$row['id_msg']] = array();
                }
            }
            $smcFunc['db_free_result']($request);
            // This is better than sorting it with the query...
            ksort($temp);
            foreach ($temp as $row) {
                $attachments[$row['id_msg']][] = $row;
            }
        }
        // What?  It's not like it *couldn't* be only guests in this topic...
        if (!empty($posters)) {
            loadMemberData($posters);
        }
        $messages_request = $smcFunc['db_query']('', '
			SELECT
				id_msg, icon, subject, poster_time, poster_ip, id_member, modified_time, modified_name, body,
				smileys_enabled, poster_name, poster_email, approved,
				id_msg_modified < {int:new_from} AS is_read
			FROM {db_prefix}messages
			WHERE id_msg IN ({array_int:message_list})
			ORDER BY id_msg' . (empty($options['view_newest_first']) ? '' : ' DESC'), array('message_list' => $messages, 'new_from' => $topicinfo['new_from']));
        // Go to the last message if the given time is beyond the time of the last message.
        if (isset($context['start_from']) && $context['start_from'] >= $topicinfo['num_replies']) {
            $context['start_from'] = $topicinfo['num_replies'];
        }
        // Since the anchor information is needed on the top of the page we load these variables beforehand.
        $context['first_message'] = isset($messages[$firstIndex]) ? $messages[$firstIndex] : $messages[0];
        if (empty($options['view_newest_first'])) {
            $context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $context['start_from'];
        } else {
            $context['first_new_message'] = isset($context['start_from']) && $_REQUEST['start'] == $topicinfo['num_replies'] - $context['start_from'];
        }
    } else {
        $messages_request = false;
        $context['first_message'] = 0;
        $context['first_new_message'] = false;
    }
    $context['jump_to'] = array('label' => addslashes(un_htmlspecialchars($txt['jump_to'])), 'board_name' => htmlspecialchars(strtr(strip_tags($board_info['name']), array('&amp;' => '&'))), 'child_level' => $board_info['child_level']);
    // Set the callback.  (do you REALIZE how much memory all the messages would take?!?)
    $context['get_message'] = 'prepareDisplayContext';
    // Now set all the wonderful, wonderful permissions... like moderation ones...
    $common_permissions = array('can_approve' => 'approve_posts', 'can_ban' => 'manage_bans', 'can_sticky' => 'make_sticky', 'can_merge' => 'merge_any', 'can_split' => 'split_any', 'calendar_post' => 'calendar_post', 'can_mark_notify' => 'mark_any_notify', 'can_send_topic' => 'send_topic', 'can_send_pm' => 'pm_send', 'can_report_moderator' => 'report_any', 'can_moderate_forum' => 'moderate_forum', 'can_issue_warning' => 'issue_warning', 'can_restore_topic' => 'move_any', 'can_restore_msg' => 'move_any');
    foreach ($common_permissions as $contextual => $perm) {
        $context[$contextual] = allowedTo($perm);
    }
    // Permissions with _any/_own versions.  $context[YYY] => ZZZ_any/_own.
    $anyown_permissions = array('can_move' => 'move', 'can_lock' => 'lock', 'can_delete' => 'remove', 'can_add_poll' => 'poll_add', 'can_remove_poll' => 'poll_remove', 'can_reply' => 'post_reply', 'can_reply_unapproved' => 'post_unapproved_replies');
    foreach ($anyown_permissions as $contextual => $perm) {
        $context[$contextual] = allowedTo($perm . '_any') || $context['user']['started'] && allowedTo($perm . '_own');
    }
    // Cleanup all the permissions with extra stuff...
    $context['can_mark_notify'] &= !$context['user']['is_guest'];
    $context['can_sticky'] &= !empty($modSettings['enableStickyTopics']);
    $context['calendar_post'] &= !empty($modSettings['cal_enabled']);
    $context['can_add_poll'] &= $modSettings['pollMode'] == '1' && $topicinfo['id_poll'] <= 0;
    $context['can_remove_poll'] &= $modSettings['pollMode'] == '1' && $topicinfo['id_poll'] > 0;
    $context['can_reply'] &= empty($topicinfo['locked']) || allowedTo('moderate_board');
    $context['can_reply_unapproved'] &= $modSettings['postmod_active'] && (empty($topicinfo['locked']) || allowedTo('moderate_board'));
    $context['can_issue_warning'] &= in_array('w', $context['admin_features']) && $modSettings['warning_settings'][0] == 1;
    // Handle approval flags...
    $context['can_reply_approved'] = $context['can_reply'];
    $context['can_reply'] |= $context['can_reply_unapproved'];
    $context['can_quote'] = $context['can_reply'] && (empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC'])));
    $context['can_mark_unread'] = !$user_info['is_guest'] && $settings['show_mark_read'];
    $context['can_send_topic'] = (!$modSettings['postmod_active'] || $topicinfo['approved']) && allowedTo('send_topic');
    // Start this off for quick moderation - it will be or'd for each post.
    $context['can_remove_post'] = allowedTo('delete_any') || allowedTo('delete_replies') && $context['user']['started'];
    // Can restore topic?  That's if the topic is in the recycle board and has a previous restore state.
    $context['can_restore_topic'] &= !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board && !empty($topicinfo['id_previous_board']);
    $context['can_restore_msg'] &= !empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] == $board && !empty($topicinfo['id_previous_topic']);
    // Wireless shows a "more" if you can do anything special.
    if (WIRELESS && WIRELESS_PROTOCOL != 'wap') {
        $context['wireless_more'] = $context['can_sticky'] || $context['can_lock'] || allowedTo('modify_any');
        $context['wireless_moderate'] = isset($_GET['moderate']) ? ';moderate' : '';
    }
    // Load up the "double post" sequencing magic.
    if (!empty($options['display_quick_reply'])) {
        checkSubmitOnce('register');
        $context['name'] = isset($_SESSION['guest_name']) ? $_SESSION['guest_name'] : '';
        $context['email'] = isset($_SESSION['guest_email']) ? $_SESSION['guest_email'] : '';
    }
}
Example #26
0
function ReportToModerator2()
{
    global $txt, $scripturl, $topic, $board, $user_info, $modSettings, $sourcedir, $language, $context, $smcFunc;
    // You must have the proper permissions!
    isAllowedTo('report_any');
    // Make sure they aren't spamming.
    spamProtection('reporttm');
    require_once $sourcedir . '/Subs-Post.php';
    // No errors, yet.
    $post_errors = array();
    // Check their session.
    if (checkSession('post', '', false) != '') {
        $post_errors[] = 'session_timeout';
    }
    // Make sure we have a comment and it's clean.
    if (!isset($_POST['comment']) || $smcFunc['htmltrim']($_POST['comment']) === '') {
        $post_errors[] = 'no_comment';
    }
    $poster_comment = strtr($smcFunc['htmlspecialchars']($_POST['comment']), array("\r" => '', "\n" => '', "\t" => ''));
    // Guests need to provide their address!
    if ($user_info['is_guest']) {
        $_POST['email'] = !isset($_POST['email']) ? '' : trim($_POST['email']);
        if ($_POST['email'] === '') {
            $post_errors[] = 'no_email';
        } elseif (preg_match('~^[0-9A-Za-z=_+\\-/][0-9A-Za-z=_\'+\\-/\\.]*@[\\w\\-]+(\\.[\\w\\-]+)*(\\.[\\w]{2,6})$~', $_POST['email']) == 0) {
            $post_errors[] = 'bad_email';
        }
        isBannedEmail($_POST['email'], 'cannot_post', sprintf($txt['you_are_post_banned'], $txt['guest_title']));
        $user_info['email'] = htmlspecialchars($_POST['email']);
    }
    // Could they get the right verification code?
    if ($user_info['is_guest'] && !empty($modSettings['guests_report_require_captcha'])) {
        require_once $sourcedir . '/Subs-Editor.php';
        $verificationOptions = array('id' => 'report');
        $context['require_verification'] = create_control_verification($verificationOptions, true);
        if (is_array($context['require_verification'])) {
            $post_errors = array_merge($post_errors, $context['require_verification']);
        }
    }
    // Any errors?
    if (!empty($post_errors)) {
        loadLanguage('Errors');
        $context['post_errors'] = array();
        foreach ($post_errors as $post_error) {
            $context['post_errors'][] = $txt['error_' . $post_error];
        }
        return ReportToModerator();
    }
    // Get the basic topic information, and make sure they can see it.
    $_POST['msg'] = (int) $_POST['msg'];
    $request = $smcFunc['db_query']('', '
		SELECT m.id_topic, m.id_board, m.subject, m.body, m.id_member AS id_poster, m.poster_name, mem.real_name
		FROM {db_prefix}messages AS m
			LEFT JOIN {db_prefix}members AS mem ON (m.id_member = mem.id_member)
		WHERE m.id_msg = {int:id_msg}
			AND m.id_topic = {int:current_topic}
		LIMIT 1', array('current_topic' => $topic, 'id_msg' => $_POST['msg']));
    if ($smcFunc['db_num_rows']($request) == 0) {
        fatal_lang_error('no_board', false);
    }
    $message = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);
    $poster_name = un_htmlspecialchars($message['real_name']) . ($message['real_name'] != $message['poster_name'] ? ' (' . $message['poster_name'] . ')' : '');
    $reporterName = un_htmlspecialchars($user_info['name']) . ($user_info['name'] != $user_info['username'] && $user_info['username'] != '' ? ' (' . $user_info['username'] . ')' : '');
    $subject = un_htmlspecialchars($message['subject']);
    // Get a list of members with the moderate_board permission.
    require_once $sourcedir . '/Subs-Members.php';
    $moderators = membersAllowedTo('moderate_board', $board);
    $request = $smcFunc['db_query']('', '
		SELECT id_member, email_address, lngfile, mod_prefs
		FROM {db_prefix}members
		WHERE id_member IN ({array_int:moderator_list})
			AND notify_types != {int:notify_types}
		ORDER BY lngfile', array('moderator_list' => $moderators, 'notify_types' => 4));
    // Check that moderators do exist!
    if ($smcFunc['db_num_rows']($request) == 0) {
        fatal_lang_error('no_mods', false);
    }
    // If we get here, I believe we should make a record of this, for historical significance, yabber.
    if (empty($modSettings['disable_log_report'])) {
        $request2 = $smcFunc['db_query']('', '
			SELECT id_report, ignore_all
			FROM {db_prefix}log_reported
			WHERE id_msg = {int:id_msg}
				AND (closed = {int:not_closed} OR ignore_all = {int:ignored})
			ORDER BY ignore_all DESC', array('id_msg' => $_POST['msg'], 'not_closed' => 0, 'ignored' => 1));
        if ($smcFunc['db_num_rows']($request2) != 0) {
            list($id_report, $ignore) = $smcFunc['db_fetch_row']($request2);
        }
        $smcFunc['db_free_result']($request2);
        // If we're just going to ignore these, then who gives a monkeys...
        if (!empty($ignore)) {
            redirectexit('topic=' . $topic . '.msg' . $_POST['msg'] . '#msg' . $_POST['msg']);
        }
        // Already reported? My god, we could be dealing with a real rogue here...
        if (!empty($id_report)) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}log_reported
				SET num_reports = num_reports + 1, time_updated = {int:current_time}
				WHERE id_report = {int:id_report}', array('current_time' => time(), 'id_report' => $id_report));
        } else {
            if (empty($message['real_name'])) {
                $message['real_name'] = $message['poster_name'];
            }
            $smcFunc['db_insert']('', '{db_prefix}log_reported', array('id_msg' => 'int', 'id_topic' => 'int', 'id_board' => 'int', 'id_member' => 'int', 'membername' => 'string', 'subject' => 'string', 'body' => 'string', 'time_started' => 'int', 'time_updated' => 'int', 'num_reports' => 'int', 'closed' => 'int'), array($_POST['msg'], $message['id_topic'], $message['id_board'], $message['id_poster'], $message['real_name'], $message['subject'], $message['body'], time(), time(), 1, 0), array('id_report'));
            $id_report = $smcFunc['db_insert_id']('{db_prefix}log_reported', 'id_report');
        }
        // Now just add our report...
        if ($id_report) {
            $smcFunc['db_insert']('', '{db_prefix}log_reported_comments', array('id_report' => 'int', 'id_member' => 'int', 'membername' => 'string', 'email_address' => 'string', 'member_ip' => 'string', 'comment' => 'string', 'time_sent' => 'int'), array($id_report, $user_info['id'], $user_info['name'], $user_info['email'], $user_info['ip'], $poster_comment, time()), array('id_comment'));
        }
    }
    // Find out who the real moderators are - for mod preferences.
    $request2 = $smcFunc['db_query']('', '
		SELECT id_member
		FROM {db_prefix}moderators
		WHERE id_board = {int:current_board}', array('current_board' => $board));
    $real_mods = array();
    while ($row = $smcFunc['db_fetch_assoc']($request2)) {
        $real_mods[] = $row['id_member'];
    }
    $smcFunc['db_free_result']($request2);
    // Send every moderator an email.
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        // Maybe they don't want to know?!
        if (!empty($row['mod_prefs'])) {
            list(, , $pref_binary) = explode('|', $row['mod_prefs']);
            if (!($pref_binary & 1) && (!($pref_binary & 2) || !in_array($row['id_member'], $real_mods))) {
                continue;
            }
        }
        $replacements = array('TOPICSUBJECT' => $subject, 'POSTERNAME' => $poster_name, 'REPORTERNAME' => $reporterName, 'TOPICLINK' => $scripturl . '?topic=' . $topic . '.msg' . $_POST['msg'] . '#msg' . $_POST['msg'], 'REPORTLINK' => !empty($id_report) ? $scripturl . '?action=moderate;area=reports;report=' . $id_report : '', 'COMMENT' => $_POST['comment']);
        $emaildata = loadEmailTemplate('report_to_moderator', $replacements, empty($row['lngfile']) || empty($modSettings['userLanguage']) ? $language : $row['lngfile']);
        // Send it to the moderator.
        sendmail($row['email_address'], $emaildata['subject'], $emaildata['body'], $user_info['email'], null, false, 2);
    }
    $smcFunc['db_free_result']($request);
    // Keep track of when the mod reports get updated, that way we know when we need to look again.
    updateSettings(array('last_mod_report_action' => time()));
    // Back to the post we reported!
    redirectexit('reportsent;topic=' . $topic . '.msg' . $_POST['msg'] . '#msg' . $_POST['msg']);
}
Example #27
0
unset($next_prev_cache);
//-----------------------------------------------------
//--- Save Comment ------------------------------------
//-----------------------------------------------------
$error = 0;
if ($action == "postcomment" && isset($HTTP_POST_VARS[URL_ID])) {
    $id = intval($HTTP_POST_VARS[URL_ID]);
    $sql = "SELECT cat_id, image_allow_comments\n          FROM " . IMAGES_TABLE . "\n          WHERE image_id = {$id}";
    $row = $site_db->query_firstrow($sql);
    if ($row['image_allow_comments'] == 0 || !check_permission("auth_postcomment", $row['cat_id']) || !$row) {
        $msg = $lang['comments_deactivated'];
    } else {
        $user_name = un_htmlspecialchars(trim($HTTP_POST_VARS['user_name']));
        $comment_headline = un_htmlspecialchars(trim($HTTP_POST_VARS['comment_headline']));
        $comment_text = un_htmlspecialchars(trim($HTTP_POST_VARS['comment_text']));
        $captcha = isset($HTTP_POST_VARS['captcha']) ? un_htmlspecialchars(trim($HTTP_POST_VARS['captcha'])) : "";
        // Flood Check
        $sql = "SELECT comment_ip, comment_date\n            FROM " . COMMENTS_TABLE . "\n            WHERE image_id = {$id}\n            ORDER BY comment_date DESC\n            LIMIT 1";
        $spam_row = $site_db->query_firstrow($sql);
        $spamtime = $spam_row['comment_date'] + 180;
        if ($session_info['session_ip'] == $spam_row['comment_ip'] && time() <= $spamtime && $user_info['user_level'] != ADMIN) {
            $msg .= ($msg != "" ? "<br />" : "") . $lang['spamming'];
            $error = 1;
        }
        $user_name_field = get_user_table_field("", "user_name");
        if (!empty($user_name_field)) {
            if ($site_db->not_empty("SELECT {$user_name_field} FROM " . USERS_TABLE . " WHERE {$user_name_field} = '" . strtolower($user_name) . "' AND " . get_user_table_field("", "user_id") . " <> '" . $user_info['user_id'] . "'")) {
                $msg .= ($msg != "" ? "<br />" : "") . $lang['username_exists'];
                $error = 1;
            }
        }
function TPortalDLAdmin()
{
    global $txt, $scripturl, $boarddir, $boardurl, $smcFunc, $context, $settings, $sourcedir;
    // check permissions
    if (isset($_POST['dl_useredit'])) {
        checkSession('post');
    } else {
        isAllowedTo('tp_dlmanager');
    }
    // add visual options to this section
    $dl_visual = explode(',', $context['TPortal']['dl_visual_options']);
    $dv = array('left', 'right', 'center', 'top', 'bottom', 'lower');
    foreach ($dv as $v => $val) {
        if (in_array($val, $dl_visual)) {
            $context['TPortal'][$val . 'panel'] = '1';
            $context['TPortal']['dl_' . $val] = '1';
        } else {
            $context['TPortal'][$val . 'panel'] = '0';
        }
    }
    if (in_array('showtop', $dl_visual)) {
        $context['TPortal']['showtop'] = true;
        $context['TPortal']['dl_top'] = true;
    } else {
        $context['TPortal']['showtop'] = false;
    }
    if ($context['TPortal']['hidebars_admin_only'] == '1') {
        tp_hidebars();
    }
    // fetch membergroups so we can quickly set permissions
    // dlmanager, dlupload, dlcreatetopic
    $context['TPortal']['perm_all_groups'] = get_grps();
    $context['TPortal']['perm_groups'] = tp_fetchpermissions(array('tp_dlmanager', 'tp_dlupload', 'tp_dlcreatetopic'));
    $context['TPortal']['boards'] = tp_fetchboards();
    $context['TPortal']['all_dlitems'] = array();
    $request = $smcFunc['db_query']('', '
		SELECT id, name	FROM {db_prefix}tp_dlmanager
		WHERE type = {string:type}
		ORDER BY name ASC', array('type' => 'dlitem'));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['TPortal']['all_dlitems'][] = array('id' => $row['id'], 'name' => $row['name']);
        }
        $smcFunc['db_free_result']($request);
    }
    // Add in BBC editor before we call in template so the headers are there
    if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
        if ($context['TPortal']['dlsub'] == 'adminaddcat') {
            $context['TPortal']['editor_id'] = 'newdladmin_text';
            TP_prebbcbox($context['TPortal']['editor_id']);
        } else {
            $context['TPortal']['editor_id'] = 'tp_dl_introtext';
            TP_prebbcbox($context['TPortal']['editor_id'], $context['TPortal']['dl_introtext']);
        }
    }
    // any items from the ftp screen?
    if (!empty($_POST['ftpdlsend'])) {
        // new category?
        if (!empty($_POST['assign-ftp-newcat'])) {
            $newcat = true;
            $newcatname = $_POST['assign-ftp-newcat'];
            if (isset($_POST['assign-ftp-cat']) && $_POST['assign-ftp-cat'] > 0) {
                $newcatparent = $_POST['assign-ftp-cat'];
            } else {
                $newcatparent = 0;
            }
            if ($newcatname == '') {
                $newcatname = '-no name-';
            }
        } else {
            $newcat = false;
            $newcatname = '';
            $newcatnow = $_POST['assign-ftp-cat'];
            $newcatparent = 0;
        }
        // if new category create it first.
        if ($newcat) {
            $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_dlmanager', array('name' => 'string', 'description' => 'string', 'icon' => 'string', 'category' => 'int', 'type' => 'string', 'downloads' => 'int', 'views' => 'int', 'file' => 'string', 'created' => 'int', 'last_access' => 'int', 'filesize' => 'int', 'parent' => 'int', 'access' => 'string', 'link' => 'string', 'author_id' => 'int', 'screenshot' => 'string', 'rating' => 'string', 'voters' => 'string', 'subitem' => 'int'), array($newcatname, '', '', 0, 'dlcat', 0, 0, '', 0, 0, 0, $newcatparent, '', '', $context['user']['id'], '', '', '', 0), array('id'));
            $newcatnow = $smcFunc['db_insert_id']($request);
        }
        // now go through each file and put it into the table.
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 19) == 'assign-ftp-checkbox') {
                $name = $value;
                $now = time();
                $fsize = filesize($boarddir . '/tp-downloads/' . $value);
                $smcFunc['db_insert']('INSERT', '{db_prefix}tp_dlmanager', array('name' => 'string', 'description' => 'string', 'icon' => 'string', 'category' => 'int', 'type' => 'string', 'downloads' => 'int', 'views' => 'int', 'file' => 'string', 'created' => 'int', 'last_access' => 'int', 'filesize' => 'int', 'parent' => 'int', 'access' => 'string', 'link' => 'string', 'author_id' => 'int', 'screenshot' => 'string', 'rating' => 'string', 'voters' => 'string', 'subitem' => 'int'), array($name, '', '', $newcatnow, 'dlitem', 1, 1, $value, $now, $now, $fsize, 0, '', '', $context['user']['id'], '', '', '', 0), array('id'));
            }
        }
        // done, set a value to make member aware of assigned category
        redirectexit('action=tpmod;dl=adminftp;ftpcat=' . $newcatnow);
    }
    // check for new category
    if (!empty($_POST['newdlsend'])) {
        // get the items
        $name = strip_tags($_POST['newdladmin_name']);
        // no html here
        if (empty($name)) {
            $name = $txt['tp-dlnotitle'];
        }
        $text = $_POST['newdladmin_text'];
        $parent = $_POST['newdladmin_parent'];
        $icon = $boardurl . '/tp-downloads/icons/' . $_POST['newdladmin_icon'];
        // special case, the access
        $dlgrp = array();
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 16) == 'newdladmin_group') {
                $vv = substr($what, 16);
                if ($vv != '-2') {
                    $dlgrp[] = $vv;
                }
            }
        }
        $access = implode(',', $dlgrp);
        // insert the category
        $request = $smcFunc['db_insert']('INSERT', '{db_prefix}tp_dlmanager', array('name' => 'string', 'description' => 'string', 'icon' => 'string', 'category' => 'int', 'type' => 'string', 'downloads' => 'int', 'views' => 'int', 'file' => 'string', 'created' => 'int', 'last_access' => 'int', 'filesize' => 'int', 'parent' => 'int', 'access' => 'string', 'link' => 'string', 'author_id' => 'int', 'screenshot' => 'string', 'rating' => 'string', 'voters' => 'string', 'subitem' => 'int'), array($name, $text, $icon, 0, 'dlcat', 0, 0, '', 0, 0, 0, $parent, $access, '', $context['user']['id'], '', '', '', 0), array('id'));
        $newcat = $smcFunc['db_insert_id']($request);
        redirectexit('action=tpmod;dl=admineditcat' . $newcat);
    }
    $myid = 0;
    // check if tag links are present
    if (isset($_POST['dladmin_itemtags'])) {
        $itemid = $_POST['dladmin_itemtags'];
        // get title
        $request = $smcFunc['db_query']('', '
			SELECT name FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} LIMIT 1', array('item' => $itemid));
        $title = $smcFunc['db_fetch_row']($request);
        // remove old ones first
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_variables 
			WHERE value3 = {string:val3} 
			AND subtype2 = {int:sub}', array('val3' => 'dladmin_itemtags', 'sub' => $itemid));
        $alltags = array();
        foreach ($_POST as $what => $value) {
            // a tag from edit items
            if (substr($what, 0, 17) == 'dladmin_itemtags_') {
                $tag = substr($what, 17);
                $itemid = $value;
                // insert new one
                $href = '?action=tpmod;dl=item' . $itemid;
                $tg = '<span style="background: url(' . $settings['tp_images_url'] . '/glyph_download.png) no-repeat;" class="taglink">' . $title[0] . '</span>';
                if (!empty($tag)) {
                    $smcFunc['db_query']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array($href, $tg, 'dladmin_itemtags', '', 0, $tag, '', '', $itemid), array('id'));
                    $alltags[] = $tag;
                }
            }
        }
        $tg = implode(',', $alltags);
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}tp_dlmanager 
			SET global_tag = {string:tag} 
			WHERE id = {int:item}', array('tag' => $tg, 'item' => $itemid));
        $myid = $itemid;
        $go = 2;
        $newgo = 2;
    }
    // check if tag links are present -categories
    if (isset($_POST['dladmin_cattags'])) {
        $itemid = $_POST['dladmin_cattags'];
        // get title
        $request = $smcFunc['db_query']('', '
			SELECT name FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} LIMIT 1', array('item' => $itemid));
        $title = $smcFunc['db_fetch_row']($request);
        // remove old ones first
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_variables 
			WHERE value3 = {string:val3} 
			AND subtype2 = {int:sub}', array('val3' => 'dladmin_cattags', 'sub' => $itemid));
        foreach ($_POST as $what => $value) {
            // a tag from edit category
            if (substr($what, 0, 16) == 'dladmin_cattags_') {
                $tag = substr($what, 16);
                $itemid = $value;
                // insert new one
                $href = '?action=tpmod;dl=cat' . $itemid;
                $title = $title[0] . ' [' . strtolower($txt['tp-downloads']) . '] ';
                $smcFunc['db_query']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array($href, $title, 'dladmin_cattags', '', 0, $tag, '', '', $itemid), array('id'));
            }
        }
        $myid = $itemid;
        $go = 3;
        $newgo = 3;
    }
    // check for access value
    if (!empty($_POST['dlsend'])) {
        $admgrp = array();
        $groupset = false;
        $dlgrp = array();
        $dlset = false;
        $visual = array();
        $visualset = false;
        $creategrp = array();
        $dlmanager_grp = array();
        $dlupload_grp = array();
        $dlcreatetopic_grp = array();
        // Our settings array to send to updateTPSettings();
        $changeArray = array();
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 13) == 'dladmin_group') {
                $val = substr($what, 13);
                if ($val != '-2') {
                    $admgrp[] = $val;
                }
                $groupset = true;
                $id = $value;
            } elseif (substr($what, 0, 8) == 'tp_group') {
                if ($value != '-2') {
                    $dlgrp[] = $value;
                }
                $dlset = true;
            } elseif (substr($what, 0, 20) == 'tp_dl_visual_options') {
                if ($value != 'not') {
                    $visual[] = $value;
                }
                $visualset = true;
            } elseif (substr($what, 0, 11) == 'tp_dlboards') {
                $creategrp[] = $value;
            }
        }
        if ($groupset) {
            $dlaccess = implode(',', $admgrp);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET access = {string:access} 
				WHERE id = {int:item}', array('access' => $dlaccess, 'item' => $id));
        }
        if (!empty($_POST['dlsettings'])) {
            $changeArray['dl_createtopic_boards'] = implode(',', $creategrp);
        }
        if ($dlset) {
            $changeArray['dl_approve_groups'] = implode(',', $dlgrp);
        }
        if ($visualset) {
            $changeArray['dl_visual_options'] = implode(',', $visual);
        }
        $go = 0;
        if (!empty($_FILES['qup_dladmin_text']['tmp_name']) && (file_exists($_FILES['qup_dladmin_text']['tmp_name']) || is_uploaded_file($_FILES['qup_dladmin_text']['tmp_name']))) {
            $name = TPuploadpicture('qup_dladmin_text', $context['user']['id'] . 'uid');
            tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
        }
        if (!empty($_FILES['qup_blockbody']['tmp_name']) && (file_exists($_FILES['qup_dladmin_text']['tmp_name']) || is_uploaded_file($_FILES['qup_dladmin_text']['tmp_name']))) {
            $name = TPuploadpicture('qup_dladmin_text', $context['user']['id'] . 'uid');
            tp_createthumb('tp-images/' . $name, 50, 50, 'tp-images/thumbs/thumb_' . $name);
        }
        // a screenshot from edit item screen?
        if (!empty($_FILES['tp_dluploadpic_edit']['tmp_name']) && (file_exists($_FILES['tp_dluploadpic_edit']['tmp_name']) || is_uploaded_file($_FILES['tp_dluploadpic_edit']['tmp_name']))) {
            $shot = true;
        } else {
            $shot = false;
        }
        if ($shot) {
            $sid = $_POST['tp_dluploadpic_editID'];
            $sfile = 'tp_dluploadpic_edit';
            $uid = $context['user']['id'] . 'uid';
            $dim = '1800';
            $suf = 'jpg,gif,png';
            $dest = 'tp-images/dlmanager';
            $sname = TPuploadpicture($sfile, $uid, $dim, $suf, $dest);
            $screenshot = $sname;
            tp_createthumb($dest . '/' . $sname, $context['TPortal']['dl_screenshotsize'][0], $context['TPortal']['dl_screenshotsize'][1], $dest . '/thumb/' . $sname);
            tp_createthumb($dest . '/' . $sname, $context['TPortal']['dl_screenshotsize'][2], $context['TPortal']['dl_screenshotsize'][3], $dest . '/listing/' . $sname);
            tp_createthumb($dest . '/' . $sname, $context['TPortal']['dl_screenshotsize'][4], $context['TPortal']['dl_screenshotsize'][5], $dest . '/single/' . $sname);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET screenshot = {string:ss} 
				WHERE id = {int:item}', array('ss' => $screenshot, 'item' => $sid));
            $uploaded = true;
        } else {
            $screenshot = '';
            $uploaded = false;
        }
        if (isset($_POST['tp_dluploadpic_link']) && !$uploaded) {
            $sid = $_POST['tp_dluploadpic_editID'];
            $screenshot = $_POST['tp_dluploadpic_link'];
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET screenshot = {string:ss} 
				WHERE id = {int:item}', array('ss' => $screenshot, 'item' => $sid));
        } else {
            $screenshot = '';
        }
        // a new file uploaded?
        if (!empty($_FILES['tp_dluploadfile_edit']['tmp_name']) && is_uploaded_file($_FILES['tp_dluploadfile_edit']['tmp_name'])) {
            $shot = true;
        } else {
            $shot = false;
        }
        if ($shot) {
            $sid = $_POST['tp_dluploadfile_editID'];
            $shotname = $_FILES['tp_dluploadfile_edit']['name'];
            $sname = strtr($shotname, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ', 'SZszYAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy');
            $sname = strtr($sname, array('Þ' => 'TH', 'þ' => 'th', 'Ð' => 'DH', 'ð' => 'dh', 'ß' => 'ss', 'Œ' => 'OE', 'œ' => 'oe', 'Æ' => 'AE', 'æ' => 'ae', 'µ' => 'u'));
            $sname = preg_replace(array('/\\s/', '/[^\\w_\\.\\-]/'), array('_', ''), $sname);
            $sname = time() . $sname;
            // check the size
            $dlfilesize = filesize($_FILES['tp_dluploadfile_edit']['tmp_name']);
            if ($dlfilesize > 1000 * $context['TPortal']['dl_max_upload_size']) {
                unlink($_FILES['tp_dluploadfile_edit']['tmp_name']);
                $error = $txt['tp-dlmaxerror'] . ' ' . $context['TPortal']['dl_max_upload_size'] . ' Kb<br /><br />' . $txt['tp-dlmaxerror2'] . ': ' . ceil($dlfilesize / 1000) . ' Kb';
                fatal_error($error);
            }
            // check the extension
            $allowed = explode(',', $context['TPortal']['dl_allowed_types']);
            $match = false;
            foreach ($allowed as $extension => $value) {
                $ext = '.' . $value;
                $extlen = strlen($ext);
                if (substr($sname, strlen($sname) - $extlen, $extlen) == $ext) {
                    $match = true;
                }
            }
            if (!$match) {
                unlink($_FILES['tp_dluploadfile_edit']['tmp_name']);
                $error = $txt['tp-dlexterror'] . ':<b> <br />' . $context['TPortal']['dl_allowed_types'] . '</b><br /><br />' . $txt['tp-dlexterror2'] . ': <b>' . $sname . '</b>';
                fatal_error($error);
            }
            $success2 = move_uploaded_file($_FILES['tp_dluploadfile_edit']['tmp_name'], $boarddir . '/tp-downloads/' . $sname);
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET file = {string:file} 
				WHERE id = {int:item}', array('file' => $sname, 'item' => $sid));
            $new_upload = true;
            // update filesize as well
            $value = filesize($boarddir . '/tp-downloads/' . $sname);
            if (!is_numeric($value)) {
                $value = 0;
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_dlmanager 
				SET filesize = {int:size}
				WHERE id = {int:item}', array('size' => $value, 'item' => $sid));
            $myid = $sid;
            $go = 2;
        }
        // get all values from forms
        foreach ($_POST as $what => $value) {
            if (substr($what, 0, 12) == 'dladmin_name') {
                $id = substr($what, 12);
                // no html here
                $value = strip_tags($value);
                if (empty($value)) {
                    $value = '-no title-';
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET name = {string:name} 
					WHERE id = {int:item}', array('name' => $value, 'item' => $id));
            } elseif (substr($what, 0, 12) == 'dladmin_icon') {
                $id = substr($what, 12);
                if ($value != '') {
                    $val = $boardurl . '/tp-downloads/icons/' . $value;
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET icon = {string:icon} 
						WHERE id = {int:item}', array('icon' => $val, 'item' => $id));
                }
            } elseif (substr($what, 0, 12) == 'dladmin_text') {
                $id = substr($what, 12);
                if (is_numeric($id)) {
                    // If we came from WYSIWYG then turn it back into BBC regardless.
                    if (!empty($_REQUEST[$what . '_mode']) && isset($_REQUEST[$what])) {
                        require_once $sourcedir . '/Subs-Editor.php';
                        $_REQUEST[$what] = html_to_bbc($_REQUEST[$what]);
                        // We need to unhtml it now as it gets done shortly.
                        $_REQUEST[$what] = un_htmlspecialchars($_REQUEST[$what]);
                        // We need this for everything else.
                        $value = $_POST[$what] = $_REQUEST[$what];
                    }
                    if (isset($_POST['dladmin_text' . $id . '_pure']) && isset($_POST['dladmin_text' . $id . '_choice'])) {
                        if ($_POST['dladmin_text' . $id . '_choice'] == 1) {
                            $value = $_POST['dladmin_text' . $id];
                        } else {
                            $value = $_POST['dladmin_text' . $id . '_pure'];
                        }
                    }
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET description = {string:desc} 
						WHERE id = {int:item}', array('desc' => $value, 'item' => $id));
                }
            } elseif (substr($what, 0, 14) == 'dladmin_delete') {
                $id = substr($what, 14);
                $request = $smcFunc['db_query']('', '
						SELECT * FROM {db_prefix}tp_dlmanager 
						WHERE id = {int:item}', array('item' => $id));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    if ($row['type'] == 'dlitem') {
                        $category = $row['category'];
                        if ($category > 0) {
                            $smcFunc['db_query']('', '
									UPDATE {db_prefix}tp_dlmanager 
									SET downloads = downloads - 1 
									WHERE id = {int:cat} LIMIT 1', array('cat' => $category));
                        }
                        // delete both screenshot and file
                        if (!empty($row['file']) && file_exists($boarddir . '/tp-downloads/' . $row['file'])) {
                            $succ = unlink($boarddir . '/tp-downloads/' . $row['file']);
                            if (!$succ) {
                                $err = $txt['tp-dlfilenotdel'] . ' (' . $row['file'] . ')';
                            }
                        }
                        if (!empty($row['screenshot']) && file_exists($boarddir . '/' . $row['screenshot'])) {
                            $succ2 = unlink($boarddir . '/' . $row['screenshot']);
                            if (!$succ2) {
                                $err .= '<br />' . $txt['tp-dlssnotdel'] . ' (' . $row['screenshot'] . ')';
                            }
                        }
                    }
                    $smcFunc['db_free_result']($request);
                }
                $smcFunc['db_query']('', '
					DELETE FROM {db_prefix}tp_dlmanager 
					WHERE id = {int:item}', array('item' => $id));
                if (isset($err)) {
                    fatal_error($err);
                }
                redirectexit('action=tpmod;dl=admincat' . $category);
            } elseif (substr($what, 0, 15) == 'dladmin_approve' && $value == 'ON') {
                $id = abs(substr($what, 15));
                $request = $smcFunc['db_query']('', '
					SELECT category FROM {db_prefix}tp_dlmanager 
					WHERE id = {int:item}', array('item' => $id));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_row']($request);
                    $newcat = abs($row[0]);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET category = {int:cat} 
						WHERE id = {int:item}', array('cat' => $newcat, 'item' => $id));
                    $smcFunc['db_query']('', '
						DELETE FROM {db_prefix}tp_variables 
						WHERE type = {string:type} 
						AND value5 = {int:val5}', array('type' => 'dl_not_approved', 'val5' => $id));
                    $smcFunc['db_free_result']($request);
                }
            } elseif (substr($what, 0, 16) == 'dl_admin_approve' && $value == 'ON') {
                $id = abs(substr($what, 16));
                $request = $smcFunc['db_query']('', '
					SELECT category FROM {db_prefix}tp_dlmanager 
					WHERE id = {int:item}', array('item' => $id));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_row']($request);
                    $newcat = abs($row[0]);
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET category = {int:cat} 
						WHERE id = {int:item}', array('cat' => $newcat, 'item' => $id));
                    $smcFunc['db_query']('', '
						DELETE FROM {db_prefix}tp_variables 
						WHERE type = {string:type} 
						AND value5 = {int:val5}', array('type' => 'dl_not_approved', 'val5' => $id));
                    $smcFunc['db_free_result']($request);
                }
            } elseif (substr($what, 0, 16) == 'dladmin_category') {
                $id = substr($what, 16);
                // update, but not on negative values :)
                if ($value > 0) {
                    $smcFunc['db_query']('', '
						UPDATE {db_prefix}tp_dlmanager 
						SET category = {int:cat} 
						WHERE id = {int:item}', array('cat' => $value, 'item' => $id));
                }
            } elseif (substr($what, 0, 14) == 'dladmin_parent') {
                $id = substr($what, 14);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET parent = {int:parent}
					WHERE id = {int:item}', array('parent' => $value, 'item' => $id));
            } elseif (substr($what, 0, 15) == 'dladmin_subitem') {
                $id = substr($what, 15);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET subitem = {int:sub}
					WHERE id = {int:item}', array('sub' => $value, 'item' => $id));
            } elseif (substr($what, 0, 11) == 'tp_dlcatpos') {
                $id = substr($what, 11);
                if (!empty($_POST['admineditcatval'])) {
                    $myid = $_POST['admineditcatval'];
                    $go = 4;
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET downloads = {int:down}
					WHERE id = {int:item}', array('down' => $value, 'item' => $id));
            } elseif (substr($what, 0, 18) == 'dladmin_screenshot') {
                $id = substr($what, 18);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET screenshot = {string:ss} 
					WHERE id = {int:item}', array('ss' => $value, 'item' => $id));
            } elseif (substr($what, 0, 12) == 'dladmin_link') {
                $id = substr($what, 12);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET link = {string:link} 
					WHERE id = {int:item}', array('link' => $value, 'item' => $id));
            } elseif (substr($what, 0, 12) == 'dladmin_file' && !isset($new_upload)) {
                $id = substr($what, 12);
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET file = {string:file}
					WHERE id = {int:item}', array('file' => $value, 'item' => $id));
                $myid = $id;
                $go = 2;
            } elseif (substr($what, 0, 12) == 'dladmin_size' && !isset($new_upload)) {
                $id = substr($what, 12);
                // check the actual size
                $name = $_POST['dladmin_file' . $id];
                $value = filesize($boarddir . '/tp-downloads/' . $name);
                if (!is_numeric($value)) {
                    $value = 0;
                }
                $smcFunc['db_query']('', '
					UPDATE {db_prefix}tp_dlmanager 
					SET filesize = {int:size}
					WHERE id = {int:item}', array('size' => $value, 'item' => $id));
            } elseif ($what == 'tp_dl_allowed_types') {
                $changeArray['dl_allowed_types'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_usescreenshot') {
                $changeArray['dl_usescreenshot'] = $value;
                $go = 1;
            } elseif (substr($what, 0, 20) == 'tp_dl_screenshotsize') {
                // which one
                $who = substr($what, 20);
                $result = $smcFunc['db_query']('', '
					SELECT value FROM {db_prefix}tp_settings 
					WHERE name = {string:name} LIMIT 1', array('name' => 'dl_screenshotsizes'));
                $row = $smcFunc['db_fetch_assoc']($result);
                $smcFunc['db_free_result']($result);
                $all = explode(',', $row['value']);
                $all[$who] = $value;
                $changeArray['dl_screenshotsizes'] = implode(',', $all);
                $go = 1;
            } elseif ($what == 'tp_dl_showfeatured') {
                $changeArray['dl_showfeatured'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_wysiwyg') {
                $changeArray['dl_wysiwyg'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_showrecent') {
                $changeArray['dl_showlatest'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_showstats') {
                $changeArray['dl_showstats'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_showcategorytext') {
                $changeArray['dl_showcategorylist'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_featured') {
                $changeArray['dl_featured'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_introtext') {
                if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
                    // If we came from WYSIWYG then turn it back into BBC regardless.
                    if (!empty($_REQUEST['tp_dl_introtext']) && isset($_REQUEST['tp_dl_introtext'])) {
                        require_once $sourcedir . '/Subs-Editor.php';
                        $_REQUEST['tp_dl_introtext'] = html_to_bbc($_REQUEST['tp_dl_introtext']);
                        // We need to unhtml it now as it gets done shortly.
                        $_REQUEST['tp_dl_introtext'] = un_htmlspecialchars($_REQUEST['tp_dl_introtext']);
                        // We need this for everything else.
                        $value = $_POST['tp_dl_introtext'] = $_REQUEST['tp_dl_introtext'];
                    }
                }
                $changeArray['dl_introtext'] = trim($value);
                $go = 1;
            } elseif ($what == 'tp_dluploadsize') {
                $changeArray['dl_max_upload_size'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_approveonly') {
                $changeArray['dl_approve'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dlallowupload') {
                $changeArray['dl_allow_upload'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dl_fileprefix') {
                $changeArray['dl_fileprefix'] = $value;
                $go = 1;
            } elseif ($what == 'tp_dltheme') {
                $changeArray['dlmanager_theme'] = $value;
                $go = 1;
            }
        }
        // Update all the changes settings finally
        updateTPSettings($changeArray);
        // if we came from useredit screen..
        if (isset($_POST['dl_useredit'])) {
            redirectexit('action=tpmod;dl=useredit' . $_POST['dl_useredit']);
        }
        if (!empty($newgo)) {
            $go = $newgo;
        }
        // guess not, admin screen then
        if ($go == 1) {
            redirectexit('action=tpmod;dl=adminsettings');
        } elseif ($go == 2) {
            redirectexit('action=tpmod;dl=adminitem' . $myid);
        } elseif ($go == 3) {
            redirectexit('action=tpmod;dl=admineditcat' . $myid);
        } elseif ($go == 4) {
            redirectexit('action=tpmod;dl=admincat' . $myid);
        }
    }
    // ****************
    TP_dlgeticons();
    // get all themes
    $context['TPthemes'] = array();
    $request = $smcFunc['db_query']('', '
		SELECT value AS name, id_theme as ID_THEME
		FROM {db_prefix}themes
		WHERE variable = {string:var}
		AND id_member = {int:id_mem}
		ORDER BY value ASC', array('var' => 'name', 'id_mem' => 0));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $context['TPthemes'][] = array('id' => $row['ID_THEME'], 'name' => $row['name']);
        }
        $smcFunc['db_free_result']($request);
    }
    // fetch all files from tp-downloads
    $context['TPortal']['tp-downloads'] = array();
    $count = 1;
    if ($handle = opendir($boarddir . '/tp-downloads')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..' && $file != '.htaccess' && $file != 'icons') {
                $size = floor(filesize($boarddir . '/tp-downloads/' . $file) / 102.4) / 10;
                $context['TPortal']['tp-downloads'][$count] = array('id' => $count, 'file' => $file, 'size' => $size);
                $count++;
            }
        }
        closedir($handle);
    }
    // get all membergroups for permissions
    $context['TPortal']['dlgroups'] = get_grps(true, true);
    //fetch all categories
    $sorted = array();
    $context['TPortal']['linkcats'] = array();
    $srequest = $smcFunc['db_query']('', '
		SELECT id, name, description, icon, access, parent 
		FROM {db_prefix}tp_dlmanager 
		WHERE type = {string:type} ORDER BY downloads ASC', array('type' => 'dlcat'));
    if ($smcFunc['db_num_rows']($srequest) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($srequest)) {
            // for the linktree
            $context['TPortal']['linkcats'][$row['id']] = array('id' => $row['id'], 'name' => $row['name'], 'parent' => $row['parent']);
            $sorted[$row['id']] = array('id' => $row['id'], 'parent' => $row['parent'], 'name' => $row['name'], 'text' => $row['description'], 'icon' => $row['icon']);
        }
        $smcFunc['db_free_result']($srequest);
    }
    // sort them
    if (count($sorted) > 1) {
        $context['TPortal']['admuploadcats'] = chain('id', 'parent', 'name', $sorted);
    } else {
        $context['TPortal']['admuploadcats'] = $sorted;
    }
    $context['TPortal']['dl_admcats'] = array();
    $context['TPortal']['dl_admcats2'] = array();
    $context['TPortal']['dl_admitems'] = array();
    $context['TPortal']['dl_admcount'] = array();
    $context['TPortal']['dl_admsubmitted'] = array();
    $context['TPortal']['dl_allitems'] = array();
    // count items in each category
    $request = $smcFunc['db_query']('', '
		SELECT file, category 
		FROM {db_prefix}tp_dlmanager 
		WHERE type = {string:type}', array('type' => 'dlitem'));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            if ($row['category'] < 0) {
                if (isset($context['TPortal']['dl_admsubmitted'][abs($row['category'])])) {
                    $context['TPortal']['dl_admsubmitted'][abs($row['category'])]++;
                } else {
                    $context['TPortal']['dl_admsubmitted'][abs($row['category'])] = 1;
                }
            } else {
                if (isset($context['TPortal']['dl_admcount'][$row['category']])) {
                    $context['TPortal']['dl_admcount'][$row['category']]++;
                } else {
                    $context['TPortal']['dl_admcount'][$row['category']] = 1;
                }
            }
            $context['TPortal']['dl_allitems'][] = $row['file'];
        }
        $smcFunc['db_free_result']($request);
    }
    // fetch all categories
    $admsub = substr($context['TPortal']['dlsub'], 5);
    if ($admsub == '') {
        $context['TPortal']['dl_title'] = $txt['tp-dladmin'];
        // fetch all categories with subcats
        $req = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type} 
			ORDER BY downloads ASC', array('type' => 'dlcat'));
        if ($smcFunc['db_num_rows']($req) > 0) {
            while ($brow = $smcFunc['db_fetch_assoc']($req)) {
                if (isset($context['TPortal']['dl_admcount'][$brow['id']])) {
                    $items = $context['TPortal']['dl_admcount'][$brow['id']];
                } else {
                    $items = 0;
                }
                if (isset($context['TPortal']['dl_admsubmitted'][$brow['id']])) {
                    $sitems = $context['TPortal']['dl_admsubmitted'][$brow['id']];
                } else {
                    $sitems = 0;
                }
                $context['TPortal']['admcats'][] = array('id' => $brow['id'], 'name' => $brow['name'], 'icon' => $brow['icon'], 'access' => $brow['access'], 'parent' => $brow['parent'], 'description' => $brow['description'], 'shortname' => $brow['link'], 'items' => $items, 'submitted' => $sitems, 'total' => $items + $sitems, 'href' => $scripturl . '?action=tpmod;dl=admincat' . $brow['id'], 'href2' => $scripturl . '?action=tpmod;dl=admineditcat' . $brow['id'], 'href3' => $scripturl . '?action=tpmod;dl=admindelcat' . $brow['id'], 'pos' => $brow['downloads']);
            }
            $smcFunc['db_free_result']($req);
        }
    } elseif (substr($admsub, 0, 3) == 'cat') {
        $cat = substr($admsub, 3);
        // get the parent first
        $request = $smcFunc['db_query']('', '
			SELECT parent, name, link 
			FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type}
			AND id = {int:item}', array('type' => 'dlcat', 'item' => $cat));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            $catparent = abs($row['parent']);
            $catname = $row['name'];
            $catshortname = $row['link'];
            $smcFunc['db_free_result']($request);
        }
        // fetch items within a category
        $request = $smcFunc['db_query']('', '
			SELECT dl.*, dl.author_id as authorID,m.real_name as realName
			FROM ({db_prefix}tp_dlmanager AS dl, {db_prefix}members AS m)
			WHERE abs(dl.category) = {int:cat}
			AND dl.type = {string:type}
			AND dl.subitem = {int:sub}
			AND dl.author_id = m.id_member
			ORDER BY dl.id DESC', array('cat' => $cat, 'type' => 'dlitem', 'sub' => 0));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['dl_admitems'][] = array('id' => $row['id'], 'name' => $row['name'], 'icon' => $row['icon'], 'category' => abs($row['category']), 'file' => $row['file'], 'filesize' => floor($row['filesize'] / 1024), 'views' => $row['views'], 'authorID' => $row['authorID'], 'author' => '<a href="' . $scripturl . '?action=profile;u=' . $row['authorID'] . '">' . $row['realName'] . '</a>', 'created' => timeformat($row['created']), 'last_access' => timeformat($row['last_access']), 'description' => $row['description'], 'downloads' => $row['downloads'], 'sshot' => $row['screenshot'], 'link' => $row['link'], 'href' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'approved' => $row['category'] < 0 ? '0' : '1', 'approve' => $scripturl . '?action=tpmod;dl=adminapprove' . $row['id']);
            }
            $smcFunc['db_free_result']($request);
        }
        // fetch all categories with subcats
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type}
			ORDER BY name ASC', array('type' => 'dlcat'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if (isset($context['TPortal']['dl_admcount'][$row['id']])) {
                    $items = $context['TPortal']['dl_admcount'][$row['id']];
                } else {
                    $items = 0;
                }
                if (isset($context['TPortal']['dl_admsubmitted'][$row['id']])) {
                    $sitems = $context['TPortal']['dl_admsubmitted'][$row['id']];
                } else {
                    $sitems = 0;
                }
                $context['TPortal']['admcats'][] = array('id' => $row['id'], 'name' => $row['name'], 'pos' => $row['downloads'], 'icon' => $row['icon'], 'shortname' => $row['link'], 'access' => $row['access'], 'parent' => $row['parent'], 'description' => $row['description'], 'items' => $items, 'submitted' => $sitems, 'total' => $items + $sitems, 'href' => $scripturl . '?action=tpmod;dl=admincat' . $row['id'], 'href2' => $scripturl . '?action=tpmod;dl=admineditcat' . $row['id'], 'href3' => $scripturl . '?action=tpmod;dl=admindelcat' . $row['id']);
            }
            $smcFunc['db_free_result']($request);
        }
        // check to see if its child
        $parents = array();
        while ($catparent > 0) {
            $parents[$catparent] = array('id' => $catparent, 'name' => $context['TPortal']['linkcats'][$catparent]['name'], 'parent' => $context['TPortal']['linkcats'][$catparent]['parent']);
            $catparent = $context['TPortal']['linkcats'][$catparent]['parent'];
        }
        // make the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=admin', $txt['tp-dladmin']);
        if (isset($parents)) {
            $parts = array_reverse($parents, TRUE);
            // add to the linktree
            foreach ($parts as $parent) {
                TPadd_linktree($scripturl . '?action=tpmod;dl=admincat' . $parent['id'], $parent['name']);
            }
        }
        // add to the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=admincat' . $cat, $catname);
    } elseif ($context['TPortal']['dlsub'] == 'adminsubmission') {
        // check any submissions if admin
        $submitted = array();
        isAllowedTo('tp_dlmanager');
        $context['TPortal']['dl_admitems'] = array();
        $request = $smcFunc['db_query']('', '
			SELECT dl.id, dl.name, dl.file, dl.created, dl.filesize, dl.author_id as authorID, m.real_name as realName
			FROM ({db_prefix}tp_dlmanager AS dl, {db_prefix}members AS m)
			WHERE dl.type = {string:type}
			AND dl.category < 0
			AND dl.author_id = m.id_member', array('type' => 'dlitem'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $rows = $smcFunc['db_num_rows']($request);
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['dl_admitems'][] = array('id' => $row['id'], 'name' => $row['name'], 'file' => $row['file'], 'filesize' => floor($row['filesize'] / 1024), 'href' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'author' => '<a href="' . $scripturl . '?action=profile;u=' . $row['authorID'] . '">' . $row['realName'] . '</a>', 'date' => timeformat($row['created']));
                $submitted[] = $row['id'];
            }
            $smcFunc['db_free_result']($request);
        }
        // check that submissions link to downloads
        $request = $smcFunc['db_query']('', '
			SELECT id,value5 FROM {db_prefix}tp_variables 
			WHERE type = {string:type}', array('type' => 'dl_not_approved'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $what = $row['id'];
                if (!in_array($row['value5'], $submitted)) {
                    $smcFunc['db_query']('', '
						DELETE FROM {db_prefix}tp_variables 
						WHERE id = {int:item}', array('item' => $what));
                }
            }
            $smcFunc['db_free_result']($request);
        }
    } elseif (substr($admsub, 0, 7) == 'editcat') {
        $context['TPortal']['dl_title'] = '<a href="' . $scripturl . '?action=tpmod;dl=admin">' . $txt['tp-dladmin'] . '</a>';
        $cat = substr($admsub, 7);
        // edit category
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} 
			AND type = {string:type} LIMIT 1', array('item' => $cat, 'type' => 'dlcat'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['admcats'][] = array('id' => $row['id'], 'name' => $row['name'], 'access' => $row['access'], 'shortname' => $row['link'], 'description' => $row['description'], 'icon' => $row['icon'], 'parent' => $row['parent']);
            }
            $smcFunc['db_free_result']($request);
        }
        if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
            $context['TPortal']['editor_id'] = 'dladmin_text' . $context['TPortal']['admcats'][0]['id'];
            TP_prebbcbox($context['TPortal']['editor_id'], $context['TPortal']['admcats'][0]['description']);
        }
    } elseif (substr($admsub, 0, 6) == 'delcat') {
        $context['TPortal']['dl_title'] = '<a href="' . $scripturl . '?action=tpmod;dl=admin">' . $txt['tp-dladmin'] . '</a>';
        $cat = substr($admsub, 6);
        // delete category and all item it's in
        $request = $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_dlmanager 
			WHERE type = {string:type}
			AND category = {int:cat}', array('type' => 'dlitem', 'cat' => $cat));
        $request = $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:cat} LIMIT 1', array('cat' => $cat));
        redirectexit('action=tpmod;dl=admin');
    } elseif (substr($admsub, 0, 8) == 'settings') {
        $context['TPortal']['dl_title'] = $txt['tp-dlsettings'];
    } elseif (substr($admsub, 0, 4) == 'item') {
        $item = substr($admsub, 4);
        $request = $smcFunc['db_query']('', '
			SELECT * FROM {db_prefix}tp_dlmanager 
			WHERE id = {int:item} 
			AND type = {string:type} LIMIT 1', array('item' => $item, 'type' => 'dlitem'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            // is it actually a subitem?
            if ($row['subitem'] > 0) {
                redirectexit('action=tpmod;dl=adminitem' . $row['subitem']);
            }
            // Add in BBC editor before we call in template so the headers are there
            if ($context['TPortal']['dl_wysiwyg'] == 'bbc') {
                $context['TPortal']['editor_id'] = 'dladmin_text' . $item;
                TP_prebbcbox($context['TPortal']['editor_id'], $row['description']);
            }
            // get all items for a list
            $context['TPortal']['admitems'] = array();
            $itemlist = $smcFunc['db_query']('', '
				SELECT id, name FROM {db_prefix}tp_dlmanager 
				WHERE id != {int:item} 
				AND type = {string:type} 
				AND subitem = 0 
				ORDER BY name ASC', array('item' => $item, 'type' => 'dlitem'));
            if ($smcFunc['db_num_rows']($itemlist) > 0) {
                while ($ilist = $smcFunc['db_fetch_assoc']($itemlist)) {
                    $context['TPortal']['admitems'][] = array('id' => $ilist['id'], 'name' => $ilist['name']);
                }
            }
            // Any additional files then..?
            $subitem = $row['id'];
            $fdata = array();
            $fetch = $smcFunc['db_query']('', '
				SELECT id, name, file, downloads, filesize, created
				FROM {db_prefix}tp_dlmanager
				WHERE type = {string:type}
				AND subitem = {int:sub}', array('type' => 'dlitem', 'sub' => $subitem));
            if ($smcFunc['db_num_rows']($fetch) > 0) {
                while ($frow = $smcFunc['db_fetch_assoc']($fetch)) {
                    if ($context['TPortal']['dl_fileprefix'] == 'K') {
                        $ffs = ceil($row['filesize'] / 1000) . ' Kb';
                    } elseif ($context['TPortal']['dl_fileprefix'] == 'M') {
                        $ffs = ceil($row['filesize'] / 1000) / 1000 . ' Mb';
                    } elseif ($context['TPortal']['dl_fileprefix'] == 'G') {
                        $ffs = ceil($row['filesize'] / 1000000) / 1000 . ' Gb';
                    }
                    $fdata[] = array('id' => $frow['id'], 'name' => $frow['name'], 'file' => $frow['file'], 'href' => $scripturl . '?action=tpmod;dl=item' . $frow['id'], 'downloads' => $frow['downloads'], 'created' => $frow['created'], 'filesize' => $ffs);
                }
                $smcFunc['db_free_result']($fetch);
            }
            if (!empty($row['screenshot'])) {
                if (substr($row['screenshot'], 0, 10) == 'tp-images/') {
                    $sshot = $boardurl . '/' . $row['screenshot'];
                } else {
                    $sshot = $boardurl . '/tp-images/dlmanager/listing/' . $row['screenshot'];
                }
            }
            $context['TPortal']['dl_admitems'][] = array('id' => $row['id'], 'name' => $row['name'], 'icon' => $row['icon'], 'category' => $row['category'], 'file' => $row['file'], 'views' => $row['views'], 'authorID' => $row['author_id'], 'description' => $row['description'], 'created' => timeformat($row['created']), 'last_access' => timeformat($row['last_access']), 'filesize' => substr($row['file'], 14) != '- empty item -' ? floor(filesize($boarddir . '/tp-downloads/' . $row['file']) / 1024) : '0', 'downloads' => $row['downloads'], 'sshot' => !empty($sshot) ? $sshot : '', 'screenshot' => $row['screenshot'], 'link' => $row['link'], 'href' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'approved' => $row['category'] < 0 ? '0' : '1', 'approve' => $scripturl . '?action=tpmod;dl=adminitem' . $row['id'], 'subitem' => $fdata);
            $authorID = $row['author_id'];
            $catparent = $row['category'];
            $itemname = $row['name'];
            $smcFunc['db_free_result']($request);
            $request = $smcFunc['db_query']('', '
				SELECT mem.real_name as realName 
				FROM {db_prefix}members as mem 
				WHERE mem.id_member = {int:id_mem}', array('id_mem' => $authorID));
            if ($smcFunc['db_num_rows']($request) > 0) {
                $row = $smcFunc['db_fetch_assoc']($request);
                $context['TPortal']['admcurrent']['member'] = $row['realName'];
                $smcFunc['db_free_result']($request);
            } else {
                $context['TPortal']['admcurrent']['member'] = '-' . $txt['guest_title'] . '-';
            }
        }
        // check to see if its child
        $parents = array();
        while ($catparent > 0) {
            $parents[$catparent] = array('id' => $catparent, 'name' => $context['TPortal']['linkcats'][$catparent]['name'], 'parent' => $context['TPortal']['linkcats'][$catparent]['parent']);
            $catparent = $context['TPortal']['linkcats'][$catparent]['parent'];
        }
        // make the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=admin', $txt['tp-dldownloads']);
        if (isset($parents)) {
            $parts = array_reverse($parents, TRUE);
            // add to the linktree
            foreach ($parts as $parent) {
                TPadd_linktree($scripturl . '?action=tpmod;dl=admincat' . $parent['id'], $parent['name']);
            }
        }
        // add to the linktree
        TPadd_linktree($scripturl . '?action=tpmod;dl=adminitem' . $item, $itemname);
    }
    loadTemplate('TPdladmin');
    if (loadLanguage('TPmodules') == false) {
        loadLanguage('TPmodules', 'english');
    }
    if (loadLanguage('TPortalAdmin') == false) {
        loadLanguage('TPortalAdmin', 'english');
    }
    // setup admin tabs according to subaction
    $context['admin_area'] = 'tp_dlmanager';
    $context['admin_tabs'] = array('title' => $txt['tp-dlheader1'], 'help' => $txt['tp-dlheader2'], 'description' => $txt['tp-dlheader3'], 'tabs' => array());
    if (allowedTo('tp_dlmanager')) {
        $context['TPortal']['subtabs'] = array('admin' => array('text' => 'tp-dltabs4', 'url' => $scripturl . '?action=tpmod;dl=admin', 'active' => substr($context['TPortal']['dlsub'], 0, 5) == 'admin' && $context['TPortal']['dlsub'] != 'adminsettings' && $context['TPortal']['dlsub'] != 'adminaddcat' && $context['TPortal']['dlsub'] != 'adminftp' && $context['TPortal']['dlsub'] != 'adminsubmission'), 'settings' => array('text' => 'tp-dltabs1', 'url' => $scripturl . '?action=tpmod;dl=adminsettings', 'active' => $context['TPortal']['dlsub'] == 'adminsettings'), 'addcategory' => array('text' => 'tp-dltabs2', 'url' => $scripturl . '?action=tpmod;dl=adminaddcat', 'active' => $context['TPortal']['dlsub'] == 'adminaddcat'), 'upload' => array('text' => 'tp-dltabs3', 'url' => $scripturl . '?action=tpmod;dl=upload', 'active' => $context['TPortal']['dlsub'] == 'upload'), 'submissions' => array('text' => 'tp-dlsubmissions', 'url' => $scripturl . '?action=tpmod;dl=adminsubmission', 'active' => $context['TPortal']['dlsub'] == 'adminsubmission'), 'ftp' => array('text' => 'tp-dlftp', 'url' => $scripturl . '?action=tpmod;dl=adminftp', 'active' => $context['TPortal']['dlsub'] == 'adminftp'));
    }
    $context['template_layers'][] = 'tpadm';
    $context['template_layers'][] = 'subtab';
    TPadminIndex('');
    $context['current_action'] = 'admin';
}
function sportal_admin_page_edit()
{
    global $txt, $context, $modSettings, $smcFunc, $sourcedir, $options;
    require_once $sourcedir . '/Subs-Editor.php';
    require_once $sourcedir . '/Subs-Post.php';
    $context['SPortal']['is_new'] = empty($_REQUEST['page_id']);
    if (!empty($_REQUEST['content_mode']) && $_POST['type'] == 'bbc') {
        $_REQUEST['content'] = html_to_bbc($_REQUEST['content']);
        $_REQUEST['content'] = un_htmlspecialchars($_REQUEST['content']);
        $_POST['content'] = $_REQUEST['content'];
    }
    $context['sides'] = array(5 => $txt['sp-positionHeader'], 1 => $txt['sp-positionLeft'], 2 => $txt['sp-positionTop'], 3 => $txt['sp-positionBottom'], 4 => $txt['sp-positionRight'], 6 => $txt['sp-positionFooter']);
    $blocks = getBlockInfo();
    $context['page_blocks'] = array();
    foreach ($blocks as $block) {
        $shown = false;
        $tests = array('all', 'allpages', 'sforum');
        if (!$context['SPortal']['is_new']) {
            $tests[] = 'p' . (int) $_REQUEST['page_id'];
        }
        foreach (array('display', 'display_custom') as $field) {
            if (substr($block[$field], 0, 4) === '$php') {
                continue 2;
            }
            $block[$field] = explode(',', $block[$field]);
            if (!$context['SPortal']['is_new'] && in_array('-p' . (int) $_REQUEST['page_id'], $block[$field])) {
                continue;
            }
            foreach ($tests as $test) {
                if (in_array($test, $block[$field])) {
                    $shown = true;
                    break;
                }
            }
        }
        $context['page_blocks'][$block['column']][] = array('id' => $block['id'], 'label' => $block['label'], 'shown' => $shown);
    }
    if (!empty($_POST['submit'])) {
        checkSession();
        if (!isset($_POST['title']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES)) === '') {
            fatal_lang_error('sp_error_page_name_empty', false);
        }
        if (!isset($_POST['namespace']) || $smcFunc['htmltrim']($smcFunc['htmlspecialchars']($_POST['namespace'], ENT_QUOTES)) === '') {
            fatal_lang_error('sp_error_page_namespace_empty', false);
        }
        $result = $smcFunc['db_query']('', '
			SELECT id_page
			FROM {db_prefix}sp_pages
			WHERE namespace = {string:namespace}
				AND id_page != {int:current}
			LIMIT 1', array('limit' => 1, 'namespace' => $smcFunc['htmlspecialchars']($_POST['namespace'], ENT_QUOTES), 'current' => (int) $_POST['page_id']));
        list($has_duplicate) = $smcFunc['db_fetch_row']($result);
        $smcFunc['db_free_result']($result);
        if (!empty($has_duplicate)) {
            fatal_lang_error('sp_error_page_namespace_duplicate', false);
        }
        if (preg_match('~[^A-Za-z0-9_]+~', $_POST['namespace']) != 0) {
            fatal_lang_error('sp_error_page_namespace_invalid_chars', false);
        }
        if (preg_replace('~[0-9]+~', '', $_POST['namespace']) === '') {
            fatal_lang_error('sp_error_page_namespace_numeric', false);
        }
        if ($_POST['type'] == 'php' && !empty($_POST['content']) && empty($modSettings['sp_disable_php_validation'])) {
            $error = sp_validate_php($_POST['content']);
            if ($error) {
                fatal_lang_error('error_sp_php_' . $error, false);
            }
        }
        $permission_set = 0;
        $groups_allowed = $groups_denied = '';
        if (!empty($_POST['permission_set'])) {
            $permission_set = (int) $_POST['permission_set'];
        } elseif (!empty($_POST['membergroups']) && is_array($_POST['membergroups'])) {
            $groups_allowed = $groups_denied = array();
            foreach ($_POST['membergroups'] as $id => $value) {
                if ($value == 1) {
                    $groups_allowed[] = (int) $id;
                } elseif ($value == -1) {
                    $groups_denied[] = (int) $id;
                }
            }
            $groups_allowed = implode(',', $groups_allowed);
            $groups_denied = implode(',', $groups_denied);
        }
        if (!empty($_POST['blocks']) && is_array($_POST['blocks'])) {
            foreach ($_POST['blocks'] as $id => $block) {
                $_POST['blocks'][$id] = (int) $block;
            }
        } else {
            $_POST['blocks'] = array();
        }
        $fields = array('namespace' => 'string', 'title' => 'string', 'body' => 'string', 'type' => 'string', 'permission_set' => 'int', 'groups_allowed' => 'string', 'groups_denied' => 'string', 'style' => 'string', 'status' => 'int');
        $page_info = array('id' => (int) $_POST['page_id'], 'namespace' => $smcFunc['htmlspecialchars']($_POST['namespace'], ENT_QUOTES), 'title' => $smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES), 'body' => $smcFunc['htmlspecialchars']($_POST['content'], ENT_QUOTES), 'type' => $_POST['type'], 'permission_set' => $permission_set, 'groups_allowed' => $groups_allowed, 'groups_denied' => $groups_denied, 'style' => sportal_parse_style('implode'), 'status' => !empty($_POST['status']) ? 1 : 0);
        if ($page_info['type'] == 'bbc') {
            preparsecode($page_info['body']);
        }
        if ($context['SPortal']['is_new']) {
            unset($page_info['id']);
            $smcFunc['db_insert']('', '{db_prefix}sp_pages', $fields, $page_info, array('id_page'));
            $page_info['id'] = $smcFunc['db_insert_id']('{db_prefix}sp_pages', 'id_page');
        } else {
            $update_fields = array();
            foreach ($fields as $name => $type) {
                $update_fields[] = $name . ' = {' . $type . ':' . $name . '}';
            }
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}sp_pages
				SET ' . implode(', ', $update_fields) . '
				WHERE id_page = {int:id}', $page_info);
        }
        $to_show = array();
        $not_to_show = array();
        $changes = array();
        foreach ($context['page_blocks'] as $page_blocks) {
            foreach ($page_blocks as $block) {
                if ($block['shown'] && !in_array($block['id'], $_POST['blocks'])) {
                    $not_to_show[] = $block['id'];
                } elseif (!$block['shown'] && in_array($block['id'], $_POST['blocks'])) {
                    $to_show[] = $block['id'];
                }
            }
        }
        foreach ($to_show as $id) {
            if (empty($blocks[$id]['display']) && empty($blocks[$id]['display_custom']) || $blocks[$id]['display'] == 'sportal') {
                $changes[$id] = array('display' => 'portal,p' . $page_info['id'], 'display_custom' => '');
            } elseif (in_array($blocks[$id]['display'], array('allaction', 'allboard'))) {
                $changes[$id] = array('display' => '', 'display_custom' => $blocks[$id]['display'] . ',p' . $page_info['id']);
            } elseif (in_array('-p' . $page_info['id'], explode(',', $blocks[$id]['display_custom']))) {
                $changes[$id] = array('display' => $blocks[$id]['display'], 'display_custom' => implode(',', array_diff(explode(',', $blocks[$id]['display_custom']), array('-p' . $page_info['id']))));
            } elseif (empty($blocks[$id]['display_custom'])) {
                $changes[$id] = array('display' => implode(',', array_merge(explode(',', $blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => '');
            } else {
                $changes[$id] = array('display' => $blocks[$id]['display'], 'display_custom' => implode(',', array_merge(explode(',', $blocks[$id]['display_custom']), array('p' . $page_info['id']))));
            }
        }
        foreach ($not_to_show as $id) {
            if (count(array_intersect(array($blocks[$id]['display'], $blocks[$id]['display_custom']), array('sforum', 'allpages', 'all'))) > 0) {
                $changes[$id] = array('display' => '', 'display_custom' => $blocks[$id]['display'] . $blocks[$id]['display_custom'] . ',-p' . $page_info['id']);
            } elseif (empty($blocks[$id]['display_custom'])) {
                $changes[$id] = array('display' => implode(',', array_diff(explode(',', $blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => '');
            } else {
                $changes[$id] = array('display' => implode(',', array_diff(explode(',', $blocks[$id]['display']), array('p' . $page_info['id']))), 'display_custom' => implode(',', array_diff(explode(',', $blocks[$id]['display_custom']), array('p' . $page_info['id']))));
            }
        }
        foreach ($changes as $id => $data) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}sp_blocks
				SET
					display = {string:display},
					display_custom = {string:display_custom}
				WHERE id_block = {int:id}', array('id' => $id, 'display' => $data['display'], 'display_custom' => $data['display_custom']));
        }
        redirectexit('action=admin;area=portalpages');
    }
    if (!empty($_POST['preview'])) {
        $permission_set = 0;
        $groups_allowed = $groups_denied = array();
        if (!empty($_POST['permission_set'])) {
            $permission_set = (int) $_POST['permission_set'];
        } elseif (!empty($_POST['membergroups']) && is_array($_POST['membergroups'])) {
            foreach ($_POST['membergroups'] as $id => $value) {
                if ($value == 1) {
                    $groups_allowed[] = (int) $id;
                } elseif ($value == -1) {
                    $groups_denied[] = (int) $id;
                }
            }
        }
        $context['SPortal']['page'] = array('id' => $_POST['page_id'], 'page_id' => $_POST['namespace'], 'title' => $smcFunc['htmlspecialchars']($_POST['title'], ENT_QUOTES), 'body' => $smcFunc['htmlspecialchars']($_POST['content'], ENT_QUOTES), 'type' => $_POST['type'], 'permission_set' => $permission_set, 'groups_allowed' => $groups_allowed, 'groups_denied' => $groups_denied, 'style' => sportal_parse_style('implode'), 'status' => !empty($_POST['status']));
        if ($context['SPortal']['page']['type'] == 'bbc') {
            preparsecode($context['SPortal']['page']['body']);
        }
        loadTemplate('PortalPages');
        $context['SPortal']['preview'] = true;
    } elseif ($context['SPortal']['is_new']) {
        $context['SPortal']['page'] = array('id' => 0, 'page_id' => 'page' . mt_rand(1, 5000), 'title' => $txt['sp_pages_default_title'], 'body' => '', 'type' => 'bbc', 'permission_set' => 3, 'groups_allowed' => array(), 'groups_denied' => array(), 'style' => '', 'status' => 1);
    } else {
        $_REQUEST['page_id'] = (int) $_REQUEST['page_id'];
        $context['SPortal']['page'] = sportal_get_pages($_REQUEST['page_id']);
    }
    if ($context['SPortal']['page']['type'] == 'bbc') {
        $context['SPortal']['page']['body'] = str_replace(array('"', '<', '>', '&nbsp;'), array('&quot;', '&lt;', '&gt;', ' '), un_preparsecode($context['SPortal']['page']['body']));
    }
    if ($context['SPortal']['page']['type'] != 'bbc') {
        $temp_editor = !empty($options['wysiwyg_default']);
        $options['wysiwyg_default'] = false;
    }
    $editorOptions = array('id' => 'content', 'value' => $context['SPortal']['page']['body'], 'width' => '95%', 'height' => '200px', 'preview_type' => 0);
    create_control_richedit($editorOptions);
    $context['post_box_name'] = $editorOptions['id'];
    if (isset($temp_editor)) {
        $options['wysiwyg_default'] = $temp_editor;
    }
    $context['SPortal']['page']['groups'] = sp_load_membergroups();
    $context['SPortal']['page']['style'] = sportal_parse_style('explode', $context['SPortal']['page']['style'], !empty($context['SPortal']['preview']));
    $context['page_title'] = $context['SPortal']['is_new'] ? $txt['sp_admin_pages_add'] : $txt['sp_admin_pages_edit'];
    $context['sub_template'] = 'pages_edit';
}
Example #30
0
function text2words($text, $max_chars = 20, $encrypt = false)
{
    global $smcFunc, $context;
    // Step 1: Remove entities/things we don't consider words:
    $words = preg_replace('~(?:[\\x0B\\0' . ($context['utf8'] ? $context['server']['complex_preg_chars'] ? '\\x{A0}' : " " : '\\xA0') . '\\t\\r\\s\\n(){}\\[\\]<>!@$%^*.,:+=`\\~\\?/\\\\]+|&(?:amp|lt|gt|quot);)+~' . ($context['utf8'] ? 'u' : ''), ' ', strtr($text, array('<br />' => ' ')));
    // Step 2: Entities we left to letters, where applicable, lowercase.
    $words = un_htmlspecialchars($smcFunc['strtolower']($words));
    // Step 3: Ready to split apart and index!
    $words = explode(' ', $words);
    if ($encrypt) {
        $possible_chars = array_flip(array_merge(range(46, 57), range(65, 90), range(97, 122)));
        $returned_ints = array();
        foreach ($words as $word) {
            if (($word = trim($word, '-_\'')) !== '') {
                $encrypted = substr(crypt($word, 'uk'), 2, $max_chars);
                $total = 0;
                for ($i = 0; $i < $max_chars; $i++) {
                    $total += $possible_chars[ord($encrypted[$i])] * pow(63, $i);
                }
                $returned_ints[] = $max_chars == 4 ? min($total, 16777215) : $total;
            }
        }
        return array_unique($returned_ints);
    } else {
        // Trim characters before and after and add slashes for database insertion.
        $returned_words = array();
        foreach ($words as $word) {
            if (($word = trim($word, '-_\'')) !== '') {
                $returned_words[] = $max_chars === null ? $word : substr($word, 0, $max_chars);
            }
        }
        // Filter out all words that occur more than once.
        return array_unique($returned_words);
    }
}