<?php

@( (bool)FALSE === strpos( $_SERVER['REQUEST_URI'], basename( __FILE__ ) ) ) OR exit( '!! ACCESS DENIED !!' );
error_reporting( _E_VALUE );

/* vim: set expandtab tabstop=4 shiftwidth=4: */

// ***** BEGIN LICENSE BLOCK ( DO NOT REMOVE ) *****

// +----------------------------------------------------------------------+
// | phpBB 1.4.x Forum For MPN 188_8                                      |
// |                                                                      |
// | -> Forum Core Functions                                              |
// +----------------------------------------------------------------------+
// | VERSION: 0.1 Alpha                                                   |
// +----------------------------------------------------------------------+
// | LICENSE: GPL 2.0 (see docs/LICENSE_GPL)                              |
// |                                                                      |
// | This file is part of phpBB 1.4.x Forum For MPN 188_8.                |
// |                                                                      |
// | phpBB 1.4.x Forum For MPN 188_8 is free software; you can            |
// | redistribute it and/or modify it under the terms of the GNU          |
// | General Public License as published by the Free Software Foundation; |
// | either version 2 of the License, or (at your option) any             |
// | later version.                                                       |
// |                                                                      |
// | phpBB 1.4.x Forum For MPN 188_8 is distributed in the hope that it   |
// | will be useful, but WITHOUT ANY WARRANTY; without even the implied   |
// | warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     |
// | See the GNU General Public License for more details.                 |
// |                                                                      |
// | You should have received a copy of the GNU General Public License    |
// | along with phpBB 1.4.x Forum For MPN 188_8; if not, write to the     |
// |                                                                      |
// | Free Software Foundation, Inc.                                       |
// | 59 Temple Place, Suite 330                                           |
// | Boston, MA 02111-1307  USA                                           |
// +----------------------------------------------------------------------+
// | AUTHOR(s):                                                           |
// |                                                                      |
// | The Original Code is the phpbb 1.4.4 Forum For MPN 188_8.            |
// | The Initial Developer of the Original Code is Eric Haddix.           |
// |                                                                      |
// | Portions created by Eric Haddix or Kiril Threndor                    |
// | <support@mpn.illearth.net> are                                       |
// | Copyright (C) 2003 Eric Haddix.  All Rights Reserved.                |
// +----------------------------------------------------------------------+
// | CONTRIBUTOR(s):                                                      |
// |                                                                      |
// |                                                                      |
// +----------------------------------------------------------------------+
// | MODIFICATIONS:                                                       |
// |                                                                      |
// |                                                                      |
// +----------------------------------------------------------------------+
// | NOTES:                                                               |
// |   The MPN 188_8 forum is nearly a complete, and in some cases entire,|
// |   recode of the phpNuke 4.4 forum which was based on phpBB 1.4.x.    |
// +----------------------------------------------------------------------+
// | SUPPORT:                                                             |
// |   WEB:   http://myphpnuke.com/                                       |
// |   EMAIL: support@mpn.illearth.net                                    |
// +----------------------------------------------------------------------+

/**
 * MPN_188_8_Modules
 *
 * @package MPN_188_8_Modules
 * @subpackage forum
 * @version $Id: core_ForumProc.php,v 1.1.2.47 2004/09/16 02:37:35 kirilt Exp $
 *
 * @author Kiril Threndor <support@mpn.illearth.net>
 * @copyright Copyright (C) 2003 Eric Haddix
 * @license http://www.gnu.org/licenses/gpl.html GPL 2.0
 * @support http://myphpnuke.com/
 * @todo finish CSS & XHTML conversion
 * @todo reformat old style formatted code to new coding style
 * @todo finish and check function comments
 *
 * @tutorial
 * @filesource
 */

// ***** END LICENSE BLOCK ( DO NOT REMOVE ) *****

/**
 * Check Request URI For A Valid Page Request.
 *
 * @return bool
 */

function checkPageRequest()
{
    $st = strrpos( $_SERVER['PHP_SELF'], '/' ) + 1;
    $ed = strpos( $_SERVER['PHP_SELF'], '.', $st );

    define( '_FORUM_PAGE_', strtolower( substr( $_SERVER['PHP_SELF'], $st, $ed - $st ) ) );

    $pgrestrict = array
    (
        'allow' => array( 'forum', 'viewforum', 'viewtopic', 'forum_submit', 'lastview', 'searchbb', 'topicadmin', 'viewpmsg', 'readpmsg', 'replypmsg', 'guestbook', 'admin' )

      , 'query' => array( 'viewforum', 'viewtopic', 'forum_submit', 'topicadmin', 'readpmsg' )

      , 'uonly' => array( 'viewpmsg', 'readpmsg', 'replypmsg' )

      /*, 'supermodonly' => array( 'topicadmin' )*/

      , 'adminonly' => array( 'admin', 'phpbbforum' )

    );

    if ( ! in_array( _FORUM_PAGE_, array_shift( $pgrestrict ) ) )
    {
        return (bool)FALSE;
    }

    foreach( $pgrestrict AS $chk => $ary )
    {
        if ( in_array( _FORUM_PAGE_, $ary ) )
        {
            switch( $chk )
            {
                case 'query':
                    if ( ( ! isset( $_SERVER['QUERY_STRING'] ) || $_SERVER['QUERY_STRING'] == '' ) && ! isset( $_POST ) ) { return (bool)FALSE; }
                break;

                case 'uonly':
                    if ( ! _MPN_USER ) { return (bool)FALSE; }
                break;

                case 'supermodonly':
                    if ( ! $GLOBALS['uinf']['supermod'] || ! _MPN_ADMIN ) { return (bool)FALSE; }
                break;

                case 'adminonly':

                    if ( _FORUM_PAGE_ != strtolower( 'admin' ) ) { continue; }

                    $incfiles = get_included_files();

                    foreach( $ary AS $fn )
                    {
                        if ( in_array( __ROOT__ . 'admin' . DIRECTORY_SEPARATOR . $fn . '.php', $incfiles ) && ! _MPN_ADMIN )
                        {
                            return (bool)FALSE;
                        }
                    }

                break;

            } // End Switch
        }// End If/Then
    } // End For/Each

    return (bool)TRUE;;

} // End Function checkPageRequest

/**
 * Generate A List Of Moderators For Output.
 *
 * Additionally set the current users moderator status for the current forum.
 *
 * @param integer ( $id -> forum id )
 * @return string ( moderators ready for output )
 */

