<?php
/***************************************************************************
 *                               func_lib.php
 *                            Global functions
 *                            -------------------
 *   begin                : Tuesday', Apr 22', 2006
 *   copyright            : ('C) 2006-2008 Ulrich Schroeter
 *
 *     added              : Friday, July 28, 2006
 *                        : function hmac()
 *     updated            : version() v2.05 rep061031.033
 *     updated            : logfile() v2.06 add SID  
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License', or
 *   ('at your option) any later version.
 * See the LICENSE file for more information.
 * DLIMP Website : http://ambrosia60.dnsalias.net/
 *----------------------------------------------------------------------------
 */


define('FUNC_LIB',1);

//=================================================

/* ---------  begin funtions ------------------------------ */

// Want to Create a md5 HMAC, but don't have hmash installed?
// Use this:


function hmac ($data) {
 // RFC 2104 HMAC implementation for php.
 // Creates an md5 HMAC.
 // Eliminates the need to install mhash to compute a HMAC
 // Hacked by Lance Rushing
 $key = 'Jefe'; 
 $b = 64; // byte length for md5
 if (strlen($key) > $b) {
 $key = pack("H*",md5($key));
 }
 $key = str_pad($key, $b, chr(0x00));
 $ipad = str_pad('', $b, chr(0x36));
 $opad = str_pad('', $b, chr(0x5c));
 $k_ipad = $key ^ $ipad ;
 $k_opad = $key ^ $opad;
 return md5($k_opad . pack("H*",md5($k_ipad . $data)));
}

// -----------------------------------------

function formatTimestamp($time) {
    global $datetime, $locale;
    setlocale (LC_TIME, $locale);
    preg_match("/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})/", $time, $datetime);
    $datetime = strftime(""._DATESTRING."", mktime($datetime[4],$datetime[5],$datetime[6],$datetime[2],$datetime[3],$datetime[1]));
    $datetime = ucfirst($datetime);
    return($datetime);
}

// -----------------------------------------

function FixQuotes ($what = "") {
    $what = preg_replace("/'/","&#39;",$what);
    while (preg_match("/\\\\/i'", $what)) {
      $what = preg_replace("/\\\\/'","&#39;",$what);
    }
    return $what;
}

// -----------------------------------------

function StripQuotes ($what = "") {
    $what = preg_replace("/'/","",$what);
    while (preg_match("/\\\\/i'", $what)) {
	$what = preg_replace("/\\\\'/","",$what);
    }
    return $what;
}

// -----------------------------------------

function check_html ($str, $strip="") {
    /* The core of this code has been lifted from phpslash */
    /* which is licenced under the GPL. */
    if ($strip == "nohtml")
    	global $AllowableHTML;
    	if (!is_array($AllowableHTML)) $AllowableHTML =array('');
	$str = stripslashes($str);
	$str = preg_replace("/<[[:space:]]*([^>]*)[[:space:]]*>/i",'<\\1>', $str);
    	    // Delete all spaces from html tags .
	$str = preg_replace("/<a[^>]*href[[:space:]]*=[[:space:]]*\"?[[:space:]]*([^\" >]*)[[:space:]]*\"?[^>]*>/i",'<a href="\\1">', $str);
    	    // Delete all attribs from Anchor, except an href, double quoted.
	$str = preg_replace("/<[[:space:]]* img[[:space:]]*([^>]*)[[:space:]]*>/i", '', $str);
	    // Delete all img tags
	$str = preg_replace("/<a[^>]*href[[:space:]]*=[[:space:]]*\"?javascript[[:punct:]]*\"?[^>]*>/i", '', $str);
	    // Delete javascript code from a href tags -- Zhen-Xjell @ http://nukecops.com
	$tmp = "";
	while (preg_match("@<(/?[[:alpha:]]*)[[:space:]]*([^>]*)>@",$str,$reg)) {
		$i = strpos($str,$reg[0]);
		$l = strlen($reg[0]);
		if ($reg[1][0] == "/") $tag = strtolower(substr($reg[1],1));
		else $tag = strtolower($reg[1]);
		if ($a = $AllowableHTML[$tag])
			if ($reg[1][0] == "/") $tag = "</$tag>";
			elseif (($a == 1) || ($reg[2] == "")) $tag = "<$tag>";
			else {
			  # Place here the double quote fix function.
			  $attrb_list=delQuotes($reg[2]);
			  // A VER
			  $attrb_list = preg_replace("/&/","&amp;",$attrb_list);
			  $tag = "<$tag" . $attrb_list . ">";
			} # Attribs in tag allowed
		else $tag = "";
		$tmp .= substr($str,0,$i) . $tag;
		$str = substr($str,$i+$l);
	}
	$str = $tmp . $str;
	return $str;
	exit;
	/* Squash PHP tags unconditionally */
	$str = preg_replace("/<\?/","",$str);
	return $str;
}

