<?php

define("MAX_SHNET_LENGTH", "255");
//define("FUNC_FALSE", FALSE);
//define("FUNC_TRUE", TRUE);
define("MAX_IP_LENGTH", "15");
define("MAX_MAC_LENGTH", "17");
define("MAX_HOSTNAME_LENGTH", "128");

define("LOCK_FALSE", "2");

/* åե̾ */
define("LOCKFILE", "dhcpadmin.lock");
define("VARDIR", "var/");

session_start();

/***********************************************************
 * analyze_dhcpd_conf()
 *
 * dhcp.confեʬϽԤ
 *
 * []
 *        $pathfile     ʬϤեѥ
 *        $type         IPv4ޤIPv6
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function analyze_dhcpd_conf($pathfile, $type) 
{
    /* dhcpd.confեɤ߹ߥå */
    if (is_readable_file($pathfile) === FALSE) {
        return FALSE;
    }

    $filedata = array();
    /* subnetshared-network¸ */
    $subnetdata = array();
    
    /* ֤ */
    $rval = 0;
    $countelm = 0;

    /* ѿ */
    define("STR_EMPTY", "");
    define("STR_START", "{");
    define("STR_END", "}");

    /* ץå */
    if ($type == "IPv4") {
        /* IPv4ξ */
        include "ipv4_constant.php";
    } else if ($type == "IPv6") {
        /* IPv6ξ */
        include "ipv6_constant.php";
    }

    /* ˲ϤԤƤ뤫å */
    if (isset($_SESSION["mtime"][STR_IP])) {
        /* եι֤ */
        $file_time = filemtime($pathfile);
        if ($_SESSION["mtime"][STR_IP] >= $file_time) {
            return TRUE;
        }
    }

    /* åѿ */
    unset($_SESSION[STR_IP]);

    /* եƤƤӹ */
    $filedata = file($pathfile);
    if ($filedata == FALSE) {
        return FALSE;
    }
    
    /* ʬɤ߹ */	
    $line = analyze_common($filedata);    

    /* Ĺ׻ */
    $len = count($filedata);
    /* ʬʹߤ */ 
    for ($i = $line; $i < $len; $i++) {
        /* ʸ(ڡԡ) */
        $data = trim($filedata[$i]);
        /* ʸ1Ϣ³ʾ夷Ƥ顢ڡ1ĤˤޤȤ */
        $data = preg_replace('/\s+/', ' ', $data);
        /* ԤǤϤʤ */
        if ($data != STR_EMPTY) {
            /* ͤ */ 
            $subnetdata[] = $data;
        }
    }

    /* subnetshared-networkʬϤ */
    $rval = analyze_subnet_shnetwork($subnetdata);
    /* ͤå */
    if ($rval === FALSE) {
        /* å */
        session_destroy();
        return FALSE;
    }

    /* եκǽϻ֤Ͽ */
    $_SESSION["mtime"][STR_IP] = filemtime($pathfile);  

    return TRUE;
}

/***********************************************************
 * analyze_common
 *
 * dhcp.confեζʬʬϽԤ
 *
 * []
 *        $filedata    եȤ¸
 *
 * [֤]
 *        $sline       subnetޤshared-networkϹ
 *
 **********************************************************/
function analyze_common($filedata)
{
    /* subnetޤshared-networkϹ */
    $sline = 0;
    $commondata = array();

    /* subnetԤå뤿Υѥ */
    $subnetstr = '/^ *' . STR_SUBNET . ' .* {$/';
    /* shared-networkԤå뤿Υѥ */
    $shnetworkstr = '/^ *' . STR_SHNETWORK . ' .* {$/';

    /* subnetshared-networkޤǷ֤ */
    foreach ($filedata as $row) {
        /* ʬλ뤫ɤå */
        if ((preg_match($subnetstr, $row) == 1) || (preg_match($shnetworkstr, $row) == 1)) {
            break;
        }
        /* ̹Ԥ¸ */
        $commondata[$sline] = $row;
        $sline++;
    }
    /* ʬ */
    if ($sline > 0) {
        set_common($commondata);
    }
    /* subnetshared-networkϹԤ֤ */
    return $sline;
}

/***********************************************************
 * set_common
 *
 * å˶ʬꤹ
 *
 * []
 *        $commondata    ʬ¸
 *
 * [֤]
 *        ʤ
 *
 **********************************************************/
function set_common($commondata)
{
    /**/
    $_SESSION[STR_IP]["_common"] = STR_EMPTY;
    /*ȤɤǤ*/
    foreach ($commondata as $row) {
        /*åͤꤹ*/
        $_SESSION[STR_IP]["_common"] .= $row;
    }
}

/***********************************************************
 * analyze_subnet_shnetwork
 *
 * dhcp.confեsubnetshared-networkʬϽԤ
 *
 * []
 *        $subnetdata    subnetshared-network¸
 *
 * [֤]
 *        TRUE              
 *        FALSE             顼
 *
 **********************************************************/
function analyze_subnet_shnetwork($subnetdata)
{
    /* ѿ */
    $shared_flag = 0; 
    $other_flag = 0;
    $newlinenum = 0;
    $shnwname = STR_EMPTY;
    $count = 0;
    $rval = "";
    $arr_shnetwork = array();
    /* åѥ */
    $subnetstr = '/^' . STR_SUBNET . ' .* {$/';
    $shnetworkstr = '/^' . STR_SHNETWORK . ' .* {$/';
	
    /* Ĺ׻ */
    $len = count($subnetdata);
    /* ǸԤޤǷ֤ */
    while ($count < $len) {
        /* shared-networkõ */
        if (preg_match($shnetworkstr, $subnetdata[$count]) == 1) {
            /* shared_networkԤʬϤ */
            $arr_shnetwork = explode(" ",$subnetdata[$count]);
            if (count($arr_shnetwork) != 3) {
                return FALSE;
            }
            $shnwname = $arr_shnetwork[1];
            if ($shnwname == "") {
                return FALSE;
            }
            $rval = analyze_shared_network($shnwname, $subnetdata, $count + 1,
                                          $newlinenum);
            $count = $newlinenum;
            /* shared-networkʬ˥顼ä */
            if ($rval === FALSE) {
                return FALSE;
            }
        /* subnetõ */
        } else if (preg_match($subnetstr, $subnetdata[$count]) == 1) {
            /* subnet򸫤Ĥ */
            $rval = analyze_subnet($subnetdata, $count + 1, $newlinenum);
            /* subnetʬϥ顼ä */
            if ($rval === FALSE) {
                return FALSE;
            }
            $count = $newlinenum;
        /* shnetsubnetδ֤ιԤɤФ */
        } else if ($subnetdata[$count] == "" || $subnetdata[$count] == " ") {
            $count++;
        /* shnetsubnetδ֤;פʹԤ¸ߤʽ񼰤Ȥߤʤ
         * '}'ˤƤ⤳ */
        } else {
            return FALSE;
        }
    }

    return TRUE;	
}

/***********************************************************
 * analyze_shared_network
 *
 * dhcp.confեshared-networkʬϽԤ
 *
 * []
 *        $shnwname      shared-network̾
 *        $subnetdata    subnetshared-network¸
 *        $linenum       shared-networkγϹ
 *        $newlinenum    shared-networkʬνλ
 *
 * [֤]
 *        TRUE           
 *        FALSE          ۾
 *
 **********************************************************/
function analyze_shared_network($shnwname, $subnetdata, $linenum, &$newlinenum)
{
    $line = STR_EMPTY;
    $num = 0;
    $sbnum = 0;
    $ebnum = 0;
    $rval = "";
    /* ̤ɤå */
    $flag = 0;
    /* shared-networkʬ¸ */
    $shnetworkline = array();

    /* shared-netoworkʬλޤǷ֤ */
    foreach ($subnetdata as $line) {
        $num++;
        /* shared-networkγϹԤ˰ư */
        if ($num < $linenum) {
            continue;
        }

        /* {򸫤Ĥ */
        if (preg_match('/.* {$/', $line)) {
            $sbnum++;
        }
        /* }򸫤Ĥ */
        if ($line == "}") {
            $ebnum++;
        }

        /* ͤ */
        $shnetworkline[] = $line;

        /* ̤Ƥɤ߹ */
        if ($sbnum == $ebnum) { 
            $flag = 1;
            $rval = get_all_subnet_in_shnetwork($shnwname, $shnetworkline); 
            if ($rval === FALSE) {
                return FALSE;
            }		
            break;
        }
    }

    /* åбְäƤ */
    if ($flag == 0) {
        return FALSE;
    }

    /* ɤǤԿ֤ */
    $newlinenum = $num;
    return TRUE;
}

/***********************************************************
 * get_all_subnet_in_shnetwork
 *
 * shaered-networkδ֤subnetʬ
 *
 * []
 *        $shnwname         shared-network̾
 *        $shnetworkline    shared-network¸
 *
 * [֤]
 *        TRUE                            
 *        FALSE             顼subnetʬ
 *
 **********************************************************/
function get_all_subnet_in_shnetwork($shnwname, $shnetworkline)
{
    /* subnetν񼰤å뤿Υѥ */
    $subnetstr = '/^' . STR_SUBNET . '.* {$/';
    /* ѿ */
    $line = STR_EMPTY;
    $num = 0;
    $sbnum = 0;
    $ebnum = 0;
    $count = 0;
    $newlinenum = 0;
    $rval = "";
    /* subnetʬ뤫ɤå */
    $flagsubnet = 0;

    /* shared-netowrkʬĹ׻ */
    $len = count($shnetworkline);
    /* ǸޤǷ֤ */
    while ($count < $len) {
        $num++;
        /* subnetʬ򸫤Ĥ */
        if (preg_match($subnetstr, $shnetworkline[$count]) == 1) {
            /* ե饰ѹ */
            $flagsubnet = 1;
            /* get_subnet_in_shnetworkƤӽФ */
            $rval = get_subnet_in_shnetwork($shnwname, $shnetworkline,
                                            $count + 1, $newlinenum);
            $count = $newlinenum;
            if ($rval === FALSE) {
                return FALSE;
            }
        } else {
            $count++;
        }
    }
    /* ֥ͥåʬʤä */
    if ($flagsubnet == 0) {
        /* åshared-networkͤ϶ꤹ */
        $_SESSION[STR_IP][$shnwname] = array();
    }
    /* ɤǤ԰֤֤ */
    return TRUE;
}

/***********************************************************
 * get_subnet_in_shnetwork
 *
 * subnetʬ
 *
 * []
 *        $shnwname         shared-network̾
 *        $shnetworkline    shared-network¸
 *        $curline          subnetʬγϹ
 *        $num              subnetʬγϹ
 * [֤]
 *        TRUE                 
 *        FALSE             顼subnetʬ
 *
 **********************************************************/
function get_subnet_in_shnetwork($shnwname, $shnetworkline, $curline, &$newlinenum)
{
    /* ѿ */
    $line = STR_EMPTY;
    $num = 0;
    /* ϹԿ */
    $snum = 0;
    /* λԿ */
    $enum = 0;
    /* ֥ͥåʬ¸ʬ */
    $subnetline = array();

    /* ֥ͥåʬ򸫤ĤƷ֤ */
    foreach ($shnetworkline as $line) {
        $num++;
        if ($num >= $curline) {
            /* {򸫤Ĥ */
            if (preg_match('/.* {/', $line)) {
                $snum++;
            }
            /* λ̤å */
            if ($line == "}") {
                $enum++;
            }
            /* ͤ¸ */
            $subnetline[] = $line;
            /* ̤ƤƤɤ߹ */		
            if ($snum == $enum) {
                $rval = analyze_subnet_info($shnwname, $subnetline);
                if ($rval === FALSE) {
                    return FALSE;
                }	
                break;
            }
        }
    }
    /* ɤǤԤ֤ */
    $newlinenum = $num;
    return TRUE;
}

/***********************************************************
 * analyze_subnet_info
 *
 * subnetʬʬϽԤ
 *
 * []
 *        $shnwname         shared-network̾
 *        $subnetline       shared-network¸
 *
 * [֤]
 *        TRUE              
 *        FALSE             顼ۥʬ
 *
 **********************************************************/
function analyze_subnet_info($shnwname, $subnetline)
{
    /* ѿ */
    $status = 0;
    $len = 0;
    $linenum = 0;
    $subnetname = STR_EMPTY;
    $hostname = STR_EMPTY;
    $data = array();
    /* ۥʬ¸ */
    $hostitem = array();
    /* ۥʬΰʳ¸ */
    $nohostitem = array();
    /* ۥȹԤν񼰤å뤿ˤΥѥ */
    $hoststr = '/^' . STR_HOST . ' .* {$/';
	
    /* Ĺ׻ */
    $len = count($subnetline);

    /* v4v6ΰ㤤ۼ */
    if (STR_IP == 'v4') {
        /* subnetĤäԤʬ䤹 */
        $data = explode(" ", $subnetline[0]);
        /* ֥ͥåȤξ¸ */
        $subnetname = $data[1]. "/". $data[3];
    } else if (STR_IP == 'v6') {
        /* subnetĤäԤϤ */
        $data = explode(" ", $subnetline[0]);
        $subnetname = $data[1];
    }

    $linenum = 0;
    /* ֥ͥåʬδ֤Ƥɤ߹ */
    while ($linenum < $len - 1) {
        /* { 򸫤Ĥ */
        if (preg_match($hoststr, $subnetline[$linenum]) == 1) {
            $data = explode(" ", $subnetline[$linenum]);
            /* ۥ̾ */
            $hostname = $data[1];
            $status++;			
        } else if ($subnetline[$linenum] == "}") {
            /* {򸫤Ĥ */
            /* {򸫤ĤƤʤä顢顼֤ */
            if ($status != 1 ) {
                return FALSE;     
            }
            $status--;
            /* make_hostؿƤӽФ */ 
            analyze_subnet_host($shnwname, $subnetname, $hostname, $hostitem);

            /* ۥȤ */
            unset($hostitem);
            $hostitem = array();
        }
        if ($status == 1) {
            array_push($hostitem, $subnetline[$linenum]);
        } else {
            if ($subnetline[$linenum] != "}") {
                array_push($nohostitem, $subnetline[$linenum]);
            }
        }
        $linenum++;
    }
    /* ۥȤΰʳǡ */
    analyze_subnet_items($shnwname, $subnetname, $nohostitem);
    return TRUE;
}