function getModerators( $id = NULL, $chkonly = FALSE )
{
    global $mpnTables, $forum;

    $id = ( ! empty( $id ) ) ? ( $id ) : ( $forum );
    $mods = '';

    if ( _MPN_ADMIN || $GLOBALS['uinf']['supermod'] )
    {
        $GLOBALS['uinf']['mod'] = (bool)TRUE;
        if ( $chkonly ) { return $GLOBALS['uinf']['mod']; }
    }
    else
    {
        $GLOBALS['uinf']['mod'] = (bool)FALSE;
    }

    $sql = 'SELECT t2.uname
            FROM  ' . $mpnTables['forummods'] . ' AS t1
            LEFT JOIN ' . $mpnTables['users'] . ' AS t2
                ON t1.user_id = t2.uid
            WHERE t1.forum_id = "' . $id . '"
                && t1.user_id > 1';

    if ( (bool)FALSE !== @( $result = mysql_query( $sql ) ) )
    {
        for( $i = 1; $i <= mysql_num_rows( $result ); $i++ )
        {
            $tmp = mysql_fetch_row( $result );

            if ( $tmp[0] === $GLOBALS['uinf']['uname'] )
            {
                $GLOBALS['uinf']['mod'] = (bool)TRUE;
                if ( $chkonly ) { break; }
            }

            $mods .= ( $i != 1 ) ? ( ', ' ) : ( '' );
            $mods .= $tmp[0];
        }
    }

    @mysql_free_result( $result );

    if ( $chkonly ) { return $GLOBALS['uinf']['mod']; }

    return $mods;

}  // End Function

/**
 * Get The Posters Data.
 *
 * @param integer ( $post_id -> ID of the current post )
 * @param integer ( $puid -> users name or id )
 * @param integer ( $chkfield -> which field to check in DB users table based on $puid )
 *
 * @global array ( $mpnTables -> MPN table array )
 * @global interger ( $mpn_anonymous_id -> anonymous id )
 * @global string ( $anonymous -> anonymous users name )
 *
 * @return array ( array of user data )
 */

function getPosterData( $post_id, $puid, $chkfield = 'uid' )
{
    global $mpnTables, $mpn_anonymous_id, $anonymous;

    $puid = (int)$puid;

    if ( $puid < - 1 )
    {
        return array( 'uid' => $puid, 'uname' => translate( 'Unknown' ), 'posts' => 0, 'rank' => 0, 'rank_display' => translate( 'Deleted User' ), 'user_sig' => '', 'mod' => FALSE, 'supermod' => FALSE, 'lastvisit' => _MPN_TIMESTAMP - ( 60 * 30 ), 'attachsig' => FALSE, 'level' => 0, 'online' => FALSE );
    }

    $duser = array( 'uid' => - $puid, 'uname' => translate( 'Unknown' ), 'posts' => 0, 'rank' => 0, 'rank_display' => translate( 'Deleted User' ), 'user_sig' => '', 'mod' => FALSE, 'supermod' => FALSE, 'lastvisit' => _MPN_TIMESTAMP - ( 60 * 30 ), 'attachsig' => FALSE, 'level' => 0, 'online' => FALSE );

    $sql = 'SELECT t1.uid, t1.uname, t1.storynum, t1.umode, t1.uorder, t1.thold, t1.noscore, t1.ublockon, t1.theme, t1.commentmax, t1.name, t1.email, t1.femail, t1.url, t1.user_avatar, t1.user_icq, t1.user_occ, t1.user_from, t1.user_from_flag, t1.user_intrest, t1.user_sig, t1.user_viewemail, t1.user_aim, t1.user_yim, t1.user_msnm, t1.bio, t1.user_regdate, t1.ublock, t2.posts, t2.attachsig, t2.rank, t2.level, t3.username AS online
            FROM ' . $mpnTables['users'] . ' AS t1
                , ' . $mpnTables['users_status'] . ' AS t2
            LEFT JOIN ' . $mpnTables['session'] . ' AS t3
                ON t1.uname = t3.username
            WHERE t1.' . $chkfield . ' = "' . $puid . '"
                && t1.' . $chkfield . ' = t2.' . $chkfield;

    if ( ! @( $result = mysql_query( $sql ) ) && ! @mysql_data_seek( $result, 0 ) )
    {
        return $duser;
    }

    if ( @( $tmp = mysql_fetch_assoc( $result ) ) )
    {
        if ( $tmp['uid'] <= 1 )
        {
            $chk_admin = ( $tmp['uid'] == - 1 );
            $usename = ( $chk_admin ) ? ( translate( 'Administrator' ) ) : ( $anonymous );
            $useid = ( $chk_admin ) ? ( - 1 ) : ( 1 );
            $rankdisp = ( $chk_admin ) ? ( translate( 'Moderator' ) ) : ( '' );

            $tmp = array( 'uid' => $useid, 'uname' => $usename, 'posts' => 0, 'rank' => 0, 'rank_display' => $rankdisp, 'user_sig' => '', 'mod' => FALSE, 'supermod' => FALSE, 'lastvisit' => _MPN_TIMESTAMP - ( 60 * 30 ), 'attachsig' => FALSE, 'level' => 0, 'online' => FALSE );
        }
        else
        {
            $tmp['rank_display'] = getPosterInfo( $tmp['uid'], $tmp['rank'], $tmp['posts'] );
        }
    }

    @mysql_free_result( $result );

    if ( empty( $tmp ) || $puid < - 1 ) { return $duser; }

    return $tmp;

} // End Function getPosterData

/**
 * Gets The Posters Rank Information.
 *
 * @param integer ( $uid -> posters ID )
 * @param integer ( $rank -> posters rank )
 * @param integer ( $posts -> number of posts for the user )
 *
 * @global interger ( $mpn_anonymous_id -> anonymous id )
 * @global array ( $mpnTables -> MPN table array )
 * @static array ( $rank_ary -> available ranks )
 * @static bool ( $sql_error -> value of sql query result )
*
 * @return string ( translated rank )
 */

function getPosterInfo( $uid, $rank, $posts )
{
    global $mpnTables;

    static $rank_ary = NULL;
    static $sql_error = FALSE;

    if ( $uid == - 1 ) { return translate( 'Moderator' ); }

    if ( empty( $rank_ary ) && ! $sql_error )
    {
        $sql = 'SELECT * FROM ' . $mpnTables['ranks'];

        @( $result = mysql_query( $sql ) )
          OR $sql_error = (bool)TRUE;

        if ( ! $sql_error )
        {
            for( $i = 0; $i < mysql_num_rows( $result ); $i++ )
            {
                $tmp = mysql_fetch_assoc( $result );
                $id = array_shift( $tmp );
                $rank_ary[ $id ] = $tmp;
            }
        }
    }

    if ( empty( $rank_ary ) || $sql_error )
    {
        return translate( 'Forum User' );
    }

    if ( $rank != 0 && isset( $rank_ary[ $rank ] ) )
    {
        return stripslashes( $rank_ary[ $rank ]['rank_title'] );
    }

    foreach( $rank_ary AS $ary )
    {
        if ( $ary['rank_min'] <= $posts && $ary['rank_max'] >= $posts && $ary['rank_special'] == 0 )
        {
            return stripslashes( $ary['rank_title'] );
        }
    }

    return translate( 'Forum User' );

} // End Function getPosterInfo

