<?php
/**
 * Common functions library of PHPGEN system.
 *
 * PHPGEN 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.
 *
 * PHPGEN 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 PHPGEN; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @copyright   EasySoft R&D Team (C) 2006
 * @author      Chunsheng Wang <wwccss@263.net>
 * @link        http://www.phpgen.com
 * @package     Include
 * @version     $Id: FuncMain.php,v 1.7 2006/08/16 15:36:11 wangcs Exp $
 */

//------------------------- SYSTEM FUNCTIONS -----------------------------------//
/**
 * Enhance the function addslashes())
 *
 * @author                  Chunsheng Wang <wwccss@263.net>
 * @param  mix     $Data    the variable to addslashes.
 * @return mix              formated variable.
 */
function sysAddSlash($Data)
{
    if(!get_magic_quotes_gpc())
    {
        if(is_array($Data))
        {
            foreach($Data as $Key => $Value)
            {
                if(is_array($Value))
                {
                    $Data[$Key] = sysAddSlash($Value);
                }
                else
                {
                    $Data[$Key] = addslashes($Value);
                }
            }
        }
        else
        {
            $Data = addslashes($Data);
        }
    }
    return $Data;
}

/**
 * Enhanced mkdir.
 *
 * @author                  Chunsheng Wang <wwccss@263.net>
 * @param  string  $Path    the dir path to make.
 */
function sysMkdir($Path)
{
    if(eregi("win", PHP_OS))
    {
        $Path = str_replace("/", "\\", $Path);
        system("mkdir $Path");
    }
    else
    {
        system("mkdir -p $Path");
        system("chmod -R 777 $Path");
    }
}

/**
 * Enhanced rm.
 *
 * @author                  Chunsheng Wang <wwccss@263.net>
 * @param  mix  $Dir   the path(es) of files to remove.
 */
function sysRM($Dir)
{
    if(eregi("win", PHP_OS))
    {
        $Dir = str_replace("/", "\\", $Dir);
        system("rmdir $Dir /s /q");
    }
    else
    {
        system("rm -fr $Dir");
    }
}

/**
 * Xcopy in PHP (For Taking Backup of your Web site)
 *
 * @author                          Imran Khalid imranlink@hotmail.com
 * @param   string  $dirPathSource  soruce dir.
 * @param   string  $dirPathTarget  target dir.
 * @param   string  $omitDir        the dir to be omited.
 * @return  array                   Files list copied.
 */
function sysXcopy($dirPathSource, $dirPathTarget, $omitDir)
{
    static $FileList;
    if ($handle = @opendir($dirPathSource))
    {
        while (false !== ($dir = readdir($handle)))
        {
            if ($dir != '.' && $dir != '..' && $dir != $omitDir)
            {
                $pos     = strpos ( $dirPathSource, "/");
                $newdir  = substr($dirPathSource, $pos);
                $pos     = strpos ( $newdir, "/");
                $newdir  = substr($newdir, $pos+1);
                $pos     = strpos ( $newdir, "/");
                $fromDir = $dirPathSource . $dir;
                $toDir   = $dirPathTarget . $dir;
                if (is_dir($fromDir))
                {
                    $mkSuccess = mkdir($toDir);
                    sysXcopy($fromDir . '/', $toDir . '/', $omitDir);
                }
                else
                {
                    copy($fromDir,$toDir);
                    $FileList[] = $toDir;
                }
            }
        }
        closedir($handle);
    }
    return $FileList;
}
//------------------------- DATABASE FUNCTIONS -----------------------------------//

/**
 * Create string like "IN('a','b')"  from "a,b"
 *
 * @author                     Chunsheng Wang <wwccss@263.net>
 * @param  string $ItemList    item list like "a,b,c".
 * @return string $ItemList    string like "IN('a','b','c')".
 */
function dbCreateIN($ItemList)
{
    if(empty($ItemList))
    {
        return false;
    }
    else
    {
        $ItemList = explode(",",$ItemList);
        foreach($ItemList AS $Item)
        {
            $ItemListTMP[] = "'$Item'";
        }
        return " IN (".join(",",$ItemListTMP).") ";
    }
}

