<?php

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

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

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

// +----------------------------------------------------------------------+
// | MPN 188_8 Core -> Function Library Class                             |
// |                                                                      |
// | -> General Function Collection                                       |
// +----------------------------------------------------------------------+
// | VERSION: 0.1 Alpha                                                   |
// +----------------------------------------------------------------------+
// | LICENSE: GPL 2.0 (see docs/LICENSE_GPL)                              |
// |                                                                      |
// | This file is part of MPN 188_8 Core.                                 |
// |                                                                      |
// | MPN 188_8 Core 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.                                                       |
// |                                                                      |
// | MPN 188_8 Core 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 MPN 188_8 Core; 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 MPN 188_8 Core.                             |
// | 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:                                                               |
// |   This is a collection of general functions used throughout MPN.     |
// +----------------------------------------------------------------------+
// | SUPPORT:                                                             |
// |   WEB:   http://myphpnuke.com/                                       |
// |   EMAIL: support@mpn.illearth.net                                    |
// +----------------------------------------------------------------------+

/**
 * MPN_188_8_Modules
 *
 * @package MPN_188_8_Core
 * @subpackage classes
 * @category General Functions
 * @version $Id: core_LIB_Functions.class.php,v 1.11.2.37 2004/08/15 12:58:23 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/
 *
 * @tutorial
 * @filesource
 */

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