/**
 * Gets An Array Of Information On The Last Post In A Given Forum
 *
 * @param integer ( $id -> forum ID )
 * @return array
 */

function getLastForumPost( $id )
{
    global $mpnTables, $forumconfig;

    $stats = array();

    // Get Stats For This Forum

    $sql = 'SELECT MAX(post_id) AS lastpid, COUNT(*) AS totalposts
            FROM ' . $mpnTables['posts'] . ' USE INDEX(forum_id)
            WHERE forum_id = ' . $id;

    @( $result = mysql_query( $sql ) )
      OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

    if ( ! @( $tmp = mysql_fetch_assoc( $result ) ) || is_null( $tmp['lastpid'] ) )
    {
        return 'No posts';
    }

    @mysql_free_result( $result );

    // Fill Return Array

    $stats['last_post_id'] = $tmp['lastpid'];
    $stats['total_posts'] = $tmp['totalposts'];

    // Get Total Topics In Forum

    $sql = 'SELECT COUNT(*) AS totaltopics
            FROM ' . $mpnTables['forumtopics'] . ' USE INDEX(forum_id)
            WHERE forum_id = ' . $id;

    @( $result = mysql_query( $sql ) )
    OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

    if ( ! @( $tmp = mysql_fetch_assoc( $result ) ) )
    {
        return 'No posts';
    }

    @mysql_free_result( $result );

    $stats['total_topics'] = $tmp['totaltopics'];

    // Get Last Post Info For This Forum

    $sql = 'SELECT t1.topic_id, t1.post_time, t1.image, t2.topic_title, t3.uname
            FROM ' . $mpnTables['forumtopics'] . ' AS t2 USE INDEX(PRIMARY)
                , ' . $mpnTables['posts'] . ' AS t1
            LEFT JOIN ' . $mpnTables['users'] . ' AS t3
                ON t1.poster_id = t3.uid
            WHERE t1.topic_id = t2.topic_id
                && t1.post_id = ' . $stats['last_post_id'];

    @( $result = mysql_query( $sql ) )
      OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

    if ( ! @( $tmp = mysql_fetch_assoc( $result ) ) )
    {
        return 'No posts';
    }

    @mysql_free_result( $result );

    // Fill Return Array

    $stats['last_topic_id'] = $tmp['topic_id'];
    $stats['post_time'] = getDisplayTime( $tmp['post_time'], 'forumdatestring2' );
    $stats['uname'] = ( ! is_null( $tmp['uname'] ) ) ? ( $tmp['uname'] ) : ( 'Unknown' );


    $stats['topic_title'] = ( strlen( $tmp['topic_title'] > 30 ) )
                          ? ( substr( $tmp['topic_title'], 0, 30 ) . '...' )
                          : ( $tmp['topic_title'] );

    $stats['image'] = ( $tmp['image'] == '' || ! is_file( __ROOT__ . 'images/forum/subject/' . $tmp['image'] ) )
                    ? ( 'icon1.gif' )
                    : ( $tmp['image'] );

    $stats['uname'] = stripslashes( $stats['uname'] );
    $stats['topic_title'] = stripslashes( $stats['topic_title'] );

    // Get Total Posts In Topic

    $sql = 'SELECT COUNT(*) AS totalposts
            FROM ' . $mpnTables['posts'] . ' USE INDEX(idxtopics)
            WHERE topic_id = ' . $stats['last_topic_id'];

    @( $result = mysql_query( $sql ) )
    OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

    if ( ! @( $tmp = mysql_fetch_assoc( $result ) ) )
    {
        return 'No posts';
    }

    @mysql_free_result( $result );

    $stats['total_topic_posts'] = $tmp['totalposts'];

    if ( $tmp['totalposts'] > $forumconfig['posts_per_page'] )
    {
        $pstrt = floor( $tmp['totalposts'] / $forumconfig['posts_per_page'] ) * $forumconfig['posts_per_page'];

        $stats['nav']= '&amp;start=' . $pstrt . '&#035;f' . $stats['last_post_id'];
    }
    else
    {
        $stats['nav'] = '&#035;f' . $stats['last_post_id'];
    }

    return $stats;

} // End Function

/**
 * Gets An Array Of Forum Topics For Listing In Table
 *
 * @param integer ( $id -> forum ID )
 * @return array
 */

function getForumTopicList( $fid )
{
    global $mpnTables, $start, $forumconfig;

    $stats = array();

    $sql = 'SELECT t1.*, t2.uname AS topic_author
            FROM ' . $mpnTables['forumtopics'] . ' AS t1 USE INDEX(forum_id)
            LEFT JOIN ' . $mpnTables['users'] . ' AS t2
                ON t1.topic_poster = t2.uid
            WHERE forum_id = ' . $fid . '
            ORDER BY topic_time DESC
            LIMIT ' . $start . ', ' . $forumconfig['posts_per_page'];

    @( $result = mysql_query( $sql ) )
      OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

    for( $i = 0; $i < mysql_num_rows( $result ); $i++ )
    {
        if ( ! @mysql_data_seek( $result, $i ) )
        {
            continue;
        }

        $stats[ $i ] = mysql_fetch_assoc( $result );

        // Get Last Post And Total Posts In Topic

        $sql = 'SELECT MAX(post_id) AS lastpid, COUNT(*) AS totalposts
                FROM ' . $mpnTables['posts'] . ' USE INDEX(topic_id)
                WHERE topic_id = ' . $stats[ $i ]['topic_id'];

        @( $result1 = mysql_query( $sql ) )
          OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

        if ( ! @( $tmp = mysql_fetch_assoc( $result1 ) ) || $tmp['totalposts'] == 0 )
        {
            unset( $stats[ $i ] );
            continue;
        }

        @mysql_free_result( $result1 );

        $stats[ $i ] = array_merge( $stats[ $i ], $tmp );

        // Get Last Post Info

        $sql = 'SELECT t1.image, t2.uname
                FROM ' . $mpnTables['posts'] . ' AS t1 USE INDEX(PRIMARY)
                LEFT JOIN ' . $mpnTables['users'] . ' AS t2
                    ON t1.poster_id = t2.uid
                WHERE t1.post_id = ' . $stats[ $i ]['lastpid'];

        @( $result1 = mysql_query( $sql ) )
          OR goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );

        if ( ! @( $tmp = mysql_fetch_assoc( $result1 ) ) )
        {
            unset( $stats[ $i ] );
            continue;
        }

        @mysql_free_result( $result1 );

        $stats[ $i ] = array_merge( $stats[ $i ], $tmp );

        // Adjustments

        $stats[ $i ]['totalposts']--;
        $stats[ $i ]['post_time'] = getDisplayTime( $stats[ $i ]['topic_time'], 'forumdatestring2' );
        $stats[ $i ]['uname'] = ( ! is_null( $stats[ $i ]['uname'] ) )
                              ? ( stripslashes( $stats[ $i ]['uname'] ) )
                              : ( 'Unknown' );

        $stats[ $i ]['topic_title'] = stripslashes( $stats[ $i ]['topic_title'] );
        $stats[ $i ]['topic_title'] = ( strlen( $stats[ $i ]['topic_title'] > 30 ) )
                                    ? ( substr( $stats[ $i ]['topic_title'], 0, 30 ) . '...' )
                                    : ( $stats[ $i ]['topic_title'] );


        $stats[ $i ]['image'] = ( $stats[ $i ]['image'] == '' || ! is_file( __ROOT__ . 'images/forum/subject/' . $stats[ $i ]['image'] ) )
                        ? ( 'icon1.gif' )
                        : ( $stats[ $i ]['image'] );
    } // End For Loop

    return $stats;

} // End Function

