function fixCategoryArticles()
{
    global $smcFunc;
    $categoryList = getCategoryInfo();
    $categoryIds = array();
    foreach ($categoryList as $category) {
        $categoryIds[] = $category['id'];
    }
    foreach ($categoryIds as $category) {
        $article_count = 0;
        $request = $smcFunc['db_query']('', '
			SELECT COUNT(*)
			FROM {db_prefix}sp_articles
			WHERE id_category = {int:id_category}', array('id_category' => $category));
        list($article_count) = $smcFunc['db_fetch_row']($request);
        $smcFunc['db_free_result']($request);
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}sp_categories
			SET articles = {int:article_count}
			WHERE id_category = {int:id_category}', array('article_count' => $article_count, 'id_category' => $category));
    }
}
function sportal_add_article()
{
    global $smcFunc, $context, $scripturl, $sourcedir, $txt;
    if (!allowedTo(array('sp_add_article', 'sp_manage_articles', 'sp_admin'))) {
        fatal_lang_error('error_sp_cannot_add_article');
    }
    require_once $sourcedir . '/Subs-PortalAdmin.php';
    loadLanguage('SPortalAdmin', sp_languageSelect('SPortalAdmin'));
    loadTemplate('PortalArticles');
    if (!empty($_POST['add_article'])) {
        $article_options = array('id_category' => !empty($_POST['category']) ? (int) $_POST['category'] : 0, 'id_message' => !empty($_POST['message']) ? (int) $_POST['message'] : 0, 'approved' => allowedTo(array('sp_admin', 'sp_manage_articles', 'sp_auto_article_approval')) ? 1 : 0);
        createArticle($article_options);
        redirectexit('topic=' . $_POST['return']);
    }
    $context['message'] = !empty($_REQUEST['message']) ? (int) $_REQUEST['message'] : 0;
    $context['return'] = !empty($_REQUEST['return']) ? $_REQUEST['return'] : '';
    if (empty($context['message'])) {
        fatal_lang_error('error_sp_no_message_id');
    }
    $request = $smcFunc['db_query']('', '
		SELECT id_message
		FROM {db_prefix}sp_articles
		WHERE id_message = {int:message}', array('message' => $context['message']));
    list($exists) = $smcFunc['db_fetch_row']($request);
    $smcFunc['db_free_result']($request);
    if ($exists) {
        fatal_lang_error('error_sp_article_exists');
    }
    $context['list_categories'] = getCategoryInfo(null, true);
    if (empty($context['list_categories'])) {
        fatal_error(allowedTo(array('sp_admin', 'sp_manage_articles')) ? $txt['error_sp_no_category'] . '<br />' . sprintf($txt['error_sp_no_category_sp_moderator'], $scripturl . '?action=admin;area=portalarticles;sa=addcategory') : $txt['error_sp_no_category_normaluser'], false);
    }
    $context['sub_template'] = 'add_article';
}
function sp_articles($parameters, $id, $return_parameters = false)
{
    global $smcFunc, $sourcedir, $modSettings, $scripturl, $txt, $color_profile;
    $block_parameters = array('category' => array(0 => $txt['sp_all']), 'limit' => 'int', 'type' => 'select', 'image' => 'select');
    if ($return_parameters) {
        require_once $sourcedir . '/Subs-PortalAdmin.php';
        $categories = getCategoryInfo();
        foreach ($categories as $category) {
            $block_parameters['category'][$category['id']] = $category['name'];
        }
        return $block_parameters;
    }
    $category = empty($parameters['category']) ? 0 : (int) $parameters['category'];
    $limit = empty($parameters['limit']) ? 5 : (int) $parameters['limit'];
    $type = empty($parameters['type']) ? 0 : 1;
    $image = empty($parameters['image']) ? 0 : (int) $parameters['image'];
    $request = $smcFunc['db_query']('', '
		SELECT
			m.id_topic, m.subject, m.poster_name, c.picture, c.name,
			mem.id_member, mem.real_name, mem.avatar,
			at.id_attach, at.attachment_type, at.filename
		FROM {db_prefix}sp_articles AS a
			INNER JOIN {db_prefix}sp_categories AS c ON (c.id_category = a.id_category)
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = a.id_message)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = m.id_board)
			LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = m.id_member)
			LEFT JOIN {db_prefix}attachments AS at ON (at.id_member = mem.id_member)
		WHERE {query_see_board}
			AND a.approved = {int:approved}' . (!empty($category) ? '
			AND a.id_category = {int:category}' : '') . '
		ORDER BY {raw:type}
		LIMIT {int:limit}', array('approved' => 1, 'category' => $category, 'type' => $type ? 'RAND()' : 'm.poster_time DESC', 'limit' => $limit));
    $articles = array();
    $colorids = array();
    while ($row = $smcFunc['db_fetch_assoc']($request)) {
        if (!empty($row['id_member'])) {
            $colorids[$row['id_member']] = $row['id_member'];
        }
        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 = '';
        }
        $articles[] = array('id' => $row['id_topic'], 'name' => $row['subject'], 'href' => $scripturl . '?topic=' . $row['id_topic'] . '.0', 'link' => '<a href="' . $scripturl . '?topic=' . $row['id_topic'] . '.0">' . $row['subject'] . '</a>', 'poster' => array('id' => $row['id_member'], 'name' => $row['real_name'], 'href' => $scripturl . '?action=profile;u=' . $row['id_member'], 'link' => empty($row['id_member']) ? $row['poster_name'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member'] . '">' . $row['real_name'] . '</a>'), 'image' => array('href' => $row['picture'], 'image' => '<img src="' . $row['picture'] . '" alt="' . $row['name'] . '" />'), 'avatar' => array('name' => $row['avatar'], 'image' => $row['avatar'] == '' ? $row['id_attach'] > 0 ? '<img src="' . (empty($row['attachment_type']) ? $scripturl . '?action=dlattach;attach=' . $row['id_attach'] . ';type=avatar' : $modSettings['custom_avatar_url'] . '/' . $row['filename']) . '" alt="" class="avatar" border="0" />' : '' : (stristr($row['avatar'], 'http://') ? '<img src="' . $row['avatar'] . '"' . $avatar_width . $avatar_height . ' alt="" class="avatar" border="0" />' : '<img src="' . $modSettings['avatar_url'] . '/' . htmlspecialchars($row['avatar']) . '" alt="" class="avatar" border="0" />'), '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'])));
    }
    $smcFunc['db_free_result']($request);
    if (empty($articles)) {
        echo '
								', $txt['error_sp_no_articles_found'];
        return;
    }
    if (!empty($colorids) && sp_loadColors($colorids) !== false) {
        foreach ($articles as $k => $p) {
            if (!empty($color_profile[$p['poster']['id']]['link'])) {
                $articles[$k]['poster']['link'] = $color_profile[$p['poster']['id']]['link'];
            }
        }
    }
    if (empty($image)) {
        echo '
								<ul class="sp_list">';
        foreach ($articles as $article) {
            echo '
									<li>', sp_embed_image('topic'), ' ', $article['link'], '</li>';
        }
        echo '
								</ul>';
    } else {
        echo '
								<table class="sp_fullwidth sp_articles">';
        foreach ($articles as $article) {
            echo '
									<tr>
										<td class="sp_articles sp_center">';
            if (!empty($article['avatar']['href']) && $image == 1) {
                echo '<a href="', $scripturl, '?action=profile;u=', $article['poster']['id'], '"><img src="', $article['avatar']['href'], '" alt="', $article['poster']['name'], '" width="40" /></a>';
            } elseif (!empty($article['image']['href']) && $image == 2) {
                echo '<img src="', $article['image']['href'], '" alt="', $article['name'], '" width="40" />';
            }
            echo '</td>
										<td>
											<span class="sp_articles_title">', $article['poster']['link'], '</span><br />
											', $article['link'], '
										</td>
									</tr>';
        }
        echo '
								</table>';
    }
}
function sportal_admin_category_delete()
{
    global $smcFunc, $context, $txt;
    // Is an id set? If yes, then we need to get some category information.
    if (!empty($_REQUEST['category_id'])) {
        // Be sure you made it an integer.
        $_REQUEST['category_id'] = (int) $_REQUEST['category_id'];
        // Do you know which one to delete?
        if (empty($_REQUEST['category_id'])) {
            fatal_lang_error('error_sp_id_empty', false);
        }
        // Get the category info. You need in template.
        $context['category_info'] = getCategoryInfo($_REQUEST['category_id']);
        $context['category_info'] = $context['category_info'][0];
        // Also get the category list.
        $context['list_categories'] = getCategoryInfo();
        // If we have one, that is itself. Delete it.
        if (count($context['list_categories']) < 2) {
            $context['list_categories'] = array();
        }
    }
    if (empty($_REQUEST['category_id']) && empty($_POST['category_id'])) {
        fatal_lang_error('error_sp_id_empty', false);
    }
    // No need to delete articles if category has no articles. But articles are executed if there isn't any other category. :P
    if (empty($_POST['delete_category']) && !empty($context['category_info']['articles'])) {
        // Call the right sub template.
        $context['sub_template'] = 'category_delete';
        $context['page_title'] = $txt['sp-categoriesDelete'];
    } elseif (!empty($_POST['delete_category'])) {
        // Again.
        checkSession();
        // Are we going to move something?
        if (!empty($_POST['category_move']) && !empty($_POST['category_move_to'])) {
            // We just need an integer.
            $_POST['category_move_to'] = (int) $_POST['category_move_to'];
            // These are the lucky ones, move them.
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}sp_articles
				SET id_category = {int:category_move_to}
				WHERE id_category = {int:category_id}', array('category_move_to' => $_POST['category_move_to'], 'category_id' => $_POST['category_id']));
            // Fix the article counts.
            fixCategoryArticles();
        } else {
            // Kill 'em all. (It's not the Metallica album. :P)
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}sp_articles
				WHERE id_category = {int:category_id}', array('category_id' => $_POST['category_id']));
        }
        // Everybody will die one day...
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}sp_categories
			WHERE id_category = {int:category_id}', array('category_id' => $_POST['category_id']));
        // Return to the list.
        redirectexit('action=admin;area=portalarticles;sa=categories');
    } else {
        // Again.
        checkSession('get');
        // Just delete the category.
        $smcFunc['db_query']('', '
			DELETE FROM {db_prefix}sp_categories
			WHERE id_category = {int:category_id}', array('category_id' => $_REQUEST['category_id']));
        // Fix the article counts.
        fixCategoryArticles();
        // Return to the list.
        redirectexit('action=admin;area=portalarticles;sa=categories');
    }
}