// -----------------------------------------

function rat($such,$string) {
  $rtlen = strlen($string);
  $slen = strlen($such);
  $rtpos = 0;
  for ($j=$rtlen; $j > 0; $j--) {
     $rtchr = substr($string,$j,$slen);
     if ($rtchr==$such) {
        if ($rtpos==0) {
           $rtpos = $j;
           $j = 0;
        }
     }
  }
return $rtpos;
}

// -----------------------------------------

function at($such,$string) {
  $slen  = strlen($such);
  $rtlen = strlen($string);
  $rtpos = 0;
  for ($j=0; $j < $rtlen; $j++) {
     $rtchr = substr($string,$j,$slen);
     if ($rtchr==$such) {
        if ($rtpos==0) {
           $rtpos = $j;
           $j = $rtlen;
        }
     }
  }
return $rtpos;
}

// -----------------------------------------

function len($t) {
  return strlen($t);
}

// -----------------------------------------

function alltrim($s) {
  return ltrim(rtrim($s));
}

// -----------------------------------------

//  perl port of perl function chomp
function chomp($p) {
 $p = str_replace(chr(10),"",$p); 
 $p = str_replace(chr(13),"",$p); 
 return $p;
}

// -----------------------------------------

// add a trailing slash
function trailslash($p="") {
  if ((substr($p,strlen($p)-1,1)!=chr(47)) and (substr($p,strlen($p)-1,1)!=chr(92))) {
    $p = $p.chr(47);
  }
  return $p;
}

// -----------------------------------------

function removechar($such,$string) {
  $slen  = strlen($such);
  if ($slen==1) {
    $rtlen = strlen($string);
    $rtxt = "";
    for ($j=0; $j < $rtlen; $j++) {
       $rtchr = substr($string,$j,$slen);
       if ($rtchr==$such) {
          // skip        
       } else {
          $rtxt = $rtxt.$rtchr;
       }
    }
  } else {
    $rtxt = $string;  
  }
  return $rtxt;
}

// -----------------------------------------

function right($string,$len) {
  // len=12
  //  12345678.TIC
  //  000000000011
  //  012345678901
  //          4321
  // ab 8,4
  $rtstr = substr($string,strlen($string)-$len,$len);

return $rtstr;
}

// -----------------------------------------

function checkaka($ct) {
 $rfnd = 0;
 $lct = len($ct);
 $jx = 0;
 while ($jx < $lct) {
   //  check 3d or 4d aka  2:244/1120, 2:244/1120.0
   if (preg_match("/([0-9]{1})/",substr($ct,$jx,1))) {
      //  num found, test aka
      $jy = $jx;
      while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
        $jy++;
      }
      if (preg_match("/([:]{1})/",substr($ct,$jy,1))) {
        $jy++;
        while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
          $jy++;
        }
        if (preg_match("@([/]{1})@",substr($ct,$jy,1))) {
          $jy++;
          while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
            $jy++;
          }
          if (preg_match("/([.]{1})/",substr($ct,$jy,1))) {
            $jy++;
            while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
              $jy++;
            }
            $rfnd = $jx+1;
            $jx = $lct;
          } else {
            $rfnd = $jx+1;
            $jx = $lct;
          }
        }
      }
   }
   $jx++;
 }
 if ($rfnd == 0) {
   //  check 2d aka  244/1120 or 244/1120.0
   $jx = 0;
   while ($jx < $lct) {
     if (preg_match("/([0-9]{1})/",substr($ct,$jx,1))) {
        //  num found, test aka
        $jy = $jx;
        while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
          $jy++;
        }
        if (preg_match("@([/]{1})@",substr($ct,$jy,1))) {
          $jy++;
          while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
            $jy++;
          }
          if (preg_match("/([.]{1})/",substr($ct,$jy,1))) {
            $jy++;
            while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
              $jy++;
            }
            $rfnd = $jx+1;
            $jx = $lct;
          } else {
            $rfnd = $jx+1;
            $jx = $lct;
          }
        }
     }
     $jx++;
   }
 }
 return $rfnd;
}


// -----------------------------------------