/***********************************************************
 * analyze_subnet_host
 *
 * subnetʬʬϽԤäƥå˥ۥʬꤹ
 *
 * []
 *        $shnwname       shared-network̾
 *        $subnetname     subnet̾
 *        $hostname       ۥȤ̾
 *        $hostitem       饤Ⱦ{פб}
 *                        ιԤ¸
 *
 * [֤]
 *       ʤ
 *
 **********************************************************/
function analyze_subnet_host($shnwname, $subnetname, $hostname, $hostitem)
{
    $num = 0;
    $tmp = array();
    /* 饤Ȥξ¸ѿ */
    $vhost = STR_EMPTY;

    /* host ... {  ֡ѡפꤵǽΤ륪ץ */
    $host_params = array( STR_HARDWARE => ",",
                          STR_FIXEDADDR  => ",",
                          STR_HOSTNAME => ",",
                          STR_BOOT => ","
                        );

    $patternboot = '/^' . '(allow|deny)' . ' ' . STR_BOOT . '.*;$/';
    $patternhost = '/^' . STR_HOSTNAME . ' ' . '.*;$/';
    $patternaddr = '/^' . STR_FIXEDADDR . ' ' . '.*;$/';
    $patternhard = '/^' . STR_HARDWARE . ' ' . '.*;$/';

    /* ۥʬå뤿ˡ֤ */
    foreach ($hostitem as $item) {
        /* Ԥν񼰤å */
        if (preg_match($patternhard, $item) == 1) {
            $tmp = str_replace(STR_HARDWARE, STR_EMPTY, $item);
            $tmp = substr($tmp, 0, -1);
            $tmp = trim($tmp);
            $host_params[STR_HARDWARE] = $tmp . ",";
        }

        /* Ԥν񼰤å */
        if (preg_match($patternaddr, $item) == 1) {
            $tmp = str_replace(STR_FIXEDADDR, STR_EMPTY, $item);
            $tmp = substr($tmp, 0, -1);
            $tmp = trim($tmp);
            $host_params[STR_FIXEDADDR] = $tmp . ",";
        }
  
        /* Ԥν񼰤å */
        if (preg_match($patternhost, $item) == 1) {
            $tmp = str_replace(STR_HOSTNAME, STR_EMPTY, $item);
            $tmp = substr($tmp, 0, -1);
            $tmp = trim($tmp);
            $host_params[STR_HOSTNAME] = $tmp . ",";
        }

        /* Ԥν񼰤å */
        if (preg_match($patternboot, $item) == 1) {
            $tmp = str_replace(STR_BOOT, STR_EMPTY, $item);
            $tmp = substr($tmp, 0, -1);
            $tmp = trim($tmp);
            $host_params[STR_BOOT] = $tmp . ",";
        }
    }

    foreach ($host_params as $param) {
        $vhost .= $param;
    }
    /* ǸΡ,פ */
    $vhost = substr($vhost, 0, -1);
    /* vhostѿ˲ԤĤ */
    $vhost .= "\n";
    $vhost = $hostname . "," . $vhost;
    /* å */
    set_subnet_host($shnwname, $subnetname, $vhost);
}


/***********************************************************
 * set_subnet_host
 *
 * å˥ۥʬꤹ
 *
 * []
 *        $shnwname         shared-network̾
 *        $subnetname       subnet̾
 *        $hostinfo         ۥȤ
 *
 * [֤]
 *        ʤ        
 *
 **********************************************************/
function set_subnet_host($shnwname, $subnetname, $hostifnfo) 
{
    /* shared-network å */
    if ($shnwname != STR_EMPTY) {
        /* subnetå */
        if ($subnetname != STR_EMPTY) {
            if (isset($_SESSION[STR_IP][$shnwname][$subnetname]["host"])) {
                $_SESSION[STR_IP][$shnwname][$subnetname]["host"]
                                                                 .= $hostifnfo;
            } else {
                $_SESSION[STR_IP][$shnwname][$subnetname]["host"] = $hostifnfo;
            }
        } else {
            /* ֥ͥåȤʤ硢å˶ */
            $_SESSION[STR_IP][$shnwname] = array();
        }
    }
}

/***********************************************************
 * analyze_subnet_items
 *
 * subnetʬʬϽԤ
 *
 * []
 *        $shnwname       shared-network̾
 *        $subnetname     subnet̾
 *        $nohostitem     롼ԡɥᥤ̾ԡDNSԡɸ꡼ֹԡ
 *                        ꡼ֹԡExtraץԡϰ
 *                        ¸ 
 *
 * [֤]
 *        ʤ
 *
 **********************************************************/
function analyze_subnet_items($shnwname, $subnetname, $nohostitem)
{
    /* ѿ */
    $tmp = STR_EMPTY;
    $arrtmp = array();
    $subnetitem = array( "router" => STR_EMPTY, 
                         "domain" => STR_EMPTY, 
                         "leasetime" => STR_EMPTY,
                         "maxleasetime" => STR_EMPTY, 
                         "dns" => STR_EMPTY, 
                         "option" => STR_EMPTY, 
                         "range" => STR_EMPTY 
                       );

    /* subnetԤν񼰤Υѥ */	
    $subnet = '/^subnet.*{$/';
    /* 롼Ԥν񼰤Υѥ */	
    $prouter = '/^'. STR_ROUTER. ' '. '.*;$/';
    /* ץԤν񼰤Υѥ */	
    $poption = '/^'. STR_OPTION. ' '. '.*;$/';
    /* DNSԤν񼰤Υѥ */	
    $pdns = '/^'. STR_DNS. ' '. '.*;$/';
    /* ɸ꡼ֹԤν񼰤Υѥ */	
    $pleasetime = '/^'. STR_LEASETIME. ' '. '.*;$/';
    /* ꡼ֹԤν񼰤Υѥ */	
    $pmaxleasetime = '/^'. STR_MAXLEASETIME. ' '. '.*;$/';
    /* ɥᥤ̾Ԥν񼰤Υѥ */	
    $pdomain = '/^'. STR_DOMAIN. ' '. '.*;$/';
    /* ϰϹԤν񼰤Υѥ */	
    $prange = '/^'. STR_RANGE. ' '. '.*;$/';
    /* ϰϤ¸ѿ */	
    $vrange = STR_EMPTY;
    /* ץ¸ѿ */
    $vextraoption = STR_EMPTY;

    /* ǸԤޤǷ֤ */	
    foreach ($nohostitem as $item) {
        /* subnet*/
        if (preg_match($subnet, $item)) {
            continue;
        }

        /* ɸ꡼֤ν񼰤å */
        if (preg_match($pleasetime, $item)) {
            $tmp = str_replace(STR_LEASETIME, STR_EMPTY, $item);
            $tmp = str_replace(";", STR_EMPTY, $tmp);
            $subnetitem["leasetime"] = trim($tmp);
            continue;
        }

        /* ꡼֤ν񼰤å */
        if (preg_match($pmaxleasetime, $item)) {
            $tmp = str_replace(STR_MAXLEASETIME, STR_EMPTY, $item);
            $tmp = str_replace(";", STR_EMPTY, $tmp);
            $subnetitem["maxleasetime"] = trim($tmp);
            continue;
        }
				
        /* ϰν񼰤å */
        if (preg_match($prange, $item)) {
            $tmp = str_replace(STR_RANGE, STR_EMPTY, $item);
            $tmp = str_replace("dynamic-bootp", STR_EMPTY, $tmp);
            $tmp = str_replace(";", STR_EMPTY, $tmp);
            $tmp = trim($tmp);
            $arrtmp = explode(" ", $tmp);
            /* ϰʣꤵ礬 */
            if ($vrange == STR_EMPTY) {
                $vrange = $arrtmp[0] . "," .$arrtmp[1];
            } else {
                $vrange .= "\n". $arrtmp[0] . "," . $arrtmp[1];
            }    
            continue;
        }
	
        /* ץν񼰤å */	
        if (preg_match($poption, $item)) {
            if (preg_match($prouter, $item)) {
                $tmp = str_replace(STR_ROUTER, STR_EMPTY, $item);
                $tmp = str_replace(";", STR_EMPTY, $tmp);
                $subnetitem["router"] = trim($tmp);
            } else if (preg_match($pdns, $item)) {
                $tmp = str_replace(STR_DNS, STR_EMPTY, $item);
                $tmp = str_replace(";", STR_EMPTY, $tmp);
                $tmp = str_replace(" ", STR_EMPTY, $tmp);
                $subnetitem["dns"] = trim($tmp);
            } else if (preg_match($pdomain, $item)) {
                $tmp = str_replace(STR_DOMAIN, STR_EMPTY, $item);
                $tmp = str_replace(";", STR_EMPTY, $tmp);
                $tmp = trim($tmp);
                $tmp = rtrim($tmp, "\"");
                $subnetitem["domain"] = ltrim($tmp, "\"");
            } else {
                $tmp = trim($item);
                $vextraoption .= $tmp. "\n";
            }
            continue;
        }

        $tmp = trim($item);
        $vextraoption .= $tmp. "\n";
    /* foreach롼פνü */
    }

    /* Extra option */
    if ($vextraoption != STR_EMPTY) {
        $subnetitem["option"] = trim($vextraoption);
    }
    /* ϰϤ */	
    if ($vrange != STR_EMPTY) {
        $subnetitem["range"] = $vrange;
    }
	
    /* åͤ¸ */
    set_subnet_items($shnwname, $subnetname, $subnetitem);
}


/***********************************************************
 * set_subnet_items
 *
 * å˥롼ԡɥᥤ̾ԡDNSԡɸ꡼ֹԡ
 * ꡼ֹԡExtraץԡϰԤꤹ
 *
 * []
 *        $shnwname       shared-network̾
 *        $subnetname     subnet̾
 *        $subnetitem     롼ԡɥᥤ̾ԡDNSԡɸ꡼ֹԡ
 *                        ꡼ֹԡExtraץԡϰ
 *                        ¸ 
 *
 * [֤]
 *        ʤ
 *
 **********************************************************/
function set_subnet_items($shnwname, $subnetname, $subnetitem)
{
    /* shared뤫ɤ */
    if ($shnwname != STR_EMPTY) {
        /* ֥ͥåȤ뤫ɤ */
        if ($subnetname != STR_EMPTY) {
            foreach ($subnetitem as $key => $value) {
                /* åΥͤꤹ */
                $_SESSION[STR_IP][$shnwname][$subnetname][$key] = $value;
            }
        } else {
            $_SESSION[STR_IP][$shnwname] = array();
        } 
    }

}

/***********************************************************
 * analyze_subnet
 *
 * subnetʬñȤʬϽԤ
 *
 * []
 *        $subnetdata       ֥ͥåʬ¸
 *        $linenum          ֥ͥåʬγϹ
 *        $newlinenum       ˥֥ͥåʬγϹ
 *
 * [֤]
 *        TRUE              
 *        FALSE             顼
 *
 **********************************************************/
function analyze_subnet($subnetdata, $linenum, &$newlinenum)
{
    /* ѿ */
    $line = STR_EMPTY;
    $num = 0;
    /* Ϲ */
    $sbnum = 0;
    /* λ */
    $ebnum = 0;
    /* subnet */
    $shnwname = STR_OTHER;
    /* ֥ͥåʬ¸ */
    $subnetline = array();

    $rval = "";

    /* ֥ͥåʬνλԤޤǷ֤ */
    foreach ($subnetdata as $line) {
        $num++;
        if ($num >= $linenum) {
            /*  { 򸫤Ĥ */
            if (preg_match('/.* {/', $line)) {
                $sbnum++;
            }
            /*  } 򸫤Ĥ */
            if ($line == "}") {
                $ebnum++;
            }

            /* ͤ */
            $subnetline[] = $line;

            /* {ȡѤפ */
            if ($sbnum == $ebnum) {
                /* subnetʬȤʬϤԤؿƤӽФ */
                $rval = analyze_subnet_info($shnwname, $subnetline);
                if ($rval === FALSE) {
                    return FALSE;
                }
                break;
            }
        }
    }

    /* {פȡ֡ѡפο̤ɤå */
    if ($sbnum != $ebnum) {
        return FALSE;
    }

    /* ֥ͥåʬγϹԤ֤ */
    $newlinenum = $num;
    return TRUE;
}

/*********************************************************
 * check_status()
 *
 * DHCPФξּؿ
 *
 * []
 *      $retval        ޥɤμ¹Խλ
 *      $command       ¹Ԥ륳ޥ
 *
 * [֤]
 *      FALSE          systemؿμ¹Լ
 *      TRUE           systemؿμ¹
 ********************************************************/
function check_status(&$retval, $command)
{
    /* ޥɤ¹ */
    /* $retval˥ޥɤνλɤ */
    $ret = exec($command, $output, $retval);
    /* execؿμ¹Լ */
    if ($ret === FALSE) {
        return FALSE;
    }
    return TRUE;
}

/*********************************************************
 * check_add_shnet()
 *
 * Shared-networkͥå
 *
 * []
 *      $shnet        Ϥ줿
 * [֤]
 *      0        
 *      1        ۾(ͥ顼)
 *      2        ۾(ͤʤ)
 **********************************************************/
function check_add_shnet($shnet)
{
    /* ʸå */
    /* shnetͤ뤫Ĵ٤ */
    if (isset($shnet) == FALSE || $shnet == "") {
        /*ͤʤä饨顼*/
        return 2;
    }
    $letters = strlen($shnet);
    if ($letters < 1 || $letters > MAX_SHNET_LENGTH) {
        return 1;
    }

    /* Ⱦѱ羮ʸ국Τߵ */
    $num = "0123456789";
    $sym = "-";
    $sl = "abcdefghijklmnopqrstuvwxyz";
    $ll = strtoupper($sl);
    $allow_letter = $num . $sl . $ll. $sym;
    if (strspn($shnet, $allow_letter) != $letters) {
        return 1;
    }
    /*̤*/
    return 0;
}