/**
 * Gets An Array Of Posts In A Given Forum Topic.
 *
 * @param integer ( $forum -> forum ID )
 * @param integer ( $topic -> topic ID )
 * @global array ( $mpnTables -> DB table array )
 * @global string ( $bgcolor1 -> theme bgcolor )
 * @global string ( $bgcolor3 -> theme bgcolor )
 * @global integer ( $mpn_anonymous_id -> anon id )
 * @global array ( $forumconfig -> array of forum config info )
 *
 * @return string ( all the posts for the topic ready for output )
 */

function getTopicArrays( $sortdir = NULL )
{
    global $forumconfig, $start, $forum, $topic;

    // Update Topic Hit Counter

    if ( _FORUM_POST_TYPE_ == 0 )
    {
        if ( ! getResultSet( 5, $forum, $topic, NULL, TRUE ) && _MPN_ADMIN )
        {
            goBack( translate( 'Query Failed' ) . '**' . __FILE__ . '***' .  __LINE__ );
        }
    }

    // REF: getResultSet( $action, $fid = NULL, $tid = NULL, $pid = NULL, $silent = FALSE, $sortdir = NULL )

    $result = getResultSet( 6, $forum, $topic, NULL, FALSE, $sortdir );
    $topic_posts = $posters_ary = array();
    $uidtrack = array();
    $total_posts = mysql_num_rows( $result );

    if ( $total_posts == 0 )
    {
        goBack( translate( 'No Posts Found For This Topic' ) );
    }

    for( $i = $start; $i < ( $start + $forumconfig['posts_per_page'] ); $i++ )
    {
        if ( ! @mysql_data_seek( $result, $i ) ) { continue; }

        $topic_posts[ $i ] = mysql_fetch_assoc( $result );
        $posters_ary[ $i ] = getPosterData( $topic_posts[ $i ]['post_id'], $topic_posts[ $i ]['poster_id'] );

        if ( $posters_ary[ $i ]['uid'] < - 1 || ! is_array( $posters_ary[ $i ] ) )
        {
            if ( _MPN_ADMIN && ! in_array( $posters_ary[ $i ]['uid'], $uidtrack ) )
            {
                 $topic_posts[ $i ]['post_text'] .= getAdminWarning( $topic_posts[ $i ]['poster_id'], $topic );
            }

            if ( ! _UM_SHOW_DELETED_USERS_CONTENT_ && ! _MPN_ADMIN )
            {
                unset( $topic_posts[ $i ], $posters_ary[ $i ] );
            }
        }

        if ( isset( $posters_ary[ $i ] ) ) { $uidtrack[] = $posters_ary[ $i ]['uid']; }
    }

    @mysql_free_result( $result );

    // Return Array Of Items For Output Processing

    return array( $topic_posts, $posters_ary, $total_posts );

} // End List Forum Posts

/**
 * Generates Activity Icons
 *
 * @param string ( $locid -> page location.
 *                 MUST correspond to the appropriate table field
 *                 name when appended with '_id' )
 *
 * @global array ( $mpnTables -> array of DB tables )
 * @global array ( $forumconfig -> array of forum config info )
 * @global array ( $myrow -> db result array )
 * @global integer ( $replys -> number of replies )
 * @return string
 */

function activityImage( $replies, $post_time, $status = NULL )
{
    global $mpnTables, $forumconfig;

    if ( _FORUM_PAGE_ != 'forum' && $status == 1 )
    {
       return '<img src="./images/forum/icons/lock.gif" alt="' . translate( 'Locked' ) . '" />';
    }

    $replies = ( empty( $replies ) )
             ? ( 0 )
             : ( $replies );

    $post_time = ( empty( $post_time ) )
               ? ( _MPN_TIMESTAMP )
               : ( strtotime( $post_time ) );

    $timecheck = ( (int)$post_time > $GLOBALS['uinf']['lastvisit'] )
               ? ( (bool)TRUE )
               : ( (bool)FALSE );

    $threscheck = ( $replies > $forumconfig['hot_threshold'] );

    $redhot = ( $timecheck && $threscheck );


    if ( $redhot && _FORUM_PAGE_ != 'forum' )
    {
        $image = 'hot_red_folder.gif';
        $alt = translate( 'Red Hot' );
    }
    else if ( $threscheck && _FORUM_PAGE_ != 'forum' )
    {
        $image = 'hot_folder.gif';
        $alt = translate( 'Hot' );
    }
    else if ( $timecheck )
    {
        $image = 'red_folder.gif';
        $alt = translate( 'Some Activity' );
    }
    else
    {
        $image = 'folder.gif';
        $alt = translate( 'No Activity' );
    }

    return '<img src="./images/forum/icons/' . $image . '" alt="' . $alt . '" />';

} // End Function

/**
 * Check Write Access
 *
 *
 */

function checkForumAccess()
{
    $chk = (bool)FALSE;
    $report = '';

    switch ( _FORUM_ACCESS_ )
    {
        case 0: $chk = (bool)TRUE; break;

        case 1:
            if ( _MPN_USER || _MPN_ADMIN )
            {
                $chk = (bool)TRUE;
            }
            else
            {
                $report = "<b>" . translate( "Please" ) . "&nbsp;<a href='user.php?op=register' title='" . translate( "New User Registration" ) . "'>" . translate( "Register" ) . "</a>&nbsp;" . translate( "To Post" ) . "</b>\n";
            }
        break;

        case 2:
            if ( $GLOBALS['uinf']['mod'] )
            {
                $chk = (bool)TRUE;
            }
            else
            {
                $report = "<b>" . translate( "Read Only Forum<br />No Posting Allowed" ) . "</b>";
            }
        break;

    } // End Switch

    if ( ! defined( '_FORUM_ALLOW_POSTING_' ) )
    {
        define( '_FORUM_ALLOW_POSTING_', $chk );
    }

    return $report;

} // End Function