class FunctionLibrary
{
    var $sitename           = 'myPHPnuke Web Portal';
    var $dbstatus           = FALSE;
    var $install_root       = NULL;
    var $snoopy             = NULL; // Nested Object


function FunctionLibrary()
{
    global $mpnTables;

    $status['dbconf']      = include_once './dbconf.php';
    $status['root_config'] = include_once './config.php';

    $status['core_Constants'] = include_once './core_Constants.php';

    if ( defined( '__ROOT__' ) ) { $this -> install_root = __ROOT__; }

    $status['language'] = @include_once './language/lang-' . $language . '.php';

    // Connect To DB

    $status['dbconn'] = $this -> dbstatus = $this -> dbConnect();

    // Define Variables

    $this -> sitename  = $sitename;

    $status['reqvar'] = ( empty( $mpnTables ) )
                      ? ( (bool)FALSE )
                      : ( (bool)TRUE );

    // Check Status Array

    if ( in_array( (bool)FALSE, $status ) )
    {
        $msg = 'FATAL ERROR: ';

        switch( TRUE )
        {
            case ( (bool)FALSE === $status['dbconn'] ):

                $msg .= 'Connection To Database Failed';

            break;

            case ( (bool)FALSE === $status['reqvar'] ):

                $msg .= 'Failed To Define Required Variables';

            break;

            case ( (bool)FALSE === $status['defroot'] ):

                $msg .= 'Cannot Determine Valid Domain';

            break;

            default:

                $msg .= 'Failed To Include Required File';

            break;

       } // End Switch

        exit( '<h2>' . $msg . '</h2>' );
    }

    // Define Image Directory Paths

    $sql = 'SELECT folder_id, path, uri FROM ' . $mpnTables['image_dirs'];

    if ( ! @( $result = mysql_query( $sql ) ) && ! @mysql_data_seek( $result, 0 ) )
    {
        exit( 'DB Error.  Unable To Define Image Paths' );
    }

    for ( $i = 1; $i <= @mysql_num_rows( $result ); $i++ )
    {
        $tmp = mysql_fetch_row( $result );

        if ( $tmp[0] == 16 ) { $tmp[1] = $tmp[1] . $language . '/'; }

        if ( is_null( $tmp[2] ) )
        {
            define( '_IMG_AURI_' . $tmp[0] . '_', _URI_IMG_ROOT . $tmp[1] );
        }
        else
        {
            define( '_IMG_AURI_' . $tmp[0] . '_', $tmp[2] );
        }

        define( '_IMG_RURI_' . $tmp[0] . '_', _URI_IMG_REL_ROOT . $tmp[1] );
    }

    @mysql_free_result( $result );

    return;

} // End Constructor

/**
 * Connect To Database
 *
 * @return bool ( True On Success, False On Fail )
 */

function dbConnect()
{
    if ( ! @( include './admin/original/dbconfig.php' ) )
    {
        return (bool)FALSE;
    }

    if ( _MPN_MYSQL_PCONNECT )
    {
        @mysql_pconnect( $dbhost, $dbuname, $dbpass );
    }
    else
    {
        @mysql_connect( $dbhost, $dbuname, $dbpass );
    }

    if ( ! @mysql_select_db( $dbname ) )
    {
        return (bool)FALSE;
    }

    unset( $dbhost, $dbuname, $dbpass, $dbname );

    return (bool)TRUE;

} // End Method dbConnect

/**
 * Check DB Table For FullText Index Support.
 *
 * Note: Must be a valid table name.
 */

function checkFTISupport( $tbl )
{
    $sql = 'SHOW TABLE STATUS LIKE "' . $tbl . '"';

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

    $tmp = mysql_fetch_row( $result );

    @mysql_free_result( $result );

    return ( isset( $tmp[1] ) && $tmp[1] == 'MyISAM' );

} // End Method checkFTISupport

/**
 * Simply Checks A URI To See If It's Valid
 *
 * @param string ( $url   -> Base URL To Check, ( must contain trailing slash ) )
 * @param string ( $fname -> Filename At Remote Site To Verify ( must be http accessible ) )
 *
 * @return bool ( true on success, false on fail )
 */

function resolveURI( $url, $fname )
{
    if ( @( include_once __ROOT__ . 'classes/core_Snoopy.class.php' ) )
    {
        $sn = new Snoopy;
        return @$sn -> fetch( $url . $fname );
    }

    return;

} // End Method resolveURI

/**
 * This Method Creates An Array Of Theme Paths
 *
 * @param integer ( create an array for listing in a slect form item )
 *
 * @return mixed ( array on success, bool on fail )
 */

function buildThemeArray( $list_it = '' )
{
    $avail_themes = NULL;

    include_once './theme_functions.php';

    if ( _T_UA_VER4 ) // NN4 Theme Directory
    {
        $avail_themes = array( _DP_THEME_PAR_NN4 );
    }
    else
    {
        $avail_themes = array( _DP_THEME_PAR );
    }

    // BUILD THE PATH ARRAY

    if ( ! empty( $avail_themes ) )
    {
        $i = 0; // Initialize Themes Array Index
        $j = 0; // Initialize Directory Array Index

        while( $j < sizeof( $avail_themes ) )
        {
            if ( ! @chdir( $avail_themes[ $j ] ) )
            {
                return (bool)FALSE;
            }

            if ( $open = opendir( '.' ) )
            {
                while ( ( $file = readdir( $open ) ) != FALSE )
                {
                    if ( ( is_dir( $file ) ) && ( $file != 'CVS' && $file != 'css' && $file != 'NN4' ) && ( ( substr( $file, 0, 1 ) ) != '.' ) )
                    {
                        if ( ! $list_it ) // Build Directory array
                        {
                            $theme_array[ $i ] = array ( $file , $avail_themes[ $j ] . $file . '/' );
                        }
                        else // Build Theme List Array
                        {
                            $theme_array[ $i ] = $file;
                        }

                        $i++; // Increment Theme Array Index
                    }
                }

                closedir( $open ); // Close The Target Directory

                if ( ! @chdir( __ROOT__ ) ) // Change Back To Root
                {
                    return (bool)FALSE;
                }
            }

            $j++;   // Increment Directory Array Index
        }

        sort( array_unique( $theme_array ) );

        return $theme_array; // Return The Created List Of Directory Links
    }

    return (bool)FALSE;

}  // End Method buildThemeArray

/**
 * Load Available Smileys Into Array
 *
 * @return array
 */

function getSmiles()
{
    global $mpnTables;
    $smile_ary = array();


    $sql = 'SELECT code, smile_url FROM ' . $mpnTables['smiles'];
    $result = mysql_query( $sql );

    if ( mysql_error() == '' && (bool)FALSE != $result )
    {
        while( list ( $code, $smile ) = mysql_fetch_row( $result ) )
        {
            $smile_ary[ $code ] = $smile;
        }
    }

    @mysql_free_result( $result );

    return $smile_ary;

} // End Method getSmiles

/**
 * Check PHP Version
 *
 * @param string ( $version -> minimum required version )
 *
 * @return bool
 */

function checkPHPVersion( $version )
{
    $testSplit    = explode ( '.' , $version );
    $currentSplit = explode ( '.' , phpversion() );

    if ( $testSplit[0] < $currentSplit[0] ) { return (bool)TRUE; }

    if ( $testSplit[0] == $currentSplit[0] )
    {
        if ( $testSplit[1] < $currentSplit[1] ) { return (bool)TRUE; }

        if ( $testSplit[1] == $currentSplit[1] )
        {
            if ( $testSplit[2] <= $currentSplit[2] ) { return (bool)TRUE; }
        }
    }

    return (bool)FALSE;

}  // End Method checkPHPVersion

/**
 *
 *
 *
 */

function checkFileUploads( $restr_scps = array() )
{
    if ( ! isset( $idx ) ) { $idx = array_keys( $_FILES ); }

    if ( ! function_exists( 'cfu_recurse' ) )
    {
        function cfu_recurse( $ary )
        {
            foreach ( $ary AS $key => $val )
            {
                if ( ! $val || $val == 0 )
                {
                    return $val;
                }
            }

            return NULL;
        }
    }

    foreach( $idx AS $key )
    {
        $msg = NULL;

        // Run Restricted Scripts Routine Here

        if ( isset( $_FILES[ $key ]['error'] ) )
        {
            $err = ( is_array( $_FILES[ $key ]['error'] ) ) ? ( cfu_recurse( $_FILES[ $key ]['error'] ) ) : ( $_FILES[ $key ]['error'] );

            if ( isset( $err ) && $err > 0 )
            {
                switch( $err )
                {
                    case 1:
                        $msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;

                    case 2:
                        $msg = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
                    break;

                    case 3:
                        $msg = 'The uploaded file was only partially uploaded';
                    break;

                    DEFAULT:
                        $msg = 'No file was uploaded';
                    break;
                }
            }
        }
        else
        {
            $err = ( is_array( $_FILES[ $key ]['size'] ) ) ? ( cfu_recurse( $_FILES[ $key ]['size'] ) ) : ( $_FILES[ $key ]['size'] );

            if ( isset( $err ) )
            {
                $msg = 'No file was uploaded';
            }
        }

        if ( ! empty( $msg ) ) { goBack( $msg ); }
    }

    return (bool)TRUE;

} // End Method

/**
 * Get File Content
 *
 * @param string  ( $file    -> fullly qualified path to file ( either local or remote )
 * @param integer ( $rettype -> how do you want the data returned )
 *
 * Return Options:
 *
 *  1 -> Return A String
 *  2 -> Return An Array
 *  3 -> Dump To Screen
 *
 * @return mixed ( array, string, screen dump )
 */

function getFileContent( $file, $rettype )
{
    $content = '';

    switch ( $rettype )
    {
        case 1: // Return String

            switch ( $this -> checkPHPVersion( '4.3.0' ) )
            {
                case (bool)FALSE: // PHP Version < 4.3.0

                    if ( $fp = @fopen( $file, 'rb' ) )
                    {
                        $content = fread( $fp, filesize( $file ) );

                        fclose( $fp );
                    }

                break;

                case (bool)TRUE: //  PHP Version >= 4.3.0

                    if ( function_exists( 'file_get_contents' ) )
                    {
                        $content = file_get_contents( $file );
                    }

                break;

            } // End Nested Switch

        break;

        case 2: // Return Array

            $content = @file( $file );

        break;

        case 3: // Output To Screen

           $content = @readfile( $file );

        break;

    } // End Switch

    return $content;

}  // End Method getFileContent

/**
 * Write Content To A File
 *
 * @param string ( $filename  -> reference to relative path and file name )
 * @param string ( $mode      -> write mode )
 * @param string ( &$data     -> reference data data being written )
 * @param string ( $f_root    -> OPT: root to file, default is install root )
 * @param bool   ( $exists    -> check if file exists before writting to it )
 *
 * @return bool
 */

function writeFile( $filename, $mode, &$data, $f_root = NULL, $exists = FALSE )
{
    if ( empty( $f_root ) ) { $f_root = $this -> install_root; }

    $filename = $f_root . $filename;

    if ( $exists && is_file( $filename ) )
    {
        return (bool)FALSE;
    }

    if ( is_file( $filename ) && ! is_writable( $filename ) )
    {
        return (bool)FALSE;
    }

    // Check And Adjust Writing Mode Just In Case

    if ( $mode == 'a' ) { $mode = 'a+b'; }
    if ( $mode != 'a+b' && $mode != 'w+b' ) { $mode = 'w+b'; }

    if ( $fp = @fopen( $filename, $mode ) )
    {
        if ( is_array( $data ) )
        {
            $cnt  = 0;
            $size = sizeof( $data );

            foreach( $data AS $key => $line )
            {
                $cnt++;

                if ( substr( $line, -2 ) !== "\n" && $cnt < $size  )
                {
                    $line .= "\n";
                }

                @fwrite( $fp, $line );
            }
        }
        else
        {
            @fwrite( $fp, $data );
        }

        @fclose( $fp );

        return (bool)TRUE;
    }
    else  // Can't Write To FIle
    {
        return (bool)FALSE;
    }

}  // End Method writeFile

/**
 * Make A Directory
 *
 * @param string ( install root relative path to directory )
 *
 * @return array ( array of bool results )
 */

function makeDir( $dir, $perm = NULL )
{
    // REF: fixPath( $rel_path, $real_path = NULL, $web = FALSE )

    if ( __SAFEMODE__ ) { goBack( 'File Uploads Has Been Disabled Due To Server Configuration' ); }

    $dir = FunctionLibrary :: fixPath( $dir );

    if ( is_dir( $dir ) ) { return; }

    $oldmask = umask( 0000 );
    $perm = ( empty( $perm ) ) ? ( 0777 ) : ( (int)$perm );
    $dirpos = strrpos( substr( $dir, 0, -1 ), DIRECTORY_SEPARATOR );
    $parent = substr( $dir, 0, ( $dirpos + 1 ) );

    if ( ! is_dir( $parent ) )
    {
        goBack( 'Directory <i>' . $parent . '</i> Does Not Exist **' . __FILE__ . '***' .  __LINE__ );
    }

    if  ( ! @is_writable( $parent ) && ! @chmod( $parent, 0777 ) )
    {
        goBack( 'Incorrect Permissions On Directory <i>' . $parent . '</i> **' . __FILE__ . '***' .  __LINE__ );
    }

    if ( is_integer( $perm ) )
    {
         $status = @mkdir( $dir, $perm );
    }
    else
    {
         $status = (bool)FALSE;
    }

    @umask( $oldmask );
    @chmod( $parent, $oldmask );

    if ( ! $status )
    {
        goBack( 'Unable To Create Directory <i>' . $dir . '</i> **' . __FILE__ . '***' .  __LINE__ );
    }

    return (bool)TRUE;

} // End Method makeDir

/**
 * Creat A Copy Of A Directory Or File
 *
 * @param string   ( $oldname -> relative path and filename of file to copy )
 * @param string   ( $newname -> relative path and filename of new file )
 * @param string   ( $f_root  -> OPT: root to file, default is install root )
 * @param string   ( $dupname -> OPT: relative path and filename of the permissions file )
 * @param interger ( $dirperm -> OPT: permissions for directory creation )
 * @param bool     ( $copy_dir_contents -> OPT: copy contents of directory when making a directory copy )
 * @param array    ( $restrict_copy -> OPT: array of file names to NOT copy )
 * @param array    ( $restrict_ext  -> OPT: array of file extensions to NOT copy )
 *
 * @return bool ( result of copy and chmod )
 */

function makeCopy(   $oldname
                   , $newname
                   , $f_root = NULL
                   , $dupname = NULL
                   , $dirperm = NULL
                   , $copy_dir_contents = FALSE
                   , $restrict_copy = NULL
                   , $restrict_ext = NULL
                 )
{
    $status  = array();

    if ( empty( $f_root ) ) { $f_root = $this -> install_root; }

    $oldname = $f_root . $oldname;
    $newname = $f_root . $newname;

    if ( ! empty( $dupname ) )
    {
        $dupname = $f_root . $dupname;
    }

    if ( is_file( $oldname ) )
    {
        if ( ! empty( $dupname ) )
        {
            $perms    = @fileperms( $dupname );
            $status['dup_copy'] = @copy( $dupname, $newname );
        }
        else
        {
            $perms = @fileperms( $oldname );
        }

        $status['file_copy'] = @copy( $oldname, $newname );
        $status['file_chmod'] = @chmod( $newname, $perms );

        return $status;
    }
    else if ( is_dir( $oldname ) )
    {
        return $this -> makeDirCopy( $oldname, $newname, $dupname, $dirperm, $copy_dir_contents, $restrict_copy, $restrict_ext );
    }
    else
    {
        return 'Cannot Copy File Or Directory: ' . $oldname;
    }

} // End Method makeCopy

/**
 * Copy A Directory And Contents If Required
 *
 * Do Not Call This Method Directly, Use makeCopy().
 *
 * return array ( results of file & dir operations  )
 */

function makeDirCopy(   $oldname
                      , $newname
                      , $dupname
                      , $dirperm
                      , $copy_dir_contents
                      , $restrict_copy
                      , $restrict_ext
                    )
{
    $status  = array();

    if ( ! is_dir( $newname ) )
    {
        if ( empty( $dirperm ) )
        {
            $dirperm = @fileperms( $oldname );
        }

        $status['mkdir'] = @mkdir( $newname, $dirperm );
    }
    else
    {
        $status['mkdir'] = (bool)FALSE;
    }

    if ( $copy_dir_contents && ! in_array( (bool)FALSE, $status ) )
    {
        $default_restrict = array( '.', '..', 'CVS' );
        $chk_ext = (bool)FALSE;

        if ( is_array( $restrict_copy ) )
        {
            $restrict_copy = array_merge( $default_restrict, $restrict_copy );
        }
        else
        {
            $restrict_copy = $default_restrict;
        }

        if ( is_array( $restrict_ext ) && ! empty( $restrict_ext ) )
        {
            $chk_ext = (bool)TRUE;
        }

        if ( is_writable( $newname ) && (bool)FALSE !== ( $status['opendir'] = $dir = @opendir( $oldname ) ) )
        {
            while( (bool)FALSE !== ( $file = @readdir( $dir ) ) )
            {
                if ( in_array( $file, $restrict_copy ) )
                {
                    continue;
                }

                if ( $chk_ext && in_array( substr( $file, ( strrpos( $file, '.' ) + 1 ) ), $restrict_ext ) )
                {
                    continue;
                }

                $status['dir_filecopy'][] = $this -> makeCopy( $oldname . '/' . $file, $newname . '/' . $file );
            }

            @closedir( $dir );
        }
    }

    return $status;

} // End Method makeDirCopy

/**
 * Get An Array Of Directory Contents
 *
 * @param string ( $dir_root      -> real path to directory root )
 * @param array  ( $allowed_files -> array of allowed file ext.
                                     ex. array( 'jpg', 'gif', 'png' )
 * @param bool   ( $strip_ext     -> OPT: strip extensions off of file names )
 *
 * @return array
 *
 * Note: Will Return Empty Array If Error Occurs
 */

function dirContents( $dir_root, $allowed_files, $strip_ext = FALSE )
{
    $file_ary = array();

    if ( (bool)FALSE !== ( $open = @opendir( $dir_root ) ) )
    {
        while ( (bool)FALSE !== ( $file = @readdir( $open ) ) )
        {
            if ( ! is_dir( $file ) && $file != 'index.html' && substr( $file, 0, 1 ) != '.' )
            {
                $tmp     = explode( '.' , $file );
                $ext_key = count( $tmp ) - 1;

                foreach ( $allowed_files AS $v )
                {
                    if ( $v === $tmp[ $ext_key ] && $strip_ext )
                    {
                        $file_ary[ $file ] = $tmp[0];
                    }
                    else if ( $v === $tmp[ $ext_key ] )
                    {
                        $file_ary[] = $file;
                    }
                }
            }
        }

        // Close The Target Directory

        closedir( $open );
    }

    return $file_ary;

}  // End Method dirContents

/**
 * Get Contents Of An Entire Directory Tree
 *
 * This will get both directories only or both files and directories
 *
 * @param string ( $base    -> base directory to start scanning from )
 * @param array  ( $sub     -> current sub-directory being scanned. )
 * @param array  ( $dirtree -> the array of results. )
 * @param bool   ( $dironly -> OPT: return array of directories only.
 *                                  dir names are stored in array keys )
 *
 * Return Array Syntax:
 *
 *  2 dimensional array ( array( 'directory_name' => array( files in dir ) ); )
 *
 * @return array
 */

function getDirTree( $base, $sub, &$dirtree, $dironly = FALSE )
{
    $base = FunctionLibrary :: fixPath( $base );

    if ( ! is_dir( $base ) )
    {
        goBack( 'Base Directory Does Not Exist **' . __FILE__ . '***' . __LINE__ );
        exit;
    }

    $bdir = ( ! empty( $sub ) ) ? ( $sub ) : ( $base );

    if ( strrchr( $bdir, DIRECTORY_SEPARATOR ) !== DIRECTORY_SEPARATOR ) { $bdir .= DIRECTORY_SEPARATOR; }

    if ( (bool)FALSE !== ( $d = dir( $bdir ) ) )
    {
        while( (bool)FALSE !== ( $fd = $d -> read() ) )
        {
            if ( $fd == 'CVS' || substr( $fd, 0, 1 ) == '.' ) { continue; }

            if ( is_dir( $bdir . $fd ) )
            {
                $dirtree[ $bdir . $fd . DIRECTORY_SEPARATOR ] = array();

                FunctionLibrary :: getDirTree( $base, $bdir . $fd, $dirtree, $dironly );
            }
            else
            {
                if ( ! $dironly ) { $dirtree[ $bdir ][] = $fd; }
            }
        }
    }

    $d -> close();

    return $dirtree;

} // End Method getDirTree

/**
 * Determine If An Array Is Multi-Dimensional
 *
 * @param array ( $array -> array to check )
 *
 * @return bool ( TRUE = Yes, FALSE = No )
 */

function is_multi_array( $array )
{
    if ( is_array( $array ) && ! empty( $array ) )
    {
        $keys = array_keys( $array );

        foreach( $keys AS $v )
        {
            if ( ! is_array( $array[ $v ] ) )
            {
                continue;
            }
            else
            {
                return (bool)TRUE;
            }
        }
    }

    return (bool)FALSE;

} // End Method is_multi_array

/**
 * Search An Array Or Multi-Dimensional Array For A Match To Needle
 *
 * @param string ( $needle   -> needle to search for )
 * @param array  ( $multiary -> Array To Search )
 *
 * @return bool match
 */

function searchMultiArray( $needle, $multiary )
{
	$match = (bool)FALSE;

	if ( in_array( $needle, $multiary ) )
	{
		$match = (bool)TRUE;
	}
	else
	{
		foreach( $multiary AS $key => $v )
		{
		    if ( is_array( $multiary[ $key ] ) )
			{
				if ( $this -> searchMultiArray( $needle, $multiary[ $key ] ) )
				{
					$match = (bool)TRUE;
					break;
				}
			}
		}
	}

	return $match;

} // End Method searchMultiArray

/**
 * Check Return Status Of A Method Process
 *
 * @param mixed ( $ret_status   -> array of bool status or string error )
 * @param bool  ( $exit_on_fail -> OPT: exit on fail ( use for logged in admin ) )
 *
 * @return bool ( bool(true) = passed, exit -> string error message = fail )
 */

function checkStatus( $ret_status, $exit_on_fail = FALSE )
{
    $chk_array[] = array();

    if ( is_string( $ret_status ) )
    {
        if ( $exit_on_fail )
        {
            var_dump( $ret_status );
            exit;
        }

        return $ret_status;
    }

    if ( is_array( $ret_status ) )
    {
        if ( FunctionLibrary :: is_multi_array( $ret_status ) )
        {
            foreach( $ret_status AS $v )
            {
                if ( FunctionLibrary :: is_multi_array( $v ) )
                {
                    $chk_array[] = $v;
                    continue;
                }

                if ( is_array( $v ) && in_array( (bool)FALSE, $ret_status ) )
                {
                    $passed = (bool)FALSE;
                    break;
                }
                else
                {
                    if ( $v !== (bool)TRUE )
                    {
                        $passed = (bool)FALSE;
                        break;
                    }
                }
            }
        }
        else
        {
            if ( in_array( (bool)FALSE, $ret_status ) )
            {
                $passed = (bool)FALSE;
            }
        }
    }

    // Process Result

    if ( ! $passed )
    {
        if ( $exit_on_fail )
        {
            var_dump( $ret_status );
            exit;
        }
        else
        {
            return( 'An Error Occured While Processing Your Request' );
        }
    }

    if ( $passed && empty( $chk_array ) )
    {
        return (bool)TRUE;
    }
    else // Found A Nested Array, Recurse
    {
        FunctionLibrary :: checkStatus( $chk_ary );
    }

} // End Method checkStatus

/**
 * Convert An Array To An Readable String.
 *
 *
 */

function arrayTOstr( $ary, $str = NULL, $literal = FALSE )
    {
        if ( ! is_array( $ary ) ) { return $str; }
        if ( ! isset( $str ) ) { $str = ''; }

        foreach( $ary AS $key => $v )
        {
            if ( is_array( $v ) || is_resource( $v ) )
            {
                if ( sizeof( $v ) > 0 )
                {
                    $v = FunctionLibrary :: arrayTOstr( $ary[ $key ], $str );
                }
            }

            if ( ! empty( $v ) && $v != '' )
            {
                $str .= strtoupper( $key ) . ': ';
                $str .= ( is_string( $v ) && $literal ) ? ( htmlspecialchars( $v ) ) : ( $v );
                $str .= '<br /><br />';
            }
        }

        return $str;

    } // End Method


/**
 * Page Redirect Handler
 *
 * @param string ( $uri -> redirect URI )
 *
 * @return void ( exit )
 */

function redirectRequest( $uri = NULL, $refresh = FALSE )
{
    if ( FunctionLibrary :: checkPHPVersion( 4.2 ) )
    {
        @ob_clean();
    }
    else
    {
        while( @ob_end_clean() );
    }

    if ( empty( $uri ) && $refresh )
    {
        @header( 'Refresh: 0; url = ' . $_SERVER['REQUEST_URI'] );
    }
    else
    {
        if ( ! $_SERVER['SAN'] -> validateInput( $uri, 1 ) )
        {
            $uri = _MPN_ROOT_URI;
        }

        if ( (bool)FALSE !== strpos( $_SERVER['SERVER_SOFTWARE'], 'IIS' ) || $refresh )
        {
            @header( 'Refresh: 0; url = ' . $uri );
        }
        else
        {
            @header( 'Location: ' . $uri );
        }
    }

    exit;

} // End Method redirectRequest

/**
 * Function For Legacy Post Support
 *
 * Checks Post Date For A Time Prior To New BBEncoder Introduction
 *
 * @param mixed ( $date -> can be an integer or string date )
 *
 * @return bool ( TRUE = Legacy Post  FALSE = New Style Post )
 */

function checkPostDate( $date )
{
    global $mpn_install_date;

    if ( empty( $date ) || $date == '' )
    {
        return (bool)TRUE;
    }

    if (    $mpn_install_date <= (int)strtotime( $date )
         || $mpn_install_date <= (int)$date
       )
    {
        return (bool)FALSE;
    }

    return (bool)TRUE;

} // End Method checkPostDate


function truncateString( &$string, $length, $chop = TRUE )
{
    if ( strlen( $string ) > $length )
    {
        if ( $chop ) { $length = strpos( $string, ' ', $length ); }
        $string = substr( $string, 0, $length );
        $string .= '...';
    }

    return $string;

} // End Method

/**
 * This Function Generates A DTD && Header For Stand Alone Pages
 *
 * @param $cssid   -> string ( CSS html ID Name )
 * @param $pagecss -> string ( Page CSS File Name )
 * @param $media   -> string ( Optional CSS Media Type )
 * @param $title   -> string ( Optional Page Title )
 *
 * return string ( header content )
 */

function generateSAHeader( $cssid, $pagecss, $media = 'all', $title = NULL )
{
   $header = '';

    $header .= '<!DOCTYPE html
	PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' . "\n";

    $header .= '<html id="' . $cssid . '">' . "\n";

        $header .= '<head>' . "\n";

            if ( ! empty( $title ) )
            {
                $header .= '<title>' . $title . '</title>' . "\n";
            }
            else
            {
                $header .= '<title>' . $this -> sitename . '</title>' . "\n";
            }
// 20040418 - AvW: 2 lines with meta tags for charset and language added
            $header .= "<meta http-equiv=\"content-type\" content=\"text/html; " . translate('charset=ISO-8859-1') . "\" />\n"; //an admin can now 'translate' his charset
            $header .= "<meta http-equiv=\"content-language\"  content=\"" . translate('en-GB') . "\" />\n"; //an admin can now 'translate' his language setting for the browser

            $header .= '<link rel="stylesheet" href="' . _URI_CSS_PAGE . $pagecss . '" type="text/css" media="' . $media . '" />' . "\n";

        $header .= '</head>' . "\n";

    return $header;

} // End Function

/**
 * Generate A Unique ID
 *
 * @return int
 */

function uniqueID()
    {
        $temp = explode ( ' ' , microtime() * 1000000 );
        $temp = ( count( $temp ) == 2 ) ? ( $temp[0] . $temp[1] ) : ( $temp[0] );
        settype( $temp , 'int' );
        $temp += time();

        return $temp;

    }  // End Method uniqueID

/**
 * Generate A Random Key String
 *
 *
 */

function generateKey( $len, $spchr = TRUE )
    {
        $str = '';

        mt_srand( FunctionLibrary :: uniqueID() );

        for ( $i = 0; $i < $len; $i++ )
        {
            switch ( mt_rand( 1, ( $spchr ) ? 4 : 3 ) )
            {
                case 1: $str .= chr( mt_rand( 48, 57 ) );  break; //0-9
                case 2: $str .= chr( mt_rand( 65, 90 ) );  break; //A-Z
                case 3: $str .= chr( mt_rand( 97, 122 ) ); break; //a-z
                case 4: $str .= chr( mt_rand( 40, 46 ) );  break; //special characters
            }
        }

        return $str;

    }  // End Method generateKey

/**
 *
 *
 *
 */

function formSelect( &$data, &$opts, &$val_text, &$val, &$label, $labelcss='', $formcss='' )
    {
        if ( empty( $val_text ) ) { $val_text = $opts; }

        if ( is_array( $opts ) )
        {
            $content = "<table summary=''>\n";

            foreach ( $opts as $key => $v )
            {
                $content .= "<tr>\n";

                    if ( isset ( $label ) )
                    {
                        $content .= "<td class='formlabel' $labelcss>\n";

                        $content .= "$label[$key]:\n";

                        $content .= "</td>\n";
                    }

                    $content .= "</td><td class='formoption' $formcss>\n";

                        $content .= "<select name='$v'>\n";

                            foreach ( $val as $key1 => $z )
                            {
                                $sel = ( $z == $data[$key] ) ? ( 'selected="yes"' ) : ( '' );

                                $content .= '<option value="' . $z . '" ' . $sel . '>' . $val_text[ $key1 ] . '</option>' . "\n";
                            }

                        $content .= "</select>\n";

                    $content .= "</td>\n";

                $content .= "</tr>\n";
            }

            $content .= "</table>\n";
        }

        return $content;

    }  // End Function


// BUILD A SINGLE OR GROUP OF RADIO BUTTONS OR CHECKBOXES


function formOption ( &$data, &$opts, &$val_text, &$val, &$label, $type=NULL, $labelcss='', $formcss='' )
    {
        if ( ( is_array( $opts ) ) && ( ! empty( $type ) ) )
        {
            $content = "<table summary=''>\n";

            foreach ( $opts as $key => $v )
            {
                $i = 0;
                $type2 = 'type="' . $type . '"';

                $content .= "<tr>\n";

                    $content .= "<td class='formlabel' $labelcss>\n";

                        $content .= "$label[$key]:\n";

                    $content .= "</td>\n";

                    if ( $type == "checkbox" ) // Checkbox
                    {
                        $sel = ( $data[$key] == 1 ) ? ( 'checked="yes"' ) : ( '' );

                        $content .= "<td class='formoption' $formcss>\n";

                            $content .= '<input name="' . $v . '" ' . $type2 . ' value="' . $val[ $key ] . '" ' . $sel . '></input>' . "\n";

                        $content .= "</td>\n";
                    }
                    else // Radio Button
                    {
                        $content .= "<td class='formoption'>\n";

                        foreach ( $val as $key1 => $z )
                        {
                            $sel = ( $data[$key] == $z ) ? ( 'checked="yes"' ) : ( '' );

                            $content .= '<input name="' . $v . '" ' . $type2 . ' value="' . $z . '" ' . $sel . '>' . $val_text[ $key1 ] . '</input>&#160;&#160;' . "\n";

                        }

                        $content .= '</td>' . "\n";
                    }

                $content .= '</tr>' . "\n";
            }

            $content .= '</table>' . "\n";
        }

        return $content;

    }  // End Function


// BUILD A SINGLE OR GROUP OF TEXT BOXES


function formTextbox( &$data, &$opts, &$val_text, &$label, &$para, $labelcss='', $formcss='' )
    {
        if ( is_null( $val_text ) ) { $val_text = $data; }

        if ( is_array( $opts ) )
        {
            $content = '<table summary="">' . "\n";

            foreach ( $opts as $key => $v )
            {
                $para1 = ( is_array( $para ) ) ? ( $para[$key] ) : ( $para );

                $content .= '<tr>' . "\n";

                    $content .= '<td class="formlabel" ' . $labelcss . '>' . "\n";

                        $content .= $label[$key] . "&#058;\n";

                    $content .= "</td><td class='formoption' $formcss>\n";

                        $content .= '<input type="textbox" name="' . $v . '" value="' . $val_text[ $key ] . '" ' . $para1 . '></input>' . "\n";

                    $content .= '</td>' . "\n";

                $content .= '</tr>' . "\n";
            }

            $content .= '</table>' . "\n";
        }

        return $content;

    }  // End Function

/**
 * Generate An Image Select Dropdown That Displays The Selected Image.
 *
 *
 */

function getShowImageSelect( $rdir, $formname, $selname, $pselimg, $imgtar )
{
    if ( ! is_dir( __ROOT__ . $rdir ) )
    {
        goBack( translate( 'Invalid Argument.  Expecting Absolute Directory Path' ) . '**' . __FILE__ . '***' .  __LINE__ );
    }

    $content = NULL;
    $allowed_files = array ( 'jpg', 'gif', 'png' );
    $dirlist = $_SERVER['F_LIB'] -> dirContents( __ROOT__ . $rdir, $allowed_files, TRUE );

    $selimg = ( is_string( $pselimg ) && is_file( __ROOT__ . $rdir . $pselimg ) )
             ? ( $pselimg )
             : ( 'pix.gif' );

    // JS Arguments

    $docTarget = 'document.images.' . $imgtar;
    $docImgPath = ( $selimg == 'pix.gif' ) ? ( _URI_IMG_ROOT ) : ( _MPN_ROOT_URI . $rdir );
    $docValue = 'document.' . $formname . '.' . $selname . '.options[document.' . $formname . '.' . $selname . '.selectedIndex].value';

    // REF: displayImage( docTarget, docImgPath, docValue )

    $content .= "<select name=\"" . $selname . "\" onChange=\"displayImage( $docTarget, '$docImgPath', $docValue )\">\n";

        foreach ( $dirlist AS $fname => $listname )
        {
            $sel = ( $fname == $selimg ) ? ( 'selected="yes"' ) : ( NULL );

            $content .= '<option ' . $sel . ' value="' . $fname . '">' . $listname . '</option>' . "\n";
        }

    $content .= '</select>' . "\n";

    $content .= '&nbsp;&nbsp;';

    $content .= '<img class="middle" name="' . $imgtar . '" src="' . _MPN_ROOT_URI . $rdir . $selimg . '" alt="' . $imgtar . '" ' . _T_NN4_BORDER . ' />' . "\n";

    return $content;

}  // End Function

/**
 *
 *
 *
 */

function chkPass( &$data )
    {
        global $minpass;

        if ( $data[0] !== $data[4] )
        {
            return ( translate( 'ERROR:  Old Password Mis-Match.' ) );
            exit;
        }
        else if ( ( isset( $data[1] ) ) && ( $data[1] !== $data[2] ) )
        {
            return ( translate( 'ERROR:  New Password Mis-Match.' ) );
            exit;
        }
        else if ( ( $data[1] != "" ) && ( $data[3] < $minpass ) )
        {
            return ( translate( 'ERROR:  Password Does Not Meet Minimum Length Requirements.' ) );
            exit;
        }

        return (bool)TRUE;
    }

/**
 *
 *
 *
 */

function checkPostVars( &$remove_keys, &$allow )
    {
        if ( sizeof( $_POST ) > $allow )
        {
            return translate( '!! SECURITY VIOLATION !!' );
        }

        foreach( $_POST AS $key => $v )
        {
            if ( !empty( $key ) && $key != '' && ! in_array( $key, $remove_keys ) )
            {
                $tmp[$key] = $v;
            }
        }

        return $tmp; // Returns Filtered Post Variables Array
    }

/**
 * Check a Table Field For A Match.
 *
 *
 */

function checkDBField( $table, $field, $data )
    {
        global $mpnTables;

        $sql = 'SELECT ' . $field . '
                FROM ' . $mpnTables[ $table ] . '
                WHERE ' . $field . ' = "' . $data . '"';

        $result = @( ( $tmp = mysql_query( $sql ) ) && mysql_data_seek( $tmp, 0 ) );
        @mysql_free_result( $tmp );
        return $result;
    }

/**
 * Change A Local Path Or Path & File To An Absolute URI Link.
 *
 * @return fixed path
 */

function localPathToURI( $path )
{
    $filechk = substr( $path, strrpos( $path, constant( 'DIRECTORY_SEPARATOR' ) ) + 1 );

    if ( strlen( $filechk ) > 0 )
    {
        $file = $filechk;
        $path = FunctionLibrary :: fixPath( substr( $path, 0, strrpos( $path, constant( 'DIRECTORY_SEPARATOR' ) ) ) ) . $file;
    }
    else
    {
        $path = FunctionLibrary :: fixPath( $path );
    }

    $srch = array( __ROOT__, constant( 'DIRECTORY_SEPARATOR' ) );
    $repl = array( _MPN_ROOT_URI, '/' );

    return str_replace( $srch, $repl, $path );

} // End Method localPathToURI


/**
 *
 * @static
 * @return string (adjusted path)
 */

function fixPath( $rel_path, $real_path = NULL, $web = FALSE )
    {
        if ( strlen( $rel_path ) < 1 )
        {
            goBack( '0 Length Path Not Allowed **' . __FILE__ . '***' . __LINE__ );
        }

        $webchk = (bool)FALSE !== strpos( $rel_path, 'http://' );
        $srch = array( '/', '\\' );
        $repl = ( $web || $webchk ) ? ( '/' ) : ( DIRECTORY_SEPARATOR );
        $rel_path = str_replace( $srch, $repl, $rel_path );
        $chk_pos_rel = strpos( $rel_path, $repl );

        $chkdomroot = ( defined( '__ROOT__' ) )
                    ? ( (bool)FALSE !== strpos( $rel_path, __ROOT__ ) )
                    : ( (bool)FALSE );

        // Check For Leading Directory Separator And Remove If Necesary

        if ( (bool)FALSE !== $chk_pos_rel && $chk_pos_rel <= 1 )
        {
            $rel_path = substr( $rel_path, $chk_pos_rel + 1 );
        }

        // Check Trailing Slash If Real Path Is Not Defined ( i.e. rel_path is a file )

        if ( empty( $real_path ) )
        {
            if ( substr( $rel_path, -1 ) != $repl ) { $rel_path = $rel_path . $repl; }

            if ( $chkdomroot )
            {
               return $rel_path;
            }
        }
        else
        {
            $real_path = str_replace( $srch, $repl, $real_path );

            if ( substr( $real_path, -1 ) != $repl ) { $real_path = $rel_path . $repl; }

            // If using $real_path, it is assumed $rel_path is a file name

            return $real_path . str_replace( $srch, '', $rel_path );
        }

        // Check And Adjust For Web Link To File

        if ( $web || $webchk )
        {
            if ( ! $webchk )
            {
                $rel_path = _MPN_ROOT_URI . $rel_path;
            }

            return $rel_path;
        }

        // Default -> Return With Doc Root Prepended

        return __ROOT__ . $rel_path;

    } // End Method fixPath

/**
 *
 *
 *
 */

function getMediaSize( $fnp, $lmtary = NULL )
    {
        if ( ! is_file( $fnp ) ) { return (bool)FALSE; }
        $ext = substr( $fnp, strrpos( $fnp, '.' ) + 1 );
        $defsize = ( isset( $lmtary['defaults'] ) ) ? ( $lmtary['defaults'] ) : ( (bool)FALSE );

        // Images Types PHP function getimagesize() will check

        $check_types = array( 'gif', 'jpg', 'png', 'swf', 'psd', 'bmp', 'tiff', 'jpc', 'jp2', 'jpx', 'jb2', 'swc', 'iff', 'xbm', 'wbmp' );

        if ( in_array( $ext, $check_types ) && ( $tmpsize = @getimagesize( $fnp ) ) )
        {
            return $tmpsize;
        }

        return $defsize;

    } // End Function getMediaSize

/**
 * Strip All The Garbage From A Filename.
 *
 * Borrowed and modified from uploads class
 */

function cleanFileName( &$filename )
    {
        $filename = strtolower( $filename );

        // Replace spaces with _

        $filename = preg_replace( '/[\s]+/', '_', $filename );

        // Remove all chars except a-z0-9-_.

        $filename = preg_replace( '/[^a-z0-9\-_\.]+/', '', $filename );

        return $filename;

    } // End Method cleanFilename

} // End Class

?>