/*********************************************************
 * set_subnet_list()
 *
 * ֥ͥåȥꥹȾ󥻥åȴؿ
 *
 * []
 *      $subnet_data           Ϥ줿
 *
 * [֤]
 *      $subnet_option         ֥ͥåȥꥹ
 ********************************************************/
function set_subnet_list($subnet_data = array())
{
    /**/
    $subnet_option = "";
    /*ǸޤǷ֤*/
    foreach ($subnet_data  as $subnet) {
        $subnet = escape_html($subnet);
        /*ץΥͤ򥻥åȤ*/
        $subnet_option = $subnet_option. "<option value=\"$subnet\" >". $subnet. "</option> \n";
    }
    /*֤ͤ*/
    return $subnet_option;
}


/*********************************************************
 * get_all_subnets
 *
 * å󤫤饵֥ͥåȤؿ
 *
 * []
 *
 * [֤]
 *      $subnet_data    ֥ͥåʬʸ
 ********************************************************/
function get_all_subnets()
{
    $subnet_data = array();
    /* ϿƤƤΥɥͥåȡ֥ͥåȤ */
    if (isset($_SESSION[STR_IP])) {
        /* ֥ͥåȤ¸ߤ뤫ɤȽǤ */
        foreach ($_SESSION[STR_IP] as $sn => $value1) {
            /* ʬǤϤʤĥ֥ͥåȤ */
            if ($sn != STR_COMMON && is_array($_SESSION[STR_IP][$sn])) {
                /* ƤΥ֥ͥåȤ */
                foreach ($_SESSION[STR_IP][$sn] as $subnet => $value2) {
                    /* subnet_data˥֥ͥåȤ¸ */
                    $subnet_data[] = $subnet;
                }
            }
        }
    }
    return $subnet_data;
}

/*********************************************************
 * check_subnet_in_session()
 *
 * ֥ͥåȤϥå¸ߤ뤫ɤåؿ
 *
 * []
 *      $subnet               ֥ͥå
 *
 * [֤]
 *      FUNC_TRUE             
 *      FUNC_FALSE            ۾
 ********************************************************/

function check_subnet_in_session($subnet_array, $subnet)
{
    /*ϿƤƤΥ֥ͥåȤ*/
    foreach ($subnet_array as $sub) {
        /*subnet_data˥֥ͥåȤ¸*/
        if ($sub == $subnet) {
            /*֥ͥåȤ¸ߤ*/
            return FUNC_TRUE;
        }
    }
    return FUNC_FALSE;
}