/**
 * Check Private Forum Access
 *
 * Also generates a login form if user is not
 * already logged into PF.
 *
 * @param string ( $esct -> linkable name of script being accessed )
 * @global array ( $mpnTables -> array of DB tables )
 * @return array ( or exit with login form )
 */

function checkPrivateForum( $esct = 'viewforum' )
{
    global $mpnTables, $forum;

    if ( ! isset( $forum ) ) { goBack( translate( 'Invalid Request' ) ); }

    $uname = ( _MPN_USER ) ? ( $GLOBALS['uinf']['uname'] ) : ( $_SERVER['REMOTE_ADDR'] );

    $sql = 'SELECT t1.forum_type, t1.forum_access, t1.forum_pass, t1.forum_name, t2.forum_pass AS tmp_pass
            FROM ' . $mpnTables['forums'] . ' AS t1
                , ' . $mpnTables['session'] . ' AS t2
            WHERE t1.forum_id = ' . $forum . '
                && t2.username = "' . $uname . '"';

    @( $result = mysql_query( $sql ) )
      OR goBack( translate( 'Invalid Forum Request' ) . '**' . __FILE__ . '***' .  __LINE__ );

    @( $tmp = mysql_fetch_assoc( $result ) )
      OR goBack( translate( 'Unable To Access Required Data' ) . '**' . __FILE__ . '***' .  __LINE__ );

    @mysql_free_result( $result );

    // Define Forum Access And Name

    define( '_FORUM_ACCESS_', $tmp['forum_access'] );
    define( '_FORUM_TYPE_', $tmp['forum_type'] );
    define( '_FORUM_NAME_', stripslashes( $tmp['forum_name'] ) );

    $tpass = ( strlen( $tmp['tmp_pass'] ) !== 32 )
           ? ( md5( $tmp['tmp_pass'] ) )
          : ( $tmp['tmp_pass'] );

    $fpass = ( strlen( $tmp['forum_pass'] ) !== 0 )
           ? ( md5( $tmp['forum_pass'] ) )
           : ( NULL );

    $ppass = ( ! empty( $_POST['passwd'] ) )
           ? ( md5( $_POST['passwd'] ) )
           : ( NULL );

    unset( $tmp['forum_pass'], $tmp['tmp_pass'], $_POST['passwd'], $_REQUEST['passwd'] );

    // No password required for forum, already logged in, or logging in
    // update DB if required and return forum info

    if ( empty( $fpass ) || $fpass === $tpass || ( ! empty( $ppass ) && $ppass === $fpass ) )
    {
        if ( ! empty( $ppass ) )
        {
            $sql = 'UPDATE ' . $mpnTables['session'] . '
                    SET forum_pass = "' . $fpass . '"
                    WHERE username = "' . $uname . '"';

            @mysql_query( $sql );
        }

       return $tmp;
    }

    // Forum is password protected, user is not logged into forum

    unset ( $tmp );

    getPrivateForumLogin( $esct, $ppass );

    exit;

} // End Function

/**
 * Check Users Reply Rights
 *
 * @param integer ( $forum_access -> access integer ID )
 * @global string ( $bgcolor1 -> theme bgcolor )
 * @global string ( $bgcolor2 -> theme bgcolor )
 * @global string ( $bgcolor3 -> theme bgcolor )
 * @return string ( access message && username or login form )
 */

function checkReplyRights()
{
    switch ( _FORUM_ACCESS_ )
    {
        case 0: return (bool)TRUE; break;

        case 1:
            if ( _MPN_USER || _MPN_ADMIN )
            {
                if ( _FORUM_ACCESS_ <= $GLOBALS['uinf']['level'] || _MPN_ADMIN )
                {
                     return (bool)TRUE;
                }
                else
                {
                    return translate( 'You Are Not Allowed To Reply In This Forum' );
                }
            }

            return translate( 'Only Registered Users Can Post New Topics And Replies In This Forum' );
        break;

        case 2:
            if ( $GLOBALS['uinf']['mod'] )
            {
                return (bool)TRUE;
            }

            $msg = translate( 'Only Moderators Are Allowed To Post In This Topic' );
            $msg .= '<br /><br />';
            $msg .= translate( 'If you are a moderator, please login to your user account before attempting to post messages.' );

            return $msg;
        break;

    } // End Switch

    return (bool)FALSE;

} // End Function

/**
 * Check Users Editing Rights
 *
 * @return bool
 */

function checkEditRights( $post_id )
{
    if ( $GLOBALS['uinf']['mod'] )
    {
        return (bool)TRUE;
    }

    if ( $GLOBALS['uinf']['uid'] > 1 )
    {
        return getResultSet( 9, NULL, NULL, $post_id, TRUE );
    }

    return (bool)FALSE;

} // End Function

/**
 * Process Forum Message For Output Or DB
 *
 * @return string ( $message )
 */

function processMessage( $output_type, $message = '', $edited = FALSE, $usersig = NULL, $post_date = NULL )
{
    global $mpn_anonymous_id;

    if ( $output_type == 2 && $message == '' && ( isset( $_POST ) && ! isset( $_POST['goback'] ) ) )
    {
        goBack( translate( 'You Can\'t Post An Empty Message' ) . '**' . __FILE__ . '***' .  __LINE__  );
        exit;
    }

    switch ( $output_type )
    {
        case 1: // Message For Display

            $message = stripslashes( $message );

            if ( _SAN_LEGACY_FORUM_ && ! is_null( $post_date ) && $_SERVER['F_LIB'] -> checkPostDate( $post_date ) )
            {
                $_SERVER['SAN'] -> sanitizeLegacyContent( $message );

                if ( _FORUM_LEGACY_NOTIFY_ )
                {
                    $msg = '<span class="warn">' . translate( _FORUM_LEGACY_NOTIFY_MSG_ ) . '</span>';
                    $message = '<div class="center">' . $msg . '</div><hr class="w60" /><br />' . $message;
                }
            }

            $_SERVER['SAN'] -> formatPost( $message, $usersig );

        break;

        case 2: // Message For Database

            $message = $GLOBALS['bbencoder'] -> BBConversion( $message, TRUE, $edited, $GLOBALS['uinf']['uname'] );

            $message = addslashes( $message );

        break;

        case 3: // Message For Edit

            $message = stripslashes( $message );
            $GLOBALS['bbencoder'] -> addsig = ( (bool)FALSE !== strpos( $message, '[addsig&#032;/]' ) );

            // REF: BBConversion( $body, $encode, $edited = FALSE, $editby = '' )

            $message = $GLOBALS['bbencoder'] -> BBConversion( $message, FALSE, $edited );

        break;

        case 4: // Quoted Message For Reply

            $message = '';

            if ( isset( $_REQUEST['qid'] ) )
            {
                $result = getResultSet( 8, NULL, NULL, $_REQUEST['qid'] );

                if ( @( $tmp = mysql_fetch_array( $result ) ) )
                {
                    $reply = '<b>On '
                            . getDisplayTime( $tmp['post_time'], 'forumdatestring2' )
                            . ' , '
                            . $tmp['uname']
                            . ' '
                            . translate( 'Wrote' )
                            . ':</b><br />'
                            . "<blockquote>"
                            . $tmp['post_text']
                            . "</blockquote>";

                    $message = $GLOBALS['bbencoder'] -> BBConversion( $reply, FALSE, $edited );
                    unset( $reply );
                    @mysql_free_result( $result );
                }
            }

        break;

        DEFAULT: // Message For Display

             $message = stripslashes( $message );

             $_SERVER['SAN'] -> formatPost( $message, $usersig );

        break;

    } // End Switch

    return $message;

}  // End Function