/**
 * Merge $SourceSQL to $TargetSQL.
 *
 * @author                     Chunsheng Wang <wwccss@263.net>
 * @param  string $TargetSQL
 * @param  string $SourceSQL
 * @return string $MergedSQL
 */
function dbMergeSQL($TargetSQL, $SourceSQL)
{
    if(eregi("WHERE", $TargetSQL))
    {
        $TargetSQL = eregi_replace("where", "WHERE", $TargetSQL);
        $TargetSQL = explode("WHERE", $TargetSQL);
        $MergedSQL = " WHERE $SourceSQL AND" . $TargetSQL[1];
    }
    else
    {
        $MergedSQL = " WHERE $SourceSQL" . $TargetSQL;
    }
    return $MergedSQL;
}

/**
 * Get the record number of a query.
 *
 * @return int                 RecNumber
 * @global object              Object of ADO class.
 * @param  string $TableName
 * @param  string $Where
 */
function dbGetRecNumber($TableName,$Where = "")
{
    global $MyDB;
    $SQL      = "SELECT COUNT(*) AS RecNumber FROM $TableName $Where";
    $ResultID = $MyDB->query($SQL);
    if($ResultID)
    {
        $DataSet = $ResultID->fetchRow();
        $ResultID->close();
        return (int)$DataSet["RecNumber"];
    }
    else
    {
        die($MyDB->errorMsg());
    }
}

/**
 * Get tables of an database.
 *
 * @author                     Chunsheng Wang <wwccss@263.net>
 * @global object              Object of ADO class.
 * @return array               The tables list of the database.
 */
function dbGetTables($DB)
{
    $ResultID    = $DB->query("SHOW TABLES");
    while($Table = $ResultID->fetchRow())
    {
        $TableName          = current($Table);
        $Tables[$TableName] = $TableName;
    }
    return $Tables;
}

/* Get fields of an table. */
function dbGetFields($DB, $TableName)
{
    $ResultID    = $DB->query("DESCRIBE $TableName");
    while($Field = $ResultID->fetchRow())
    {
        $MyField["Name"]          = $Field["Field"];
        $MyField["Label"]         = $Field["Field"];
        $MyField["Type"]          = $Field["Type"];
        $MyField["Size"]          = explode("(", $Field["Type"]);
        $MyField["Size"]          = explode(")", $MyField["Size"][1]);
        $MyField["Size"]          = $MyField["Size"][0];
        $Fields[$MyField["Name"]] = $MyField;
    }
    return $Fields;
}
/* Get keys of an table. */
function dbGetUniqueKeys($DB, $TableName)
{
    $ResultID    = $DB->query("SHOW INDEX FROM $TableName");
    while($Index = $ResultID->fetchRow())
    {
        if(!$Index["Non_unique"])
        {
            if($Index["Key_name"] == "PRIMARY")
            {
                $IndexList["Primary"] = $Index["Column_name"];
            }
            else
            {
                $IndexList[$Index["Key_name"]][] = $Index["Column_name"];
            }
        }
    }
    return $IndexList;
}

/*------------------------------ Array FUNCTIONS--------------------------*/
/**
 * Get all deepest keys of an array.
 *
 * @author                     Chunsheng Wang <wwccss@263.net>
 * @param  array  $Array       the array variable.
 * @param  string $ArrayName   the name of the variable, note it's a string, no "$" before it.
 * @param  boole  $Restart     If set restart to ture, will unset Keys and ParentArray.
 * @param  string $Key         the topper level key.
 * @return array               all deepest keys.
 */
function arrayGetKeys($Array, $ArrayName, $Restart = true, $Key = "")
{
    static $Keys;
    static $ParentArray;
    if($Restart)
    {
        $Keys        = array();
        $ParentArray = array();
        $Restart     = false;
    }
    empty($ParentArray) ? $ParentArray = $Array : "";

    if(is_array($Array))
    {
        foreach($Array as $CurrentKey => $Value)
        {
            /* Concat the keys with top level. */
            $CurrentKey = $Key . '["' . $CurrentKey . '"]';

            /* If the value of the key is an array, ommit it. */
            $EvalCode =  '$CurrentItem = $ParentArray' . $CurrentKey . ";";
            eval($EvalCode);
            !is_array($CurrentItem) ? $Keys[] = $CurrentKey : "";

            /* Recursion. */
            if(is_array($Value))
            {
                arrayGetKeys($Value, $ArrayName, $Restart, $CurrentKey);
            }
        }
    }
    return $Keys;
}