function removeaka($ct) {
 $rfnd = 0;
 $lct = len($ct);
 $jx = 0;
 while ($jx < $lct) {
   //  check 3d or 4d aka  2:244/1120, 2:244/1120.0
   if (preg("/([0-9]{1})/",substr($ct,$jx,1))) {
      //  num found, test aka
      $jy = $jx;
      while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
        $jy++;
      }
      if (preg_match("/([:]{1})/",substr($ct,$jy,1))) {
        $jy++;
        while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
          $jy++;
        }
        if (preg_match("@([/]{1})@",substr($ct,$jy,1))) {
          $jy++;
          while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
            $jy++;
          }
          if (preg_match("/([.]{1})/",substr($ct,$jy,1))) {
            $jy++;
            while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
              $jy++;
            }
            $ct = substr($ct,0,$jx-1)." ".substr($ct,$jy);
            $rfnd = $jx+1;
            $jx = $lct;
          } else {
            $ct = substr($ct,0,$jx-1)." ".substr($ct,$jy);
            $rfnd = $jx+1;
            $jx = $lct;
          }
        }
      }
   }
   $jx++;
 }
 if ($rfnd == 0) {
   //  check 2d aka  244/1120 or 244/1120.0
   $jx = 0;
   while ($jx < $lct) {
     if (preg_match("/([0-9]{1})/",substr($ct,$jx,1))) {
        //  num found, test aka
        $jy = $jx;
        while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
          $jy++;
        }
        if (preg_match("@([/]{1})@",substr($ct,$jy,1))) {
          $jy++;
          while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
            $jy++;
          }
          if (preg_match("/([.]{1})/",substr($ct,$jy,1))) {
            $jy++;
            while (preg_match("/([0-9]{1})/",substr($ct,$jy,1))) {
              $jy++;
            }
            $ct = substr($ct,0,$jx-1)." ".substr($ct,$jy);
            $rfnd = $jx+1;
            $jx = $lct;
          } else {
            $ct = substr($ct,0,$jx-1)." ".substr($ct,$jy);
            $rfnd = $jx+1;
            $jx = $lct;
          }
        }
     }
     $jx++;
   }
 }
 return $ct;
}


// -----------------------------------------

// * Function Check Drive + Path + Files.BBS

// -----------------------------------------
function chkdpf($p) {

  global $vlddrive,$vldpath,$vldfbbs,$cddrive;

  $vlddrive = 0;
  $vldpath  = 0;
  $vldfbbs  = 0;
  $cddrive  = 0;

  // prevent CDROM identification for Groups definitions
  if ($p!="") {
    $drive= substr($p,0,3);
    if (is_dir($drive)) {
       $vlddrive = 1;
    }

    $df = disk_free_space($drive);
    if ($df==0) {
       $cddrive = 1;
    }

    $file = trim($p);
    if (is_dir($file)) {
       $vldpath = 1;
    }

    //  if (file_exists($file)) {
    $file = trim($p)."FILES.BBS";
    if (file_exists($file)) {
       $vldfbbs = 1;
    }
  }

  if (DEBUG!=0) {
       echo "Path: ".$p." Drive: ".$drive." Diskfree: ".$df."\n";
       echo "Drive:Path:Files.Bbs:CD :: ".$vlddrive.":".$vldpath.":".$vldfbbs.":".$cddrive."\n";
  }

 // returns sum
 return $vlddrive+$vldpath+$vldfbbs+$cddrive;
}

// -----------------------------------------
//
//   logfile(logtype, text)
// 
//   logtypes:  L regular log
//              E error log
//              D debug log
//              Q close all 'used' logs
// -----------------------------------------

// for init:
// $actpath = str_replace(chr(92),chr(47),getcwd());
// $logfile = $actpath."/nlimport.log";
// $logfile_debug = $actpath."/nlimport_debug.log";
// $logfile_error = $actpath."/nlimport.err";