// ##### PRIMARY SQL / DB FUNCTIONS #####


/**
 * Get A Database Result Resource
 *
 * @return object
 */

function getResultSet( $action, $fid = NULL, $tid = NULL, $pid = NULL, $retbool = FALSE, $sortdir = NULL )
{
    global $mpnTables, $start, $forumconfig;

    $updins = array( 5 );

    switch( $action )
    {
        case 1: // Get Forum ID, Name, And Cat For Nav DropDown

            $sql = 'SELECT t1.forum_id, t1.forum_name, t2.cat_title
                    FROM  ' . $mpnTables['forums'] . ' AS t1 USE INDEX(idxforumscatid)
                    LEFT JOIN ' . $mpnTables['categories'] . ' AS t2
                        ON t1.cat_id = t2.cat_id
                    ORDER BY t1.cat_id ' . _FORUM_NAVCAT_ORDER_;
        break;

        case 2: // Get Forum Categories For Main Forum Page

            $sql = 'SELECT t1.cat_title, t2.*
                    FROM  ' . $mpnTables['categories'] . ' AS t1
                        , ' . $mpnTables['forums'] . ' AS t2 USE INDEX(idxforumscatid)
                    WHERE t1.cat_id = t2.cat_id
                    ORDER BY t2.cat_id ' . _FORUM_CAT_ORDER_ . ', t2.forum_id ' . _FORUM_LIST_ORDER_;
        break;

        case 3: // Check For Topic Posters ID When Editing

            $sql = 'SELECT ( MIN(post_id) <=> ' . $pid . ' ) AS orig_post
                    FROM ' . $mpnTables['posts'] . ' USE INDEX(topic_id)
                    WHERE topic_id = ' . $tid . '
                        && poster_id = ' . $GLOBALS['uinf']['uid'] . '
                        && ' . $GLOBALS['uinf']['uid'] . ' > 1';
        break;

        case 4: // Get Topic Title And Status

            $sql = 'SELECT topic_title, topic_status
                    FROM ' . $mpnTables['forumtopics'] . ' USE INDEX(idxtitletime)
                    WHERE forum_id = ' . $fid . '
                        && topic_id = ' . $tid;
        break;

        case 5: // Update Topic Count

             $sql = 'UPDATE ' . $mpnTables['forumtopics'] . '
                     SET topic_views = ( topic_views + 1 )
                     WHERE topic_id = ' . $tid;
        break;

        case 6: // Get All Posts In Topic

            $sortdir = ( ! empty( $sortdir ) ) ? ( $sortdir ) : ( 'ASC' );

            $sql = 'SELECT * FROM ' . $mpnTables['posts'] . ' USE INDEX(idxtopics)
                    WHERE topic_id = ' . $tid . '
                        && forum_id = ' . $fid . '
                    ORDER BY post_id ' . $sortdir;
        break;

        case 7: // Forum Submission

            $sql = 'SELECT t1.*, t2.uname, t2.uid, t2.user_sig
                    FROM  ' . $mpnTables['posts'] . ' AS t1
                        , ' . $mpnTables['users'] . ' AS t2
                    WHERE t1.post_id = "' . $pid . '"
                        && t1.poster_id = t2.uid';
        break;

        case 8: // Get Message For Quoting

            $sql = 'SELECT t1.post_text, t1.post_time, t2.uname
                    FROM  ' . $mpnTables['posts'] . ' AS t1
                        , ' . $mpnTables['users'] . ' AS t2
                    WHERE t1.post_id = ' . $pid . '
                        && t1.poster_id = t2.uid';
        break;

        case 9: // Check User Edit Rights

            $sql = 'SELECT ( post_id = ' . (int)$pid . ' )
                    FROM  ' . $mpnTables['posts'] . '
                    WHERE poster_id = ' . (int)$GLOBALS['uinf']['uid'] . '
                        && ' . (int)$GLOBALS['uinf']['uid'] . ' > 1';
        break;

        case 10: // Get Forum Name & Topic Title, Restrict Private Forums

            $sql = 'SELECT t1.topic_title, t2.forum_name
                    FROM ' . $mpnTables['forumtopics'] . ' AS t1 USE INDEX(idxtitletime)
                        , ' . $mpnTables['forums'] . ' AS t2
                    WHERE t1.topic_id = ' . $tid . '
                        && t1.forum_id = ' . $fid . '
                        && t1.forum_id = t2.forum_id
                        && t2.forum_type <> 1';
        break;

        case 11: // Get All ID's Of Private Forums

            $sql = 'SELECT forum_id
                    FROM ' . $mpnTables['forums'] . '
                    WHERE forum_type = 1';

        break;

        DEFAULT:
            return (bool)FALSE;
        break;

    } // End Switch

    // Check Valid Query

    if ( ! @( $result = mysql_query( $sql ) ) )
    {
        if ( $retbool ) { return (bool)FALSE; }

        goBack( translate( 'Query Failed' ) . '<br/ >' . $sql . '**' . __FILE__ . '***' .  __LINE__ );
    }

    // If Update Or Insert Query, Return True

    if ( in_array( $action, $updins ) ) { return (bool)TRUE; }

    // Check For Valid Result Set

    if ( $retbool )
    {
        if ( ! @mysql_data_seek( $result, 0 ) )
        {
            return (bool)FALSE;
        }
        else
        {
            return (bool)TRUE;
        }
    }

    return $result;

} // End Function

/**
 * Retrieve Stats About The Forum
 *
 * @return mixed
 */