/*********************************************************
 * check_add_subnet_data()
 *
 * ϥǡåؿ
 *
 * []
 *      $post                     Ϥ줿
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_add_subnet_data($post)
{

    /*Сѿ*/
    global $msgarr;
    global $err_msg;
    global $log_msg;

    /*֥ͥåȤϤʤ*/
    if ($post["subnet"] == "") {
        $err_msg = $msgarr['29001'][SCREEN_MSG];
        $log_msg = $msgarr['29001'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ͥåȥޥϤʤ*/
    if ($post["netmask"] == "") {
        $err_msg = $msgarr['29003'][SCREEN_MSG];
        $log_msg = $msgarr['29003'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ʸ*/
    $ret = check_format_ip($post["subnet"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29002'][SCREEN_MSG];
        $log_msg = $msgarr['29002'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ʸ*/
    $ret = check_format_ip($post["netmask"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29004'][SCREEN_MSG];
        $log_msg = $msgarr['29004'][LOG_MSG];
        return FUNC_FALSE;
    }

    return FUNC_TRUE;
}

/*********************************************************
 * check_format_ip()
 *
 * եޥåIPåؿ
 *
 * []
 *      $ip                       Ϥ
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_format_ip($ip)
{
    /* IPv6ξηå */
    if (STR_IP == 'v6') {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE) {
            return FUNC_FALSE;
        }
        return FUNC_TRUE;
    }

    /* IPv4ξηå */
    /*ʬ䤷ͤ¸*/
    $arrar_ip = array();
    $len = 0;

    /*ɽꤹ*/
    $number = '[0-9]{1,3}';
    $ipregular = '/^'. $number. '\.'. $number. '\.'. $number. '\.'. $number. '$/';

    /*ĹȽ*/
    $len = strlen($ip);
    if (($len < 7) || ($len > 15)) {
        return FUNC_FALSE;
    }

    /*ʸ*/
    if (!preg_match($ipregular, $ip)) {
        return FUNC_FALSE;
    }

    /*ɥåȤIPʬ䤹*/
    $array_ip = explode(".", $ip);
    /*255礭ɤȽǤ*/
    foreach ($array_ip as $number) {
        /*255礭*/
        if ($number > 255) {
            return FUNC_FALSE;
        }
    }
    return FUNC_TRUE;
}

/*********************************************************
 * check_subnet_router()
 *
 * 롼ηåؿ
 *
 * []
 *      $router                   롼
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_subnet_router($router)
{
    $len = strlen($router);

    /*롼Ĺå*/
    if ($len > 15 || $len < 7) {
        return FUNC_FALSE;
    }

    /*롼ηåؿƤӽФ*/
    $ret = check_format_ip($router);
    /*֤ͤȽǤ*/
    if ($ret === FUNC_FALSE) {
        return FUNC_FALSE;
    }
    /*FUNC_TRUE֤*/
    return FUNC_TRUE;
}

/*********************************************************
 * check_subnet_dns()
 *
 * DNSɥ쥹ͤåؿ
 *
 * []
 *      $dns                      dnsХɥ쥹
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_subnet_dns($dns)
{
    /*dnsФΥɥ쥹¸*/
    $ip_array = array();
    $new_ip_array = array();
    /*dnsĹ*/
    $len = strlen($dns);

    /*DNSХɥ쥹Ĺå*/
    if ($len > 159) {
        return FUNC_FALSE;
    }

    /*,פdnsʬ䤹*/
    $ip_array = explode(",", $dns);

    /*10ʾϤƤʤǧ*/
    $num = count($ip_array);
    if ($num > 10) {
        return FUNC_FALSE;
    }

    /*ƱIPɥ쥹ʣꤵƤʤ*/
    $new_ip_array = array_unique($ip_array);
    $new_num = count($new_ip_array);
    if ($num != $new_num) {
        return FUNC_FALSE;
    }

    /*ʸå*/
    foreach ($ip_array as $ip) {
        /*IPɥ쥹ηå*/
        $ret = check_format_ip($ip);
        if ($ret === FUNC_FALSE) {
            return FUNC_FALSE;
        }
    }

    return FUNC_TRUE;
}

/*********************************************************
 * check_subnet_leasetime()
 *
 * ɸ꡼֤ĺ꡼֤åؿ
 *
 * []
 *      $leasetime                ꡼
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_subnet_leasetime($leasetime)
{
    /*ɽ*/
    $time_regular = '/^'. '[0-9]{1,}'. '$/';
    $len = strlen($leasetime);

    /*꡼֤Ĺå*/
    if ($len > 8) {
        return FUNC_FALSE;
    }

    /*ɽȽǤ*/
    if (!preg_match($time_regular, $leasetime)) {
        return FUNC_FALSE;
   }
    return FUNC_TRUE;

}

/*********************************************************
 * check_subnet_option()
 *
 * Extraץåؿ
 *
 * []
 *      $option                   extraץ
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_subnet_option($option)
{
    $len = strlen($option);
    /*꡼֤Ĺå*/
    if ($len > 512) {
        return FUNC_FALSE;
    }
    return FUNC_TRUE;
}

/*********************************************************
 * check_update_subnet_data()
 *
 * Extraץåؿ
 *
 * []
 *      $post                     $_POSTϤ
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_update_subnet_data($post)
{
    /*Сѿ*/
    global $msgarr;
    global $err_msg;
    global $log_msg;

    $ret = FUNC_FALSE;

    /*롼Ϥ뤫ɤå*/
    if ($post["router"] == "") {
        $err_msg = $msgarr['29008'][SCREEN_MSG];
        $log_msg = $msgarr['29008'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ɸ꡼֤Ϥ뤫ɤå*/
    if ($post["leasetime"] == "") {
        $err_msg = $msgarr['29011'][SCREEN_MSG];
        $log_msg = $msgarr['29011'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*꡼֤Ϥ뤫ɤå*/
    if ($post["maxleasetime"] == "") {
        $err_msg = $msgarr['29013'][SCREEN_MSG];
        $log_msg = $msgarr['29013'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*DNSФϤ뤫ɤå*/
    if ($post["dnsserver"] == "") {
        $err_msg = $msgarr['29015'][SCREEN_MSG];
        $log_msg = $msgarr['29015'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*롼ηå*/
    $ret = check_subnet_router($post["router"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29009'][SCREEN_MSG];
        $log_msg = $msgarr['29009'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ɥᥤ̾å*/
    $ret = check_defdomain($post["domainname"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['29010'][SCREEN_MSG];
        $log_msg = $msgarr['29010'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ɸ꡼֤ηå*/
    $ret = check_subnet_leasetime($post["leasetime"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29012'][SCREEN_MSG];
        $log_msg = $msgarr['29012'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*꡼֤ηå*/
    $ret = check_subnet_leasetime($post["maxleasetime"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29014'][SCREEN_MSG];
        $log_msg = $msgarr['29014'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*DNSХɥ쥹Τå*/
    $ret = check_subnet_dns($post["dnsserver"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29016'][SCREEN_MSG];
        $log_msg = $msgarr['29016'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*Etraץå*/
    $ret = check_subnet_option($post["exoption"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29017'][SCREEN_MSG];
        $log_msg = $msgarr['29017'][LOG_MSG];
        return FUNC_FALSE;
    }
    return FUNC_TRUE;
}

/*********************************************************
 * dgp_location_hidden()
 *
 * ͤϤؿ
 *
 * []
 *      $url                     url
 *      $hiarray                 $_POSTϤ
 *
 * [֤]
 *      ʤ                     
 ********************************************************/

function dgp_location_hidden($url, $hiarray = null)
{
    global $sesskey;

    /* å */
    $hidden = "<input type=\"hidden\" name=\"sk\" value=\"" .
               $sesskey . "\">";

    if (is_array($hiarray)) {
        foreach ($hiarray as $key => $value) {
            $hidden .= "\n" . "<input type=\"hidden\" name=\"$key\" " .
                              "value=\"$value\">";
        }
    }

    /* HTML */
    display_header();
    print <<<EOD
<script type="text/javascript">
<!--
function msgConfirm(msg) {
        return(window.confirm(msg));
}

function dgpSubmit(url) {
    document.common.action = url;
    document.common.submit();
}
// -->
</script>
<body onload="dgpSubmit('$url')">
...
<form method="post" name="common">
    $hidden
</form>
</body>
</html>
EOD;
    exit;

}

/*********************************************************
 * check_same_name()
 *
 * Ʊ̾õؿ
 *
 * []
 *      $session       Ӥ륻å
 *      $shname        Shared-network̾
 *
 * [֤]
 *      TRUE           Ʊ̾
 *      FALSE          Ʊ̾ʤ
 ********************************************************/

function check_same_name($session, $shname)
{
    /* Ʊ̾å */
    foreach ($session as $key => $value) {
        if ($key != "_other" && $key != "_common") {
            /* ʣĤä */
            if ($key == $shname) {
            return TRUE;
            }
        }
    }
    return FALSE;
}

/*********************************************************
 * re_display()
 *
 * ֥ͥåȤɽؿ
 *
 * []
 *      $left          °֥ͥå
 *      $right         ̤°֥ͥå
 *
 * [֤]
 *      ʤ
 ********************************************************/

function re_display($left, $right)
{
    global $tag;

    if (is_array($left)) {
        foreach ($left as $inshsubnet) {
            $tag["<<SUBNET>>"] .= "<option value=\"$inshsubnet\">$inshsubnet</option>\n";
        }
    }

    if (is_array($right)) {
        foreach ($right as $othershsubnet) {
            $tag["<<OTHERSUBNET>>"] .= "<option value=\"$othershsubnet\">$othershsubnet</option>\n";
        }
    }
}


/*********************************************************
 * set_range_list()
 *
 * ϰϥꥹȾ󥻥åȴؿ
 *
 * []
 *      $range_data            Ϥ줿
 *
 * [֤]
 *      $range_option          ϰϥꥹ
 ********************************************************/
function set_range_list($range_data = array())
{
    /**/
    $newrange = "";
    $range_option = "";
    /*ǸޤǷ֤*/
    foreach ($range_data  as $range) {
        $exp_range = explode(",", $range);
        $newrange = $exp_range[0] . " - " . $exp_range[1];
        $range = escape_html($range);
        /*ץΥͤ򥻥åȤ*/
        $range_option = $range_option . "<option value=\"$range\" >" .
                        $newrange . "</option> \n";
    }
    /*֤ͤ*/
    return $range_option;
}


/*********************************************************
 * get_list_range()
 *
 * å󤫤ϰϤξؿ
 *
 * []
 *      $range_data            ϰ
 *      $subnet                ߥ֥ͥå
 *
 * [֤]
 *      $FUNC_TRUE             
 *      $FUNC_FALSE            ۾
 ********************************************************/
function get_list_range(&$range_data, &$sn, $subnet)
{
    /*ϰϤͤ*/
    if (isset($_SESSION[STR_IP])) {
        /*shared-network_otherʬ*/
        foreach ($_SESSION[STR_IP] as $sn => $value1) {
            if ($sn != STR_COMMON && is_array($_SESSION[STR_IP][$sn])) {
               /*֥ͥåȤϥåˤ*/
                foreach ($_SESSION[STR_IP][$sn] as $sub => $key) {
                /*֥ͥåȤ¸ߤ*/
                    if ($subnet == $sub) {
                        if (isset($_SESSION[STR_IP][$sn][$subnet]["range"]) &&
                            $_SESSION[STR_IP][$sn][$subnet]["range"] != "") {
                            $range_data =
                     explode("\n", $_SESSION[STR_IP][$sn][$subnet]["range"]);
                        } else {
                            $range_data = array();
                        }
                        return FUNC_TRUE;
                    }
                }
            }
        }
     }
    return FUNC_FALSE;
}

/*********************************************************
 * check_range_in_session()
 *
 * åˡϰϤ뤫ɤåؿ
 *
 * []
 *      $rangelist             ϰϤ
 *      $range                 åϰ
 *
 * [֤]
 *      FUNC_TRUE              
 *      FUNC_FALSE             ۾
 ********************************************************/
function check_range_in_session($rangelist, $range) {
    /*ϰϤͤ*/
    foreach ($rangelist  as $rg) {
        /*ϰϤ¸ߤ*/
        if ($range == $rg) {
            return FUNC_TRUE;
        }       
    }
    return FUNC_FALSE;
}

/*********************************************************
 * update_range_session()
 *
 * åϰϤξ󥻥åȴؿ
 *
 * []
 *      $range_data            Ϥ줿
 *
 * [֤]
 *      ʤ
 ********************************************************/
function update_range_session($range_data, $sn, $subnet)
{
    $range_update = "";
    /*ϰϤƷ֤*/
    foreach ($range_data as $range) {
        if ($range_update == "") {
            /*ʸ*/
            $range_update = $range;
        } else {
            /*ϰϤɲä*/
            $range_update .= "\n" . $range;
        }
    }
    /*ϰϤåunsetޤ*/
    if ($range_update == "") {
        unset($_SESSION[STR_IP][$sn][$subnet]["range"]);
    } else {
        /*å˿ϰϤ¸*/
        $_SESSION[STR_IP][$sn][$subnet]["range"] = $range_update;
    }
}

/*********************************************************
 * check_hostname()
 *
 * ۥ̾ͥå
 *
 * []
 *      $hostname    Ϥ줿ۥ̾ 
 * [֤]
 *      TRUE         
 *      FALSE        ۾
 **********************************************************/
function check_hostname($hostname) 
{
    /* ʸå */
    /* hostnameͤ뤫Ĵ٤ */
    if (isset($hostname) && $hostname != "") {
        $length = strlen($hostname);
        if ($length > MAX_HOSTNAME_LENGTH) {
            return FALSE;
        }

        /* Ⱦѱ羮ʸ국Τߵ */
        $num = "0123456789";
        $sl = "abcdefghijklmnopqrstuvwxyz";
        $ll = strtoupper($sl);
        $sym = "!\"#$%&'()=-~^|@`[{;+:*]}<.>/?\\_";
        $allow_letter = $num . $sl . $ll . $sym;
        if (strspn($hostname, $allow_letter) != $length) {
            return FALSE;
        }
    }
    /*ͤʤäTRUE*/
    return TRUE;
}

/*********************************************************
 * check_search_in()
 *
 * 饤ͥå
 *
 * []
 *      $hostname    Ϥ줿ۥ̾
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 *      3            IPɥ쥹顼
 **********************************************************/
function check_search_in($hostname, $mac, $ip)
{
    /* hostnameå */
    $ret = check_hostname($hostname);
    if ($ret == FALSE) {
        return 1;
    }

    /* IPv4, v6ǽ櫓 */
    if (STR_IP == 'v4') {
        /* macɥ쥹å */
        $ret = check_mac($mac);
        if ($ret == FALSE) {
            return 2;
        }
    } elseif (STR_IP == 'v6') {
        /* DUIDå */
        if (check_duid($mac) === FALSE) {
            return 2;
        }
    }

    /* IPå */
    $ret = check_ip($ip);
    if ($ret === FALSE) {
        return 3;
    }

    return 0;
}


/*********************************************************
 * check_duid()
 *
 * DUIDϤ̵ͭʸååԤ
 *
 * []
 *          $duid   åDUID
 *
 * [֤]
 *          TRUE    ̵ޤͤʤ
 *          FALSE   ꤢ
 *********************************************************/
function check_duid($duid)
{
    /* ϤʤХ롼 */
    if (isset($duid) === FALSE) {
        return TRUE;
    }
    if ($duid == "") {
        return TRUE;
    }

    /* ʸå */
    if (strlen($duid) > 128) {
        return FALSE;
    }

    /* å */
    /* 0-F1or2夬':'ڤǹƬޤ³ѥ */
    $pattern = '/^([0-9a-fA-F]{1,2})(:[0-9a-fA-F]{1,2})*$/';
    if (preg_match($pattern, $duid) === 0) {
        return FALSE;
    } 

    return TRUE;
}


/*********************************************************
 * check_ip()
 *
 * ipɥ쥹ͥå
 *
 * []
 *      $ip        Ϥ줿
 * [֤]
 *      TRUE         
 *      FALSE        ۾
 **********************************************************/
function check_ip($ip)
{
    /* IPv6̤Ǥν */
    if (STR_IP == 'v6') {
        if (!isset($ip) || $ip == "") {
            return TRUE;
        }
        if (strlen($ip) > 39) {
            return FALSE;
        }
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === FALSE) {
            return FALSE;
        } 
        return TRUE;
    }

    /* IPv4 */
    /* ʸå */
    /* ipͤ뤫Ĵ٤ */
    if (isset($ip) && $ip != "") {
        $length = strlen($ip);
        if ($length > MAX_IP_LENGTH) {
            return FALSE;
        }

        $num = "0123456789";
        $sym = ".";
        $allow_letter = $num . $sym;
        if (strspn($ip, $allow_letter) != $length) {
            return FALSE;
        }

        /*ʬϤͤ¸*/
        $arrar_ip = array();

        /*ɽꤹ*/
        $number = '[0-9]{1,}';
        $ipregular = '/^' . $number . '\.' . $number . '\.' . $number . '\.' . $number . '$/';

        /*ʸ*/
        if (!preg_match($ipregular, $ip)) {
            return FALSE;
        }

        /*ɥåȤIPʬ䤹*/
        $array_ip = explode(".", $ip);
        /*255礭ɤȽǤ*/
        foreach ($array_ip as $number) {
            /*255礭*/
            if ($number > 255) {
                return FALSE;
            }
        }
        return TRUE;
    }
    /*ͤʤäTRUE*/
    return TRUE;
}

/*********************************************************
 * check_mac()
 *
 * macɥ쥹ͥå
 *
 * []
 *      $mac        Ϥ줿
 * [֤]
 *      TRUE         
 *      FALSE        ۾
 **********************************************************/
function check_mac($mac)
{
    /* ʸå */
    /* macͤ뤫Ĵ٤ */
    if (isset($mac) && $mac != "") {
        $length = strlen($mac);
        if ($length > MAX_MAC_LENGTH) {
            return FALSE;
        }
        /* Ϥ줿ͤ:뤫 */
        $ret = strpbrk($mac, ':');
        if ($ret != FALSE) {
            /* ::Ƕڤ */
            $split = explode(":", $mac);
            foreach ($split as $macsplit) {
                /* 1ޤ2ǤʤФʤʤ */
                if (strlen($macsplit) > 2) {
                    return FALSE;
                }
            }
        }
        /* Ⱦѱ羮ʸ(a~f)국Τߵ */
        $num = "0123456789";
        $sl = "abcdef";
        $ll = strtoupper($sl);
        $sym = ":.";
        $allow_letter = $num . $sl . $ll . $sym;
        if (strspn($mac, $allow_letter) != $length) {
            return FALSE;
        }
    }
    /*ͤʤäTRUE*/
    return TRUE;
}

/*********************************************************
 * client_re_display()
 *
 * ͤɽؿ
 *
 * []
 *      $select        򤵤줿IP߽
 *      $host_match    򤵤줿ۥ̾ΰ׾
 *      $mac_match     򤵤줿IPɥ쥹ΰ׾
 *
 * [֤]
 *      ʤ
 ********************************************************/

function client_re_display($select, $host_match, $mac_match)
{
    global $tag;

    /* v4v6ΰ㤤ۼ */
    $ident = STR_IP == "v4" ? "<<MAC_MATCH>>" : "<<DUID_MATCH>>";

    /* ۥ̾ΰ׾ */
    if ($host_match == "same") {
$tag["<<HOST_MATCH>>"] = <<<END
              <option value="same" selected>Ȱפ</option>
              <option value="into">ޤ</option>
END;
    } else {
$tag["<<HOST_MATCH>>"] = <<<END
              <option value="same">Ȱפ</option>
              <option value="into" selected>ޤ</option>
END;
    }

    /* MACɥ쥹DUIDΰ׾ */
    if ($mac_match == "same") {
$tag[$ident] = <<<END
              <option value="same" selected>Ȱפ</option>
              <option value="into">ޤ</option>
END;
    } else {
$tag[$ident] = <<<END
              <option value="same">Ȱפ</option>
              <option value="into" selected>ޤ</option>
END;
    }

    /* IP߽ */
    if ($select == "allow") {
$tag["<<SEARCHLEASE>>"] = <<<END
             <input type=radio name=ipselect value="allow" checked> 
             <input type=radio name=ipselect value="deny"> 
             <input type=radio name=ipselect value="noselect"> ̤
END;
    } else if ($select == "deny") {
$tag["<<SEARCHLEASE>>"] = <<<END
             <input type=radio name=ipselect value="allow"> 
             <input type=radio name=ipselect value="deny" checked> 
             <input type=radio name=ipselect value="noselect"> ̤
END;
    } else if ($select == "noselect") {
$tag["<<SEARCHLEASE>>"] = <<<END
             <input type=radio name=ipselect value="allow"> 
             <input type=radio name=ipselect value="deny"> 
             <input type=radio name=ipselect value="noselect" checked> ̤
END;
    }
}


/*********************************************************
 * create_backup_file()
 *
 * Хååץեؿ
 *
 * []
 *      $filebackup           Хåå̾
 *      $pahtfile             Хååץե
 *
 * [֤]
 *      ʤ
 ********************************************************/
function create_back_file($pathfile, $backupfile)
{

    if (is_dir($backupfile)) {
        return FUNC_FALSE;
    }

    if (file_exists($backupfile) && (!is_writable($backupfile))) {
        return FUNC_FALSE;
    }

    $mtime = filemtime($pathfile);

    /* ԡ */
    $ret = copy($pathfile, $backupfile);
    /* ͤȽǤ */
    if ($ret !== TRUE) {
        return FUNC_FALSE;
    }

    /* mtimeѹ */
    $ret = touch($backupfile, $mtime);
    if ($ret !== TRUE) {
        return FUNC_FALSE;
    }

    return FUNC_TRUE;
}


 /********************************************************
 * create_tmp_file()
 *
 * dhcpd.confΰեؿ
 *
 * []
 *      $pahtfile             եΥѥ
 *
 * [֤]
 *      ʤ
 ********************************************************/
function create_tmp_file ($pathfile)
{
    $linehost = "";

    if (is_dir($pathfile)) {
        return FUNC_FALSE;
    }

    if (file_exists($pathfile) && (!is_writable($pathfile))) {
        return FUNC_FALSE;
    }

    /* ե򳫤 */
    $tmpFile  = fopen($pathfile, "w");
    if ($tmpFile === FALSE) {
        return FUNC_FALSE;
    }

    /* ʬ */
    if (isset($_SESSION[STR_IP][STR_COMMON])) {
        $ret = fwrite($tmpFile, $_SESSION[STR_IP][STR_COMMON]);
        /* 񤯻顼ȯ */
        if (!$ret) {
            /* եĤ */
            fclose($tmpFile);
            return FUNC_FALSE;
        }
    }

    /* ֥ͥåȤ */
    $ret = create_subnet($tmpFile);
    /* ֤ͤȽǤ */
    if ($ret === FUNC_FALSE) {
        /* եĤ */
        fclose($tmpFile);
        return FUNC_FALSE;
    }

    /* shared-network */
    $ret = create_shared_network($tmpFile, "sn");
    /* ֤ͤȽǤ */
    if ($ret === FUNC_FALSE) {
        /* եĤ */
        fclose($tmpFile);
        return FUNC_FALSE;
    }
    /* եĤ */
    fclose($tmpFile);

    return FUNC_TRUE;

}



/*********************************************************
 * create_linesubnet()
 *
 * ե˥֥ͥåʬ񤭹ؿ
 *
 * []
 *      $allsubnet           ֥ͥåȤ¸
 *      $tmpFile             ե
 *
 * [֤]
 *      FUNC_TRUE            
 *      FUNC_FALSE           ۾
 ********************************************************/
function create_linesubnet($allsubnet, $tmpFile, $type = NULL)
{
    /* ѥ顼᥿θ */
    $properties = array ( STR_ROUTER => "router",
                          STR_LEASETIME => "leasetime",
                          STR_MAXLEASETIME => "maxleasetime",
                          STR_DOMAIN => "domain",
                          STR_DNS => "dns",
                          STR_OPTION => "option"
                        );
    $linehost = "";
    $space_subnet = "";
    $space_item   = "    ";
    $space_phost  = "        ";
    if ($type == "sn") {
        $space_subnet = "    ";
        $space_item   = "        ";
        $space_phost  = "            ";
    }

    /* v4v6ǽ񤭹ƤѤ */
    /* ֥ͥåʬ */
    foreach ($allsubnet as $subnet_netmask => $value) {
        if (STR_IP == "v4") {
            /* ֥ͥåȤϡ/׶ڤǳǼƤ */
            $array_subnet = explode("/", $subnet_netmask);
            /* ֥ͥåȹԤ */
            $subnetline = $space_subnet . STR_SUBNET . " " . $array_subnet[0] .
                          " netmask " . $array_subnet[1] . " {\n";
        } else if (STR_IP == "v6") {
            /* ֥ͥåȤ"IP/ޥ"ηǳǼƤ */
            $subnetline = $space_subnet . STR_SUBNET . " " . $subnet_netmask .
                          " {\n";
        }
        /* ֥ͥåȹԤ񤭹 */
        $ret = fwrite($tmpFile, $subnetline);
        if (!$ret) {
            return FUNC_FALSE;
        }

        /* range¸ߤ뤫ɤå */
        if (isset($allsubnet[$subnet_netmask]["range"])) {
            /* ϰϹԤ */
            $array_range = explode("\n", $allsubnet[$subnet_netmask]["range"]);
            foreach ($array_range as $range) {
                if ($range != "") {
                    $arr_ip = explode(",", $range);
                    /* ϰϹԤ */
                    $bootp = (STR_IP == 'v4') ? " dynamic-bootp " : " ";
                    $linerange = $space_item . STR_RANGE . $bootp .
                                 $arr_ip[0] . " " . $arr_ip[1] . ";\n";
                    /* եϰϤ񤭹 */
                    $ret = fwrite($tmpFile, $linerange);
                    if (!$ret) {
                        return FUNC_FALSE;
                    }
                }
            }
        }

        /* ꤬¸ߤХե˽񤭹 */
        foreach ($properties as $key => $value) {
            if (isset($allsubnet[$subnet_netmask][$value])) {
                /* Ԥ */
                if ($allsubnet[$subnet_netmask][$value] != "") {
                    /* ɥᥤξ */
                    if ($key === "option domain-name" || $key === "option dhcp6.domain-search") {
                        /* ͤ¸ߤ硢ͤ""ǰϤ */
                        if ($allsubnet[$subnet_netmask][$value] !== "") {
                            $newline = $space_item . $key . " \"" . 
                                       $allsubnet[$subnet_netmask][$value] . "\";\n";
                        }
                    /* ץξ */
                    } else if ($key === "option"){
                        $options = trim($allsubnet[$subnet_netmask][$value]);
                        $options = preg_replace("/\n\s+/", "\n", $options);
                        $options = preg_replace("/\n/", "\n$space_item", $options);
                        $newline = $space_item. $options . "\n";
                    /* ɥᥤʳξ */
                    } else {
                        $newline = $space_item . $key . " " . 
                                   $allsubnet[$subnet_netmask][$value] . ";\n";
                    }
                    /* ե˾ */
                    $ret = fwrite($tmpFile, $newline);
                    if (!$ret) {
                        return FUNC_FALSE;
                    }
                }
            }
        }

        /* 饤Ȥ¸ߤ뤫ɤå */
        if (isset($allsubnet[$subnet_netmask]["host"])) {
            /* \nפǥ饤Ⱦʬ䤹 */
            $array_host = explode("\n", $allsubnet[$subnet_netmask]["host"]);
            foreach ($array_host as $host) {
                if ($host != "") {
                    $array_param = explode(",", $host);
                    /* ΩۥȤ */
                    if ($array_param[0] != "") {
                        /* 饤Ȥ񤭹 */
                        $ret = fwrite($tmpFile, $space_item . "host " .
                                      $array_param[0] .  " {\n");
                        if (!$ret) {
                            return FUNC_FALSE;
                        }
                        /* hardware mac */
                        if (isset($array_param[1]) && $array_param[1] != "") {
                            $lineparam = $space_phost . STR_HARDWARE . " " .
                                         $array_param[1] . ";\n";
                            fwrite($tmpFile, $lineparam);
                            if (!$ret) {
                                return FUNC_FALSE;
                            }
                        }

                        /* IPɥ쥹 */
                        if (isset($array_param[2]) && $array_param[2] != "") {
                            $lineparam = $space_phost . STR_FIXEDADDR . " " .
                                         $array_param[2] . ";\n";
                            fwrite($tmpFile, $lineparam);
                            if (!$ret) {
                                return FUNC_FALSE;
                            }
                            if (!$ret) {
                                return FUNC_FALSE;
                            }
                        }

                        /* ۥ̾ */
                        if (isset($array_param[3]) && $array_param[3] != "") {
                            $lineparam =  $space_phost . STR_HOSTNAME . " " .
                                          $array_param[3] . ";\n";
                            $ret = fwrite($tmpFile, $lineparam);
                            if (!$ret) {
                                return FUNC_FALSE;
                            }
                        }

                        /* allow/deny */
                        if (isset($array_param[4]) && $array_param[4] != "") {
                            $lineparam = $space_phost . $array_param[4] . " " .
                                         STR_BOOT . ";\n";
                            fwrite($tmpFile, $lineparam);
                            if (!$ret) {
                                return FUNC_FALSE;
                            }
                        }

                        /* 饤ȤΡ}פ񤭹 */
                        $ret = fwrite($tmpFile, $space_item . "}\n");
                        if (!$ret) {
                            return FUNC_FALSE;
                        }
                    }
                }
            }
        }

        /* ֥ͥåȤΡ} */
        $ret = fwrite($tmpFile, $space_subnet . "}\n");
        if (!$ret) {
            return FUNC_FALSE;
        }
    }
    return FUNC_TRUE;
}
                               


/*********************************************************
 * create_subnet()
 *
 * ֥ͥåʬե˽񤭽Фؿ
 *
 * []
 *      $tmpFile             ե
 *
 * [֤]
 *      FUNC_TRUE            
 *      FUNC_FALSE           ۾
 ********************************************************/
function create_subnet($tmpfile)
{
    /*֥ͥåȤ¸ߤ뤫ɤȽǤ*/
    if (isset($_SESSION[STR_IP][STR_OTHER]) &&
       is_array($_SESSION[STR_IP][STR_OTHER])) {
        /*ե˥֥ͥåȤ񤭹ؿƤӽФ*/
        $ret = create_linesubnet($_SESSION[STR_IP][STR_OTHER], $tmpfile);
        /*֤ͤȽǤ*/
        if ($ret === FUNC_FALSE) {
            return FUNC_FALSE;
        }
    }
    return FUNC_TRUE;
}

/*********************************************************
 * create_shared_network()
 *
 * shared-networkʬؿ
 *
 * []
 *      $tmpFile             ե
 *
 * [֤]
 *      FUNC_TRUE            
 *      FUNC_FALSE           ۾
 ********************************************************/
function create_shared_network($tmpfile)
{
     if (isset($_SESSION[STR_IP]) && is_array($_SESSION[STR_IP])) {
        /*֥ͥå*/
        foreach ($_SESSION[STR_IP] as $sn => $subnet) {
            if ( ($sn != STR_OTHER) && ($sn != STR_COMMON)) {
                /*shared-networkԤ*/
                $linesn = "shared-network " . $sn . " {\n";
                $ret = fwrite($tmpfile, $linesn);
                if (!$ret) {
                    return FUNC_FALSE;
                }
                if (count($_SESSION[STR_IP][$sn]) != 0) {
                    /*ե˥֥ͥåȤ񤭹ؿƤӽФ*/
                    $ret = create_linesubnet($_SESSION[STR_IP][$sn], $tmpfile, "sn");
                    /*֤ͤȽǤ*/
                    if ($ret === FUNC_FALSE) {
                        return FUNC_FALSE;
                    }
                }

                /*եˡ}פ񤭹*/
                $ret = fwrite($tmpfile, "}\n");
                if ($ret === FUNC_FALSE) {
                    return FUNC_FALSE;
                }
            }
        }
    }
    return FUNC_TRUE;
}


/*********************************************************
 * overwrite_setting_file()
 *
 * ե񤭤ؿ
 *
 * []
 *      $tmpFile             ե
 *      $settingfile         ե
 *
 * [֤]
 *      FUNC_TRUE            
 *      FUNC_FALSE           ۾
 ********************************************************/
function overwrite_setting_file($tmpfile, $settingfile)
{

    /*ޥɤ¹Ԥ*/
    $ret = rename($tmpfile, $settingfile);

    if ($ret === FALSE) {
        return FUNC_FALSE;
    }
    return FUNC_TRUE;
}



/*********************************************************
 * run_command()
 *
 * ޥɤ¹Ԥ ؿ
 *
 * []
 *      $cmd                 ¹ԥޥ
 *
 * [֤]
 *      FUNC_TRUE            
 *      FUNC_FALSE           ۾
 ********************************************************/
function run_command($cmd)
{
    $output = "";
    /*ޥɤ¹Ԥ*/
    exec($cmd, $output, $ret);
    if ($ret == 0) {
        return FUNC_TRUE;
    }
    return FUNC_FALSE;
}


/*********************************************************
 * restart_service()
 *
 * dhcpdӥƵưؿ
 *
 * []
 *      $cmd                 ¹ԥޥ
 *
 * [֤]
 *      FUNC_TRUE            
 *      FUNC_FALSE           ۾
 ********************************************************/
function restart_service($cmd)
{
     $output = "";
     /*ޥɤ¹Ԥ*/
     exec($cmd, $output, $ret);

     if ($ret == 0) {
          return FUNC_TRUE;
     }
     return FUNC_FALSE;
}

/***********************************************************
 * dhcpadmin_login_check
 *
 * ťΥåԤ
 *
 * []
 *        ʤ
 *
 * [֤]
 *        FUNC_TRUE           
 *        FUNC_FALSE          顼
 *        LOCK_FALSE          ť
 *
 **********************************************************/
function dhcpadmin_login_check(&$lock_file)
{
    global $domain;
    global $basedir;

    /* åեΥѥ */
    $lock_file = $basedir .  VARDIR . $domain . '/' . LOCKFILE;

    /* tmpեΥѥ */
    $tmp_file = $basedir .  VARDIR . $domain . '/' . LOCKFILE . '.' . getmypid();

    /* åե¸߳ǧ */
    if (file_exists($lock_file)) {

        /* ťˤʤäƤʤå */
        $ret = dhcpadmin_check_lockfile($lock_file);
        if ($ret !== FUNC_TRUE) {
            return $ret;
        }
    }

    /* åեκ */
    $ret = dhcpadmin_make_lockfile($lock_file, $tmp_file);
    if ($ret === FALSE) {
        return FUNC_FALSE;
    }

    return FUNC_TRUE;
}

/***********************************************************
 * dhcpadmin_make_lockfile
 *
 * åեκ
 *
 * []
 *        $lock_file     åեΥѥ 
 *        $lock_file     եΥѥ 
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function dhcpadmin_make_lockfile($lock_file, $tmp_file)
{
    global $env;

    /*  */
    $data = $env['loginuser'] . "\t" . $_SERVER["REMOTE_ADDR"] . "\t" . time();

    /* ե򥪡ץ */
    $tmp_fp = fopen($tmp_file, "w");
    if ($tmp_fp === FALSE) {
        return FALSE;
    }

    /* ե˽񤭹 */
    $ret = fwrite($tmp_fp, $data);
    fclose($tmp_fp);
    if ($ret === FALSE) {
        unlink($tmp_file);
        return FALSE;
    }

    /* åե֤ */
    $ret = rename($tmp_file, $lock_file);
    if ($ret === FALSE) {
        unlink($tmp_file);
        return FUNC_FALSE;
    }

    return TRUE;
}

/***********************************************************
 * dhcpadmin_check_lockfile
 *
 * åեƥå
 *
 * []
 *        $lock_file     åեΥѥ
 *
 * [֤]
 *        FUNC_TRUE           
 *        FUNC_FALSE          顼
 *        LOCK_FALSE          ť
 *
 **********************************************************/
function dhcpadmin_check_lockfile($lock_file)
{
    global $web_conf;
    global $env;

    /* åեɤ߹ */
    $ret = dhcpadmin_read_lockfile($lock_file, $filedata);
    if ($ret === FALSE) {
        return FUNC_FALSE;
    }

    $lock_time = $web_conf["dhcpadmin"]["locktime"] + $filedata[2];

    /* åե˴Ƥ褤å */
    if (time() < $lock_time) {

        /* 桼̾,IPɥ쥹å */
        if (($filedata[0] != $env['loginuser']) || ($filedata[1] != $_SERVER["REMOTE_ADDR"])) {
            return LOCK_FALSE;
        }
    }

    return FUNC_TRUE;
}

/***********************************************************
 * dhcpadmin_del_lockfile
 *
 * åեκ
 *
 * []
 *        ʤ
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function dhcpadmin_del_lockfile()
{
    global $domain;
    global $basedir;
    global $env;

    /* åեΥѥ */
    $lock_file = $basedir . VARDIR . $domain . '/' . LOCKFILE;

    /* åեɤ߹ */
    $ret = dhcpadmin_read_lockfile($lock_file, $filedata);
    if ($ret === FALSE) {
        return FUNC_FALSE;
    }

    /* 桼̾,IPɥ쥹å */
    if (($filedata[0] != $env['loginuser']) || ($filedata[1] != $_SERVER["REMOTE_ADDR"])) {
        return LOCK_FALSE;
    }

    /* եκ */
    $ret = unlink($lock_file);
    if ($ret === FALSE) {
        return LOCK_FALSE;
    }

    return FUNC_TRUE; 
}

/***********************************************************
 * dhcpadmin_read_lockfile
 *
 * åեɤ߹
 *
 * []
 *        $lock_file     åեΥѥ
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function dhcpadmin_read_lockfile($lock_file, &$filedata)
{
    /* ե򥪡ץ */
    $fp = fopen($lock_file, "r");
    if ($fp === FALSE) {
        return FALSE;
    }

    /* եɤ߹ */
    $buffer = fgets($fp);
    fclose($fp);
    if ($buffer === FALSE) {
        return FALSE;
    }

    $filedata = explode("\t", $buffer, 3);
    if ($filedata === FALSE) {
        return FALSE;
    } elseif (!isset($filedata[2])) {
        return FALSE;
    }

    return TRUE;
}

/***********************************************************
 * check_add_range
 *
 * ϰϤϤåؿ
 *
 * []
 *        $startrange     ϰ()
 *        $endrange       ϰ()
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function check_add_range($startrange, $endrange)
{
    global $msgarr;
    global $err_msg;
    global $log_msg;

    /*ϰ()Ϥ뤫ɤå*/
    if ($startrange == "") {
        $err_msg = $msgarr['31001'][SCREEN_MSG];
        $log_msg = $msgarr['31001'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ϰ()Ϥ뤫ɤå*/
    if ($endrange == "") {
        $err_msg = $msgarr['31002'][SCREEN_MSG];
        $log_msg = $msgarr['31002'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ϰ()̤å*/
    $ret = check_format_ip($startrange);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['31003'][SCREEN_MSG];
        $log_msg = $msgarr['31003'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ϰ()̤å*/
    $ret = check_format_ip($endrange);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['31004'][SCREEN_MSG];
        $log_msg = $msgarr['31004'][LOG_MSG];
        return FUNC_FALSE;
    }

    return FUNC_TRUE;
}

/***********************************************************
 * check_duplicate_range
 *
 * ϰϤνʣå뤹ؿ
 *
 * []
 *        $sn             shared-networkȤ_other
 *        $subnet         ֥ͥå
 *        $startrange     ϰ()
 *        $endrange       ϰ()
 *
 * [֤]
 *        TRUE            
 *        FALSE           顼
 *
 **********************************************************/

function check_duplicate_range($sn, $subnet, $startrange, $endrange, $oldrange = "")
{

    global $msgarr;
    global $err_msg;
    global $log_msg;

    $range_data = array();
    $arr_ip = array();
    $arr_sub = array();
    $arr_subnet = array();
    $arr_ip = array();
    $arr_start = array();
    $arr_end = array();

    $dup_range = $startrange . "," . $endrange;
    /*֥ͥåȤʬ*/
    $arr_sub = explode(".", $subnet);
    $arr_start = explode(".", $startrange);
    $arr_end = explode(".", $endrange);
    $arr_ip = explode("/", $subnet);

    $bcast = ip2long($arr_ip[0]);
    $nmask = ip2long($arr_ip[1]);

    /*ϰ*/
    $ret = ipcompare($startrange, $arr_ip[0], $arr_ip[1]);
    if ($ret == FALSE) {
        $err_msg = sprintf($msgarr['31007'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31007'][LOG_MSG], $dup_range);
        return FUNC_FALSE;
    }

    /*ϰ*/
    $ret = ipcompare($endrange, $arr_ip[0], $arr_ip[1]);
    if ($ret == FALSE) {
        $err_msg = sprintf($msgarr['31007'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31007'][LOG_MSG], $dup_range);
        return FUNC_FALSE;
    }

    /*ϰ()ϰ()*/
    $ret = strcmp($startrange, $endrange);
    if ($ret >= 0) {
        $err_msg = sprintf($msgarr['31008'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31008'][LOG_MSG], $dup_range);
        return FUNC_FALSE;
    }

    /*ϰϤ*/
    $ret = get_list_range($range_data, $sn, $subnet);
    if ($ret === FUNC_FALSE) {
        $err_msg = sprintf($msgarr['31005'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31005'][LOG_MSG], $dup_range);
        return FUNC_FALSE;
    }

    /*ѹξ硢ѹϰϤ*/
    if ($oldrange != "") {
        /*ϰoldsubnetunset*/
        $key = array_search($oldrange, $range_data);
        if ($key !== FALSE) {
            unset($range_data[$key]);
        }
    }

    /*롼*/
    foreach ($range_data as $linerange) {
        /*,פϰϤʬ䤹*/
        $arr_ip = explode(",", $linerange);
        $ret1 = strcmp($startrange, $arr_ip[1]);
        $ret2 = strcmp($endrange, $arr_ip[0]);
        if (!(($ret1 > 0) || ($ret2 < 0))) {
            $err_msg = sprintf($msgarr['31006'][SCREEN_MSG], $dup_range);
            $log_msg = sprintf($msgarr['31006'][LOG_MSG], $dup_range);
            return FUNC_FALSE;
        }
    }
    return FUNC_TRUE;
}


function ipcompare ($ip1, $ip2, $mask) {
    $masked1 = ip2long($ip1) & ip2long($mask);
    $masked2 = ip2long($ip2) & ip2long($mask);
    if ($masked1 == $masked2) {
        return true;
    }
    return false;
}


/***********************************************************
 * check_delete_range()
 * ϰϤˡhostޤ뤫ɤå
 *
 *
 * []
 *      $host       饤Ȥʸ
 *      $range      ϰϤ򤷤
 *
 * [֤]
 *        FUNC_TRUE            
 *        FUNC_FALSE           顼
 *
 ***********************************************************/
function check_delete_range($hoststr, $range) { 
    /* 饤Ȥʬ*/
    $host_array = explode("\n", $hoststr);
    list($lower, $upper) = explode(',', $range, 2);

    $lower_dec = inet_pton($lower);
    $upper_dec = inet_pton($upper);

    foreach ($host_array as $host) {
        $list_item = explode(",", $host);
        if (isset($list_item[2])) {
            if ($list_item[2] != "") {
                $ip = $list_item[2];
                $ip_dec = inet_pton($ip);
                if ( ($ip_dec >= $lower_dec) && ($ip_dec <= $upper_dec) ) {
                    return FALSE;
                }
            }
        }
    }
    return TRUE;
}



/***********************************************************
 * check_duplicate_v6range()
 *
 * ϰԽ̤ǸƤӽФ롣
 * Ϥ줿ϰϤ֥ͥåȤ˼ޤäƤ뤫ɤ
 * ϰ()()羮طŬڤɤ
 * ¾ϰȤ֤äƤʤå롣
 *
 * ξ硢ѹΥǡκ⤳δؿǹԤ
 *
 * []
 *      $sn         shared-network̾
 *      $subnet     ֥ͥåȤIP/mask
 *      $startrange Ϥ줿ϰ()
 *      $endrange   Ϥ줿ϰ()
 *      $oldrange   ξ硢ϰ
 *
 * [֤]
 *        FUNC_TRUE            
 *        FUNC_FALSE           顼
 *
 ***********************************************************/
function check_duplicate_v6range ($sn, $subnet, $startrange, $endrange, $oldrange = "")
{
    /* 顼å */
    global $msgarr, $err_msg, $log_msg;
    $dup_range = $startrange . "," . $endrange;

    /************************
     * ֥ͤͥåϰˤ뤫ɤΥå
     ************************/
    /* IPʬȥޥʬʬ */
    list($net, $mask) = explode("/", $subnet);
    /* ޥ(32Ȥ64Ȥ)ХȤѴ */
    $binMask = masktobyte($mask);
    /* IPɥ쥹ХȤѴ */
    $maskNet = inet_pton($net) & $binMask; // ѤȤ뤳Ȥǥޥ򤫤
    $sRange = inet_pton($startrange); // ˻ѤΤǺϥޥʤ
    $eRange = inet_pton($endrange);

    /* ϰϳϥɥ쥹Ƚüɥ쥹˥ޥ򤫤줬$netȰפ
       ֥ͥå˴ޤޤƤ */
    if ($maskNet != ($sRange & $binMask) || $maskNet != ($eRange & $binMask)) {
        $err_msg = sprintf($msgarr['31007'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31007'][LOG_MSG], $dup_range);
        return FUNC_FALSE; 
    }

    /* ͤ羮طΥå */
    if ($sRange > $eRange) {
        $err_msg = sprintf($msgarr['31008'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31008'][LOG_MSG], $dup_range);
        return FUNC_FALSE;
    }

    /* $subnet˴ޤޤƤϰϤ$range_data˳Ǽ */
    $ret = get_list_range($range_data, $sn, $subnet);
    if ($ret === FUNC_FALSE) {
        $err_msg = sprintf($msgarr['31005'][SCREEN_MSG], $dup_range);
        $log_msg = sprintf($msgarr['31005'][LOG_MSG], $dup_range);
        return FUNC_FALSE;
    }

    /* ξ硢ϰϤ */
    if ($oldrange != "") {
        /* ϰoldsubnetunset */
        $key = array_search($oldrange, $range_data);
        if ($key !== FALSE) {
            unset($range_data[$key]);
        }
    }

    /* ϿѤߤ¾ΥȽʣʤå */
    foreach ($range_data as $linerange) {
        /* (,λ)ηǳǼƤ */
        $arr_ip = explode(",", $linerange);
        $head = inet_pton($arr_ip[0]);
        $tail = inet_pton($arr_ip[1]);
        /* ʣå(eRange < head || tail < sRange)Ȥ롣
         * sRange < eRange ϤλǴݾڤƤ */
        if ($eRange >= $head && $tail >= $sRange) {
            $err_msg = sprintf($msgarr['31006'][SCREEN_MSG], $dup_range);
            $log_msg = sprintf($msgarr['31006'][LOG_MSG], $dup_range);
            return FUNC_FALSE;
        }
    }

    return FUNC_TRUE;
}

/***********************************************************
 * masktobyte()
 *
 * ꤵ줿֥ͥåȥޥ顢inet_pton()ΤƱͤη
 * Хʥǡ롣
 *
 * []
 *      $mask       ֥ͥåȥޥ(0~128)
 *
 * [֤]
 *      $binMask    ХʥѴ줿ޥ
 ***********************************************************/
function masktobyte($mask)
{
    /* ޥ3216ʿɽ */
    /* ޤf¤٤ */
    $binMask = str_repeat('f', $mask / 4);
    /* fʤΤä */
    switch ($mask % 4) {
        case 1:
            $binMask .= "8";
            break;
        case 2:
            $binMask .= "c";
            break;
        case 3:
            $binMask .= "e";
            break;
    }
    /*  */
    $binMask = str_pad($binMask, 32, '0');
    /* 16ʿեޥå(H*)ǥХʥʸ˥ѥå */
    $binMask = pack("H*", $binMask);

    return $binMask;
}


/***********************************************************
 * mod_range_session
 *
 * ϰϤ򹹿뤹ؿ
 *
 * []
 *        $sn             shared-networkȤ_other
 *        $subnet         ֥ͥå
 *        $old_range      ϰ
 *        $startrange     ϰ()
 *        $endrange       ϰ()
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function mod_range_session($sn, $subnet, $startrange, $endrange, $old_range)
{
    global $msgarr;
    global $err_msg;
    global $log_msg;

    /* ѿ */
    $str_new_range = "";
    $str_old_range = "";
    $new_range = "";
    /* ϰϤ¸ߤ */
    if ($_SESSION[STR_IP][$sn][$subnet]["range"]) {
         $str_old_range = $_SESSION[STR_IP][$sn][$subnet]["range"];
         /* ϰϤ */
         $new_range = $startrange . "," . $endrange;
         /* ŤϰϤ */
         $old_range = str_replace(" - ", ",", $old_range);
         $str_new_range = str_replace($old_range, $new_range, $str_old_range,
                                      $count);
        /* dhcpd.conf˽񤭴äƤ */
        if ($count != 1) {
            $err_msg = sprintf($msgarr['31005'][SCREEN_MSG], $old_range);
            $log_msg = sprintf($msgarr['31005'][LOG_MSG], $old_range);
            return FUNC_FALSE;
        }
        /* åϰϤ򹹿 */
        $_SESSION[STR_IP][$sn][$subnet]["range"] = $str_new_range;
        return FUNC_TRUE;
    }
    $err_msg = sprintf($msgarr['31005'][SCREEN_MSG], $old_range);
    $log_msg = sprintf($msgarr['31005'][LOG_MSG], $old_range);
    return FUNC_FALSE;
}



/***********************************************************
 * add_range_session()
 *
 * ϰϤϿؿ
 *
 * []
 *        $sn             shared-networkȤ_other
 *        $subnet         ֥ͥå
 *        $startrange     ϰ()
 *        $endrange       ϰ()
 *
 * [֤]
 *        TRUE           
 *        FALSE          顼
 *
 **********************************************************/
function add_range_session($sn, $subnet, $startrange, $endrange)
{

    global $msgarr;
    global $err_msg;
    global $log_msg;

    /*ϰϤ*/
    $new_range = $startrange . "," .$endrange;
    if (isset($_SESSION[STR_IP][$sn][$subnet]["range"]) &&
        $_SESSION[STR_IP][$sn][$subnet]["range"] != "") {
         /*åϰϤɲä*/
         $_SESSION[STR_IP][$sn][$subnet]["range"] .= "\n" . $new_range;
    } else {
         $_SESSION[STR_IP][$sn][$subnet]["range"] = $new_range;
    }

    return FUNC_TRUE;
}


/*********************************************************
 * check_search_date()
 *
 * եå
 *
 * []
 *      $year         ǯ
 *      $mon          
 *      $day          
 *                    YYYY-MM-DDȤ
 *                      âɬ⣲ǤʤƤɤ
 * [֤]
 *      TRUE          
 *      FALSE         ۾
 **********************************************************/
function check_search_date($year, $mon, $day)
{
    // ƻꤵƤʤȤ̵
    if ($year == "" && $mon == "" && $day == "") {
        return TRUE;
    }

    // å(ǯ)
    if (!preg_match('/^[0-9]{4}$/', $year)) {
        return FALSE;
    }

    // å()
    if (!preg_match('/^[0-9]{1,2}$/', $mon)) {
        return FALSE;
    }

    // å()
    if (!preg_match('/^[0-9]{1,2}$/', $day)) {
        return FALSE;
    }

    // ¸ߤդå
    if (!checkdate($mon, $day, $year)) {
        return FALSE;
    }

    return TRUE;
}

/*********************************************************
 * check_macaddr()
 *
 * Ϥ줿MACɥ쥹2:ڤˤ
 *
 * []
 *      $postmacaddr Ϥ줿MACɥ쥹
 * [֤]
 *      $macaddr    2:ڤMACɥ쥹
 **********************************************************/
function check_macaddr($postmacaddr)
{

    $macaddr = "";
    /* Ϥ줿ͤ:뤫 */
    /* 1ޤ2ν */
    $ret = strpbrk($postmacaddr, ':');
    if ($ret != FALSE) {
        /* ::Ƕڤ */
        $split = explode(":", $postmacaddr);
        /* 2ˤ */
        foreach ($split as $macsplit) {
            /* 1ʤƬ0Ĥ2ˤ */
            if (strlen($macsplit) == 1) {
                $macsplit = "0" . $macsplit;
            }
            $macaddr .= $macsplit . ":";
        }
        $macaddr = substr($macaddr, 0, -1);
        $macaddr = strtolower($macaddr);
        return $macaddr;
    }
    /* Ϥ줿ͤ.뤫 */
    $ret = strpbrk($postmacaddr, '.');
    if ($ret != FALSE) {
        /* ..Ƕڤ */
        $macpieces = explode(".", $postmacaddr);
        foreach ($macpieces as $macpiece) {
            $split = str_split($macpiece, 2);
                foreach ($split as $macsplit) {
                    /* 1ʤƬ0Ĥ2ˤ */
                    if (strlen($macsplit) == 1) {
                        $macsplit = "0" . $macsplit;
                    }
                    $macaddr .= $macsplit .":";
                }
        }
        $macaddr = substr($macaddr, 0, -1);
        $macaddr = strtolower($macaddr);
        return $macaddr;
    }
    /* Ϥ줿ͤ˶ڤʸ̵ */
    $split = str_split($postmacaddr, 2);
    foreach ($split as $macsplit) {
        /* 1ʤƬ0Ĥ2ˤ */
        if (strlen($macsplit) == 1) {
            $macsplit = "0" . $macsplit;
        }
        $macaddr .= $macsplit .":";
    }
    $macaddr = substr($macaddr, 0, -1);
    $macaddr = strtolower($macaddr);
    return $macaddr;
}

/*********************************************************
 * check_add_subnet_data_v6()
 *
 * ϥǡåؿ(v6)
 *
 * []
 *      $post                     Ϥ줿
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_add_subnet_data_v6($post)
{
    /* Сѿ */
    global $msgarr;
    global $err_msg;
    global $log_msg;

    /* ֥ͥåȤϤʤä */
    if ($post["subnet"] == "") {
        $err_msg = $msgarr['29001'][SCREEN_MSG];
        $log_msg = $msgarr['29001'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ץեåϤʤä*/
    if ($post["netmask"] == "") {
        $err_msg = $msgarr['29021'][SCREEN_MSG];
        $log_msg = $msgarr['29021'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*֥ͥåȤηå*/
    $ret = filter_var($post["subnet"], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
    if ($ret === FALSE) {
        $err_msg = $msgarr['29002'][SCREEN_MSG];
        $log_msg = $msgarr['29002'][LOG_MSG];
        return FUNC_FALSE;
    }

    /* ץեåηå */
    $num = "0123456789";
    $len = strlen($post["netmask"]);
    // ȾѿΤߵ
    if (strspn($post["netmask"], $num) != $len) {
        $err_msg = $msgarr['29022'][SCREEN_MSG];
        $log_msg = $msgarr['29022'][LOG_MSG];
        return FUNC_FALSE;
    }
    // ʸ
    if ((1 > $post["netmask"]) || (128 < $post["netmask"])) {
        $err_msg = $msgarr['29004'][SCREEN_MSG];
        $log_msg = $msgarr['29004'][LOG_MSG];
        return FUNC_FALSE;
    }

    return FUNC_TRUE;
}

/*********************************************************
 * check_add_mac()
 *
 * macɥ쥹ͥå
 *
 * []
 *      $mac        Ϥ줿
 * [֤]
 *      TRUE         
 *      FALSE        ۾
 **********************************************************/
function check_add_mac($mac)
{
    /* ʸå */
    /* macͤ뤫Ĵ٤ */
    if (isset($mac) && $mac != "") {
        $length = strlen($mac);
        if ($length > MAX_MAC_LENGTH) {
            return FALSE;
        }
        /* Ϥ줿ͤ:뤫 */
        $ret = strpbrk($mac, ':');
        if ($ret != FALSE) {
            /*ɽꤹ*/
            $number = '[a-fA-F0-9]{1,}';
            $macregular = '/^' . $number . '\:' . $number . '\:' . $number . '\:' . $number . '\:' . $number . '\:' . $number . '$/';
            /*ʸ*/
            if (!preg_match($macregular, $mac)) {
                return FALSE;
            }
            /* ::Ƕڤ */
            $split = explode(":", $mac);
            foreach ($split as $macsplit) {
                /* 1ޤ2ǤʤФʤʤ */
                if (strlen($macsplit) > 2) {
                    return FALSE;
                }
            }
        }
        /* Ϥ줿ͤ.뤫 */
        $ret = strpbrk($mac, '.');
        if ($ret != FALSE) {
            /*ɽꤹ*/
            $number = '[a-fA-F0-9]{1,}';
            $macregular = '/^' . $number . '\.' . $number . '\.' . $number . '$/';
            /*ʸ*/
            if (!preg_match($macregular, $mac)) {
                return FALSE;
            }
            /* ..Ƕڤ */
            $split = explode(".", $mac);
            foreach ($split as $macsplit) {
                /* 4ǤʤФʤʤ */
                if (strlen($macsplit) !=  4) {
                    return FALSE;
                }
            }
        }
        /* Ϥ줿ͤ.:ʤ */
        $ret = strpbrk($mac, '.:');
        if ($ret == FALSE) {
            /* Ⱦѱ羮ʸ(a~f)Τߵ */
            $num = "0123456789";
            $sl = "abcdef";
            $ll = strtoupper($sl);
            $allow_letter = $num . $sl . $ll;
            if (strspn($mac, $allow_letter) != $length) {
                return FALSE;
            }
            if (strlen($mac) != 12) {
                return FALSE;
            }
        }
    }
    /*ͤʤäTRUE*/
    return TRUE;
}

/*********************************************************
 * check_update_subnet_data_v6()
 *
 * ͥåȥԽ̤ͥåؿ
 *
 * []
 *      $post                     $_POSTϤ
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_update_subnet_data_v6($post)
{
    /*Сѿ*/
    global $msgarr;
    global $err_msg;
    global $log_msg;

    $ret = FUNC_FALSE;

    /*ɸ꡼֤Ϥ줿ɤå*/
    if ($post["leasetime"] == "") {
        $err_msg = $msgarr['29011'][SCREEN_MSG];
        $log_msg = $msgarr['29011'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*꡼֤Ϥ줿ɤå*/
    if ($post["maxleasetime"] == "") {
        $err_msg = $msgarr['29013'][SCREEN_MSG];
        $log_msg = $msgarr['29013'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*DNSФϤ줿ɤå*/
    if ($post["dnsserver"] == "") {
        $err_msg = $msgarr['29015'][SCREEN_MSG];
        $log_msg = $msgarr['29015'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ɥᥤ̾å*/
    $ret = check_defdomain($post["domainname"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['29010'][SCREEN_MSG];
        $log_msg = $msgarr['29010'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*ɸ꡼֤ηå*/
    $ret = check_subnet_leasetime($post["leasetime"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29012'][SCREEN_MSG];
        $log_msg = $msgarr['29012'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*꡼֤ηå*/
    $ret = check_subnet_leasetime($post["maxleasetime"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29014'][SCREEN_MSG];
        $log_msg = $msgarr['29014'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*DNSХɥ쥹å*/
    $ret = check_subnet_dns_v6($post["dnsserver"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29016'][SCREEN_MSG];
        $log_msg = $msgarr['29016'][LOG_MSG];
        return FUNC_FALSE;
    }

    /*Etraץå*/
    $ret = check_subnet_option($post["exoption"]);
    if ($ret === FUNC_FALSE) {
        $err_msg = $msgarr['29017'][SCREEN_MSG];
        $log_msg = $msgarr['29017'][LOG_MSG];
        return FUNC_FALSE;
    }
    return FUNC_TRUE;
}

/*********************************************************
 * check_subnet_dns_v6()
 *
 * DNSɥ쥹ͤåؿ
 *
 * []
 *      $dns                      dnsХɥ쥹
 *
 * [֤]
 *      FUNC_TRUE                 
 *      FUNC_FALSE                ۾
 ********************************************************/
function check_subnet_dns_v6($dns)
{

    /*dnsФΥɥ쥹¸*/
    $ip_array = array();

    /*dnsĹ*/
    $len = strlen($dns);

    /*DNSХɥ쥹Ĺå*/
    if ($len > 399) {
        return FUNC_FALSE;
    }

    /*,פdnsʬ䤹*/
    $ip_array = explode(",", $dns);

    /*10ʾϤƤʤǧ*/
    $num = count($ip_array);
    if ($num > 10) {
        return FUNC_FALSE;
    }

    /*ƱIPɥ쥹ʣꤵƤʤ*/
    $new_ip_array = array_unique($ip_array);
    $new_num = count($new_ip_array);
    if ($num != $new_num) {
        return FUNC_FALSE;
    }

    /*ʸå*/
    foreach ($ip_array as $ip) {
        /*IPɥ쥹ηå*/
        $ret = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
        if ($ret === FALSE) {
            return FUNC_FALSE;
        }
    }

    return FUNC_TRUE;
}

/*********************************************************
 * check_add_duplication()
 *
 * νʣå 
 *
 * []
 *      $hoststr      $_SESSION 
 *      $post         ̤ϤäƤ 
 *
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 *      3            IPɥ쥹顼
 **********************************************************/
function check_add_duplication($hoststr, $post)
{

    $hosts = explode("\n", $hoststr);
    foreach ($hosts as $host) {
        /* [host]Ȥʤcontinue */
        if ($host == "") {
            continue;
        }
        $check_ret = check_duplication($host, $post);
        if ($check_ret != 0) {
            return $check_ret;
        }
    }
    return 0;
}

/*********************************************************
 * check_mod_duplication()
 *
 * Խξνʣå
 *
 * []
 *      $hoststr      $_SESSION
 *      $post         ̤ϤäƤ
 *
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 *      3            IPɥ쥹顼
 **********************************************************/
function check_mod_duplication($hoststr, $post)
{

    $old_sn = $post["oldsn"];
    $old_host = $post["oldhost"];
    /* IPv4, v6ǽ櫓 */
    if (STR_IP == 'v4') {
        $old_mac = $post["oldmacaddr"];
    } elseif (STR_IP == 'v6') {
        $old_mac = $post["oldduid"];
    }
    $old_ip = $post["oldipaddr"];
    $old_select = $post["oldipselect"];

    $olddata = $old_host . "," . $old_mac . "," . $old_ip . "," . "\"$old_host\"" . "," . "$old_select";

    $hosts = explode("\n", $hoststr);
    foreach ($hosts as $host) {
        /* [host]Ȥʤcontinue */
        if ($host == "") {
            continue;
        }
        /* SESSIONƱʤcontinue */
        if ($olddata == $host) {
            continue;
        }
        $check_ret  = check_duplication($host, $post);
        if ($check_ret != 0) {
            return $check_ret;
        }
    }
    return 0;
}

/*********************************************************
 * check_duplication()
 *
 * ʣå
 *
 * []
 *      $host        $_SESSION
 *      $post        ̤ϤäƤ
 *
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 *      3            IPɥ쥹顼
 **********************************************************/
function check_duplication($host, $post)
{
    /* ޤǶڤ */
    list($subhost, $s_mac, $s_ip, $s_hostname, $s_select) = explode(",", $host);
    $s_hostname = ltrim($s_hostname, "\"");
    $s_hostname = rtrim($s_hostname, "\"");

    /* ۥ̾ʣƤ뤫 */
    if ($post["host"] == $s_hostname) {
        return 1;
    }
    /* IPv4, v6ǽ櫓 */
    if (STR_IP == 'v4') {
        /* MACɥ쥹ʣƤ뤫 */
        $p_mac = check_macaddr($post["macaddr"]);
        if ($p_mac == $s_mac) {
            return 2;
        }
        /* IPɥ쥹뤫 */
        if ($post["ipaddr"] != "") {
            if ($post["ipaddr"] == $s_ip) {
                return 3;
            }
        }
    } elseif (STR_IP == 'v6') {
        /* DUIDʣƤ뤫 */
        $p_duid = check_macaddr($post["duid"]);
        if ($p_duid == $s_mac) {
            return 2;
        }
        /* IPv6ɥ쥹뤫 */
        if ($post["ipaddr"] != "") {
            /* Хʥ· */
            $p_ip = inet_pton($post["ipaddr"]);
            $s_ip = inet_pton($s_ip);
            if ($p_ip == $s_ip) {
                return 3;
            }
        }
    }
    return 0;
}
/*********************************************************
 * mod_client()
 *
 * ԽξϿ
 *
 * []
 *      $hoststr      $_SESSION
 *      $post         ̤ϤäƤ
 *
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 **********************************************************/
function mod_client($hoststr, $post)
{

    $old_host = $post["oldhost"];
    /* IPv4, v6ǽ櫓 */
    if (STR_IP == 'v4') {
        $old_mac = $post["oldmacaddr"];
    } elseif (STR_IP == 'v6') {
        $old_mac = $post["oldduid"];
    }
    $old_ip = $post["oldipaddr"];
    $old_select = $post["oldipselect"];
    $inselect = $post["ipselect"];
    $client = "";
    $olddata = $old_host . "," . $old_mac . "," . $old_ip . "," . "\"$old_host\"" . "," . "$old_select";

    $hosts = explode("\n", $hoststr);
    foreach ($hosts as $host) {
        /* [host]Ȥʤcontinue */
        if ($host == "") {
            continue;
        }

        if ($olddata != $host) {
            $client .= $host . "\n";
            continue;
        }

        /* ۥ̾ؤ */
        $newhostname = $post["host"];
        /* MACɥ쥹 */
        if (STR_IP == 'v4') {
            $newmac = check_macaddr($post["macaddr"]);
        } else if (STR_IP == 'v6') {
            $newmac = check_macaddr($post["duid"]);
        }
        /* IPɥ쥹 */
        $newip = $post["ipaddr"];
        $client .= $newhostname . "," . $newmac . "," . $newip . "," . "\"$newhostname\"" . "," . $inselect . "\n";
    }
    return $client;
}

/*********************************************************
 * check_add_in()
 *
 * 饤Խͥå
 *
 * []
 *      $post        ̤ϤäƤ 
 * [֤]
 *      0            
 *      1            ۥ̤̾
 *      2            MACɥ쥹̤
 *      3            IPɥ쥹̤
 *      4            ۥ̾顼
 *      5            MACɥ쥹顼
 *      6            IPɥ쥹顼
 **********************************************************/

function check_add_in($post)
{
    $hostname = escape_html($post["host"]);
    $mac = escape_html($post["macaddr"]);
    $ip = escape_html($post["ipaddr"]);

    $must = check_must($post);
    switch ($must) {
    case 1:
        return 1;
    case 2:
    /* MACɥ쥹Ϥʤ */
        return 2;
    case 3:
    /* IP߽꤬򤵤Ƥ뤫 */
        return 3;
    case 0:
        $ret = check_hostname($hostname);
        if ($ret == FALSE) {
            return 4;
        }
        $ret = check_add_mac($mac);
        if ($ret == FALSE) {
            return 5;
        }
        $ret = check_ip($ip);
        if ($ret == FALSE) {
            return 6;
        }
        return 0;
    }
}

/*********************************************************
 * check_must()
 *
 * ɬܹܤϤƤ뤫å
 *
 * []
 *      $post       ̤Ϥ줿
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 *      3            IPɥ쥹顼
 **********************************************************/
function check_must($post)
{
    /* ۥ̾Ϥ뤫 */
    if ($post["host"] == "") {
        return 1;
    }
    /* IPv4, v6ǽ櫓 */
    if (STR_IP == 'v4') {
        /* MACɥ쥹Ϥ뤫 */
        if ($post["macaddr"] == "") {
            return 2;
        }
    } else if (STR_IP == 'v6') {
        /* DUIDɥ쥹Ϥ뤫 */
        if ($post["duid"] == "") {
            return 2;
        }
    }
    /* IP߽꤬򤵤Ƥ뤫 */
    if (empty($post["ipselect"])) {
        return 3;
    }
    return 0;
}

/*********************************************************
 * search_sn()
 *
 * ֥ͥåȤ¸ߤ뤫åshared-network֤ 
 *
 * []
 *      $in_sub       ̤Ϥ줿֥ͥå
 * [֤]
 *      $sn          ֥ͥåȤ¸ߤȤshared-network 
 **********************************************************/
function search_sn($in_sub)
{
    foreach ($_SESSION[STR_IP] as $sn => $value){
        if (is_array($_SESSION[STR_IP]["$sn"])) {
            foreach ($_SESSION[STR_IP]["$sn"] as $sub => $value) {
            /* ֥ͥåȤ¸ߤ뤫 */
                if ($sub == $in_sub) {
                    return $sn;
                }
            }
        }
    }
}

/*********************************************************
 * new_add_host()
 *
 * Ͽؿ 
 *
 * []
 *      $post         ̤Ϥ줿
 *      $hostline     ɲäΥۥȤ
 * [֤]
 *      $hostline     åϿʸ 
 **********************************************************/
function new_add_host($post, $hostline)
{
    $in_case = $post["ipselect"];
    $in_host = $post["host"];
    /* IPv4, v6ǽ櫓 */
    if (STR_IP == 'v4') {
        $in_mac = $post["macaddr"];
    } else if (STR_IP == 'v6') {
        $in_mac = $post["duid"];
    }
    $in_mac = check_macaddr($in_mac);
    $in_ip = $post["ipaddr"];
    $hostline .= $in_host . "," . $in_mac . "," . $in_ip . "," . "\"$in_host\"" . "," . $in_case . "\n";
    return $hostline;
}

/*********************************************************
 * in_range_ipv6()
 *
 * Ϥ줿IPv6֥ͥåϰ⤫   
 *
 * []
 *      $ipv6 Ϥ줿IPv6
 * [֤]
 *      TRUE           
 *      FALSE          顼
 **********************************************************/
function in_range_ipv6($subnet, $ipv6)
{

    /* IPʬȥޥʬʬ */
    list($net, $mask) = explode("/", $subnet);
    /* ޥ(32Ȥ64Ȥ)ХȤѴ */
    $binMask = masktobyte($mask);
    /* ѤȤ뤳Ȥǥޥ򤫤 */
    $maskNet = inet_pton($net) & $binMask; // ѤȤ뤳Ȥǥޥ򤫤
    /* IPv6ɥ쥹ХȤѴޥ򤫤 */
    $maskipv6 = inet_pton($ipv6) & $binMask;

    /* ޥ򤫤IPʬȥޥ򤫤Ϥ줿IPv6Ȥ */
    /* ƱǤʤϰϳʤΤǥ顼 */
    if ($maskNet != $maskipv6) {
        return FALSE;
    }
    return TRUE;
}

/*********************************************************
 * in_range_ipv4()
 *
 * Ϥ줿IPɥ쥹֥ͥåϰ⤫
 *
 * []
 *      $ipv4 Ϥ줿IPv4
 * [֤]
 *      TRUE           
 *      FALSE          顼
 **********************************************************/
function in_range_ipv4($subnet, $ipv4)
{
    /* IPʬȥޥʬʬ */
    list($net, $mask) = explode("/", $subnet);
    /* ޥͤХȤѴ */
    $binMask = inet_pton($mask);
    /* ѤȤ뤳Ȥǥޥ򤫤 */
    $maskNet = inet_pton($net) & $binMask;
    /* IPv6ɥ쥹ХȤѴޥ򤫤 */
    $maskipv4 = inet_pton($ipv4) & $binMask;

    /* ޥ򤫤IPʬȥޥ򤫤Ϥ줿IPv4Ȥ */
    /* ƱǤʤϰϳʤΤǥ顼 */
    if ($maskNet != $maskipv4) {
        return FALSE;
    }
    return TRUE;
}


/*********************************************************
 * check_duplication_data()
 *
 * ʣå 
 *
 * []
 *      $data         ե1 
 *
 * [֤]
 *      0            
 *      1            ۥ̾顼
 *      2            MACɥ쥹顼
 *      3            IPɥ쥹顼
 *      4            Shared-network顼
 **********************************************************/
function check_duplication_data($f_data)
{
    $data = rtrim($f_data);
    /* ޤǶڤ */
    list($f_subnet, $f_hostname, $f_mac, $f_ip, $f_select) = explode(",", $data);
    /* shared-network */
    $sn = judge_sn($f_subnet);
    if ($sn == "") {
        return 4;
    }
    /* ۥȤȤнʣå */
    if (isset($_SESSION[STR_IP]["$sn"]["$f_subnet"]["host"])) {
        $s_hostline = $_SESSION[STR_IP]["$sn"]["$f_subnet"]["host"];

        $s_hosts = explode("\n", $s_hostline);
        foreach ($s_hosts as $s_host) {
            /* [host]Ȥʤcontinue */
            if ($s_host == "") {
                continue;
            }

            /* ޤǶڤ */
            list($s_host, $s_mac, $s_ip, $s_hostname, $s_select) = explode(",", $s_host);
            $s_hostname = ltrim($s_hostname, "\"");
            $s_hostname = rtrim($s_hostname, "\"");

            /* ۥ̾ʣƤ뤫 */
            if ($s_hostname == $f_hostname) {
                return 1;
            }
            /* MACɥ쥹ʣƤ뤫 */
            $d_mac = check_macaddr($f_mac);
            if ($s_mac == $f_mac) {
                return 2;
            }
            /* IPɥ쥹뤫 */
            if ($f_ip != "") {
                if ($s_ip == $f_ip) {
                    return 3;
                }
            }
        }
    }
    /* ۥȤȤʤreturn0 */
    return 0;
}

/*********************************************************
 * check_input_searchdata()
 *
 * ͥå
 *
 * []
 *      $data         
 *
 * [֤]
 *      TRUE          
 *      FALSE         ۾
 **********************************************************/
function check_input_searchdata($data)
{
    global $msgarr;
    global $err_msg;
    global $log_msg;

    // ߽()ͥå
    $ret = check_search_date($data["ssyear"], $data["ssmon"], $data["ssday"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['35001'][SCREEN_MSG];
        $log_msg = $msgarr['35001'][LOG_MSG];
        return FALSE;
    }

    // ߽(λ)ͥå
    $ret = check_search_date($data["seyear"], $data["semon"], $data["seday"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['35002'][SCREEN_MSG];
        $log_msg = $msgarr['35002'][LOG_MSG];
        return FALSE;
    }

    // ߽ϰϥå
    $ret = check_search_range($data["ssyear"], $data["ssmon"], $data["ssday"],
                              $data["seyear"], $data["semon"], $data["seday"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['35007'][SCREEN_MSG];
        $log_msg = $msgarr['35007'][LOG_MSG];
        return FALSE;
    }

    // ߽д()ͥå
    $ret = check_search_date($data["esyear"], $data["esmon"], $data["esday"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['35003'][SCREEN_MSG];
        $log_msg = $msgarr['35003'][LOG_MSG];
        return FALSE;
    }

    // ߽д(λ)ͥå
    $ret = check_search_date($data["eeyear"], $data["eemon"], $data["eeday"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['35004'][SCREEN_MSG];
        $log_msg = $msgarr['35004'][LOG_MSG];
        return FALSE;
    }

    // ߽дϰϥå
    $ret = check_search_range($data["esyear"], $data["esmon"], $data["esday"],
                              $data["eeyear"], $data["eemon"], $data["eeday"]);
    if ($ret === FALSE) {
        $err_msg = $msgarr['35008'][SCREEN_MSG];
        $log_msg = $msgarr['35008'][LOG_MSG];
        return FALSE;
    }

    return TRUE;
}

/*********************************************************
 * check_search_range()
 *
 * ϰϥå
 *
 * []
 *      $syear        ǯ()
 *      $smon         ()
 *      $sday         ()
 *      $eyear        ǯ(λ)
 *      $emon         (λ)
 *      $eday         (λ)
 * 
 * [֤]
 *      TRUE          
 *      FALSE         ۾
 **********************************************************/
function check_search_range($syear, $smon, $sday, $eyear, $emon, $eday)
{
    // ƻꤵƤʤȤ̵
    if ($syear == "" && $smon == "" && $sday == "") {
        return TRUE;
    }

    // ƻꤵƤʤȤ̵
    if ($eyear == "" && $emon == "" && $eday == "") {
        return TRUE;
    }
    // ǯʸ
    $sdata = sprintf("%04d%02d%02d", $syear, $smon, $sday);
    $edata = sprintf("%04d%02d%02d", $eyear, $emon, $eday);

    // ϤȽλ
    if ($sdata > $edata) {
        return FALSE;
    }

    return TRUE;
}

/*********************************************************
 * check_lease_time()
 *
 * եå
 *
 * []
 *      $syear        ǯ()
 *      $smon         ()
 *      $sday         ()
 *      $eyear        ǯ(λ)
 *      $emon         (λ)
 *      $eday         (λ)
 *      $time_data    ߽ or ߽д
 *
 * [֤]
 *      TRUE          
 *      FALSE         ۾
 **********************************************************/
function check_lease_time($syear, $smon, $sday, $eyear, $emon, $eday, $time_data)
{

    // ͤLinuxѹ
    $leasefile_time = strtotime($time_data);

    // դꤵƤʤȤ̵()
    if ($syear != "") {

        // Linuxѹ
        $tmp = sprintf("%04d%02d%02d 00:00:00", $syear, $smon, $sday);
        $start_time = strtotime($tmp);

        // ֤
        if ($leasefile_time < $start_time) {
            return FALSE;
        }
    }

    // դꤵƤʤȤ̵(λ)
    if ($eyear != "") {

        // Linuxѹ
        $tmp = sprintf("%04d%02d%02d 23:59:59", $eyear, $emon, $eday);
        $end_time = strtotime($tmp);

        // ֤
        if ($leasefile_time > $end_time) {
            return FALSE;
        }
    }

    return TRUE;
}

/*********************************************************
 * judge_sn()
 *
 * оݥ֥ͥåȤShared-network¸ߤ뤫å
 * shared-network֤ 
 *
 * []
 *      $subnet       ֥ͥå
 * [֤]
 *      $sn           Shared-network 
 **********************************************************/
function judge_sn($subnet)
{
    foreach ($_SESSION[STR_IP] as $sn => $value){
        if (is_array($_SESSION[STR_IP]["$sn"])) {
            foreach ($_SESSION[STR_IP]["$sn"] as $sub => $value) {
                /* ֥ͥåȤ¸ߤ뤫 */
                if ($sub == $subnet) {
                    return $sn;
                }
            }
        }
    }   
    /* ¸ߤʤж֤ */
    $sn = ""; 
    return $sn;
}


/*********************************************************
 * Move_Subnets()
 *
 * Shared-networkԽ̤ƤФ롣
 * °֥ͥåȤΥꥹȤȤˡܹԺȤɬפȽ̤
 * Υ֥ͥåȤΥǡҤ롣
 *
 * []
 *      $SubList  °륵֥ͥå̾ꥹ
 *      $FromSn   ưɥͥåȥ̾
 *      $ToSn     ư襷ɥͥåȥ̾
 *
 * [֤]
 *      ʤ($_SESSIONѹ)
 ********************************************************/
function Move_Subnets($SubList, $FromSn, $ToSn)
{
    /* ưȤȶäԤʤ */
    if (!isset($_SESSION[STR_IP][$FromSn])) {
        return;
    }
    if (!is_array($_SESSION[STR_IP][$FromSn])) {
        return;
    }

    /* ListΥǡ1Ĥĳǧ */
    foreach ($SubList as $needle) {
        /* ư¸ߤ뤫ǧ */
        foreach ($_SESSION[STR_IP][$FromSn] as $Sub => $SubData) {
            /* ȤȰưΤΤǤСҺȤԤ */
            if ($needle == $Sub) {
                $_SESSION[STR_IP][$ToSn][$Sub] = 
                                              $_SESSION[STR_IP][$FromSn][$Sub];
                unset($_SESSION[STR_IP][$FromSn][$Sub]);

                /* ֥ͥåȤϽʣʤΤǡ1ĸĤä鼡ؿʤ */
                break;
            }
        }
    }

    return;
}


?>