/**
 * Convert an array structure to string.
 *
 * @author                        Chunsheng Wang <wwccss@263.net>
 * @param  array  $Array          the array variable.
 * @param  string $PreArrayName   the name of the pre variable, note it's a string, no "$" before it.
 * @param  string $LastArrayName  the name of the last variable, note it's a string, no "$" before it.
 * @param  booble $Restart        Restart param will passwd to arrayGetkeys function.
 * @return string                 the code to build the array.
 */
function array2String($Array, $PreArrayName, $LastArrayName, $Restart = true)
{
    $$PreArrayName = $Array;

    /* Get all keys of the array and compute the max length. */
    $Keys = arrayGetKeys($Array, $PreArrayName, $Restart);

    foreach($Keys as $Key)
    {
        $KeyLength[] = strlen($Key);
    }
    $MaxLength = max($KeyLength) + 10;

    /* Cycle the keys, get it's value, compound the string. */
    foreach($Keys as $Key)
    {
        $PreKey   = "$" . $PreArrayName  . $Key;
        $LastKey  = "$" . $LastArrayName . $Key;
        $LastKey  = str_pad($LastKey, $MaxLength);
        $EvalCode = '$Value = ' . $PreKey . ";";
        eval($EvalCode);
        $ArrayString .= $LastKey . '= "' . $Value . "\";\n";
    }
    return sysAddSlash("<?php\n" . $ArrayString . "?>");
}

/**
 * Sort an two-dimension array by some level two items use array_multisort() function.
 *
 * arraySort($Array,"Key1","SORT_ASC","SORT_RETULAR","Key2"……)
 * @author                      Chunsheng Wang <wwccss@263.net>
 * @param  array   $ArrayData   the array to sort.
 * @param  string  $KeyName1    the first item to sort by.
 * @param  string  $SortOrder1  the order to sort by("SORT_ASC"|"SORT_DESC")
 * @param  string  $SortType1   the sort type("SORT_REGULAR"|"SORT_NUMERIC"|"SORT_STRING")
 * @return array                sorted array.
 */
function arraySort($ArrayData,$KeyName1,$SortOrder1 = "SORT_ASC",$SortType1 = "SORT_REGULAR")
{
    if(!is_array($ArrayData))
    {
        return $ArrayData;
    }

    // Get args number.
    $ArgCount = func_num_args();

    // Get keys to sort by and put them to SortRule array.
    for($I = 1;$I < $ArgCount;$I ++)
    {
        $Arg = func_get_arg($I);
        if(!eregi("SORT",$Arg))
        {
            $KeyNameList[] = $Arg;
            $SortRule[]    = '$'.$Arg;
        }
        else
        {
            $SortRule[]    = $Arg;
        }
    }

    // Get the values according to the keys and put them to array.
    foreach($ArrayData AS $Key => $Info)
    {
        foreach($KeyNameList AS $KeyName)
        {
            ${$KeyName}[$Key] = $Info[$KeyName];
        }
    }

    // Create the eval string and eval it.
    $EvalString = 'array_multisort('.join(",",$SortRule).',$ArrayData);';
    eval ($EvalString);
    return $ArrayData;
}

/**
 * Create an array like people1=>1, people2=>2, people is the prefix.
 *
 * @author                      Chunsheng Wang <wwccss@263.net>
 * @param  int     $Min
 * @param  int     $Max
 * @param  string  $Prefix
 * @return array
 */
function arrayRange($Min, $Max, $Prefix)
{
    $Range = range($Min, $Max);
    foreach($Range as $Item)
    {
        $ItemList[$Prefix . $Item] = $Item;
    }
    return $ItemList;
}
?>