function getStats( $id, $type, $subtype )
{
    global $mpnTables;

    switch( $type )
    {
        case 'count':

            $defret = 0;

            switch( $subtype )
            {
                 case 'all':
                    $sql = 'SELECT MAX(post_id), COUNT(post_id) AS total
                            FROM ' . $mpnTables['posts'];
                break;

                case 'forum':
                    $sql = 'SELECT MAX(post_id), count(post_id) AS total
                            FROM ' . $mpnTables['posts'] . ' USE INDEX(forum_id)
                            WHERE forum_id = ' . $id;
                break;

                case 'topic':
                    $sql = 'SELECT MAX(post_id), COUNT(post_id) AS total
                            FROM ' . $mpnTables['posts'] . ' USE INDEX(idxtopics)
                            WHERE topic_id = ' . $id;
                break;

                case 'forum_topics':
                    $sql = 'SELECT COUNT(topic_id) AS total
                            FROM ' . $mpnTables['forumtopics'] . ' USE INDEX(forum_id)
                            WHERE forum_id = ' . $id;
                break;

                case 'pmsgs':
                    $sql = 'SELECT COUNT(*) AS total
                            FROM ' . $mpnTables['priv_msgs'] . '
                            WHERE to_userid = ' . $id;
                break;

                case 'newpmsgs':
                    $sql = 'SELECT COUNT(*) AS total
                            FROM ' . $mpnTables['priv_msgs'] . '
                            WHERE to_userid = ' . $id . '
                                && read_msg = 0';
                break;

                default:
                    return 0;
                break;
            }

        break;

        case 'exists':

            $defret = (bool)FALSE;

            switch( $subtype )
            {
                case 'forum':
                    $sql = 'SELECT forum_id
                            FROM ' . $mpnTables['forums'] . '
                            WHERE forum_id = ' . $id;
                break;

                case 'topic':
                    $sql = 'SELECT topic_id
                           FROM ' . $mpnTables['forumtopics'] . '
                            WHERE topic_id = ' . $id;
                break;
            }

        break;

        case 'locked':

            $defret = (bool)FALSE;

            switch( $subtype )
            {
                case 'forum':
                    $sql = 'SELECT forum_status
                            FROM ' . $mpnTables['forums'] . '
                            WHERE forum_id = ' . $id;
                break;

                case 'topic':
                    $sql = 'SELECT topic_status
                            FROM ' . $mpnTables['forumtopics'] . '
                            WHERE topic_id = ' . $id;
                break;
            }

        break;

        default:
            return $defret;
        break;
    }

    if ( empty( $sql ) ) { return $defret; }
    if ( ! @( $result = mysql_query( $sql ) ) ) { return $defret; }
    if ( ! @( $tmp = mysql_fetch_row( $result ) ) ) { return $defret; }

    if ( sizeof( $tmp ) > 1 )
    {
        $GLOBALS['fpid'] = 'f' . $tmp[0];
        return $tmp[1];
    }

    return $tmp[0];

} // End Function getStats

/**
 * Save Posted Content
 *
 * @return void
 */

function savePost()
{
    global $mpnTables, $forum, $topic, $post_id, $start, $serv_offset, $mpn_new_forumtopic_notify, $redirect;

    // Adjust Incoming Data

    $action = $_POST['action'];

    $message = processMessage( 2, $_POST['message'], ( $action == 3 ) ? ( (bool)TRUE ) : ( (bool)FALSE ) );

    $image_subject = ( isset( $_POST['image_subject'] ) )
                   ? ( addslashes( $_POST['image_subject'] )  )
                   : ( addslashes( 'icon1.gif' ) );

    $notify = ( isset( $_POST['notify2'] ) && $GLOBALS['uinf']['uid'] > 1 )
            ? ( 1 )
            : ( 0 );

    $poster_ip = addslashes( $_SERVER['REMOTE_ADDR'] );
    $time = addslashes( date( 'Y-m-d H:i', mktime( date( 'H' ) + $serv_offset ) ) );
    $userid = ( ( _MPN_ADMIN && ! _MPN_USER ) && ! _FORUM_ADMIN_USER_ ) ? ( - 1 ) : ( $GLOBALS['uinf']['uid'] );

    if ( empty( $_POST['subject'] ) || $_POST['subject'] == '' )
    {
        goBack( translate( 'Empty Subject' ), TRUE, TRUE );
    }
    else
    {
        $subject = addslashes( $_POST['subject'] );
    }


    // SET SQL QUERIES


    switch ( $action )
    {
        case 1: // Save New Topic

            $sql = 'SELECT MAX(t1.topic_id), MAX(t2.post_id)
                    FROM  ' . $mpnTables['forumtopics'] . ' AS t1
                        , ' . $mpnTables['posts'] . ' AS t2';

            @( ( $result = mysql_query( $sql ) ) && ( $tmp = mysql_fetch_row( $result ) ) )
              OR goBack( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );

            $newtid = $topic = $tmp[0] + 1;
            $newpid = $tmp[1] + 1;

            $redirect = './viewtopic.php?&forum=' . $forum . '&topic=' . $newtid;

            @mysql_free_result( $result );

            $sql1 = 'INSERT INTO ' . $mpnTables['forumtopics'] . '
                     SET  topic_id = "' . $newtid . '"
                        , topic_title = "' . $subject . '"
                        , topic_poster = "' . $userid . '"
                        , forum_id = "' . $forum . '"
                        , topic_time = "' . $time . '"
                        , topic_notify = "' . $notify . '"';

            $sql2 = 'INSERT INTO ' . $mpnTables['posts'] . '
                     SET  post_id = "' . $newpid . '"
                        , image = "' . $image_subject . '"
                        , topic_id = "' . $newtid . '"
                        , forum_id = "' . $forum . '"
                        , poster_id = "' . $userid . '"
                        , post_text = "' . $message . '"
                        , post_time = "' . $time . '"
                        , poster_ip = "' . $poster_ip . '"';

        break;

        case 2: // Save New Post

            $sql = 'SELECT MAX(post_id)
                    FROM ' . $mpnTables['posts'];

            @( ( $result = mysql_query( $sql ) ) && ( $tmp = mysql_fetch_row( $result ) ) )
              OR goBack( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );

            $newpid = $tmp[0] + 1;

            @mysql_free_result( $result );

            $sql1 = 'INSERT INTO ' . $mpnTables['posts'] . '
                     SET  post_id = "' . $newpid . '"
                        , image = "' . $image_subject . '"
                        , topic_id = "' . $topic . '"
                        , forum_id = "' . $forum . '"
                        , poster_id = "' . $userid . '"
                        , post_text = "' . $message . '"
                        , post_time = "' . $time . '"
                        , poster_ip = "' . $poster_ip . '"';


            $sql2 = 'UPDATE ' . $mpnTables['forumtopics'] . '
                     SET topic_time = "' . $time . '"
                     WHERE topic_id = "' . $topic . '"';

        break;

        case 3: // Save Edited Post

            $sql1 = 'UPDATE ' . $mpnTables['posts'] . '
                     SET   post_text = "' . $message . '"
                        , image = "' . $image_subject . '"
                     WHERE post_id = "' . $post_id . '"';

           $sql2 = 'UPDATE ' . $mpnTables['forumtopics'] . '
                     SET topic_time = "' . $time . '"
                        , topic_title = "' . $subject . '"
                     WHERE topic_id = "' . $topic . '"';

        break;

        case 4: // Delete Post

            if ( ! isset( $_POST['post_id'] ) )
            {
                goBack( 'Invalid Request **' . __FILE__ . '***' .  __LINE__ );
            }

            $sql = 'DELETE FROM ' . $mpnTables['posts'] . '
                    WHERE post_id = "' . $post_id . '"';

            @( mysql_query( $sql ) )
              OR goBack( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );

            if ( getStats( $topic, 'count', 'topic' ) == 0 )
            {
                $sql = 'DELETE FROM ' . $mpnTables['forumtopics'] . '
                        WHERE topic_id = "' . $topic . '"';

                @( mysql_query( $sql ) )
                  OR goBack( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );
            }

        break;

    } // End Switch


    // EXECUTE QUERIES


    if ( $action <= 3 )
    {
        if ( ! @mysql_query( $sql1 ) || ! @mysql_query( $sql2 ) )
        {
            goBack( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );
        }

        if ( $GLOBALS['uinf']['uid'] > 1 && $action < 3 ) // Increment Users Post Count
        {
            $sql = 'UPDATE ' . $mpnTables['users_status'] . '
                    SET posts = posts + 1
                    WHERE uid = "' . $GLOBALS['uinf']['uid'] . '"';

            @( mysql_query( $sql ) )
              OR goHome( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );
        }
    }

    if ( $action == 1 && $mpn_new_forumtopic_notify == 1 )
    {
        sendMailNote( 'admin' );
    }

    if ( $action == 2 && $notify == 1 && $GLOBALS['uinf']['uid'] > 1 )
    {
        $sql = 'SELECT t1.topic_notify, t2.uid, t2.email, t2.uname
                FROM  ' . $mpnTables['forumtopics'] . ' AS t1
                    , ' . $mpnTables['users'] . ' AS t2
                WHERE t.topic_id = "' . $topic . '"
                    && t.topic_poster = u.uid';

        if ( ! @( $result = mysql_query( $sql ) ) && _MPN_ADMIN )
        {
            goHome( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );
        }

        if ( (bool)FALSE != $result )
        {
            if ( ! @( $tmp = mysql_fetch_array( $result ) ) && _MPN_ADMIN )
            {
                goHome( 'Query Failed **' . __FILE__ . '***' .  __LINE__ );
            }

            if ( $tmp['topic_notify'] == 1 && $tmp['uid'] != $GLOBALS['uinf']['uid'] )
            {
                sendMailNote( 'user', $tmp  );
            }
        }

        // TODO: Needs To Be coded into site mailers

        /*if ( $admin_post_notify )
        {
            require_once( "./admin/sitemail/site_mailer.php" );

        	sendAdminMailer( 3 );
        }*/
    }

    if ( isset( $redirect ) )
    {
       $_SERVER['F_LIB'] -> redirectRequest( $redirect );
    }
    else
    {
        $_SERVER['F_LIB'] -> redirectRequest( 'viewtopic.php?topic=' . $topic . '&forum=' . $forum . '&start=' . $start );
    }

    exit;

} // End Function savePost