function logfile($ltyp='0',$ltext='') {
  // $logfile = "nlimport.log";
  // $logfile_debug = "nlimport_debug.log";
  // $logfile_error = "nlimport.err";
  //  $ltyp: E error, D debug, L regular log, Q program termination, close logs
  global $logfile,$logfile_debug,$logfile_error,$crlf,$sid;
  $prtxt = "";
  // $today = date("D j M y");               // Sat Mar 10 15:16:08 MST 2001
  
  if (isset($sid)) {
    $ldat = $crlf."----------  ".date("D j M y",time())." [".$sid."], ".PROG."; Import".$crlf;
    $ltim = "# ".date("H:i:s",time())." [".$sid."] ";  
  } else {
    $ldat = $crlf."----------  ".date("D j M y",time()).", ".PROG."; Import".$crlf;
    $ltim = "# ".date("H:i:s",time())."  ";  
  }
  if (strtoupper($ltyp)=="Q") {
    $fin = $ltim.PROG." finished.".$crlf;
    // close all opened logs
    if (defined('_LDEFLOG')) {
      $llf = $logfile;      
      $fp = fopen($llf, "a");
      fputs($fp,$fin);
      fclose($fp);
    }
    if (defined('_LDEFDBG')) {
      $llf = $logfile_debug;      
      $fp = fopen($llf, "a");
      fputs($fp,$fin);
      fclose($fp);
    }
    if (defined('_LDEFERR')) {
      $llf = $logfile_error;
      $fp = fopen($llf, "a");
      fputs($fp,$fin);
      fclose($fp);
    }
  } else {
    // Header?  ----------  Fri 28 Dec 07, Z2PNTHDR 1.00; Build
    // Entry    # 12:05:41  Total Regions found in Config: 25
    if (strtoupper($ltyp)=="E") {
      $llf = $logfile_error;
      // $fp = fopen($llf, "a");
      if (!defined('_LDEFERR')) {
        define('_LDEFERR',True);
        $prtxt = $ldat;        
      }
      // fclose($fp);
    } else {
      if (strtoupper($ltyp)=="D") {
        $llf = $logfile_debug;      
        if (!defined('_LDEFDBG')) {
          define('_LDEFDBG',True);      
          $prtxt = $ldat;        
        }
      } else {
        $llf = $logfile;      
        if (!defined('_LDEFLOG')) {
          define('_LDEFLOG',True);      
          $prtxt = $ldat;        
        }
      }
    }
    $fp = fopen($llf, "a");
    fputs($fp,$prtxt.$ltim.$ltext.$crlf);
    fclose($fp);
  }
  return True;
}

// -----------------------------------------
//    Packer Support
// -----------------------------------------

// for init:
// require_once 'includes/configurator2.php';
// $compresscfg = Configurator::open('includes/compress.cfg');
// $compresscfg->parse();
// $pck = array();
// $pck = $compresscfg->getDirectives();
// // print_r($compresscfg->getDirectives());


function packeridentifier($test) {
  global $pck;
  $xi = count($pck);
  $htest = "";
  for ($i=0;$i<6;$i++) {
    $htest .= sprintf("%02x",ord(substr($test,$i,1)));
  }
  // $htest = sprintf("%07x",$test);
  if (DEBUG) {
    echo "[".$htest."]\r\n";
  }
  $i = 0;
  //for ($i=0;$i<$xi;$i++) {
  foreach ($pck as $p1) {
    $i++;
    //$p1 = current($pck);
    if (DEBUG) {
      echo "(".$i.") ";
      print_r($p1);
    }
    // 0,526172211a0700
    //   0 1 2 3 4 5 6 
    //$cmpcmd = explode(",",$pck[$i]['Ident']);
    //echo "[".str_repeat(" ",$cmpcmd[0]).$cmpcmd[1]."]".$pck[$i]['Ident']."\r\n";
    // echo "[".$i."] ".$p1['Ident']."\r\n";
    $cmpcmd = explode(",",alltrim($p1['Ident']));
    // echo $cmpcmd[0]." => ".$cmpcmd[1]." => ".key($pck)."\r\n";
    if (substr($htest,$cmpcmd[0]*2,strlen($cmpcmd[1]))==$cmpcmd[1]) {
      // echo "[".substr($htest,$cmpcmd[0]*2,strlen($cmpcmd[1]))."] in [".$htest."]\r\n";
      // return key($pck);
      return $p1['Extension'];      
    }
    //next($pck);
  } 

  return False;
}

// -----------------------------------------
//
//    Temp Dir support
//
// -----------------------------------------

// for init:
// //   our $tmpdir = tempdir(CLEANUP => 1);
// $tmpdir = tempnam("", "tmp");
// if (is_file($tmpdir)) {
//   unlink($tmpdir);
// }
// $tmp2dir = $actpath."/".basename($tmpdir);
// if (is_dir($tmp2dir)) {
//   // use existing path?
// } else {
//   mkdir($tmp2dir, 0700);
//   if (is_dir($tmp2dir)) {
//     // ok
//   } else {
//     logfile("E","Tempdir ".$tmp2dir." couldn't be created.");
//     die("Tempdir couldn't be created.");
//   }
// }

// // remove temp dir
// if (is_dir($tmp2dir)) {
//   // remove temp path
//   chdir($actpath);
//   full_rmdir(basename($tmpdir));
// }


