/**
 *	Display all the custom fields, including new/edit/save/delete UI hooks
 *
 *	@since 2.0
*/
function shd_admin_custom_main()
{
    global $context, $smcFunc, $modSettings, $txt;
    $context['custom_fields'] = array();
    $query = shd_db_query('', '
		SELECT id_field, active, field_order, field_name, field_desc, field_loc, icon, field_type, can_see, can_edit
		FROM {db_prefix}helpdesk_custom_fields
		ORDER BY field_order', array());
    while ($row = $smcFunc['db_fetch_assoc']($query)) {
        $row['active_string'] = empty($row['active']) ? 'inactive' : 'active';
        $row['field_type'] = $context['field_types'][$row['field_type']][1];
        // convert the integer in the DB into the string for language + image uses
        $row['can_see'] = explode(',', $row['can_see']);
        $row['can_edit'] = explode(',', $row['can_edit']);
        $row['field_desc'] = parse_bbc($row['field_desc'], false);
        $context['custom_fields'][] = $row;
    }
    if (!empty($context['custom_fields'])) {
        $context['custom_fields'][0]['is_first'] = true;
        $context['custom_fields'][count($context['custom_fields']) - 1]['is_last'] = true;
    }
    // Final stuff before we go.
    $context['page_title'] = $txt['shd_admin_custom_fields'];
    $context['sub_template'] = 'shd_custom_field_home';
}
Example #2
0
function getLastPost()
{
    global $scripturl, $modSettings, $board;
    // Find it by the board - better to order by board than sort the entire messages table.
    $request = smf_db_query('
		SELECT ml.poster_time, ml.subject, ml.id_topic, ml.poster_name, ml.body, ml.id_msg, b.id_board,
			ml.smileys_enabled
		FROM {db_prefix}boards AS b
			INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = b.id_last_msg)
		WHERE {query_wanna_see_board}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . '
			AND ml.approved = {int:is_approved}
		ORDER BY b.id_msg_updated DESC
		LIMIT 1', array('recycle_board' => $modSettings['recycle_board'], 'is_approved' => 1));
    if (mysql_num_rows($request) == 0) {
        return array();
    }
    $row = mysql_fetch_assoc($request);
    mysql_free_result($request);
    $board = $row['id_board'];
    // Censor the subject and post...
    censorText($row['subject']);
    censorText($row['body']);
    $row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled']), array('<br />' => '&#10;')));
    parse_bbc_stage2($row['body'], $row['id_msg']);
    if (commonAPI::strlen($row['body']) > 128) {
        $row['body'] = commonAPI::substr($row['body'], 0, 128) . '...';
    }
    // Send the data.
    return array('topic' => $row['id_topic'], 'subject' => $row['subject'], 'short_subject' => shorten_subject($row['subject'], 35), 'preview' => $row['body'], 'time' => timeformat($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new', 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.new;topicseen#new">' . $row['subject'] . '</a>');
}
Example #3
0
function PrintTopic()
{
    global $db_prefix, $topic, $txt, $scripturl, $context;
    global $board_info;
    if (empty($topic)) {
        fatal_lang_error(472, false);
    }
    // Get the topic starter information.
    $request = db_query("\n\t\tSELECT m.posterTime, IFNULL(mem.realName, m.posterName) AS posterName\n\t\tFROM {$db_prefix}messages AS m\n\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = m.ID_MEMBER)\n\t\tWHERE m.ID_TOPIC = {$topic}\n\t\tORDER BY ID_MSG\n\t\tLIMIT 1", __FILE__, __LINE__);
    if (mysql_num_rows($request) == 0) {
        fatal_lang_error('smf232');
    }
    $row = mysql_fetch_assoc($request);
    mysql_free_result($request);
    // Lets "output" all that info.
    loadTemplate('Printpage');
    $context['template_layers'] = array('print');
    $context['board_name'] = $board_info['name'];
    $context['category_name'] = $board_info['cat']['name'];
    $context['poster_name'] = $row['posterName'];
    $context['post_time'] = timeformat($row['posterTime'], false);
    // Split the topics up so we can print them.
    $request = db_query("\n\t\tSELECT subject, posterTime, body, IFNULL(mem.realName, posterName) AS posterName\n\t\tFROM {$db_prefix}messages AS m\n\t\t\tLEFT JOIN {$db_prefix}members AS mem ON (mem.ID_MEMBER = m.ID_MEMBER)\n\t\tWHERE ID_TOPIC = {$topic}\n\t\tORDER BY ID_MSG", __FILE__, __LINE__);
    $context['posts'] = array();
    while ($row = mysql_fetch_assoc($request)) {
        // Censor the subject and message.
        censorText($row['subject']);
        censorText($row['body']);
        $context['posts'][] = array('subject' => $row['subject'], 'member' => $row['posterName'], 'time' => timeformat($row['posterTime'], false), 'timestamp' => forum_time(true, $row['posterTime']), 'body' => parse_bbc($row['body'], 'print'));
        if (!isset($context['topic_subject'])) {
            $context['topic_subject'] = $row['subject'];
        }
    }
    mysql_free_result($request);
}
 public function Format($String)
 {
     try {
         $Result = parse_bbc($String);
     } catch (Exception $Ex) {
         $Result = '<!-- Error: ' . htmlspecialchars($Ex->getMessage()) . '-->' . Gdn_Format::Display($String);
     }
     return $Result;
 }
function PrintTopic()
{
    global $topic, $txt, $scripturl, $context, $user_info;
    global $board_info, $smcFunc, $modSettings;
    // Redirect to the boardindex if no valid topic id is provided.
    if (empty($topic)) {
        redirectexit();
    }
    // Whatever happens don't index this.
    $context['robot_no_index'] = true;
    // Get the topic starter information.
    $request = $smcFunc['db_query']('', '
		SELECT m.poster_time, IFNULL(mem.real_name, m.poster_name) AS poster_name
		FROM {db_prefix}messages AS m
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
		WHERE m.id_topic = {int:current_topic}
		ORDER BY m.id_msg
		LIMIT 1', array('current_topic' => $topic));
    // Redirect to the boardindex if no valid topic id is provided.
    if ($smcFunc['db_num_rows']($request) == 0) {
        redirectexit();
    }
    $row = $smcFunc['db_fetch_assoc']($request);
    $smcFunc['db_free_result']($request);
    // Lets "output" all that info.
    loadTemplate('Printpage');
    $context['template_layers'] = array('print');
    $context['board_name'] = $board_info['name'];
    $context['category_name'] = $board_info['cat']['name'];
    $context['poster_name'] = $row['poster_name'];
    $context['post_time'] = timeformat($row['poster_time'], false);
    $context['parent_boards'] = array();
    foreach ($board_info['parent_boards'] as $parent) {
        $context['parent_boards'][] = $parent['name'];
    }
    // Split the topics up so we can print them.
    $request = $smcFunc['db_query']('', '
		SELECT subject, poster_time, body, IFNULL(mem.real_name, poster_name) AS poster_name
		FROM {db_prefix}messages AS m
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
		WHERE m.id_topic = {int:current_topic}' . ($modSettings['postmod_active'] && !allowedTo('approve_posts') ? '
			AND (m.approved = {int:is_approved}' . ($user_info['is_guest'] ? '' : ' OR m.id_member = {int:current_member}') . ')' : '') . '
		ORDER BY m.id_msg', array('current_topic' => $topic, 'is_approved' => 1, 'current_member' => $user_info['id']));
    $context['posts'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        // Censor the subject and message.
        censorText($row['subject']);
        censorText($row['body']);
        $context['posts'][] = array('subject' => $row['subject'], 'member' => $row['poster_name'], 'time' => timeformat($row['poster_time'], false), 'timestamp' => forum_time(true, $row['poster_time']), 'body' => parse_bbc($row['body'], 'print'));
        if (!isset($context['topic_subject'])) {
            $context['topic_subject'] = $row['subject'];
        }
    }
    $smcFunc['db_free_result']($request);
    // Set a canonical URL for this page.
    $context['canonical_url'] = $scripturl . '?topic=' . $topic . '.0';
}
Example #6
0
 /**
  * Convert bbCode into HTML
  */
 function formatBBCode($text, $smileys = true)
 {
     // We doing this the SMF way?
     if ($this->config['Core']['Auth'] == 'SMF') {
         require_once $this->config['Path']['Auth_Local'] . 'Sources/Subs.php';
         return parse_bbc($text, $smileys);
     } else {
         // We don't HAVE bbcode, bitch!
         return $text;
     }
 }
Example #7
0
/**
 * Prepares an array of the forum news items
 *
 * @package News
 * @return array
 */
function getNews()
{
    global $modSettings;
    $admin_current_news = array();
    // Ready the current news.
    foreach (explode("\n", $modSettings['news']) as $id => $line) {
        $admin_current_news[$id] = array('id' => $id, 'unparsed' => un_preparsecode($line), 'parsed' => preg_replace('~<([/]?)form[^>]*?[>]*>~i', '<em class="smalltext">&lt;$1form&gt;</em>', parse_bbc($line)));
    }
    $admin_current_news['last'] = array('id' => 'last', 'unparsed' => '', 'parsed' => '<div id="moreNewsItems_preview"></div>');
    return $admin_current_news;
}
Example #8
0
function getLastPosts($latestPostOptions)
{
    global $scripturl, $txt, $user_info, $modSettings, $smcFunc, $context;
    // Find all the posts.  Newer ones will have higher IDs.  (assuming the last 20 * number are accessable...)
    // !!!SLOW This query is now slow, NEEDS to be fixed.  Maybe break into two?
    $request = $smcFunc['db_query']('substring', '
		SELECT
			m.poster_time, m.subject, m.id_topic, m.id_member, m.id_msg,
			IFNULL(mem.real_name, m.poster_name) AS poster_name, t.id_board, b.name AS board_name,
			SUBSTRING(m.body, 1, 385) AS body, m.smileys_enabled
		FROM {db_prefix}messages AS m
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
		WHERE m.id_msg >= {int:likely_max_msg}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . '
			AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
			AND t.approved = {int:is_approved}
			AND m.approved = {int:is_approved}' : '') . '
		ORDER BY m.id_msg DESC
		LIMIT ' . $latestPostOptions['number_posts'], array('likely_max_msg' => max(0, $modSettings['maxMsgID'] - 50 * $latestPostOptions['number_posts']), 'recycle_board' => $modSettings['recycle_board'], 'is_approved' => 1));
    $posts = array();
    $context['MemberColor_ID_MEMBER'] = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        // Censor the subject and post for the preview ;).
        censorText($row['subject']);
        censorText($row['body']);
        $row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br />' => '&#10;')));
        if ($smcFunc['strlen']($row['body']) > 128) {
            $row['body'] = $smcFunc['substr']($row['body'], 0, 128) . '...';
        }
        // Build the array.
        $posts[] = array('board' => array('id' => $row['id_board'], 'name' => $row['board_name'], 'href' => $scripturl . '?board=' . $row['id_board'] . '.0', 'link' => '<a href="' . $scripturl . '?board=' . $row['id_board'] . '.0">' . $row['board_name'] . '</a>'), 'topic' => $row['id_topic'], 'poster' => array('id' => $row['id_member'], 'name' => $row['poster_name'], 'href' => empty($row['id_member']) ? '' : $scripturl . '?action=profile;u=' . $row['id_member'], 'link' => empty($row['id_member']) ? (!empty($modSettings['MemberColorGuests']) ? '<span style="color:' . $modSettings['MemberColorGuests'] . ';">' : '') . $row['poster_name'] . (!empty($modSettings['MemberColorGuests']) ? '</span>' : '') : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '" title="' . $txt['profile_of'] . ' ' . $row['poster_name'] . '">' . $row['poster_name'] . '</a>'), 'subject' => $row['subject'], 'short_subject' => shorten_subject($row['subject'], 24), 'preview' => $row['body'], 'time' => timeformat($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'raw_timestamp' => $row['poster_time'], 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#msg' . $row['id_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.msg' . $row['id_msg'] . ';topicseen#msg' . $row['id_msg'] . '" rel="nofollow">' . $row['subject'] . '</a>');
        //The Last Posters id for the MemberColor.
        if (!empty($modSettings['MemberColorRecentLastPost']) && !empty($row['id_member'])) {
            $context['MemberColor_ID_MEMBER'][$row['id_member']] = $row['id_member'];
        }
    }
    $smcFunc['db_free_result']($request);
    // Know set the colors for the Recent posts...
    if (!empty($context['MemberColor_ID_MEMBER'])) {
        $colorDatas = load_onlineColors($context['MemberColor_ID_MEMBER']);
        //So Let's Color The Recent Posts ;)
        if (!empty($modSettings['MemberColorRecentLastPost']) && is_array($posts)) {
            foreach ($posts as $postkey => $postid_memcolor) {
                if (!empty($colorDatas[$postid_memcolor['poster']['id']]['colored_link'])) {
                    $posts[$postkey]['poster']['link'] = $colorDatas[$postid_memcolor['poster']['id']]['colored_link'];
                }
            }
        }
    }
    return $posts;
}
    /**
     * InitContent.
     * Checks the autocache and create the content if necessary.
     */
    function pmxc_InitContent()
    {
        global $smcFunc, $context, $user_info, $scripturl, $txt;
        if ($this->visible) {
            $this->download_content = parse_bbc($this->cfg['content']);
            if (isset($this->cfg['config']['settings']['download_board']) && !empty($this->cfg['config']['settings']['download_board'])) {
                // get downloads for board
                $request = $smcFunc['db_query']('', '
						SELECT a.id_attach, a.size, a.downloads, t.id_topic, t.locked, m.subject, m.body
						FROM {db_prefix}attachments a
						LEFT JOIN {db_prefix}messages m ON (a.id_msg = m.id_msg)
						LEFT JOIN {db_prefix}topics t ON (m.id_topic = t.id_topic)
						WHERE m.id_board = {int:board} AND a.mime_type NOT LIKE {string:likestr} AND t.locked = 0', array('board' => $this->cfg['config']['settings']['download_board'], 'likestr' => 'IMAGE%'));
                $dlacs = implode('=1,', $this->cfg['config']['settings']['download_acs']);
                $entrys = $smcFunc['db_num_rows']($request);
                if ($entrys > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $this->download_content .= '
						<div style="text-align:left;">';
                        if (allowPmxGroup($dlacs)) {
                            $this->download_content .= '
							<a href="' . $scripturl . '?action=dlattach;id=' . $row['id_attach'] . ';fld=' . $this->cfg['id'] . '">
								<img style="vertical-align:middle;" src="' . $context['pmx_imageurl'] . 'download.png" alt="*" title="' . (empty($row['file_order']) ? $row['subject'] : substr($row['subject'], 4)) . '" /></a>';
                        }
                        if ($user_info['is_admin']) {
                            $this->download_content .= '
							<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '">
								<strong>' . (empty($row['file_order']) ? $row['subject'] : substr($row['subject'], 4)) . '</strong>
							</a>';
                        } else {
                            $this->download_content .= '
							<strong>' . (empty($row['file_order']) ? $row['subject'] : substr($row['subject'], 4)) . '</strong>';
                        }
                        $this->download_content .= '
							<div class="dlcomment">' . parse_bbc(trim($row['body'])) . '</div>
							<b>[' . round($row['size'] / 1000, 3) . '</b> ' . $txt['pmx_kb_downloads'] . '<b>' . $row['downloads'] . '</b>]
						</div>' . ($entrys > 1 ? '<hr class="pmx_hr" />' : '');
                        $entrys--;
                    }
                    $smcFunc['db_free_result']($request);
                } else {
                    $this->download_content .= '<br />' . $txt['pmx_download_empty'];
                }
            } else {
                $this->download_content .= '<br />' . $txt['pmx_download_empty'];
            }
        }
        // return the visibility flag (true/false)
        return $this->visible;
    }
Example #10
0
 /**
  * testBBcode, parse bbcode and checks that the results are what we expect
  */
 public function testBBcode()
 {
     foreach ($this->bbcTestCases as $testcase) {
         $name = $testcase[0];
         $test = $testcase[1];
         $expected = $testcase[2];
         $result = parse_bbc($test);
         $this->assertEqual($expected, $result);
     }
     foreach ($this->bbcInvalidTestCases as $testcase) {
         $name = $testcase[0];
         $test = $testcase[1];
         $result = parse_bbc($test);
         $this->assertEqual($test, $result);
     }
 }
    /**
     * ShowContent
     */
    function pmxc_ShowContent()
    {
        global $context, $txt;
        if (!empty($this->cfg['config']['settings']['printing'])) {
            $printdir = 'ltr';
            $printChars = $context['character_set'];
            echo '
			<img class="pmx_printimg" src="' . $context['pmx_imageurl'] . 'Print.png" alt="Print" title="' . $txt['pmx_text_printing'] . '" onclick="PmxPrintPage(\'' . $printdir . '\', \'' . $this->cfg['id'] . '\', \'' . $printChars . '\', \'' . $this->getUserTitle() . '\')" />
			<div id="print' . $this->cfg['id'] . '">';
        }
        // Write out bbc parsed content
        echo '
			' . PortaMx_BBCsmileys(parse_bbc($this->cfg['content'], false), $this->cfg['config']['settings']['disableHSimg']);
        if (!empty($this->cfg['config']['settings']['printing'])) {
            echo '
			</div>';
        }
    }
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 #13
0
    /**
     * Administration page in Posts and Topics > BBC.
     *
     * - This method handles displaying and changing which BBC tags are enabled on the forum.
     *
     * @uses Admin template, edit_bbc_settings sub-template.
     */
    public function action_bbcSettings_display()
    {
        global $context, $txt, $modSettings, $scripturl;
        // Initialize the form
        $this->_initBBCSettingsForm();
        $config_vars = $this->_bbcSettings->settings();
        // Make sure a nifty javascript will enable/disable checkboxes, according to BBC globally set or not.
        addInlineJavascript('
			toggleBBCDisabled(\'disabledBBC\', ' . (empty($modSettings['enableBBC']) ? 'true' : 'false') . ');', true);
        // We'll need this forprepare_db() and save_db()
        require_once SUBSDIR . '/SettingsForm.class.php';
        // Make sure we check the right tags!
        $modSettings['bbc_disabled_disabledBBC'] = empty($modSettings['disabledBBC']) ? array() : explode(',', $modSettings['disabledBBC']);
        // Save page
        if (isset($_GET['save'])) {
            checkSession();
            // Security: make a pass through all tags and fix them as necessary
            $bbcTags = array();
            foreach (parse_bbc(false) as $tag) {
                $bbcTags[] = $tag['tag'];
            }
            if (!isset($_POST['disabledBBC_enabledTags'])) {
                $_POST['disabledBBC_enabledTags'] = array();
            } elseif (!is_array($_POST['disabledBBC_enabledTags'])) {
                $_POST['disabledBBC_enabledTags'] = array($_POST['disabledBBC_enabledTags']);
            }
            // Work out what is actually disabled!
            $_POST['disabledBBC'] = implode(',', array_diff($bbcTags, $_POST['disabledBBC_enabledTags']));
            // Notify addons and integrations
            call_integration_hook('integrate_save_bbc_settings', array($bbcTags));
            // Save the result
            Settings_Form::save_db($config_vars);
            // And we're out of here!
            redirectexit('action=admin;area=postsettings;sa=bbc');
        }
        // Make sure the template stuff is ready now...
        $context['sub_template'] = 'show_settings';
        $context['page_title'] = $txt['manageposts_bbc_settings_title'];
        $context['post_url'] = $scripturl . '?action=admin;area=postsettings;save;sa=bbc';
        $context['settings_title'] = $txt['manageposts_bbc_settings_title'];
        Settings_Form::prepare_db($config_vars);
    }
Example #14
0
function getLastPosts($latestPostOptions)
{
    global $scripturl, $txt, $user_info, $modSettings, $smcFunc, $context;
    // Find all the posts.  Newer ones will have higher IDs.  (assuming the last 20 * number are accessable...)
    // !!!SLOW This query is now slow, NEEDS to be fixed.  Maybe break into two?
    $request = smf_db_query('
		SELECT
			m.poster_time, m.subject, m.id_topic, m.id_member, m.id_msg, b.name, m1.subject AS first_subject,
			IFNULL(mem.real_name, m.poster_name) AS poster_name, t.id_board, b.name AS board_name,
			SUBSTRING(m.body, 1, 385) AS body, m.smileys_enabled
		FROM {db_prefix}messages AS m
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
			INNER JOIN {db_prefix}messages AS m1 ON (m1.id_msg = t.id_first_msg)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
		WHERE m.id_msg >= {int:likely_max_msg}' . (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
			AND b.id_board != {int:recycle_board}' : '') . '
			AND {query_wanna_see_board}' . ($modSettings['postmod_active'] ? '
			AND t.approved = {int:is_approved}
			AND m.approved = {int:is_approved}' : '') . '
		ORDER BY m.id_msg DESC
		LIMIT ' . $latestPostOptions['number_posts'], array('likely_max_msg' => max(0, $modSettings['maxMsgID'] - 50 * $latestPostOptions['number_posts']), 'recycle_board' => $modSettings['recycle_board'], 'is_approved' => 1));
    $posts = array();
    while ($row = mysql_fetch_assoc($request)) {
        // Censor the subject and post for the preview ;).
        censorText($row['subject']);
        censorText($row['body']);
        $row['body'] = strip_tags(strtr(parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']), array('<br />' => '&#10;')));
        if (commonAPI::strlen($row['body']) > 128) {
            $row['body'] = commonAPI::substr($row['body'], 0, 128) . '...';
        }
        $bhref = URL::board($row['id_board'], $row['board_name'], 0, true);
        $mhref = URL::user($row['id_member'], $row['poster_name']);
        $thref = URL::topic($row['id_topic'], $row['first_subject'], 0, false, '.msg' . $row['id_msg'], ';topicseen#msg' . $row['id_msg']);
        // Build the array.
        $posts[] = array('board' => array('id' => $row['id_board'], 'name' => $row['board_name'], 'href' => $bhref, 'link' => '<a href="' . $bhref . '">' . $row['board_name'] . '</a>'), 'topic' => $row['id_topic'], 'poster' => array('id' => $row['id_member'], 'name' => $row['poster_name'], 'href' => empty($row['id_member']) ? '' : $mhref, 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $mhref . '">' . $row['poster_name'] . '</a>'), 'subject' => $row['subject'], 'short_subject' => shorten_subject($row['subject'], 35), 'preview' => $row['body'], 'time' => timeformat($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'raw_timestamp' => $row['poster_time'], 'href' => $thref, 'link' => '<a href="' . $thref . '" rel="nofollow">' . $row['first_subject'] . '</a>');
    }
    mysql_free_result($request);
    return $posts;
}
function ModifyBBCSettings($return_config = false)
{
    global $context, $txt, $modSettings, $helptxt, $scripturl, $sourcedir;
    $config_vars = array(array('check', 'enableBBC'), array('check', 'enablePostHTML'), array('check', 'autoLinkUrls'), '', array('bbc', 'disabledBBC'));
    if ($return_config) {
        return $config_vars;
    }
    // Setup the template.
    require_once $sourcedir . '/ManageServer.php';
    $context['sub_template'] = 'show_settings';
    $context['page_title'] = $txt['manageposts_bbc_settings_title'];
    // Make sure we check the right tags!
    $modSettings['bbc_disabled_disabledBBC'] = empty($modSettings['disabledBBC']) ? array() : explode(',', $modSettings['disabledBBC']);
    // Saving?
    if (isset($_GET['save'])) {
        checkSession();
        // Clean up the tags.
        $bbcTags = array();
        foreach (parse_bbc(false) as $tag) {
            $bbcTags[] = $tag['tag'];
        }
        if (!isset($_POST['disabledBBC_enabledTags'])) {
            $_POST['disabledBBC_enabledTags'] = array();
        } elseif (!is_array($_POST['disabledBBC_enabledTags'])) {
            $_POST['disabledBBC_enabledTags'] = array($_POST['disabledBBC_enabledTags']);
        }
        // Work out what is actually disabled!
        $_POST['disabledBBC'] = implode(',', array_diff($bbcTags, $_POST['disabledBBC_enabledTags']));
        saveDBSettings($config_vars);
        redirectexit('action=admin;area=postsettings;sa=bbc');
    }
    $context['post_url'] = $scripturl . '?action=admin;area=postsettings;save;sa=bbc';
    $context['settings_title'] = $txt['manageposts_bbc_settings_title'];
    prepareDBSettingContext($config_vars);
}
    /**
     * fetch_data.
     * Fetch Boards, Topics, Messages and Attaches.
     */
    function fetch_data()
    {
        global $context, $smcFunc, $modSettings, $settings, $boardurl, $scripturl, $txt;
        $boards = !empty($this->cfg['config']['settings']['board']) ? $this->cfg['config']['settings']['board'] : array();
        $this->cfg['config']['settings']['total'] = empty($this->cfg['config']['settings']['total']) ? 1 : $this->cfg['config']['settings']['total'];
        $this->posts = null;
        $this->attaches = null;
        $this->imgName = '';
        if (!empty($boards)) {
            // Load the message icons
            $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'moved', 'recycled');
            $icon_sources = array();
            foreach ($stable_icons as $icon) {
                $icon_sources[$icon] = 'images_url';
            }
            // find the n post from each board
            $this->cfg['config']['settings']['total'] = empty($this->cfg['config']['settings']['total']) ? 1 : $this->cfg['config']['settings']['total'];
            $msgids = array();
            $curboard = 0;
            $request = $smcFunc['db_query']('', '
				SELECT b.id_board, b.name, t.id_topic, t.num_replies, t.num_views, m.*
				FROM {db_prefix}topics as t
				LEFT JOIN {db_prefix}boards as b ON (t.id_board = b.id_board)
				LEFT JOIN {db_prefix}messages as m ON (t.id_first_msg = m.id_msg)
				WHERE b.id_board IN ({array_int:boards}) AND {query_wanna_see_board}
					' . ($modSettings['postmod_active'] ? ' AND m.approved = {int:approv}' : '') . '
					AND t.id_last_msg >= {int:min_msg}
				ORDER BY b.id_board ASC, t.id_topic DESC', array('boards' => $boards, 'min_msg' => $modSettings['maxMsgID'] - 100 * $this->cfg['config']['settings']['total'], 'approv' => 1));
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                if ($row['id_board'] != $curboard) {
                    $curboard = $row['id_board'];
                    $max = $this->cfg['config']['settings']['total'];
                }
                if (!empty($max)) {
                    $msgids[$row['id_topic']] = $row['id_msg'];
                    $max--;
                    $row['body'] = parse_bbc($row['body'], $row['smileys_enabled'], $row['id_msg']);
                    // Check that this message icon is there...
                    if (empty($modSettings['messageIconChecks_disable']) && !isset($icon_sources[$row['icon']])) {
                        $icon_sources[$row['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $row['icon'] . '.png') ? 'images_url' : 'default_images_url';
                    }
                    censorText($row['subject']);
                    censorText($row['body']);
                    // Rescale inline Images ?
                    if (!empty($this->cfg['config']['settings']['rescale']) || empty($this->cfg['config']['settings']['rescale']) && !is_numeric($this->cfg['config']['settings']['rescale'])) {
                        // find all images
                        if (preg_match_all('~<img[^>]*>~iS', $row['body'], $matches) > 0) {
                            // remove smileys
                            foreach ($matches[0] as $i => $data) {
                                if (strpos($data, $modSettings['smileys_url']) !== false) {
                                    unset($matches[0][$i]);
                                }
                            }
                            // images found?
                            if (count($matches[0]) > 0) {
                                $this->imgName = $this->cfg['blocktype'] . '-' . $this->cfg['id'];
                                if (empty($this->cfg['config']['settings']['rescale'])) {
                                    $fnd = array('~ class?=?"[^"]*"~', '~ alt?=?"[^"]*"~', '~ title?=?"[^"]*"~');
                                } else {
                                    $fnd = array('~ width?=?"\\d+"~', '~ height?=?"\\d+"~', '~ class?=?"[^"]*"~', '~ alt?=?"[^"]*"~', '~ title?=?"[^"]*"~');
                                }
                                // modify the images for highslide
                                foreach ($matches[0] as $i => $data) {
                                    $datlen = strlen($data);
                                    preg_match('~src?=?"([^\\"]*\\")~i', $data, $src);
                                    $alt = substr(strrchr($src[1], '/'), 1);
                                    $alt = str_replace(array('_', '-'), ' ', strtoupper(substr($alt, 0, strrpos($alt, '.'))));
                                    $tmp = str_replace($src[0], ' class="' . $this->imgName . '" alt="' . $alt . '" ' . $src[0], preg_replace($fnd, '', $data));
                                    // highslide disabled?
                                    if (!empty($context['pmx']['settings']['disableHS']) || !empty($context['pmx']['settings']['disableHSonfront'])) {
                                        $row['body'] = substr_replace($row['body'], $tmp, strpos($row['body'], $data), $datlen);
                                    } elseif (empty($this->cfg['config']['settings']['disableHSimg']) && empty($context['pmx']['settings']['disableHSonfront'])) {
                                        $row['body'] = substr_replace($row['body'], '<a href="' . $boardurl . '" class="' . $this->imgName . ' highslide" title="' . $txt['pmx_hs_expand'] . '" onclick="return hs.expand(this, {src: \'' . str_replace('"', '', $src[1]) . '\', align: \'center\', headingEval: \'this.thumb.alt\'})">' . $tmp . '</a>', strpos($row['body'], $data), $datlen);
                                    } else {
                                        $row['body'] = substr_replace($row['body'], $tmp, strpos($row['body'], $data), $datlen);
                                    }
                                }
                            }
                        }
                    } elseif (is_numeric($this->cfg['config']['settings']['rescale'])) {
                        $row['body'] = PortaMx_revoveLinks($row['body'], false, true);
                    }
                    // teaser enabled ?
                    if (!empty($this->cfg['config']['settings']['teaser'])) {
                        $row['body'] = PortaMx_Tease_posts($row['body'], $this->cfg['config']['settings']['teaser'], '', false, false);
                    }
                    $this->posts[] = array('id_board' => $row['id_board'], 'board_name' => $row['name'], 'id' => $row['id_topic'], 'message_id' => $row['id_msg'], 'icon' => '<img src="' . $settings[$icon_sources[$row['icon']]] . '/post/' . $row['icon'] . '.png" alt="' . $row['icon'] . '" />', 'subject' => $row['subject'], 'time' => timeformat($row['poster_time']), 'timestamp' => forum_time(true, $row['poster_time']), 'body' => $row['body'], 'replies' => $row['num_replies'], 'views' => $row['num_views'], 'poster' => array('id' => $row['id_member'], 'name' => $row['poster_name'], 'href' => !empty($row['id_member']) ? $scripturl . '?action=profile;u=' . $row['id_member'] : '', 'link' => !empty($row['id_member']) ? '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['poster_name'] . '</a>' : $row['poster_name']), 'locked' => !empty($row['locked']));
                }
            }
            $smcFunc['db_free_result']($request);
            // any post found?
            if (!is_null($this->posts)) {
                // get attachments if show thumnails set
                $allow_boards = boardsAllowedTo('view_attachments');
                if (!empty($this->cfg['config']['settings']['thumbs']) && !empty($allow_boards)) {
                    $request = $smcFunc['db_query']('', '
						SELECT a.id_msg, a.id_attach, a.id_thumb, a.filename, m.id_topic
						FROM {db_prefix}attachments AS a
						LEFT JOIN {db_prefix}messages AS m ON (a.id_msg = m.id_msg)
						WHERE a.id_msg IN({array_int:messages}) AND a.mime_type LIKE {string:like}' . ($allow_boards === array(0) ? '' : (!$modSettings['postmod_active'] || allowedTo('approve_posts') ? '' : ' AND m.approved = 1 AND a.approved = 1') . ' AND m.id_board IN ({array_int:boards})') . '
						ORDER BY m.id_msg DESC, a.id_attach ASC', array('messages' => $msgids, 'like' => 'IMAGE%', 'boards' => $allow_boards));
                    $thumbs = array();
                    $msgcnt = array();
                    $saved = !empty($this->cfg['config']['settings']['thumbcnt']) ? $this->cfg['config']['settings']['thumbcnt'] : 0;
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        if (!in_array($row['id_attach'], $thumbs)) {
                            if (!empty($this->cfg['config']['settings']['thumbcnt'])) {
                                if (!in_array($row['id_msg'], $msgcnt)) {
                                    $saved = $this->cfg['config']['settings']['thumbcnt'];
                                } elseif (in_array($row['id_msg'], $msgcnt) && empty($saved)) {
                                    continue;
                                }
                            }
                            $saved--;
                            $msgcnt[] = $row['id_msg'];
                            $thumbs[] = $row['id_thumb'];
                            $this->attaches[$row['id_msg']][] = array('topic' => $row['id_topic'], 'image' => $row['id_attach'], 'thumb' => empty($row['id_thumb']) ? $row['id_attach'] : $row['id_thumb'], 'fname' => str_replace('_thumb', '', $row['filename']));
                        }
                    }
                    $smcFunc['db_free_result']($request);
                }
            }
        }
    }
Example #17
0
/**
 * Attempt to clean up illegal BBC caused by browsers like Opera which don't obey the rules
 * @param string $text
 * @return string
 */
function legalise_bbc($text)
{
    global $modSettings;
    // Don't care about the texts that are too short.
    if (strlen($text) < 3) {
        return $text;
    }
    // We are going to cycle through the BBC and keep track of tags as they arise - in order. If get to a block level tag we're going to make sure it's not in a non-block level tag!
    // This will keep the order of tags that are open.
    $current_tags = array();
    // This will quickly let us see if the tag is active.
    $active_tags = array();
    // A list of tags that's disabled by the admin.
    $disabled = empty($modSettings['disabledBBC']) ? array() : array_flip(explode(',', strtolower($modSettings['disabledBBC'])));
    // Add flash if it's disabled as embedded tag.
    if (empty($modSettings['enableEmbeddedFlash'])) {
        $disabled['flash'] = true;
    }
    // Get a list of all the tags that are not disabled.
    $all_tags = parse_bbc(false);
    $valid_tags = array();
    $self_closing_tags = array();
    foreach ($all_tags as $tag) {
        if (!isset($disabled[$tag['tag']])) {
            $valid_tags[$tag['tag']] = !empty($tag['block_level']);
        }
        if (isset($tag['type']) && $tag['type'] == 'closed') {
            $self_closing_tags[] = $tag['tag'];
        }
    }
    // Don't worry if we're in a code/nobbc.
    $in_code_nobbc = false;
    // Right - we're going to start by going through the whole lot to make sure we don't have align stuff crossed as this happens load and is stupid!
    $align_tags = array('left', 'center', 'right', 'pre');
    // Remove those align tags that are not valid.
    $align_tags = array_intersect($align_tags, array_keys($valid_tags));
    // These keep track of where we are!
    if (!empty($align_tags) && count($matches = preg_split('~(\\[/?(?:' . implode('|', $align_tags) . ')\\])~', $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1) {
        // The first one is never a tag.
        $isTag = false;
        // By default we're not inside a tag too.
        $insideTag = null;
        foreach ($matches as $i => $match) {
            // We're only interested in tags, not text.
            if ($isTag) {
                $isClosingTag = substr($match, 1, 1) === '/';
                $tagName = substr($match, $isClosingTag ? 2 : 1, -1);
                // We're closing the exact same tag that we opened.
                if ($isClosingTag && $insideTag === $tagName) {
                    $insideTag = null;
                } elseif (!$isClosingTag && $insideTag === null) {
                    $insideTag = $tagName;
                } else {
                    unset($matches[$i]);
                }
            }
            // The next one is gonna be the other one.
            $isTag = !$isTag;
        }
        // We're still inside a tag and had no chance for closure?
        if ($insideTag !== null) {
            $matches[] = '[/' . $insideTag . ']';
        }
        // And a complete text string again.
        $text = implode('', $matches);
    }
    // Quickly remove any tags which are back to back.
    $backToBackPattern = '~\\[(' . implode('|', array_diff(array_keys($valid_tags), array('td', 'anchor'))) . ')[^<>\\[\\]]*\\]\\s*\\[/\\1\\]~';
    $lastlen = 0;
    while (strlen($text) !== $lastlen) {
        $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
    }
    // Need to sort the tags my name length.
    uksort($valid_tags, 'sort_array_length');
    // These inline tags can compete with each other regarding style.
    $competing_tags = array('color', 'size');
    // In case things changed above set these back to normal.
    $in_code_nobbc = false;
    $new_text_offset = 0;
    // These keep track of where we are!
    if (count($parts = preg_split(sprintf('~(\\[)(/?)(%1$s)((?:[\\s=][^\\]\\[]*)?\\])~', implode('|', array_keys($valid_tags))), $text, -1, PREG_SPLIT_DELIM_CAPTURE)) > 1) {
        // Start with just text.
        $isTag = false;
        // Start outside [nobbc] or [code] blocks.
        $inCode = false;
        $inNoBbc = false;
        // A buffer containing all opened inline elements.
        $inlineElements = array();
        // A buffer containing all opened block elements.
        $blockElements = array();
        // A buffer containing the opened inline elements that might compete.
        $competingElements = array();
        // $i: text, $i + 1: '[', $i + 2: '/', $i + 3: tag, $i + 4: tag tail.
        for ($i = 0, $n = count($parts) - 1; $i < $n; $i += 5) {
            $tag = $parts[$i + 3];
            $isOpeningTag = $parts[$i + 2] === '';
            $isClosingTag = $parts[$i + 2] === '/';
            $isBlockLevelTag = isset($valid_tags[$tag]) && $valid_tags[$tag] && !in_array($tag, $self_closing_tags);
            $isCompetingTag = in_array($tag, $competing_tags);
            // Check if this might be one of those cleaned out tags.
            if ($tag === '') {
                continue;
            } elseif ($tag === 'code') {
                // We're inside a code block and closing it.
                if ($inCode && $isClosingTag) {
                    $inCode = false;
                    // Reopen tags that were closed before the code block.
                    if (!empty($inlineElements)) {
                        $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
                    }
                } elseif (!$inCode && !$inNoBbc && $isOpeningTag) {
                    // If there are still inline elements left open, close them now.
                    if (!empty($inlineElements)) {
                        $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
                        //$inlineElements = array();
                    }
                    $inCode = true;
                }
                // Nothing further to do.
                continue;
            } elseif ($tag === 'nobbc') {
                // We're inside a nobbc block and closing it.
                if ($inNoBbc && $isClosingTag) {
                    $inNoBbc = false;
                    // Some inline elements might've been closed that need reopening.
                    if (!empty($inlineElements)) {
                        $parts[$i + 4] .= '[' . implode('][', array_keys($inlineElements)) . ']';
                    }
                } elseif (!$inNoBbc && !$inCode && $isOpeningTag) {
                    // Can't have inline elements still opened.
                    if (!empty($inlineElements)) {
                        $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
                        //$inlineElements = array();
                    }
                    $inNoBbc = true;
                }
                continue;
            } elseif ($inCode || $inNoBbc) {
                continue;
            }
            // We're dealing with an opening tag.
            if ($isOpeningTag) {
                // Everyting inside the square brackets of the opening tag.
                $elementContent = $parts[$i + 3] . substr($parts[$i + 4], 0, -1);
                // A block level opening tag.
                if ($isBlockLevelTag) {
                    // Are there inline elements still open?
                    if (!empty($inlineElements)) {
                        // Close all the inline tags, a block tag is coming...
                        $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
                        // Now open them again, we're inside the block tag now.
                        $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
                    }
                    $blockElements[] = $tag;
                } elseif (!in_array($tag, $self_closing_tags)) {
                    // Can't have two opening elements with the same contents!
                    if (isset($inlineElements[$elementContent])) {
                        // Get rid of this tag.
                        $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
                        // Now try to find the corresponding closing tag.
                        $curLevel = 1;
                        for ($j = $i + 5, $m = count($parts) - 1; $j < $m; $j += 5) {
                            // Find the tags with the same tagname
                            if ($parts[$j + 3] === $tag) {
                                // If it's an opening tag, increase the level.
                                if ($parts[$j + 2] === '') {
                                    $curLevel++;
                                } else {
                                    $curLevel--;
                                    // Gotcha! Clean out this closing tag gone rogue.
                                    if ($curLevel === 0) {
                                        $parts[$j + 1] = $parts[$j + 2] = $parts[$j + 3] = $parts[$j + 4] = '';
                                        break;
                                    }
                                }
                            }
                        }
                    } else {
                        if ($isCompetingTag) {
                            if (!isset($competingElements[$tag])) {
                                $competingElements[$tag] = array();
                            }
                            $competingElements[$tag][] = $parts[$i + 4];
                            if (count($competingElements[$tag]) > 1) {
                                $parts[$i] .= '[/' . $tag . ']';
                            }
                        }
                        $inlineElements[$elementContent] = $tag;
                    }
                }
            } else {
                // Closing the block tag.
                if ($isBlockLevelTag) {
                    // Close the elements that should've been closed by closing this tag.
                    if (!empty($blockElements)) {
                        $addClosingTags = array();
                        while ($element = array_pop($blockElements)) {
                            if ($element === $tag) {
                                break;
                            }
                            // Still a block tag was open not equal to this tag.
                            $addClosingTags[] = $element['type'];
                        }
                        if (!empty($addClosingTags)) {
                            $parts[$i + 1] = '[/' . implode('][/', array_reverse($addClosingTags)) . ']' . $parts[$i + 1];
                        }
                        // Apparently the closing tag was not found on the stack.
                        if (!is_string($element) || $element !== $tag) {
                            // Get rid of this particular closing tag, it was never opened.
                            $parts[$i + 1] = substr($parts[$i + 1], 0, -1);
                            $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
                            continue;
                        }
                    } else {
                        // Get rid of this closing tag!
                        $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
                        continue;
                    }
                    // Inline elements are still left opened?
                    if (!empty($inlineElements)) {
                        // Close them first..
                        $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
                        // Then reopen them.
                        $parts[$i + 5] = '[' . implode('][', array_keys($inlineElements)) . ']' . $parts[$i + 5];
                    }
                } else {
                    // Are we expecting this tag to end?
                    if (in_array($tag, $inlineElements)) {
                        foreach (array_reverse($inlineElements, true) as $tagContentToBeClosed => $tagToBeClosed) {
                            // Closing it one way or the other.
                            unset($inlineElements[$tagContentToBeClosed]);
                            // Was this the tag we were looking for?
                            if ($tagToBeClosed === $tag) {
                                break;
                            } else {
                                $parts[$i] .= '[/' . $tagToBeClosed . ']';
                            }
                        }
                        if ($isCompetingTag && !empty($competingElements[$tag])) {
                            array_pop($competingElements[$tag]);
                            if (count($competingElements[$tag]) > 0) {
                                $parts[$i + 5] = '[' . $tag . $competingElements[$tag][count($competingElements[$tag]) - 1] . $parts[$i + 5];
                            }
                        }
                    } else {
                        $parts[$i + 1] = $parts[$i + 2] = $parts[$i + 3] = $parts[$i + 4] = '';
                    }
                }
            }
        }
        // Close the code tags.
        if ($inCode) {
            $parts[$i] .= '[/code]';
        } elseif ($inNoBbc) {
            $parts[$i] .= '[/nobbc]';
        } elseif (!empty($inlineElements)) {
            $parts[$i] .= '[/' . implode('][/', array_reverse($inlineElements)) . ']';
        }
        // Now close the block elements.
        if (!empty($blockElements)) {
            $parts[$i] .= '[/' . implode('][/', array_reverse($blockElements)) . ']';
        }
        $text = implode('', $parts);
    }
    // Final clean up of back to back tags.
    $lastlen = 0;
    while (strlen($text) !== $lastlen) {
        $lastlen = strlen($text = preg_replace($backToBackPattern, '', $text));
    }
    return $text;
}
Example #18
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__);
    }
}
    /**
     * 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 #20
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');
}
/**
 *	Loads any custom fields that are active
 *
 *	@param bool $is_ticket (default true) Whether to load custom fields based on editing a ticket or a message.
 *	@param int $ticketContext The appropriate value to load for; if editing a ticket this represents the ticket id, if editing a reply this represents the message id, if empty this is a new instance of either so no need to attempt loading data.
 *
 *	@since 2.0
*/
function shd_load_custom_fields($is_ticket = true, $ticketContext = 0, $dept = 0)
{
    global $sourcedir, $context, $smcFunc;
    $field_values = array();
    if (!empty($ticketContext)) {
        $query = shd_db_query('', '
			SELECT cfv.id_field, cfv.value
			FROM {db_prefix}helpdesk_custom_fields_values AS cfv
			WHERE cfv.id_post = {int:ticketContext}
				AND cfv.post_type = {int:field_type}', array('ticketContext' => $ticketContext, 'field_type' => $is_ticket ? CFIELD_TICKET : CFIELD_REPLY));
        while ($row = $smcFunc['db_fetch_assoc']($query)) {
            $field_values[$row['id_field']] = $row['value'];
        }
        $smcFunc['db_free_result']($query);
    }
    // Load up our custom field defintions from the database
    $custom_fields = shd_db_query('', '
		SELECT cf.id_field, cf.active, cf.field_order, cf.field_name, cf.field_desc, cf.field_loc, cf.icon,
			cf.field_type, cf.field_options, cf.default_value, cf.bbc, cf.can_see, cf.can_edit, cf.field_length,
			cf.display_empty, cfd.required, cf.placement, cfd.id_dept
		FROM {db_prefix}helpdesk_custom_fields AS cf
			INNER JOIN {db_prefix}helpdesk_custom_fields_depts AS cfd ON (cf.id_field = cfd.id_field' . (!empty($dept) ? ' AND cfd.id_dept = {int:dept}' : '') . ')
		WHERE cf.active = 1
			AND cf.field_loc IN ({array_int:visibility})
		ORDER BY cf.field_order', array('visibility' => $is_ticket ? array(CFIELD_TICKET, CFIELD_REPLY | CFIELD_TICKET) : array(CFIELD_REPLY, CFIELD_REPLY | CFIELD_TICKET), 'dept' => $dept));
    $context['ticket_form']['custom_fields'] = array();
    $loc = $is_ticket ? 'ticket' : $ticketContext;
    $is_staff = shd_allowed_to('shd_staff', $dept);
    $is_admin = shd_allowed_to('admin_helpdesk', $dept);
    // this includes forum admins
    // Loop through all fields and figure out where they should be.
    while ($row = $smcFunc['db_fetch_assoc']($custom_fields)) {
        // Can the user even see this field? If we can't see the field, it doesn't exist to us for posting purposes.
        list($user_see, $staff_see) = explode(',', $row['can_see']);
        list($user_edit, $staff_edit) = explode(',', $row['can_edit']);
        if ($is_admin) {
            $editable = true;
        } elseif ($is_staff) {
            if ($staff_see == 0) {
                continue;
            }
            $editable = $staff_edit == 1;
        } elseif ($user_see == 1) {
            $editable = $user_edit == 1;
        } else {
            continue;
        }
        // Load up the fields and do some extra parsing
        if (!isset($context['ticket_form']['custom_fields'][$loc][$row['id_field']])) {
            $context['ticket_form']['custom_fields'][$loc][$row['id_field']] = array('id' => $row['id_field'], 'order' => $row['field_order'], 'location' => $row['field_loc'], 'length' => $row['field_length'], 'name' => $row['field_name'], 'desc' => parse_bbc($row['field_desc'], false), 'icon' => $row['icon'], 'options' => !empty($row['field_options']) ? unserialize($row['field_options']) : array(), 'type' => $row['field_type'], 'default_value' => $row['field_type'] == CFIELD_TYPE_LARGETEXT ? explode(',', $row['default_value']) : $row['default_value'], 'display_empty' => !empty($row['required']) ? 1 : $row['display_empty'], 'bbc' => !empty($row['bbc']), 'is_required' => $row['field_type'] == CFIELD_TYPE_MULTI ? (int) $row['required'] : !empty($row['required']), 'visible' => array($user_see, $staff_see), 'editable' => !empty($editable), 'depts' => array());
            if ($row['field_type'] == CFIELD_TYPE_RADIO || $row['field_type'] == CFIELD_TYPE_MULTI) {
                foreach ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'] as $k => $v) {
                    if ($k != 'inactive') {
                        $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'][$k] = strpos($v, '[') !== false ? parse_bbc($v) : $v;
                    }
                }
            } elseif ($row['field_type'] == CFIELD_TYPE_SELECT) {
                foreach ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'] as $k => $v) {
                    if ($k != 'inactive') {
                        $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options'][$k] = strpos($v, '[') !== false ? trim(strip_tags(parse_bbc($v))) : trim($v);
                    }
                }
            }
        }
        $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['depts'][] = $row['id_dept'];
        if (!empty($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options']) && empty($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options']['inactive'])) {
            $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['options']['inactive'] = array();
        }
        if (isset($field_values[$row['id_field']])) {
            if ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['type'] == CFIELD_TYPE_MULTI) {
                $field_values[$row['id_field']] = explode(',', $field_values[$row['id_field']]);
            }
            // Large text boxes may need fixing.
            if ($context['ticket_form']['custom_fields'][$loc][$row['id_field']]['type'] == CFIELD_TYPE_LARGETEXT) {
                require_once $sourcedir . '/Subs-Editor.php';
                $field_values[$row['id_field']] = html_to_bbc($field_values[$row['id_field']]);
            }
            $context['ticket_form']['custom_fields'][$loc][$row['id_field']]['value'] = $field_values[$row['id_field']];
        }
    }
    $context['ticket_form']['custom_fields_context'] = $loc;
}
function prepareDisplayContext($reset = false)
{
    global $settings, $txt, $modSettings, $scripturl, $options, $user_info, $smcFunc;
    global $memberContext, $context, $messages_request, $topic, $attachments, $topicinfo;
    static $counter = null;
    // If the query returned false, bail.
    if ($messages_request == false) {
        return false;
    }
    // Remember which message this is.  (ie. reply #83)
    if ($counter === null || $reset) {
        $counter = empty($options['view_newest_first']) ? $context['start'] : $context['total_visible_posts'] - $context['start'];
    }
    // Start from the beginning...
    if ($reset) {
        return @$smcFunc['db_data_seek']($messages_request, 0);
    }
    // Attempt to get the next message.
    $message = $smcFunc['db_fetch_assoc']($messages_request);
    if (!$message) {
        $smcFunc['db_free_result']($messages_request);
        return false;
    }
    // $context['icon_sources'] says where each icon should come from - here we set up the ones which will always exist!
    if (empty($context['icon_sources'])) {
        $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'moved', 'recycled', 'wireless', 'clip');
        $context['icon_sources'] = array();
        foreach ($stable_icons as $icon) {
            $context['icon_sources'][$icon] = 'images_url';
        }
    }
    // Message Icon Management... check the images exist.
    if (empty($modSettings['messageIconChecks_disable'])) {
        // If the current icon isn't known, then we need to do something...
        if (!isset($context['icon_sources'][$message['icon']])) {
            $context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.gif') ? 'images_url' : 'default_images_url';
        }
    } elseif (!isset($context['icon_sources'][$message['icon']])) {
        $context['icon_sources'][$message['icon']] = 'images_url';
    }
    // If you're a lazy bum, you probably didn't give a subject...
    $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
    // Are you allowed to remove at least a single reply?
    $context['can_remove_post'] |= allowedTo('delete_own') && (empty($modSettings['edit_disable_time']) || max($message['modified_time'], $message['poster_time']) + $modSettings['edit_disable_time'] * 60 >= time()) && $message['id_member'] == $user_info['id'];
    // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
    if (!loadMemberContext($message['id_member'], true)) {
        // Notice this information isn't used anywhere else....
        $memberContext[$message['id_member']]['name'] = $message['poster_name'];
        $memberContext[$message['id_member']]['id'] = 0;
        $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
        $memberContext[$message['id_member']]['link'] = $message['poster_name'];
        $memberContext[$message['id_member']]['email'] = $message['poster_email'];
        $memberContext[$message['id_member']]['show_email'] = showEmailAddress(true, 0);
        $memberContext[$message['id_member']]['is_guest'] = true;
    } else {
        $memberContext[$message['id_member']]['can_view_profile'] = allowedTo('profile_view_any') || $message['id_member'] == $user_info['id'] && allowedTo('profile_view_own');
        $memberContext[$message['id_member']]['is_topic_starter'] = $message['id_member'] == $context['topic_starter_id'];
        $memberContext[$message['id_member']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member']]['warning_status'] && ($context['user']['can_mod'] || !$user_info['is_guest'] && !empty($modSettings['warning_show']) && ($modSettings['warning_show'] > 1 || $message['id_member'] == $user_info['id']));
    }
    $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
    // Do the censor thang.
    censorText($message['body']);
    censorText($message['subject']);
    // Run BBC interpreter on the message.
    $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
    // Compose the memory eat- I mean message array.
    $output = array('attachment' => loadAttachmentContext($message['id_msg']), 'alternate' => $counter % 2, 'id' => $message['id_msg'], 'href' => $scripturl . '?topic=' . $topic . '.msg' . $message['id_msg'] . '#msg' . $message['id_msg'], 'link' => '<a href="' . $scripturl . '?topic=' . $topic . '.msg' . $message['id_msg'] . '#msg' . $message['id_msg'] . '" rel="nofollow">' . $message['subject'] . '</a>', 'member' => &$memberContext[$message['id_member']], 'icon' => $message['icon'], 'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.gif', 'subject' => $message['subject'], 'time' => timeformat($message['poster_time']), 'timestamp' => forum_time(true, $message['poster_time']), 'counter' => $counter, 'modified' => array('time' => timeformat($message['modified_time']), 'timestamp' => forum_time(true, $message['modified_time']), 'name' => $message['modified_name']), 'body' => $message['body'], 'new' => empty($message['is_read']), 'approved' => $message['approved'], 'first_new' => isset($context['start_from']) && $context['start_from'] == $counter, 'is_ignored' => !empty($modSettings['enable_buddylist']) && !empty($options['posts_apply_ignore_list']) && in_array($message['id_member'], $context['user']['ignoreusers']), 'can_approve' => !$message['approved'] && $context['can_approve'], 'can_unapprove' => $message['approved'] && $context['can_approve'], 'can_modify' => (!$context['is_locked'] || allowedTo('moderate_board')) && (allowedTo('modify_any') || allowedTo('modify_replies') && $context['user']['started'] || allowedTo('modify_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || !$message['approved'] || max($message['modified_time'], $message['poster_time']) + $modSettings['edit_disable_time'] * 60 > time())), 'can_remove' => allowedTo('delete_any') || allowedTo('delete_replies') && $context['user']['started'] || allowedTo('delete_own') && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || max($message['modified_time'], $message['poster_time']) + $modSettings['edit_disable_time'] * 60 > time()), 'can_see_ip' => allowedTo('moderate_forum') || $message['id_member'] == $user_info['id'] && !empty($user_info['id']));
    // Is this user the message author?
    $output['is_message_author'] = $message['id_member'] == $user_info['id'];
    if (empty($options['view_newest_first'])) {
        $counter++;
    } else {
        $counter--;
    }
    return $output;
}
Example #23
0
function loadMemberContext($user, $display_custom_fields = false)
{
    global $memberContext, $user_profile, $txt, $scripturl, $user_info;
    global $context, $modSettings, $settings;
    static $dataLoaded = array();
    // If this person's data is already loaded, skip it.
    if (isset($dataLoaded[$user])) {
        return true;
    }
    // We can't load guests or members not loaded by loadMemberData()!
    if ($user == 0) {
        return false;
    }
    if (!isset($user_profile[$user])) {
        trigger_error('loadMemberContext(): member id ' . $user . ' not previously loaded by loadMemberData()', E_USER_WARNING);
        return false;
    }
    // Well, it's loaded now anyhow.
    $dataLoaded[$user] = true;
    $profile = $user_profile[$user];
    // Censor everything.
    censorText($profile['signature']);
    censorText($profile['personal_text']);
    censorText($profile['location']);
    // Set things up to be used before hand.
    $gendertxt = $profile['gender'] == 2 ? $txt['female'] : ($profile['gender'] == 1 ? $txt['male'] : '');
    $profile['signature'] = str_replace(array("\n", "\r"), array('<br />', ''), $profile['signature']);
    $profile['signature'] = parse_bbc($profile['signature'], true, 'sig' . $profile['id_member']);
    $profile['is_online'] = (!empty($profile['show_online']) || allowedTo('moderate_forum')) && $profile['is_online'] > 0;
    $profile['stars'] = empty($profile['stars']) ? array('', '') : explode('#', $profile['stars']);
    // Setup the buddy status here (One whole in_array call saved :P)
    $profile['buddy'] = in_array($profile['id_member'], $user_info['buddies']);
    $buddy_list = !empty($profile['buddy_list']) ? explode(',', $profile['buddy_list']) : array();
    // If we're always html resizing, assume it's too large.
    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 = '';
    }
    $m_href = URL::user($profile['id_member'], $profile['real_name']);
    // What a monstrous array...
    $memberContext[$user] = array('username' => $profile['member_name'], 'name' => $profile['real_name'], 'id' => $profile['id_member'], 'is_buddy' => $profile['buddy'], 'is_reverse_buddy' => in_array($user_info['id'], $buddy_list), 'buddies' => $buddy_list, 'title' => !empty($modSettings['titlesEnable']) ? $profile['usertitle'] : '', 'href' => $m_href, 'link' => '<a class="member group_' . (empty($profile['id_group']) ? $profile['id_post_group'] : $profile['id_group']) . '" onclick="getMcard(' . $profile['id_member'] . ');return(false);" href="' . $m_href . '" title="' . $txt['profile_of'] . ' ' . $profile['real_name'] . '">' . $profile['real_name'] . '</a>', 'email' => $profile['email_address'], 'show_email' => showEmailAddress(!empty($profile['hide_email']), $profile['id_member']), 'registered' => empty($profile['date_registered']) ? $txt['not_applicable'] : timeformat($profile['date_registered']), 'blurb' => $profile['personal_text'], 'gender' => array('name' => $gendertxt, 'image' => !empty($profile['gender']) ? '<img class="gender" src="' . $settings['images_url'] . '/' . ($profile['gender'] == 1 ? 'Male' : 'Female') . '.gif" alt="' . $gendertxt . '" />' : ''), 'birth_date' => empty($profile['birthdate']) || $profile['birthdate'] === '0001-01-01' ? '0000-00-00' : (substr($profile['birthdate'], 0, 4) === '0004' ? '0000' . substr($profile['birthdate'], 4) : $profile['birthdate']), 'signature' => $profile['signature'], 'location' => $profile['location'], 'real_posts' => $profile['posts'], 'posts' => comma_format($profile['posts']), 'avatar' => array('name' => $profile['avatar'], 'image' => $profile['avatar'] == '' ? $profile['id_attach'] > 0 ? '<img class="avatar" src="' . (empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename']) . '" alt="" />' : '' : (stristr($profile['avatar'], 'http://') ? '<img class="avatar" src="' . $profile['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" />' : '<img class="avatar" src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($profile['avatar']) . '" alt="" />'), 'href' => $profile['avatar'] == '' ? $profile['id_attach'] > 0 ? empty($profile['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $profile['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename'] : '' : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar']), 'url' => $profile['avatar'] == '' ? '' : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar'])), 'last_login' => empty($profile['last_login']) ? $txt['never'] : !empty($profile['show_online']) || allowedTo('moderate_forum') ? timeformat($profile['last_login']) : $txt['hidden'], 'ip' => htmlspecialchars($profile['member_ip']), 'ip2' => htmlspecialchars($profile['member_ip2']), 'online' => array('is_online' => $profile['is_online'], 'text' => $txt[$profile['is_online'] ? 'online' : 'offline'], 'href' => $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'], 'link' => '<a href="' . $scripturl . '?action=pm;sa=send;u=' . $profile['id_member'] . '">' . $txt[$profile['is_online'] ? 'online' : 'offline'] . '</a>', 'image_href' => $settings['images_url'] . '/' . ($profile['buddy'] ? 'buddy_' : '') . ($profile['is_online'] ? 'useron' : 'useroff') . '.gif', 'label' => $txt[$profile['is_online'] ? 'online' : 'offline']), 'language' => commonAPI::ucwords(strtr($profile['lngfile'], array('_' => ' ', '-utf8' => ''))), 'is_activated' => isset($profile['is_activated']) ? $profile['is_activated'] : 1, 'is_banned' => isset($profile['is_activated']) ? $profile['is_activated'] >= 10 : 0, 'options' => $profile['options'], 'is_guest' => false, 'group' => $profile['member_group'], 'group_id' => $profile['id_group'], 'post_group_id' => $profile['id_post_group'], 'post_group' => $profile['post_group'], 'group_stars' => str_repeat('<img src="' . str_replace('$language', $context['user']['language'], isset($profile['stars'][1]) ? $settings['images_url'] . '/' . $profile['stars'][1] : '') . '" alt="*" />', empty($profile['stars'][0]) || empty($profile['stars'][1]) ? 0 : $profile['stars'][0]), 'warning' => $profile['warning'], 'warning_status' => !empty($modSettings['warning_mute']) && $modSettings['warning_mute'] <= $profile['warning'] ? 'mute' : (!empty($modSettings['warning_moderate']) && $modSettings['warning_moderate'] <= $profile['warning'] ? 'moderate' : (!empty($modSettings['warning_watch']) && $modSettings['warning_watch'] <= $profile['warning'] ? 'watch' : '')), 'local_time' => timeformat_static(time() + ($profile['time_offset'] - $user_info['time_offset']) * 3600, false), 'liked' => isset($profile['liked']) ? $profile['liked'] : 0, 'likesgiven' => isset($profile['likesgiven']) ? $profile['likesgiven'] : 0, 'notify_optout' => isset($profile['notify_optout']) ? $profile['notify_optout'] : '');
    if ($memberContext[$user]['avatar']['name'] == 'gravatar') {
        $hash = md5(strtolower(trim($memberContext[$user]['email'])));
        $memberContext[$user]['avatar']['image'] = '<img class="avatar" alt="avatar" src="http://www.gravatar.com/avatar/' . $hash . '" />';
        $memberContext[$user]['avatar']['href'] = 'http://www.gravatar.com/avatar/' . $hash;
        $memberContext[$user]['avatar']['url'] = $memberContext[$user]['avatar']['href'];
    }
    // First do a quick run through to make sure there is something to be shown.
    $memberContext[$user]['has_messenger'] = false;
    // Are we also loading the members custom fields into context?
    if ($display_custom_fields && !empty($modSettings['displayFields'])) {
        $memberContext[$user]['custom_fields'] = array();
        if (!isset($context['display_fields'])) {
            $context['display_fields'] = unserialize($modSettings['displayFields']);
        }
        foreach ($context['display_fields'] as $custom) {
            if (empty($custom['title']) || empty($profile['options'][$custom['colname']])) {
                continue;
            }
            $value = $profile['options'][$custom['colname']];
            // BBC?
            if ($custom['bbc']) {
                $value = parse_bbc($value);
            } elseif (isset($custom['type']) && $custom['type'] == 'check') {
                $value = $value ? $txt['yes'] : $txt['no'];
            }
            // Enclosing the user input within some other text?
            if (!empty($custom['enclose'])) {
                $value = strtr($custom['enclose'], array('{SCRIPTURL}' => $scripturl, '{IMAGES_URL}' => $settings['images_url'], '{DEFAULT_IMAGES_URL}' => $settings['default_images_url'], '{INPUT}' => $value));
            }
            $memberContext[$user]['custom_fields'][] = array('title' => $custom['title'], 'colname' => $custom['colname'], 'value' => $value, 'placement' => !empty($custom['placement']) ? $custom['placement'] : 0);
        }
    }
    HookAPI::callHook('integrate_loadmembercontext', array(&$memberContext[$user], &$profile));
    return true;
}
Example #24
0
function create_control_verification(&$verificationOptions, $do_test = false)
{
    global $txt, $modSettings, $options, $smcFunc;
    global $context, $settings, $user_info, $sourcedir, $scripturl;
    // First verification means we need to set up some bits...
    if (empty($context['controls']['verification'])) {
        // The template
        //if(!isset($verificationOptions['skip_template']))
        //	loadTemplate('GenericControls');
        // Some javascript ma'am?
        if (!empty($verificationOptions['override_visual']) || !empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual'])) {
            $context['html_headers'] .= '
		<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/captcha.js"></script>';
        }
        $context['use_graphic_library'] = in_array('gd', get_loaded_extensions());
        // Skip I, J, L, O, Q, S and Z.
        $context['standard_captcha_range'] = array_merge(range('A', 'H'), array('K', 'M', 'N', 'P', 'R'), range('T', 'Y'));
    }
    // Always have an ID.
    assert(isset($verificationOptions['id']));
    $isNew = !isset($context['controls']['verification'][$verificationOptions['id']]);
    // Log this into our collection.
    if ($isNew) {
        $context['controls']['verification'][$verificationOptions['id']] = array('id' => $verificationOptions['id'], 'show_visual' => !empty($verificationOptions['override_visual']) || !empty($modSettings['visual_verification_type']) && !isset($verificationOptions['override_visual']), 'number_questions' => isset($verificationOptions['override_qs']) ? $verificationOptions['override_qs'] : (!empty($modSettings['qa_verification_number']) ? $modSettings['qa_verification_number'] : 0), 'max_errors' => isset($verificationOptions['max_errors']) ? $verificationOptions['max_errors'] : 3, 'image_href' => $scripturl . '?action=verificationcode;vid=' . $verificationOptions['id'] . ';rand=' . md5(mt_rand()), 'text_value' => '', 'questions' => array());
    }
    $thisVerification =& $context['controls']['verification'][$verificationOptions['id']];
    // Add javascript for the object.
    if ($context['controls']['verification'][$verificationOptions['id']]['show_visual']) {
        $context['inline_footer_script'] .= '
			var verification' . $verificationOptions['id'] . 'Handle = new smfCaptcha("' . $thisVerification['image_href'] . '", "' . $verificationOptions['id'] . '", ' . ($context['use_graphic_library'] ? 1 : 0) . ');';
    }
    // Is there actually going to be anything?
    if (empty($thisVerification['show_visual']) && empty($thisVerification['number_questions'])) {
        return false;
    } elseif (!$isNew && !$do_test) {
        return true;
    }
    // If we want questions do we have a cache of all the IDs?
    if (!empty($thisVerification['number_questions']) && empty($modSettings['question_id_cache'])) {
        if (($modSettings['question_id_cache'] = CacheAPI::getCache('verificationQuestionIds', 300)) == null) {
            $request = smf_db_query('
				SELECT id_comment
				FROM {db_prefix}log_comments
				WHERE comment_type = {string:ver_test}', array('ver_test' => 'ver_test'));
            $modSettings['question_id_cache'] = array();
            while ($row = mysql_fetch_assoc($request)) {
                $modSettings['question_id_cache'][] = $row['id_comment'];
            }
            mysql_free_result($request);
            if (!empty($modSettings['cache_enable'])) {
                CacheAPI::putCache('verificationQuestionIds', $modSettings['question_id_cache'], 300);
            }
        }
    }
    if (!isset($_SESSION[$verificationOptions['id'] . '_vv'])) {
        $_SESSION[$verificationOptions['id'] . '_vv'] = array();
    }
    // Do we need to refresh the verification?
    if (!$do_test && (!empty($_SESSION[$verificationOptions['id'] . '_vv']['did_pass']) || empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) || $_SESSION[$verificationOptions['id'] . '_vv']['count'] > 3) && empty($verificationOptions['dont_refresh'])) {
        $force_refresh = true;
    } else {
        $force_refresh = false;
    }
    // This can also force a fresh, although unlikely.
    if ($thisVerification['show_visual'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['code']) || $thisVerification['number_questions'] && empty($_SESSION[$verificationOptions['id'] . '_vv']['q'])) {
        $force_refresh = true;
    }
    $verification_errors = array();
    // Start with any testing.
    if ($do_test) {
        // This cannot happen!
        if (!isset($_SESSION[$verificationOptions['id'] . '_vv']['count'])) {
            fatal_lang_error('no_access', false);
        }
        // ... nor this!
        if ($thisVerification['number_questions'] && (!isset($_SESSION[$verificationOptions['id'] . '_vv']['q']) || !isset($_REQUEST[$verificationOptions['id'] . '_vv']['q']))) {
            fatal_lang_error('no_access', false);
        }
        if ($thisVerification['show_visual'] && (empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) || empty($_SESSION[$verificationOptions['id'] . '_vv']['code']) || strtoupper($_REQUEST[$verificationOptions['id'] . '_vv']['code']) !== $_SESSION[$verificationOptions['id'] . '_vv']['code'])) {
            $verification_errors[] = 'wrong_verification_code';
        }
        if ($thisVerification['number_questions']) {
            // Get the answers and see if they are all right!
            $request = smf_db_query('
				SELECT id_comment, recipient_name AS answer
				FROM {db_prefix}log_comments
				WHERE comment_type = {string:ver_test}
					AND id_comment IN ({array_int:comment_ids})', array('ver_test' => 'ver_test', 'comment_ids' => $_SESSION[$verificationOptions['id'] . '_vv']['q']));
            $incorrectQuestions = array();
            while ($row = mysql_fetch_assoc($request)) {
                if (empty($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) || trim(commonAPI::htmlspecialchars(strtolower($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]))) != strtolower($row['answer'])) {
                    $incorrectQuestions[] = $row['id_comment'];
                }
            }
            mysql_free_result($request);
            if (!empty($incorrectQuestions)) {
                $verification_errors[] = 'wrong_verification_answer';
            }
        }
    }
    // Any errors means we refresh potentially.
    if (!empty($verification_errors)) {
        if (empty($_SESSION[$verificationOptions['id'] . '_vv']['errors'])) {
            $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
        } elseif ($_SESSION[$verificationOptions['id'] . '_vv']['errors'] > $thisVerification['max_errors']) {
            $force_refresh = true;
        }
        // Keep a track of these.
        $_SESSION[$verificationOptions['id'] . '_vv']['errors']++;
    }
    // Are we refreshing then?
    if ($force_refresh) {
        // Assume nothing went before.
        $_SESSION[$verificationOptions['id'] . '_vv']['count'] = 0;
        $_SESSION[$verificationOptions['id'] . '_vv']['errors'] = 0;
        $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = false;
        $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
        $_SESSION[$verificationOptions['id'] . '_vv']['code'] = '';
        // Generating a new image.
        if ($thisVerification['show_visual']) {
            // Are we overriding the range?
            $character_range = !empty($verificationOptions['override_range']) ? $verificationOptions['override_range'] : $context['standard_captcha_range'];
            for ($i = 0; $i < 6; $i++) {
                $_SESSION[$verificationOptions['id'] . '_vv']['code'] .= $character_range[array_rand($character_range)];
            }
        }
        // Getting some new questions?
        if ($thisVerification['number_questions']) {
            // Pick some random IDs
            $questionIDs = array();
            if ($thisVerification['number_questions'] == 1) {
                $questionIDs[] = $modSettings['question_id_cache'][array_rand($modSettings['question_id_cache'], $thisVerification['number_questions'])];
            } else {
                foreach (array_rand($modSettings['question_id_cache'], $thisVerification['number_questions']) as $index) {
                    $questionIDs[] = $modSettings['question_id_cache'][$index];
                }
            }
        }
    } else {
        // Same questions as before.
        $questionIDs = !empty($_SESSION[$verificationOptions['id'] . '_vv']['q']) ? $_SESSION[$verificationOptions['id'] . '_vv']['q'] : array();
        $thisVerification['text_value'] = !empty($_REQUEST[$verificationOptions['id'] . '_vv']['code']) ? commonAPI::htmlspecialchars($_REQUEST[$verificationOptions['id'] . '_vv']['code']) : '';
    }
    // Have we got some questions to load?
    if (!empty($questionIDs)) {
        $request = smf_db_query('
			SELECT id_comment, body AS question
			FROM {db_prefix}log_comments
			WHERE comment_type = {string:ver_test}
				AND id_comment IN ({array_int:comment_ids})', array('ver_test' => 'ver_test', 'comment_ids' => $questionIDs));
        $_SESSION[$verificationOptions['id'] . '_vv']['q'] = array();
        while ($row = mysql_fetch_assoc($request)) {
            $thisVerification['questions'][] = array('id' => $row['id_comment'], 'q' => parse_bbc($row['question']), 'is_error' => !empty($incorrectQuestions) && in_array($row['id_comment'], $incorrectQuestions), 'a' => isset($_REQUEST[$verificationOptions['id'] . '_vv'], $_REQUEST[$verificationOptions['id'] . '_vv']['q'], $_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) ? commonAPI::htmlspecialchars($_REQUEST[$verificationOptions['id'] . '_vv']['q'][$row['id_comment']]) : '');
            $_SESSION[$verificationOptions['id'] . '_vv']['q'][] = $row['id_comment'];
        }
        mysql_free_result($request);
    }
    $_SESSION[$verificationOptions['id'] . '_vv']['count'] = empty($_SESSION[$verificationOptions['id'] . '_vv']['count']) ? 1 : $_SESSION[$verificationOptions['id'] . '_vv']['count'] + 1;
    // Return errors if we have them.
    if (!empty($verification_errors)) {
        return $verification_errors;
    } elseif ($do_test) {
        $_SESSION[$verificationOptions['id'] . '_vv']['did_pass'] = true;
    }
    // Say that everything went well chaps.
    return true;
}
Example #25
0
/**
 * Send it!
 */
function MessagePost2()
{
    global $txt, $context, $sourcedir;
    global $user_info, $modSettings, $scripturl, $smcFunc;
    isAllowedTo('pm_send');
    require_once $sourcedir . '/Subs-Auth.php';
    loadLanguage('PersonalMessage', '', false);
    // Extract out the spam settings - it saves database space!
    list($modSettings['max_pm_recipients'], $modSettings['pm_posts_verification'], $modSettings['pm_posts_per_hour']) = explode(',', $modSettings['pm_spam_settings']);
    // Initialize the errors we're about to make.
    $post_errors = array();
    // Check whether we've gone over the limit of messages we can send per hour - fatal error if fails!
    if (!empty($modSettings['pm_posts_per_hour']) && !allowedTo(array('admin_forum', 'moderate_forum', 'send_mail')) && $user_info['mod_cache']['bq'] == '0=1' && $user_info['mod_cache']['gq'] == '0=1') {
        // How many have they sent this last hour?
        $request = $smcFunc['db_query']('', '
			SELECT COUNT(pr.id_pm) AS post_count
			FROM {db_prefix}personal_messages AS pm
				INNER JOIN {db_prefix}pm_recipients AS pr ON (pr.id_pm = pm.id_pm)
			WHERE pm.id_member_from = {int:current_member}
				AND pm.msgtime > {int:msgtime}', array('current_member' => $user_info['id'], 'msgtime' => time() - 3600));
        list($postCount) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        if (!empty($postCount) && $postCount >= $modSettings['pm_posts_per_hour']) {
            if (!isset($_REQUEST['xml'])) {
                fatal_lang_error('pm_too_many_per_hour', true, array($modSettings['pm_posts_per_hour']));
            } else {
                $post_errors[] = 'pm_too_many_per_hour';
            }
        }
    }
    // If your session timed out, show an error, but do allow to re-submit.
    if (!isset($_REQUEST['xml']) && checkSession('post', '', false) != '') {
        $post_errors[] = 'session_timeout';
    }
    $_REQUEST['subject'] = isset($_REQUEST['subject']) ? trim($_REQUEST['subject']) : '';
    $_REQUEST['to'] = empty($_POST['to']) ? empty($_GET['to']) ? '' : $_GET['to'] : $_POST['to'];
    $_REQUEST['bcc'] = empty($_POST['bcc']) ? empty($_GET['bcc']) ? '' : $_GET['bcc'] : $_POST['bcc'];
    // Route the input from the 'u' parameter to the 'to'-list.
    if (!empty($_POST['u'])) {
        $_POST['recipient_to'] = explode(',', $_POST['u']);
    }
    // Construct the list of recipients.
    $recipientList = array();
    $namedRecipientList = array();
    $namesNotFound = array();
    foreach (array('to', 'bcc') as $recipientType) {
        // First, let's see if there's user ID's given.
        $recipientList[$recipientType] = array();
        if (!empty($_POST['recipient_' . $recipientType]) && is_array($_POST['recipient_' . $recipientType])) {
            foreach ($_POST['recipient_' . $recipientType] as $recipient) {
                $recipientList[$recipientType][] = (int) $recipient;
            }
        }
        // Are there also literal names set?
        if (!empty($_REQUEST[$recipientType])) {
            // We're going to take out the "s anyway ;).
            $recipientString = strtr($_REQUEST[$recipientType], array('\\"' => '"'));
            preg_match_all('~"([^"]+)"~', $recipientString, $matches);
            $namedRecipientList[$recipientType] = array_unique(array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $recipientString))));
            foreach ($namedRecipientList[$recipientType] as $index => $recipient) {
                if (strlen(trim($recipient)) > 0) {
                    $namedRecipientList[$recipientType][$index] = $smcFunc['htmlspecialchars']($smcFunc['strtolower'](trim($recipient)));
                } else {
                    unset($namedRecipientList[$recipientType][$index]);
                }
            }
            if (!empty($namedRecipientList[$recipientType])) {
                $foundMembers = findMembers($namedRecipientList[$recipientType]);
                // Assume all are not found, until proven otherwise.
                $namesNotFound[$recipientType] = $namedRecipientList[$recipientType];
                foreach ($foundMembers as $member) {
                    $testNames = array($smcFunc['strtolower']($member['username']), $smcFunc['strtolower']($member['name']), $smcFunc['strtolower']($member['email']));
                    if (count(array_intersect($testNames, $namedRecipientList[$recipientType])) !== 0) {
                        $recipientList[$recipientType][] = $member['id'];
                        // Get rid of this username, since we found it.
                        $namesNotFound[$recipientType] = array_diff($namesNotFound[$recipientType], $testNames);
                    }
                }
            }
        }
        // Selected a recipient to be deleted? Remove them now.
        if (!empty($_POST['delete_recipient'])) {
            $recipientList[$recipientType] = array_diff($recipientList[$recipientType], array((int) $_POST['delete_recipient']));
        }
        // Make sure we don't include the same name twice
        $recipientList[$recipientType] = array_unique($recipientList[$recipientType]);
    }
    // Are we changing the recipients some how?
    $is_recipient_change = !empty($_POST['delete_recipient']) || !empty($_POST['to_submit']) || !empty($_POST['bcc_submit']);
    // Check if there's at least one recipient.
    if (empty($recipientList['to']) && empty($recipientList['bcc'])) {
        $post_errors[] = 'no_to';
    }
    // Make sure that we remove the members who did get it from the screen.
    if (!$is_recipient_change) {
        foreach ($recipientList as $recipientType => $dummy) {
            if (!empty($namesNotFound[$recipientType])) {
                $post_errors[] = 'bad_' . $recipientType;
                // Since we already have a post error, remove the previous one.
                $post_errors = array_diff($post_errors, array('no_to'));
                foreach ($namesNotFound[$recipientType] as $name) {
                    $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
                }
            }
        }
    }
    // Did they make any mistakes?
    if ($_REQUEST['subject'] == '') {
        $post_errors[] = 'no_subject';
    }
    if (!isset($_REQUEST['message']) || $_REQUEST['message'] == '') {
        $post_errors[] = 'no_message';
    } elseif (!empty($modSettings['max_messageLength']) && $smcFunc['strlen']($_REQUEST['message']) > $modSettings['max_messageLength']) {
        $post_errors[] = 'long_message';
    } else {
        // Preparse the message.
        $message = $_REQUEST['message'];
        preparsecode($message);
        // Make sure there's still some content left without the tags.
        if ($smcFunc['htmltrim'](strip_tags(parse_bbc($smcFunc['htmlspecialchars']($message, ENT_QUOTES), false), '<img>')) === '' && (!allowedTo('admin_forum') || strpos($message, '[html]') === false)) {
            $post_errors[] = 'no_message';
        }
    }
    // Wrong verification code?
    if (!$user_info['is_admin'] && !isset($_REQUEST['xml']) && !empty($modSettings['pm_posts_verification']) && $user_info['posts'] < $modSettings['pm_posts_verification']) {
        require_once $sourcedir . '/Subs-Editor.php';
        $verificationOptions = array('id' => 'pm');
        $context['require_verification'] = create_control_verification($verificationOptions, true);
        if (is_array($context['require_verification'])) {
            $post_errors = array_merge($post_errors, $context['require_verification']);
        }
    }
    // If they did, give a chance to make ammends.
    if (!empty($post_errors) && !$is_recipient_change && !isset($_REQUEST['preview']) && !isset($_REQUEST['xml'])) {
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    }
    // Want to take a second glance before you send?
    if (isset($_REQUEST['preview'])) {
        // Set everything up to be displayed.
        $context['preview_subject'] = $smcFunc['htmlspecialchars']($_REQUEST['subject']);
        $context['preview_message'] = $smcFunc['htmlspecialchars']($_REQUEST['message'], ENT_QUOTES);
        preparsecode($context['preview_message'], true);
        // Parse out the BBC if it is enabled.
        $context['preview_message'] = parse_bbc($context['preview_message']);
        // Censor, as always.
        censorText($context['preview_subject']);
        censorText($context['preview_message']);
        // Set a descriptive title.
        $context['page_title'] = $txt['preview'] . ' - ' . $context['preview_subject'];
        // Pretend they messed up but don't ignore if they really did :P.
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    } elseif ($is_recipient_change) {
        // Maybe we couldn't find one?
        foreach ($namesNotFound as $recipientType => $names) {
            $post_errors[] = 'bad_' . $recipientType;
            foreach ($names as $name) {
                $context['send_log']['failed'][] = sprintf($txt['pm_error_user_not_found'], $name);
            }
        }
        return messagePostError(array(), $namedRecipientList, $recipientList);
    }
    // Want to save this as a draft and think about it some more?
    if (!empty($modSettings['drafts_enabled']) && !empty($modSettings['drafts_pm_enabled']) && isset($_POST['save_draft'])) {
        require_once $sourcedir . '/Drafts.php';
        SavePMDraft($post_errors, $recipientList);
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    } elseif (!empty($modSettings['max_pm_recipients']) && count($recipientList['to']) + count($recipientList['bcc']) > $modSettings['max_pm_recipients'] && !allowedTo(array('moderate_forum', 'send_mail', 'admin_forum'))) {
        $context['send_log'] = array('sent' => array(), 'failed' => array(sprintf($txt['pm_too_many_recipients'], $modSettings['max_pm_recipients'])));
        return messagePostError($post_errors, $namedRecipientList, $recipientList);
    }
    // Protect from message spamming.
    spamProtection('pm');
    // Prevent double submission of this form.
    checkSubmitOnce('check');
    // Do the actual sending of the PM.
    if (!empty($recipientList['to']) || !empty($recipientList['bcc'])) {
        $context['send_log'] = sendpm($recipientList, $_REQUEST['subject'], $_REQUEST['message'], !empty($_REQUEST['outbox']), null, !empty($_REQUEST['pm_head']) ? (int) $_REQUEST['pm_head'] : 0);
    } else {
        $context['send_log'] = array('sent' => array(), 'failed' => array());
    }
    // Mark the message as "replied to".
    if (!empty($context['send_log']['sent']) && !empty($_REQUEST['replied_to']) && isset($_REQUEST['f']) && $_REQUEST['f'] == 'inbox') {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}pm_recipients
			SET is_read = is_read | 2
			WHERE id_pm = {int:replied_to}
				AND id_member = {int:current_member}', array('current_member' => $user_info['id'], 'replied_to' => (int) $_REQUEST['replied_to']));
    }
    // If one or more of the recipient were invalid, go back to the post screen with the failed usernames.
    if (!empty($context['send_log']['failed'])) {
        return messagePostError($post_errors, $namesNotFound, array('to' => array_intersect($recipientList['to'], $context['send_log']['failed']), 'bcc' => array_intersect($recipientList['bcc'], $context['send_log']['failed'])));
    }
    // Message sent successfully?
    if (!empty($context['send_log']) && empty($context['send_log']['failed'])) {
        $context['current_label_redirect'] = $context['current_label_redirect'] . ';done=sent';
    }
    // Go back to the where they sent from, if possible...
    redirectexit($context['current_label_redirect']);
}
function up_print_page_above($left, $right, $copyright = '', $call_forum = 0, $call_front_page = 0)
{
    global $settings, $context, $txt, $options, $ultimateportalSettings, $user_info;
    if (!empty($ultimateportalSettings['up_left_right_collapse'])) {
        if (!empty($call_forum)) {
            echo '
				<div align="center">';
            if (!empty($ultimateportalSettings['up_forum_enable_col_left']) && !empty($left)) {
                echo '<img src="' . $settings['default_images_url'] . '/ultimate-portal/icons/clickandbuyleft.png" alt="" />
					<span onclick="collapse(1,\'upleftcollapse\')" style="cursor: pointer;">
						<span id="upleftcollapse">	
						 ' . ($user_info['is_guest'] ? !empty($_COOKIE['up_left']) : !empty($options['up_left']) ? $txt['ultport_unhide'] : $txt['ultport_hide']) . '
						</span>
						' . $txt['ultport_col_left'] . '
					</span>';
                echo !empty($ultimateportalSettings['up_forum_enable_col_right']) && !empty($right) && !empty($ultimateportalSettings['up_left_right_collapse']) ? '|' : '';
            }
            if (!empty($ultimateportalSettings['up_forum_enable_col_right']) && !empty($right) && !empty($ultimateportalSettings['up_left_right_collapse'])) {
                echo '
					<span onclick="collapse(2,\'uprightcollapse\')" style="cursor: pointer;">
						<span id="uprightcollapse">	
							' . ($user_info['is_guest'] ? !empty($_COOKIE['up_right']) : !empty($options['up_right']) ? $txt['ultport_unhide'] : $txt['ultport_hide']) . '
						</span>
						' . $txt['ultport_col_right'] . ' <img src="' . $settings['default_images_url'] . '/ultimate-portal/icons/clickandbuyright.png" alt="" />				
					</span>';
            }
            echo '		
				</div>';
        } else {
            echo '
				<div align="center">';
            if (!empty($ultimateportalSettings['ultimate_portal_enable_col_left']) && !empty($left) && !empty($ultimateportalSettings['up_left_right_collapse'])) {
                echo '<img src="' . $settings['default_images_url'] . '/ultimate-portal/icons/clickandbuyleft.png" alt="" />
					<span onclick="collapse(1,\'upleftcollapse\')" style="cursor: pointer;">
						<span id="upleftcollapse">	
						 ' . ($user_info['is_guest'] ? !empty($_COOKIE['up_left']) : !empty($options['up_left']) ? $txt['ultport_unhide'] : $txt['ultport_hide']) . '
						</span>
						' . $txt['ultport_col_left'] . '
					</span>';
                echo !empty($ultimateportalSettings['ultimate_portal_enable_col_right']) && !empty($right) && !empty($ultimateportalSettings['up_left_right_collapse']) ? '|' : '';
            }
            if (!empty($ultimateportalSettings['ultimate_portal_enable_col_right']) && !empty($right) && !empty($ultimateportalSettings['up_left_right_collapse'])) {
                echo '
					<span onclick="collapse(2,\'uprightcollapse\')" style="cursor: pointer;">
						<span id="uprightcollapse">	
							' . ($user_info['is_guest'] ? !empty($_COOKIE['up_right']) : !empty($options['up_right']) ? $txt['ultport_unhide'] : $txt['ultport_hide']) . '
						</span>
						' . $txt['ultport_col_right'] . '	<img src="' . $settings['default_images_url'] . '/ultimate-portal/icons/clickandbuyright.png" alt="" />			
					</span>';
            }
            echo '		
				</div>';
        }
    }
    //Global Announcements
    if (!empty($ultimateportalSettings['up_news_global_announcement'])) {
        //Now control if your theme, it's "Curve" or "Variation Curve"
        echo '
			' . (!empty($ultimateportalSettings['up_use_curve_variation']) ? '<table width="100%" cellpadding="5" cellspacing="1"><tr><td colspan="3" id="global_annoucements" align="left" valign="top" width="100%"><span class="clear upperframe"><span></span></span><div class="roundframe"><div class="innerframe"><div class="cat_bar"><h4 style="font-size:12px" class="catbg"><span class="left"></span>' : '<table class="tborder" width="100%" cellpadding="5" cellspacing="1"><tr><td class="catbg" id="global_annoucements" align="left" valign="top" width="100%">') . '
					<img style="vertical-align: middle;" alt="" border="0" src="' . $settings['default_images_url'] . '/ultimate-portal/icons/info.png"/>&nbsp;' . $txt['ultport_announcement'] . '
					<span onclick="collapseBlock(\'announcement\',\'image_collapse_announcement\')" style="cursor: pointer;">
						' . ($user_info['is_guest'] ? !empty($_COOKIE['up_bk_announcement']) : !empty($options['up_bk_announcement']) ? '<img id="image_collapse_announcement" align="right" src="' . $settings['default_theme_url'] . '/images/ultimate-portal/expand.gif" alt="+" border="0" style="padding: 8px 0pt 0pt;"/>' : '<img id="image_collapse_announcement" align="right" src="' . $settings['default_theme_url'] . '/images/ultimate-portal/collapse.gif" alt="-" border="0" style="padding: 8px 0pt 0pt;"/>') . '
					</span>
		' . (!empty($ultimateportalSettings['up_use_curve_variation']) ? '</h4></div></div>' : '</td></tr><tr><td align="left" class="windowbg" width="100%">') . '
					<p class="smallpadding" id="up_bk_announcement" ' . ($user_info['is_guest'] ? !empty($_COOKIE['up_bk_announcement']) : !empty($options['up_bk_announcement']) ? ' style="display: none;"' : '') . '>
							' . parse_bbc($ultimateportalSettings['up_news_global_announcement']) . '
					</p>
		' . (!empty($ultimateportalSettings['up_use_curve_variation']) ? '</div><span class="lowerframe"><span></span></span>' : '') . '					
				</td>
			</tr>
			</table>';
    } else {
        echo '';
    }
    //End Announcements
    //Multiblock Header
    up_print_MultiBlock('header');
    echo '	
	<table id="up_bk_table_main" summary="" style="width:100%" cellpadding="3" cellspacing="0">
		<tr>';
    if (!empty($left) && !empty($context['load_block_left'])) {
        echo '
			<td id="up_left" align="left" valign="top" width="' . (!empty($ultimateportalSettings['ultimate_portal_width_col_left']) ? $ultimateportalSettings['ultimate_portal_width_col_left'] : '15%') . '" ' . (empty($ultimateportalSettings['ultimate_portal_enable_col_left']) || ($user_info['is_guest'] ? !empty($_COOKIE['up_left']) : !empty($options['up_left'])) ? ' style="display: none;"' : '') . '>
				', up_get_column("left"), '
			</td>';
    }
    echo '					
			<td align="left" valign="top" width="' . (!empty($ultimateportalSettings['ultimate_portal_width_col_center']) ? empty($right) && empty($left) ? '100%' : $ultimateportalSettings['ultimate_portal_width_col_center'] : '70%') . '">';
    //Column Center
    if (empty($call_forum) && !empty($call_front_page)) {
        up_get_column("center");
    }
}
Example #27
0
function PackageGBrowse()
{
    global $txt, $boardurl, $context, $scripturl, $boarddir, $sourcedir, $forum_version, $context, $db_prefix;
    if (isset($_GET['server'])) {
        if ($_GET['server'] == '') {
            redirectexit('action=packageget');
        }
        $server = (int) $_GET['server'];
        // Query the server list to find the current server.
        $request = db_query("\n\t\t\tSELECT name, url\n\t\t\tFROM {$db_prefix}package_servers\n\t\t\tWHERE ID_SERVER = {$server}\n\t\t\tLIMIT 1", __FILE__, __LINE__);
        list($name, $url) = mysql_fetch_row($request);
        mysql_free_result($request);
        // If the server does not exist, dump out.
        if (empty($url)) {
            fatal_lang_error('smf191', false);
        }
        // If there is a relative link, append to the stored server url.
        if (isset($_GET['relative'])) {
            $url = $url . (substr($url, -1) == '/' ? '' : '/') . $_GET['relative'];
        }
        // Clear any "absolute" URL.  Since "server" is present, "absolute" is garbage.
        unset($_GET['absolute']);
    } elseif (isset($_GET['absolute']) && $_GET['absolute'] != '') {
        // Initialize the requried variables.
        $server = '';
        $url = $_GET['absolute'];
        $name = '';
        $_GET['package'] = $url . '/packages.xml?language=' . $context['user']['language'];
        // Clear any "relative" URL.  Since "server" is not present, "relative" is garbage.
        unset($_GET['relative']);
        $token = checkConfirm('get_absolute_url');
        if ($token !== true) {
            $context['sub_template'] = 'package_confirm';
            $context['page_title'] = $txt['smf183'];
            $context['confirm_message'] = sprintf($txt['package_confirm_view_package_content'], htmlspecialchars($_GET['absolute']));
            $context['proceed_href'] = $scripturl . '?action=packageget;sa=browse;absolute=' . urlencode($_GET['absolute']) . ';confirm=' . $token;
            return;
        }
    } else {
        fatal_lang_error('smf191', false);
    }
    // In safe mode or on lycos?  Try this URL. (includes package-list for informational purposes ;).)
    //if (@ini_get('safe_mode'))
    //	redirectexit($url . '/index.php?package-list&language=' . $context['user']['language'] . '&ref=' . $boardurl);
    // Attempt to connect.  If unsuccessful... try the URL.
    if (!isset($_GET['package']) || file_exists($_GET['package'])) {
        $_GET['package'] = $url . '/packages.xml?language=' . $context['user']['language'];
    }
    // Check to be sure the packages.xml file actually exists where it is should be... or dump out.
    if ((isset($_GET['absolute']) || isset($_GET['relative'])) && !url_exists($_GET['package'])) {
        fatal_lang_error('packageget_unable', false, array($url . '/index.php'));
    }
    // Read packages.xml and parse into xmlArray. (the true tells it to trim things ;).)
    $listing = new xmlArray(fetch_web_data($_GET['package']), true);
    // Errm.... empty file?  Try the URL....
    if (!$listing->exists('package-list')) {
        fatal_lang_error('packageget_unable', false, array($url . '/index.php'));
    }
    // List out the packages...
    $context['package_list'] = array();
    $listing = $listing->path('package-list[0]');
    // Use the package list's name if it exists.
    if ($listing->exists('list-title')) {
        $name = $listing->fetch('list-title');
    }
    // Pick the correct template.
    $context['sub_template'] = 'package_list';
    $context['page_title'] = $txt['smf183'] . ($name != '' ? ' - ' . $name : '');
    $context['package_server'] = $server;
    $instmods = loadInstalledPackages();
    // Look through the list of installed mods...
    foreach ($instmods as $installed_mod) {
        $installed_mods[$installed_mod['id']] = $installed_mod['version'];
    }
    // Get default author and email if they exist.
    if ($listing->exists('default-author')) {
        $default_author = htmlspecialchars($listing->fetch('default-author'));
        if ($listing->exists('default-author/@email')) {
            $default_email = $listing->fetch('default-author/@email');
        }
    }
    // Get default web site if it exists.
    if ($listing->exists('default-website')) {
        $default_website = $listing->fetch('default-website');
        if ($listing->exists('default-website/@title')) {
            $default_title = htmlspecialchars($listing->fetch('default-website/@title'));
        }
    }
    $the_version = strtr($forum_version, array('SMF ' => ''));
    if (!empty($_SESSION['version_emulate'])) {
        $the_version = $_SESSION['version_emulate'];
    }
    $packageNum = 0;
    $sections = $listing->set('section');
    foreach ($sections as $i => $section) {
        $packages = $section->set('title|heading|text|remote|rule|modification|language|avatar-pack|theme|smiley-set');
        foreach ($packages as $thisPackage) {
            $package =& $context['package_list'][];
            $package['type'] = $thisPackage->name();
            // It's a Title, Heading, Rule or Text.
            if (in_array($package['type'], array('title', 'heading', 'text', 'rule'))) {
                $package['name'] = htmlspecialchars($thisPackage->fetch('.'));
            } elseif ($package['type'] == 'remote') {
                $remote_type = $thisPackage->exists('@type') ? $thisPackage->fetch('@type') : 'relative';
                if ($remote_type == 'relative' && substr($thisPackage->fetch('@href'), 0, 7) != 'http://') {
                    if (isset($_GET['absolute'])) {
                        $current_url = $_GET['absolute'] . '/';
                    } elseif (isset($_GET['relative'])) {
                        $current_url = $_GET['relative'] . '/';
                    } else {
                        $current_url = '';
                    }
                    $current_url .= $thisPackage->fetch('@href');
                    if (isset($_GET['absolute'])) {
                        $package['href'] = $scripturl . '?action=packageget;sa=browse;absolute=' . $current_url;
                    } else {
                        $package['href'] = $scripturl . '?action=packageget;sa=browse;server=' . $context['package_server'] . ';relative=' . $current_url;
                    }
                } else {
                    $current_url = $thisPackage->fetch('@href');
                    $package['href'] = $scripturl . '?action=packageget;sa=browse;absolute=' . $current_url;
                }
                $package['name'] = htmlspecialchars($thisPackage->fetch('.'));
                $package['link'] = '<a href="' . $package['href'] . '">' . $package['name'] . '</a>';
            } else {
                if (isset($_GET['absolute'])) {
                    $current_url = $_GET['absolute'] . '/';
                } elseif (isset($_GET['relative'])) {
                    $current_url = $_GET['relative'] . '/';
                } else {
                    $current_url = '';
                }
                $server_att = $server != '' ? ';server=' . $server : '';
                $package += $thisPackage->to_array();
                if (isset($package['website'])) {
                    unset($package['website']);
                }
                $package['author'] = array();
                if ($package['description'] == '') {
                    $package['description'] = $txt['pacman8'];
                } else {
                    $package['description'] = parse_bbc(preg_replace('~\\[[/]?html\\]~i', '', htmlspecialchars($package['description'])));
                }
                $package['is_installed'] = isset($installed_mods[$package['id']]);
                $package['is_current'] = $package['is_installed'] && $installed_mods[$package['id']] == $package['version'];
                $package['is_newer'] = $package['is_installed'] && $installed_mods[$package['id']] > $package['version'];
                // This package is either not installed, or installed but old.  Is it supported on this version of SMF?
                if (!$package['is_installed'] || !$package['is_current'] && !$package['is_newer']) {
                    if ($thisPackage->exists('version/@for')) {
                        $package['can_install'] = matchPackageVersion($the_version, $thisPackage->fetch('version/@for'));
                    }
                } else {
                    $package['can_install'] = false;
                }
                $already_exists = getPackageInfo(basename($package['filename']));
                $package['download_conflict'] = !empty($already_exists) && $already_exists['id'] == $package['id'] && $already_exists['version'] != $package['version'];
                $package['href'] = $url . '/' . $package['filename'];
                $package['name'] = htmlspecialchars($package['name']);
                $package['link'] = '<a href="' . $package['href'] . '">' . $package['name'] . '</a>';
                $package['download']['href'] = $scripturl . '?action=packageget;sa=download' . $server_att . ';package=' . $current_url . $package['filename'] . ($package['download_conflict'] ? ';conflict' : '') . ';sesc=' . $context['session_id'];
                $package['download']['link'] = '<a href="' . $package['download']['href'] . '">' . $package['name'] . '</a>';
                if ($thisPackage->exists('author') || isset($default_author)) {
                    if ($thisPackage->exists('author/@email')) {
                        $package['author']['email'] = htmlspecialchars($thisPackage->fetch('author/@email'));
                    } elseif (isset($default_email)) {
                        $package['author']['email'] = $default_email;
                    }
                    if ($thisPackage->exists('author') && $thisPackage->fetch('author') != '') {
                        $package['author']['name'] = htmlspecialchars($thisPackage->fetch('author'));
                    } else {
                        $package['author']['name'] = $default_author;
                    }
                    if (!empty($package['author']['email'])) {
                        // Only put the "mailto:" if it looks like a valid email address.  Some may wish to put a link to an SMF IM Form or other web mail form.
                        $package['author']['href'] = preg_match('~^[\\w\\.\\-]+@[\\w][\\w\\-\\.]+[\\w]$~', $package['author']['email']) != 0 ? 'mailto:' . $package['author']['email'] : $package['author']['email'];
                        $package['author']['link'] = '<a href="' . $package['author']['href'] . '">' . $package['author']['name'] . '</a>';
                    }
                }
                if ($thisPackage->exists('website') || isset($default_website)) {
                    if ($thisPackage->exists('website') && $thisPackage->exists('website/@title')) {
                        $package['author']['website']['name'] = htmlspecialchars($thisPackage->fetch('website/@title'));
                    } elseif (isset($default_title)) {
                        $package['author']['website']['name'] = $default_title;
                    } elseif ($thisPackage->exists('website')) {
                        $package['author']['website']['name'] = htmlspecialchars($thisPackage->fetch('website'));
                    } else {
                        $package['author']['website']['name'] = $default_website;
                    }
                    if ($thisPackage->exists('website') && $thisPackage->fetch('website') != '') {
                        $authorhompage = $thisPackage->fetch('website');
                    } else {
                        $authorhompage = $default_website;
                    }
                    if (strpos(strtolower($authorhompage), 'a href') === false) {
                        $package['author']['website']['href'] = $authorhompage;
                        $package['author']['website']['link'] = '<a href="' . $authorhompage . '">' . $package['author']['website']['name'] . '</a>';
                    } else {
                        if (preg_match('/a href="(.+?)"/', $authorhompage, $match) == 1) {
                            $package['author']['website']['href'] = $match[1];
                        } else {
                            $package['author']['website']['href'] = '';
                        }
                        $package['author']['website']['link'] = $authorhompage;
                    }
                } else {
                    $package['author']['website']['href'] = '';
                    $package['author']['website']['link'] = '';
                }
            }
            $package['is_remote'] = $package['type'] == 'remote';
            $package['is_title'] = $package['type'] == 'title';
            $package['is_heading'] = $package['type'] == 'heading';
            $package['is_text'] = $package['type'] == 'text';
            $package['is_line'] = $package['type'] == 'rule';
            $packageNum = in_array($package['type'], array('title', 'heading', 'text', 'remote', 'rule')) ? 0 : $packageNum + 1;
            $package['count'] = $packageNum;
        }
    }
    // Lets make sure we get a nice new spiffy clean $package to work with.  Otherwise we get PAIN!
    unset($package);
    foreach ($context['package_list'] as $i => $package) {
        if ($package['count'] == 0 || isset($package['can_install'])) {
            continue;
        }
        $context['package_list'][$i]['can_install'] = false;
        $packageInfo = getPackageInfo($url . '/' . $package['filename']);
        if (!empty($packageInfo) && $packageInfo['xml']->exists('install')) {
            $installs = $packageInfo['xml']->set('install');
            foreach ($installs as $install) {
                if (!$install->exists('@for') || matchPackageVersion($the_version, $install->fetch('@for'))) {
                    // Okay, this one is good to go.
                    $context['package_list'][$i]['can_install'] = true;
                    break;
                }
            }
        }
    }
}
function template_tpshout_shoutblock()
{
    global $context, $scripturl, $txt, $settings;
    if (!isset($context['TPortal']['shoutbox'])) {
        $context['TPortal']['shoutbox'] = '';
    }
    $context['tp_shoutbox_form'] = 'tp_shoutbox';
    $context['tp_shout_post_box_name'] = 'tp_shout';
    if (!empty($context['TPortal']['shoutbox_stitle'])) {
        echo '<p style="margin-top: 0;">' . parse_bbc($context['TPortal']['shoutbox_stitle'], true) . '</p><hr><br>';
    }
    if ($context['TPortal']['shoutbox_usescroll'] > '0') {
        echo '
		<marquee id="tp_marquee" behavior="scroll" direction="down" scrollamount="' . $context['TPortal']['shoutbox_scrollduration'] . '" height="' . $context['TPortal']['shoutbox_height'] . '">
			<div class="tp_shoutframe">' . $context['TPortal']['shoutbox'] . '</div>
		</marquee>';
    } else {
        echo '
    <table cellpadding="0" align="center" width="100%" cellspacing="0" style="table-layout: fixed;">
		<tr>
			<td>
				<div class="middletext" style="width: 99%; height: ' . $context['TPortal']['shoutbox_height'] . 'px; overflow: auto;">
					<div class="tp_shoutframe">' . $context['TPortal']['shoutbox'] . '</div>
				</div>
			</td>
		</tr>
	</table>';
    }
    if (!$context['user']['is_guest'] && allowedTo('tp_can_shout')) {
        echo '
		<form  accept-charset="' . $context['character_set'] . '" class="smalltext" style="padding: 0; text-align: center; margin: 0; width: 95%;" name="' . $context['tp_shoutbox_form'] . '"  id="' . $context['tp_shoutbox_form'] . '" action="' . $scripturl . '?action=tpmod;shout=save" method="post" ><hr>
		<textarea class="editor" name="' . $context['tp_shout_post_box_name'] . '" id="' . $context['tp_shout_post_box_name'] . '" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onchange="storeCaret(this);" style="width: 100%;margin-top: 1em; height: 80px;"  tabindex="', $context['tabindex']++, '"></textarea><br />';
        if (!empty($context['TPortal']['show_shoutbox_smile'])) {
            shout_smiley_code();
            print_shout_smileys();
        }
        if (!empty($context['TPortal']['show_shoutbox_icons'])) {
            shout_bcc_code();
        }
        echo '
		<div id="shout_errors"></div><hr>
		<div style="overflow: hidden;">
			<a href="', $scripturl, '?action=tpmod;shout=show50" title="' . $txt['tp-shout-history'] . '"><img class="floatleft" src="' . $settings['tp_images_url'] . '/TPhistory.png" alt="" /></a>
			<input onclick="TPupdateShouts(\'save\'); return false;" type="submit" name="shout_send" value="&nbsp;' . $txt['shout!'] . '&nbsp;" tabindex="', $context['tabindex']++, '" class="button_submit" />
			<a id="tp_shout_refresh" onclick="TPupdateShouts(\'fetch\'); return false;" href="', $scripturl, '?action=tpmod;shout=refresh" title="' . $txt['tp-shout-refresh'] . '"><img class="floatright" src="' . $settings['tp_images_url'] . '/TPrefresh.png" alt="" /></a>
		</div>
		<input type="hidden" id="tp-shout-name" name="tp-shout-name" value="' . $context['user']['name'] . '" />
		<input type="hidden" name="sc" value="', $context['session_id'], '" />
	</form>';
    }
}
Example #29
0
function loadMemberContext($user)
{
    global $memberContext, $user_profile, $txt, $scripturl, $user_info;
    global $context, $modSettings, $ID_MEMBER, $board_info, $settings;
    global $db_prefix, $func;
    static $dataLoaded = array();
    // If this person's data is already loaded, skip it.
    if (isset($dataLoaded[$user])) {
        return true;
    }
    // We can't load guests or members not loaded by loadMemberData()!
    if ($user == 0) {
        return false;
    }
    if (!isset($user_profile[$user])) {
        trigger_error('loadMemberContext(): member id ' . $user . ' not previously loaded by loadMemberData()', E_USER_WARNING);
        return false;
    }
    // Well, it's loaded now anyhow.
    $dataLoaded[$user] = true;
    $profile = $user_profile[$user];
    // Censor everything.
    censorText($profile['signature']);
    censorText($profile['personalText']);
    censorText($profile['location']);
    // Set things up to be used before hand.
    $gendertxt = $profile['gender'] == 2 ? $txt[239] : ($profile['gender'] == 1 ? $txt[238] : '');
    $profile['signature'] = str_replace(array("\n", "\r"), array('<br />', ''), $profile['signature']);
    $profile['signature'] = parse_bbc($profile['signature'], true, 'sig' . $profile['ID_MEMBER']);
    $profile['is_online'] = (!empty($profile['showOnline']) || allowedTo('moderate_forum')) && $profile['isOnline'] > 0;
    $profile['stars'] = empty($profile['stars']) ? array('', '') : explode('#', $profile['stars']);
    // Setup the buddy status here (One whole in_array call saved :P)
    $profile['buddy'] = in_array($profile['ID_MEMBER'], $user_info['buddies']);
    $buddy_list = !empty($profile['buddy_list']) ? explode(',', $profile['buddy_list']) : array();
    // If we're always html resizing, assume it's too large.
    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 = '';
    }
    // What a monstrous array...
    $memberContext[$user] = array('username' => &$profile['memberName'], 'name' => &$profile['realName'], 'id' => &$profile['ID_MEMBER'], 'is_guest' => $profile['ID_MEMBER'] == 0, 'is_buddy' => $profile['buddy'], 'is_reverse_buddy' => in_array($ID_MEMBER, $buddy_list), 'buddies' => $buddy_list, 'title' => !empty($modSettings['titlesEnable']) ? $profile['usertitle'] : '', 'href' => $scripturl . '?action=profile;u=' . $profile['ID_MEMBER'], 'link' => '<a href="' . $scripturl . '?action=profile;u=' . $profile['ID_MEMBER'] . '" title="' . $txt[92] . ' ' . $profile['realName'] . '">' . $profile['realName'] . '</a>', 'email' => &$profile['emailAddress'], 'hide_email' => $profile['emailAddress'] == '' || !empty($modSettings['guest_hideContacts']) && $user_info['is_guest'] || !empty($profile['hideEmail']) && !empty($modSettings['allow_hideEmail']) && !allowedTo('moderate_forum') && $ID_MEMBER != $profile['ID_MEMBER'], 'email_public' => (empty($profile['hideEmail']) || empty($modSettings['allow_hideEmail'])) && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']), 'registered' => empty($profile['dateRegistered']) ? $txt[470] : timeformat($profile['dateRegistered']), 'registered_timestamp' => empty($profile['dateRegistered']) ? 0 : forum_time(true, $profile['dateRegistered']), 'blurb' => &$profile['personalText'], 'gender' => array('name' => $gendertxt, 'image' => !empty($profile['gender']) ? '<img src="' . $settings['images_url'] . '/' . ($profile['gender'] == 1 ? 'Male' : 'Female') . '.gif" alt="' . $gendertxt . '" border="0" />' : ''), 'website' => array('title' => &$profile['websiteTitle'], 'url' => &$profile['websiteUrl']), 'birth_date' => empty($profile['birthdate']) || $profile['birthdate'] === '0001-01-01' ? '0000-00-00' : (substr($profile['birthdate'], 0, 4) === '0004' ? '0000' . substr($profile['birthdate'], 4) : $profile['birthdate']), 'signature' => &$profile['signature'], 'location' => &$profile['location'], 'icq' => $profile['ICQ'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array('name' => &$profile['ICQ'], 'href' => 'http://www.icq.com/whitepages/about_me.php?uin=' . $profile['ICQ'], 'link' => '<a href="http://www.icq.com/whitepages/about_me.php?uin=' . $profile['ICQ'] . '" target="_blank"><img src="http://status.icq.com/online.gif?img=5&amp;icq=' . $profile['ICQ'] . '" alt="' . $profile['ICQ'] . '" width="18" height="18" border="0" /></a>', 'link_text' => '<a href="http://www.icq.com/whitepages/about_me.php?uin=' . $profile['ICQ'] . '" target="_blank">' . $profile['ICQ'] . '</a>') : array('name' => '', 'add' => '', 'href' => '', 'link' => '', 'link_text' => ''), 'aim' => $profile['AIM'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array('name' => &$profile['AIM'], 'href' => 'aim:goim?screenname=' . urlencode(strtr($profile['AIM'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'], 'link' => '<a href="aim:goim?screenname=' . urlencode(strtr($profile['AIM'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'] . '"><img src="' . $settings['images_url'] . '/aim.gif" alt="' . $profile['AIM'] . '" border="0" /></a>', 'link_text' => '<a href="aim:goim?screenname=' . urlencode(strtr($profile['AIM'], array(' ' => '%20'))) . '&amp;message=' . $txt['aim_default_message'] . '">' . $profile['AIM'] . '</a>') : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''), 'yim' => $profile['YIM'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array('name' => &$profile['YIM'], 'href' => 'http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['YIM']), 'link' => '<a href="http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['YIM']) . '"><img src="http://opi.yahoo.com/online?u=' . urlencode($profile['YIM']) . '&amp;m=g&amp;t=0" alt="' . $profile['YIM'] . '" border="0" /></a>', 'link_text' => '<a href="http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($profile['YIM']) . '">' . $profile['YIM'] . '</a>') : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''), 'msn' => $profile['MSN'] != '' && (empty($modSettings['guest_hideContacts']) || !$user_info['is_guest']) ? array('name' => &$profile['MSN'], 'href' => 'http://members.msn.com/' . $profile['MSN'], 'link' => '<a href="http://members.msn.com/' . $profile['MSN'] . '" target="_blank"><img src="' . $settings['images_url'] . '/msntalk.gif" alt="' . $profile['MSN'] . '" border="0" /></a>', 'link_text' => '<a href="http://members.msn.com/' . $profile['MSN'] . '" target="_blank">' . $profile['MSN'] . '</a>') : array('name' => '', 'href' => '', 'link' => '', 'link_text' => ''), 'real_posts' => $profile['posts'], 'posts' => $profile['posts'] > 100000 ? $txt[683] : ($profile['posts'] == 1337 ? 'leet' : comma_format($profile['posts'])), 'avatar' => array('name' => &$profile['avatar'], 'image' => $profile['avatar'] == '' ? $profile['ID_ATTACH'] > 0 ? '<img src="' . (empty($profile['attachmentType']) ? $scripturl . '?action=dlattach;attach=' . $profile['ID_ATTACH'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename']) . '" alt="" class="avatar" border="0" />' : '' : (stristr($profile['avatar'], 'http://') ? '<img src="' . $profile['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" class="avatar" border="0" />' : '<img src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($profile['avatar']) . '" alt="" class="avatar" border="0" />'), 'href' => $profile['avatar'] == '' ? $profile['ID_ATTACH'] > 0 ? empty($profile['attachmentType']) ? $scripturl . '?action=dlattach;attach=' . $profile['ID_ATTACH'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $profile['filename'] : '' : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar']), 'url' => $profile['avatar'] == '' ? '' : (stristr($profile['avatar'], 'http://') ? $profile['avatar'] : $modSettings['avatar_url'] . '/' . $profile['avatar'])), 'last_login' => empty($profile['lastLogin']) ? $txt['never'] : timeformat($profile['lastLogin']), 'last_login_timestamp' => empty($profile['lastLogin']) ? 0 : forum_time(0, $profile['lastLogin']), 'karma' => array('good' => &$profile['karmaGood'], 'bad' => &$profile['karmaBad'], 'allow' => !$user_info['is_guest'] && $user_info['posts'] >= $modSettings['karmaMinPosts'] && allowedTo('karma_edit') && !empty($modSettings['karmaMode']) && $ID_MEMBER != $user), 'ip' => htmlspecialchars($profile['memberIP']), 'ip2' => htmlspecialchars($profile['memberIP2']), 'online' => array('is_online' => $profile['is_online'], 'text' => &$txt[$profile['is_online'] ? 'online2' : 'online3'], 'href' => $scripturl . '?action=pm;sa=send;u=' . $profile['ID_MEMBER'], 'link' => '<a href="' . $scripturl . '?action=pm;sa=send;u=' . $profile['ID_MEMBER'] . '">' . $txt[$profile['is_online'] ? 'online2' : 'online3'] . '</a>', 'image_href' => $settings['images_url'] . '/' . ($profile['buddy'] ? 'buddy_' : '') . ($profile['is_online'] ? 'useron' : 'useroff') . '.gif', 'label' => &$txt[$profile['is_online'] ? 'online4' : 'online5']), 'language' => $func['ucwords'](strtr($profile['lngfile'], array('_' => ' ', '-utf8' => ''))), 'is_activated' => isset($profile['is_activated']) ? $profile['is_activated'] : 1, 'is_banned' => isset($profile['is_activated']) ? $profile['is_activated'] >= 10 : 0, 'options' => $profile['options'], 'is_guest' => false, 'group' => $profile['member_group'], 'group_color' => $profile['member_group_color'], 'group_id' => $profile['ID_GROUP'], 'post_group' => $profile['post_group'], 'post_group_color' => $profile['post_group_color'], 'group_stars' => str_repeat('<img src="' . str_replace('$language', $context['user']['language'], isset($profile['stars'][1]) ? $settings['images_url'] . '/' . $profile['stars'][1] : '') . '" alt="*" border="0" />', empty($profile['stars'][0]) || empty($profile['stars'][1]) ? 0 : $profile['stars'][0]), 'local_time' => timeformat(time() + ($profile['timeOffset'] - $user_info['time_offset']) * 3600, false));
    return true;
}
/**
* Receive all the posts from the articles manager, check it, then save it.
* Finally the articles are prepared and the template loaded.
*/
function PortaMx_AdminArticles()
{
    global $smcFunc, $pmxCacheFunc, $context, $sourcedir, $scripturl, $modSettings, $user_info, $txt;
    $admMode = isset($_GET['action']) ? $_GET['action'] : '';
    // fix the linktree
    if ($admMode == 'admin') {
        foreach ($context['linktree'] as $key => $data) {
            if (strpos($data['url'], 'pmx_articles') !== false) {
                $context['linktree'] = array_merge(array_slice($context['linktree'], 0, $key), array(array('url' => $scripturl . '?action=admin;area=pmx_center;' . $context['session_var'] . '=' . $context['session_id'], 'name' => $txt['pmx_extension'])), array_slice($context['linktree'], $key, count($context['linktree']) - $key));
                break;
            }
        }
    }
    if (($admMode == 'admin' || $admMode == 'portamx') && isset($_GET['area']) && $_GET['area'] == 'pmx_articles') {
        if (allowPmx('pmx_admin, pmx_articles, pmx_create')) {
            require_once $context['pmx_sourcedir'] . 'AdminSubs.php';
            $context['pmx']['subaction'] = !empty($_POST['sa']) ? $_POST['sa'] : 'overview';
            // From template ?
            if (PortaMx_checkPOST()) {
                // Make sure we have a valid session...
                checkSession('post');
                // get current pageindex
                if (isset($_POST['articlestart'])) {
                    $context['pmx']['articlestart'] = $_POST['articlestart'];
                }
                // actions from overview?
                if ($context['pmx']['subaction'] == 'overview' && empty($_POST['cancel_overview'])) {
                    // from xml on overview?
                    if (isset($_POST['xml'])) {
                        $xmlResult = '';
                    }
                    // filter set ?
                    if (isset($_POST['filter'])) {
                        $_SESSION['PortaMx']['filter'] = $_POST['filter'];
                    }
                    // Row pos updates from overview?
                    if (!empty($_POST['upd_rowpos'])) {
                        list($fromID, $place, $idto) = Pmx_StrToArray($_POST['upd_rowpos']);
                        $request = $smcFunc['db_query']('', '
							SELECT id
							FROM {db_prefix}portamx_articles
							WHERE id ' . ($place == 'before' ? '<' : '>') . ' {int:id}
							LIMIT 1', array('id' => $idto));
                        list($toID) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        $toID = is_null($toID) ? $place == 'before' ? -1 : 0 : $toID;
                        $request = $smcFunc['db_query']('', '
							SELECT MAX(id) +1
							FROM {db_prefix}portamx_articles', array());
                        list($maxID) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // create the query...
                        if ($toID == -1) {
                            // move from to first
                            $query = array('SET id = 0 WHERE id = ' . $fromID, 'SET id = id + 1 WHERE id >= 1 AND id <= ' . $fromID, 'SET id = 1 WHERE id = 0');
                        } elseif ($toID == 0) {
                            // move from to end
                            $query = array('SET id = ' . $maxID . ' WHERE id = ' . $fromID, 'SET id = id - 1 WHERE id >= ' . $fromID);
                        } elseif ($toID > $fromID) {
                            // to > from - move to after from
                            $query = array('SET id = id + 1 WHERE id >= ' . $toID, 'SET id = ' . $toID . ' WHERE id = ' . $fromID, 'SET id = id - 1 WHERE id >= ' . $fromID);
                        } else {
                            // to < from - move to before from
                            $query = array('SET id = 0 WHERE id = ' . $fromID, 'SET id = id + 1 WHERE id >= ' . $toID . ' AND id <= ' . $fromID, 'SET id = ' . $toID . ' WHERE id = 0');
                        }
                        // execute
                        foreach ($query as $qdata) {
                            $smcFunc['db_query']('', 'UPDATE {db_prefix}portamx_articles ' . $qdata, array());
                        }
                    }
                    // updates from overview popups ?
                    if (!empty($_POST['upd_overview'])) {
                        $updates = array();
                        foreach ($_POST['upd_overview'] as $updkey => $updvalues) {
                            foreach ($updvalues as $id => $values) {
                                if ($updkey == 'title') {
                                    foreach ($values as $key => $val) {
                                        if ($key == 'lang') {
                                            foreach ($val as $langname => $langvalue) {
                                                $updates[$id]['config'][$updkey][$langname] = $langvalue;
                                            }
                                        } else {
                                            $updates[$id]['config'][$updkey . '_' . $key] = $val;
                                        }
                                    }
                                } else {
                                    $updates[$id][$updkey] = $values;
                                }
                            }
                        }
                        // save all updates
                        $idList = array();
                        $catList = array();
                        foreach ($updates as $id => $values) {
                            $idList[] = $id;
                            foreach ($values as $rowname => $data) {
                                $request = $smcFunc['db_query']('', '
									SELECT config, catid, acsgrp
									FROM {db_prefix}portamx_articles
									WHERE id = {int:id}', array('id' => $id));
                                $row = $smcFunc['db_fetch_assoc']($request);
                                $smcFunc['db_free_result']($request);
                                $catList[] = $row['catid'];
                                // update config
                                if ($rowname == 'config') {
                                    $cfg = unserialize($row['config']);
                                    foreach ($data as $ckey => $cval) {
                                        if ($ckey == 'title') {
                                            foreach ($cval as $lang => $val) {
                                                $cfg[$ckey][$lang] = $val;
                                            }
                                        } else {
                                            $cfg[$ckey] = $cval;
                                        }
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET config = {string:config}
										WHERE id = {int:id}', array('id' => $id, 'config' => serialize($cfg)));
                                } elseif ($rowname == 'category') {
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET catid = {int:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => $data));
                                } else {
                                    $mode = substr($rowname, 0, 3);
                                    // update (replace)
                                    if ($mode == 'upd') {
                                        $newacs = explode(',', $data);
                                    } elseif ($mode == 'add') {
                                        $newacs = array_unique(array_merge(explode(',', $row['acsgrp']), explode(',', $data)));
                                    } else {
                                        $newacs = array_unique(array_diff(explode(',', $row['acsgrp']), explode(',', $data)));
                                    }
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_articles
										SET acsgrp = {string:val}
										WHERE id = {int:id}', array('id' => $id, 'val' => implode(',', $newacs)));
                                    // send by xml?
                                    if (isset($_POST['xml'])) {
                                        $request = $smcFunc['db_query']('', '
											SELECT active
											FROM {db_prefix}portamx_articles
											WHERE id = {int:id}', array('id' => $id));
                                        list($active) = $smcFunc['db_fetch_row']($request);
                                        $smcFunc['db_free_result']($request);
                                        $acsnew = implode(',', $newacs);
                                        $xmlResult .= (!empty($xmlResult) ? '&' : '') . $id . '|' . $acsnew . '|' . count($newacs) . '|' . intval(allowPmxGroup($newacs)) . '|' . (!empty($active) ? '1' : '0');
                                    }
                                }
                            }
                        }
                        // clear cached blocks && Cat/Art Session Keys
                        $pmxCacheFunc['clean']();
                        if (isset($_SESSION['PortaMx'])) {
                            foreach ($_SESSION['PortaMx'] as $key => $val) {
                                if (strpos($key, 'pmxpost_') !== false) {
                                    unset($_SESSION['PortaMx'][$key]);
                                }
                            }
                        }
                        if (isset($_POST['xml'])) {
                            // return update result
                            ob_start();
                            if (!empty($_POST['result'])) {
                                echo $_POST['result'];
                            } else {
                                echo $xmlResult;
                            }
                            ob_end_flush();
                            exit;
                        }
                    }
                    // add a new article
                    if (!empty($_POST['add_new_article'])) {
                        $article = PortaMx_getDefaultArticle($_POST['add_new_article']);
                        $context['pmx']['subaction'] = 'editnew';
                    } elseif (!empty($_POST['edit_article']) || !empty($_POST['clone_article'])) {
                        $id = !empty($_POST['clone_article']) ? $_POST['clone_article'] : $_POST['edit_article'];
                        // load the article for edit/clone
                        $request = $smcFunc['db_query']('', '
							SELECT *
							FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $id));
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $article = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $row['config'], 'content' => $row['content'], 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby']);
                        $smcFunc['db_free_result']($request);
                        if (!empty($_POST['clone_article'])) {
                            $article['id'] = 0;
                            $article['active'] = 0;
                            $article['approved'] = 0;
                            $article['owner'] = $user_info['id'];
                            $article['created'] = 0;
                            $article['updated'] = 0;
                            $article['updatedby'] = 0;
                            $context['pmx']['subaction'] = 'editnew';
                        } else {
                            $context['pmx']['subaction'] = 'edit';
                        }
                    } elseif (!empty($_POST['delete_article'])) {
                        $delid = $_POST['delete_article'];
                        // get the current page
                        $context['pmx']['articlestart'] = getCurrentPage($delid, $context['pmx']['settings']['manager']['artpage'], true);
                        $smcFunc['db_query']('', '
							DELETE FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $delid));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    } elseif (!empty($_POST['chg_approved'])) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_articles
							SET approved = CASE WHEN approved = 0 THEN {int:apptime} ELSE 0 END, approvedby = {int:appmember}
							WHERE id = {int:id}', array('id' => $_POST['chg_approved'], 'apptime' => forum_time(), 'appmember' => $user_info['id']));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    } elseif (!empty($_POST['chg_active'])) {
                        $smcFunc['db_query']('', '
							UPDATE {db_prefix}portamx_articles
							SET active = CASE WHEN active = 0 THEN {int:apptime} ELSE 0 END
							WHERE id = {int:id}', array('id' => $_POST['chg_active'], 'apptime' => forum_time()));
                        // clear cached blocks
                        $pmxCacheFunc['clean']();
                    }
                    if (isset($_POST['xml']) && (!empty($_POST['chg_active']) || !empty($_POST['chg_approved']))) {
                        $id = !empty($_POST['chg_active']) ? $_POST['chg_active'] : $_POST['chg_approved'];
                        $request = $smcFunc['db_query']('', '
							SELECT active, approved
							FROM {db_prefix}portamx_articles
							WHERE id = {int:id}', array('id' => $id));
                        list($active, $approved) = $smcFunc['db_fetch_row']($request);
                        $smcFunc['db_free_result']($request);
                        // return update result
                        ob_start();
                        echo $id . ',' . (!empty($_POST['chg_active']) ? intval(!empty($active)) : intval(!empty($approved)));
                        ob_end_flush();
                        exit;
                    }
                } elseif (!empty($_POST['cancel_edit']) || !empty($_POST['cancel_overview'])) {
                    // called fron blocks move/clone ?
                    if (!empty($_POST['fromblock'])) {
                        // on cancel after saved remove the article
                        if ($_POST['sa'] == 'edit' && !empty($_POST['id'])) {
                            $smcFunc['db_query']('', '
								DELETE FROM {db_prefix}portamx_articles
								WHERE id = {int:id}', array('id' => $_POST['id']));
                            $pmxCacheFunc['clean']();
                        }
                        // redirect back to the blocks manager
                        @(list($mode, $side, $bid) = explode('.', $_POST['fromblock']));
                        redirectexit('action=' . $admMode . ';area=pmx_blocks;sa=' . $side . ';' . $context['session_var'] . '=' . $context['session_id']);
                    }
                    // Otherwise let's load the overview
                    $context['pmx']['subaction'] = 'overview';
                } elseif ($context['pmx']['subaction'] == 'editnew' || $context['pmx']['subaction'] == 'edit') {
                    $context['pmx']['fromblock'] = $_POST['fromblock'];
                    // check defined numeric vars (check_num_vars holds the posted array to check like [varname][varname] ...)
                    if (isset($_POST['check_num_vars'])) {
                        foreach ($_POST['check_num_vars'] as $val) {
                            $data = explode(',', $val);
                            $post = '$_POST' . str_replace(array('[', ']'), array('[\'', '\']'), $data[0]);
                            if (eval("return isset({$post});") && eval("return !is_numeric({$post});")) {
                                eval("{$post} = {$data['1']};");
                            }
                        }
                    }
                    if (isset($_POST['content']) && PortaMx_makeSafeContent($_POST['content']) != '') {
                        // convert html/script to bbc
                        if ($_POST['ctype'] == 'bbc_script' && in_array($_POST['contenttype'], array('html', 'script'))) {
                            $_POST['content'] = PortaMx_SmileyToBBC($_POST['content']);
                            if (preg_match_all('/<img.*(style[^\\"]*\\"([^\\"]*\\"))[^>]*>/U', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $repl = ' ' . str_replace(array('"', ': ', ':', 'px;'), array('', '="', '="', '" '), $match[2][$key]);
                                    $_POST['content'] = str_replace($val, str_replace($match[1][$key], $repl, $val), $_POST['content']);
                                }
                            }
                            require_once $sourcedir . '/Subs-Editor.php';
                            $modSettings['smiley_enable'] = true;
                            $user_info['smiley_set'] = 'PortaMx';
                            $_POST['content'] = html_to_bbc($_POST['content']);
                        } elseif ($_POST['contenttype'] == 'bbc_script' && in_array($_POST['ctype'], array('html', 'script'))) {
                            $_POST['content'] = PortaMx_BBCsmileys(parse_bbc(PortaMx_makeSafeContent($_POST['content'], $_POST['contenttype']), false));
                            $_POST['content'] = str_replace(array('<hr>', '<br>'), array('<hr />', '<br />'), $_POST['content']);
                            $_POST['content'] = preg_replace_callback('/<\\/[^>]*>|<[^\\/]*\\/>|<ul[^>]*>|<ol[^>]*>/', create_function('$matches', 'return $matches[0] ."\\n";'), $_POST['content']);
                            if (preg_match_all('/<img[^w]*(width=\\"([0-9]+)\\")(\\sheight=\\"([\\s0-9]+)\\")[^>]*>/', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $_POST['content'] = str_replace($match[1][$key], '', $_POST['content']);
                                    $_POST['content'] = str_replace($match[3][$key], 'style="width: ' . $match[2][$key] . 'px;height: ' . $match[4][$key] . 'px;"', $_POST['content']);
                                }
                                $_POST['content'] = preg_replace('/px;"[^c]*class=/', 'px;" class=', $_POST['content']);
                            }
                        } elseif ($_POST['ctype'] == 'php' && $_POST['contenttype'] == 'php') {
                            pmxPHP_convert();
                        } elseif ($_POST['ctype'] == 'html' && $_POST['contenttype'] == 'html') {
                            $_POST['content'] = str_replace('/ckeditor/../Smileys/', '/Smileys/', $_POST['content']);
                            if (preg_match_all('~<img.*(class[^r]*resized[^\\"]*\\")[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== '/>' ? array('>', '/>') : array(' />', '/>');
                                    $repl = str_replace($match[1][$key], '', $val);
                                    $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $repl), $_POST['content']);
                                }
                            } elseif (preg_match_all('~<img[^>]*>~', $_POST['content'], $match) > 0) {
                                foreach ($match[0] as $key => $val) {
                                    $endChr = substr($val, -2) !== ' />' ? array('>', '/>') : array(' />', '/>');
                                    if (strpos($val, '/Smileys/') === false) {
                                        $_POST['content'] = str_replace($val, str_replace($endChr[0], ' class="bbc_img resized"' . $endChr[1], $val), $_POST['content']);
                                    }
                                }
                            }
                        }
                    }
                    // get all data
                    $article = array('id' => $_POST['id'], 'name' => $_POST['name'], 'catid' => $_POST['catid'], 'acsgrp' => !empty($_POST['acsgrp']) ? implode(',', $_POST['acsgrp']) : '', 'ctype' => $_POST['ctype'], 'config' => serialize($_POST['config']), 'content' => $_POST['content'], 'active' => $_POST['active'], 'owner' => $_POST['owner'], 'created' => $_POST['created'], 'approved' => $_POST['approved'], 'approvedby' => $_POST['approvedby'], 'updated' => $_POST['updated'], 'updatedby' => $_POST['updatedby']);
                    // save article if have content..
                    if (!empty($article['content']) && empty($_POST['edit_change']) && (!empty($_POST['save_edit']) || !empty($article['content']) && !empty($_POST['save_edit_continue']))) {
                        // if new article get the last id
                        if ($context['pmx']['subaction'] == 'editnew') {
                            $request = $smcFunc['db_query']('', '
								SELECT MAX(id)
								FROM {db_prefix}portamx_articles', array());
                            list($dbid) = $smcFunc['db_fetch_row']($request);
                            $smcFunc['db_free_result']($request);
                            $article['id'] = strval(1 + ($dbid === null ? $article['id'] : $dbid));
                            $article['created'] = forum_time();
                            // auto approve for admins
                            if (allowPmx('pmx_admin')) {
                                $article['approved'] = forum_time();
                                $article['approvedby'] = $user_info['id'];
                            }
                            // insert new article
                            $smcFunc['db_insert']('ignore', '
								{db_prefix}portamx_articles', array('id' => 'int', 'name' => 'string', 'catid' => 'int', 'acsgrp' => 'string', 'ctype' => 'string', 'config' => 'string', 'content' => 'string', 'active' => 'int', 'owner' => 'int', 'created' => 'int', 'approved' => 'int', 'approvedby' => 'int', 'updated' => 'int', 'updatedby' => 'int'), $article, array());
                            // clear cache
                            $pmxCacheFunc['clean']();
                        } else {
                            $article['updated'] = forum_time();
                            $article['updatedby'] = $user_info['id'];
                            // update the article
                            $smcFunc['db_query']('', '
								UPDATE {db_prefix}portamx_articles
								SET name = {string:name}, catid = {int:catid}, acsgrp = {string:acsgrp}, ctype = {string:ctype}, config = {string:config},
										content = {string:content}, active = {int:active}, owner = {int:owner}, created = {int:created}, approved = {int:approved},
										approvedby = {int:approvedby}, updated = {int:updated}, updatedby = {int:updatedby}
								WHERE id = {int:id}', array('id' => $article['id'], 'name' => $article['name'], 'catid' => $article['catid'], 'acsgrp' => $article['acsgrp'], 'ctype' => $article['ctype'], 'config' => $article['config'], 'content' => $article['content'], 'active' => $article['active'], 'owner' => $article['owner'], 'created' => $article['created'], 'approved' => $article['approved'], 'approvedby' => $article['approvedby'], 'updated' => $article['updated'], 'updatedby' => $article['updatedby']));
                        }
                        // clear cache
                        $pmxCacheFunc['clean']();
                        $context['pmx']['subaction'] = 'edit';
                    }
                    // continue edit ?
                    if (!empty($_POST['save_edit']) || !empty($_POST['save_edit_continue'])) {
                        if (empty($_POST['save_edit_continue'])) {
                            // edit done, is it a move/clone from blocks?
                            if (!empty($context['pmx']['fromblock'])) {
                                @(list($mode, $side, $bid) = explode('.', $context['pmx']['fromblock']));
                                // was block moved?
                                if ($mode == 'move') {
                                    $request = $smcFunc['db_query']('', '
										SELECT pos, blocktype
										FROM {db_prefix}portamx_blocks
										WHERE id = {int:bid}', array('bid' => $bid));
                                    $block = $smcFunc['db_fetch_assoc']($request);
                                    $smcFunc['db_free_result']($request);
                                    // update all pos >= moved id
                                    $smcFunc['db_query']('', '
										UPDATE {db_prefix}portamx_blocks
										SET pos = pos - 1
										WHERE side = {string:side} AND pos >= {int:pos}', array('side' => $side, 'pos' => $block['pos']));
                                    // delete the block
                                    $smcFunc['db_query']('', '
										DELETE FROM {db_prefix}portamx_blocks
										WHERE id = {int:id}', array('id' => $bid));
                                    // clear cache and SEF pages list
                                    $pmxCacheFunc['clean']();
                                }
                            }
                            // go to article overview
                            $context['pmx']['subaction'] = 'overview';
                            $context['pmx']['articlestart'] = getCurrentPage($article['id'], $context['pmx']['settings']['manager']['artpage']);
                        }
                    }
                    // clear cached blocks
                    $pmxCacheFunc['clean']();
                }
                if ($context['pmx']['subaction'] == 'overview') {
                    if (!isset($context['pmx']['articlestart'])) {
                        $context['pmx']['articlestart'] = 0;
                    }
                    redirectexit('action=' . $admMode . ';area=pmx_articles;' . $context['session_var'] . '=' . $context['session_id'] . ';pg=' . $context['pmx']['articlestart']);
                }
            }
            // load the template, initialize the page title
            loadTemplate($context['pmx_templatedir'] . 'AdminArticles');
            $context['page_title'] = $txt['pmx_articles'];
            $context['pmx']['AdminMode'] = $admMode;
            $context['pmx']['RegBlocks'] = eval($context['pmx']['registerblocks']);
            // direct edit request?
            if (isset($_GET['sa']) && PortaMx_makeSafe($_GET['sa']) == 'edit' && !empty($_GET['id'])) {
                // move or clone from blocks?
                if (isset($_GET['from'])) {
                    $context['pmx']['fromblock'] = PortaMx_makeSafe($_GET['from']) . '.' . PortaMx_makeSafe($_GET['id']);
                    // load the block
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_blocks
						WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $smcFunc['db_free_result']($request);
                    // modify the config array
                    $cfg = unserialize($row['config']);
                    if (isset($cfg['pagename'])) {
                        $pgname = $cfg['pagename'];
                        unset($cfg['pagename']);
                    } else {
                        $pgname = '';
                    }
                    unset($cfg['ext_opts']);
                    if (isset($cfg['frontmode'])) {
                        unset($cfg['frontmode']);
                    }
                    $cfg['can_moderate'] = allowedTo('admin_forum') ? 0 : 1;
                    $article = array('id' => 0, 'name' => $pgname, 'catid' => 0, 'acsgrp' => $row['acsgrp'], 'ctype' => $row['blocktype'], 'config' => serialize($cfg), 'content' => $row['content'], 'active' => 0, 'owner' => $user_info['id'], 'created' => 0, 'approved' => 0, 'approvedby' => 0, 'updated' => 0, 'updatedby' => 0);
                    $context['pmx']['subaction'] = 'editnew';
                    $context['pmx']['articlestart'] = 0;
                } else {
                    $context['pmx']['fromblock'] = '';
                    $request = $smcFunc['db_query']('', '
						SELECT *
						FROM {db_prefix}portamx_articles
						WHERE id = {int:id}', array('id' => PortaMx_makeSafe($_GET['id'])));
                    if ($smcFunc['db_num_rows']($request) > 0) {
                        $row = $smcFunc['db_fetch_assoc']($request);
                        $article = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $row['config'], 'content' => $row['content'], 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby']);
                        $smcFunc['db_free_result']($request);
                        $context['pmx']['subaction'] = 'edit';
                        $context['pmx']['articlestart'] = 0;
                    }
                }
            }
            // continue edit or overview?
            if ($context['pmx']['subaction'] == 'overview') {
                // load article data for overview
                if (!allowPmx('pmx_articles') && allowPmx('pmx_create', true)) {
                    $where = 'WHERE a.owner = {int:owner}';
                } else {
                    $where = '';
                }
                if (!isset($_SESSION['PortaMx']['filter'])) {
                    $_SESSION['PortaMx']['filter'] = array('category' => '', 'approved' => 0, 'active' => 0, 'myown' => 0, 'member' => '');
                }
                if ($_SESSION['PortaMx']['filter']['category'] != '') {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'a.catid IN ({array_int:catfilter})';
                }
                if ($_SESSION['PortaMx']['filter']['approved'] != 0) {
                    $where .= empty($where) ? 'WHERE ' : ' AND ';
                    if ($_SESSION['PortaMx']['filter']['active'] != 0) {
                        $where .= '(a.approved = 0 OR a.active = 0)';
                    } else {
                        $where .= 'a.approved = 0';
                    }
                }
                if ($_SESSION['PortaMx']['filter']['active'] != 0) {
                    $where .= empty($where) ? 'WHERE ' : ' AND ';
                    if ($_SESSION['PortaMx']['filter']['approved'] != 0) {
                        $where .= '(a.active = 0 OR a.approved = 0)';
                    } else {
                        $where .= 'a.active = 0';
                    }
                }
                if ($_SESSION['PortaMx']['filter']['myown'] != 0) {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'a.owner = {int:owner}';
                }
                if ($_SESSION['PortaMx']['filter']['member'] != '') {
                    $where .= (empty($where) ? 'WHERE ' : ' AND ') . 'm.member_name LIKE {string:memname}';
                }
                if (isset($_GET['pg']) && !is_array($_GET['pg'])) {
                    $context['pmx']['articlestart'] = PortaMx_makeSafe($_GET['pg']);
                    unset($_GET['pg']);
                } elseif (!isset($context['pmx']['articlestart'])) {
                    $context['pmx']['articlestart'] = 0;
                }
                $cansee = allowPmx('pmx_articles, pmx_create', true);
                $isadmin = allowPmx('pmx_admin');
                $memerIDs = array();
                $context['pmx']['articles'] = array();
                $context['pmx']['article_rows'] = array();
                $context['pmx']['totalarticles'] = 0;
                $result = null;
                $request = $smcFunc['db_query']('', '
					SELECT a.id, a.name, a.catid, a.acsgrp, a.ctype, a.config, a.active, a.owner, a.created, a.approved, a.approvedby, a.updated, a.updatedby, a.content, c.artsort, c.level, c.name AS catname
					FROM {db_prefix}portamx_articles AS a' . ($_SESSION['PortaMx']['filter']['member'] != '' ? '
					LEFT JOIN {db_prefix}members AS m ON (a.owner = m.id_member)' : '') . '
					LEFT JOIN {db_prefix}portamx_categories AS c ON (a.catid = c.id)
					' . $where . '
					ORDER BY a.id', array('catfilter' => Pmx_StrToArray($_SESSION['PortaMx']['filter']['category']), 'memname' => str_replace('*', '%', $_SESSION['PortaMx']['filter']['member']), 'owner' => $user_info['id']));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $cfg = unserialize($row['config']);
                        if (!empty($isadmin) || $cansee && !empty($cfg['can_moderate'])) {
                            $memerIDs[] = $row['owner'];
                            $memerIDs[] = $row['approvedby'];
                            $memerIDs[] = $row['updatedby'];
                            $context['pmx']['article_rows'][$row['id']] = array('name' => $row['name'], 'cat' => str_repeat('&bull;', $row['level']) . $row['catname']);
                            $result[] = array('id' => $row['id'], 'name' => $row['name'], 'catid' => $row['catid'], 'cat' => str_repeat('&bull;', $row['level']) . $row['catname'], 'acsgrp' => $row['acsgrp'], 'ctype' => $row['ctype'], 'config' => $cfg, 'active' => $row['active'], 'owner' => $row['owner'], 'created' => $row['created'], 'approved' => $row['approved'], 'approvedby' => $row['approvedby'], 'updated' => $row['updated'], 'updatedby' => $row['updatedby'], 'content' => $row['content']);
                        }
                    }
                    $smcFunc['db_free_result']($request);
                    if (!empty($result)) {
                        foreach ($result as $st => $data) {
                            $context['pmx']['articles'][$st] = $data;
                        }
                        $context['pmx']['totalarticles'] = count($result);
                        if ($context['pmx']['totalarticles'] <= $context['pmx']['articlestart']) {
                            $context['pmx']['articlestart'] = 0;
                        }
                        // get all members names
                        $request = $smcFunc['db_query']('', '
							SELECT id_member, member_name
							FROM {db_prefix}members
							WHERE id_member IN ({array_int:members})', array('members' => array_unique($memerIDs)));
                        if ($smcFunc['db_num_rows']($request) > 0) {
                            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                                $context['pmx']['articles_member'][$row['id_member']] = $row['member_name'];
                            }
                            $smcFunc['db_free_result']($request);
                        }
                    }
                }
                // load popup js for overview
                loadJavascriptFile(PortaMx_loadCompressed('PortaMxPopup.js'), array('external' => true));
            } elseif (empty($_POST['save_edit'])) {
                // prepare the editor
                PortaMx_EditArticle($article['ctype'], 'content', $article['content']);
                // load the class file and create the object
                require_once $context['pmx_sysclassdir'] . 'PortaMx_AdminArticlesClass.php';
                $context['pmx']['editarticle'] = new PortaMxC_SystemAdminArticle($article);
                $context['pmx']['editarticle']->pmxc_AdmArticle_loadinit();
            }
        } else {
            fatal_error($txt['pmx_acces_error']);
        }
    }
}