/**
 * Send Post Notification Emails
 *
 *
 */

function sendMailNote( $who, $data = array() )
{
    global $forum, $topic, $topic_subject, $mailmethod, $mpn_new_forumtopic_notify, $adminmail, $sitename, $smtp;

    if ( $who == 'user' && empty( $data ) )
    {
        goHome( 'Expecting Array In Second Argument **' . __FILE__ . '***' .  __LINE__ );
    }

    @( include_once __ROOT__ . 'class.phpmailer.php' )
      OR goHome( translate( 'Include Error' ) );

    $mail = new phpmailer();

    $mail -> IsHTML( TRUE );

    if ( $mailmethod == 0 )
    {
        $mail -> IsMail();
    }
    else
    {
        $mail -> IsSMTP();
        $mail -> Host = $smtp;
    }

    $mail -> From = $adminmail;
    $mail -> FromName = $sitename . translate(' Mailer');

    switch( $who )
    {
        case 'admin':

            $message = translate('A new topic has been posted to the forums: ') . "\n\n";
            $message .= '<a href="' . _MPN_ROOT_URI . 'viewtopic.php?topic=' . $topic . '&forum=' . $forum . '" target="_blank">' . stripslashes( $topic_subject ) . '</a>';
            $subject = translate( 'New topic in the Forums on ' ) . $sitename;


            $mail -> AddAddress( $adminmail );

        break;

        case 'user':

            $subject = translate('A reply to your topic has been posted');
            $message  = translate('Dear ') . $data['uname'] . ",\n";
            $message .= '&nbsp;&nbsp;' . translate( 'You are receiving this email because a message you posted on ' );
            $message .= $sitename . translate( ' forums has been replied to, and you selected to be notified of this event.' ) . "\n\n";
            $message .= translate( 'You may view your topic from this ') . "<a href=\"" . _MPN_ROOT_URI . "viewtopic.php?topic=$topic&forum=$forum\" target=\"_blank\"> link</a>.";
            $message .= "\n\n---------\n";
            $message .= translate( 'Thank you for using ' ) . $sitename . translate( ' forums' );

            $mail -> AddAddress( $data['email'] );

        break;

    } // End Switch

    $mail -> Subject = stripslashes( $subject );
    $mail -> Body = nl2br( stripslashes( $message ) );
    $mail -> AltBody = stripslashes( $message );

    if ( ! $mail -> Send() && _MPN_ADMIN )
    {
        goHome( 'Failed To Send Mail **' . __FILE__ . '***' .  __LINE__  );
    }

    return;

} // End Function sendMailNote


// ##### ADMIN ROUTINES #####


/**
 * Execute Forum Maintenance Routines.
 *
 * @author Kiril Threndor
 * @return void
 */

function runForumMaint()
{
     global $mpnTables;

     if ( ! _ADMIN_TRUSTED ) { exit( '!! ACCESS DENIED !!' ); }

     $fcm = new ForumMaint( $mpnTables );

     // REF: fixTopics( $topicid, $uid, $newuid = NULL, $topic_only = FALSE )
     // REF: fixAllTables( $uid, $newuid = NULL, $topicid = FALSE, $topic_only = FALSE, $action = 'del' )

     switch( $_POST['action'] )
     {
        case 0:  // Fix This Topic Only

            $result = $fcm -> fixTopics( $_POST['topicid'], $_POST['puid'], $_POST['newuid'], TRUE );

       break;

        case 1: // Fix All Topics

            $result = $fcm -> fixTopics( $_POST['topicid'], $_POST['puid'], $_POST['newuid'], FALSE );

        break;

       /* case 2: // Fix All Related Tables

            //$result = $fcm -> fixAllTables( $_POST['puid'], $_POST['newuid'], $_POST['topicid'], FALSE, 'mark' );

        break;*/

        default:
            return;
        break;

    } // End Switch

    return;

} // End Function runForumMaint

?>