function  unpackndl2tmp($archiv,$packer) {
  global $tmp2dir,$pck;
  $actualdir = getcwd();
  chdir($tmp2dir);
  $cmdstring = $pck[$packer]['Extract'];
  $cmdshl = str_replace(" %f", "", $cmdstring);  
  $cmdshl = str_replace("%a", $archiv, $cmdshl);
  echo $cmdshl."\r\n";
  // to directory ".getcwd()."\r\n";
  logfile('D',$cmdshl);
  passthru($cmdshl,$rw);
  // echo $rw."\r\n";
  chdir($actualdir);
  return True;
}

// -----------------------------------------

function full_rmdir( $dir )     {
  if ( !is_writable( $dir ) )   {
    if ( !@chmod( $dir, 0777 ) )    {
      return FALSE;
    }
  }
  $d = dir( $dir );
  while ( FALSE !== ( $entry = $d->read() ) )   {
    if ( $entry == '.' || $entry == '..' )   {
      continue;
    }
    $entry = $dir . '/' . $entry;
    if ( is_dir( $entry ) )   {
      if ( !$this->full_rmdir( $entry ) )   {
        return FALSE;
      }
      continue;
    }
    if ( !@unlink( $entry ) )  {
      $d->close();
      return FALSE;
    }
  }
  $d->close();
  rmdir( $dir );
  return TRUE;
}

// -----------------------------------------

function cleantmpdir() {
  global $tmp2dir;
  $actualdir = getcwd();
  chdir($tmp2dir);
  $workdir = $tmp2dir."\\"; 

  $blockslist = array();
  $blocksdir = dir($workdir);
  while($func=$blocksdir->read()) {
    $blockslist .= "$func ";
    // echo $sourcepath.$func."\r\n";
    if (strtoupper($func)<>".") {
      if (strtoupper($func)<>"..") {
        if (is_dir($workdir.$func)) {
          // name is a subdir
          // recursivly handle paths
          full_rmdir($workdir.$func);
        } else {
          //  no path, is file
          //      $input = file_get_contents($areapath.$func);
          //      $fbbs = $input;
          if (file_exists($workdir.$func)) {
            unlink($workdir.$func);
          }
        }
      }
    }
  }
  
  chdir($actualdir);
  return True;
}


/* ---------  CRC16 (Xmodem, FTSC) ----------------------- */

function crc16dt1() {
    define('_CRC16Tab',True);
    logfile('D', "Build CRC16 table.");
    global $CRC16Tab;
    $i = 0;
    for ($i = 0; $i < 256; $i++) {
        $CRC16Tab[$i] = crc16dt2($i);
    }
}

// -----------------------------------------

function crc16dt2($index) {
    $i=0;
    $a = 0;
    $index <<= 8;
    for ($i=8; $i>0; $i--) {
        if (( $index ^ $a ) & 0x8000 ) {
            $a = ($a << 1) ^ 0x1021;
        } else {
            $a <<= 1;
        }
        $index <<= 1;
    }
    return ($a & 0xFFFF);
}

// -----------------------------------------

function crc16dtf($fstr) {
    if (!defined('_CRC16Tab')) {
      // Build CRC16 table
      crc16dt1();
    }
    global $CRC16Tab;
    $lfcrc = 0;
    // $lfcrc = crc16dti($lfcrc);
    $lfcrc = crc16dtp($lfcrc,$fstr,strlen($fstr));
    return $lfcrc;
}

// -----------------------------------------

function crc16dtp($crcptr,$buffer,$length) {
    if (!defined('_CRC16Tab')) {
      // Build CRC16 table
      crc16dt1();
    }
    global $CRC16Tab;

    // const unsigned char *ptr = buffer;
    // $ptr = 0;
    // size_t ctr;
    $ctr = 0;
    for ($ctr = 0; $ctr < $length; $ctr++) {
          $ptr = ord(substr($buffer,$ctr,1));
          $crcptr = (((($crcptr) << 8) ^
                    $CRC16Tab [ (((($crcptr) >> 8) ^ ($ptr)) & 0xFF) ])
                    & 0xFFFF);
    }
    return $crcptr;
}

// -----------------------------------------

function doy2date($y,$dno) {
  // date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
  $i = 0;
  $j = 0;
  while ($dno>0) {
    $i++;
    $lastday = mktime(0, 0, 0, $i+1, 0, $y);
    if ($lastday < $dno) {
      $dno = $dno - $lastday;
    } else {
      $j = $dno;
      $dno = 0;
    }
  }

  $dat = date("Y-m-d",mktime(0,0,0,$i, $j, $y));  
  return $dat;
}

/* ---------  end funtions  ------------------------------ */


?>