<?php

//Funktionen
function makeuptime($time)		//Generiert aus Minuten Tage, Stunden und Minuten
{
	$minuten = $time % 60;
	$weiter = ($time - $minuten) / 60;
	$stunden = $weiter % 24;
	$tage = ($weiter - $stunden) / 24;
	return sprintf("%dD %02d:%02d", (int)$tage, (int)$stunden, (int)$minuten);
}

function makeuptime2 ($time)		//Generiert aus Sekunden Stunden, Minuten und Sekunden
{
	$sekunden = $time % 60;
	$weiter = ($time - $sekunden) / 60;
	$minuten = $weiter % 60;
	$stunden = ($weiter - $minuten) / 60;
	return sprintf("%02d:%02d:%02d", (int)$stunden, (int)$minuten, (int)$sekunden);
}

function __autoload($class_name) {
    require_once "classes/" . $class_name . '.class.php';
}

function error_handler($errno, $errstr, $errfile, $errline) {
	global $logging;

	if (error_reporting() == 0) return;

    $errortype = array (
        E_ERROR              => 'Error',
        E_WARNING            => 'Warning',
        E_PARSE              => 'Parsing Error',
        E_NOTICE             => 'Notice',
        E_CORE_ERROR         => 'Core Error',
        E_CORE_WARNING       => 'Core Warning',
        E_COMPILE_ERROR      => 'Compile Error',
        E_COMPILE_WARNING    => 'Compile Warning',
        E_USER_ERROR         => 'User Error',
        E_USER_WARNING       => 'User Warning',
        E_USER_NOTICE        => 'User Notice',
        E_STRICT             => 'Runtime Notice',
        E_RECOVERABLE_ERROR  => 'Catchable Fatal Error'
    );

    $dir = dirname(__FILE__);
    $errfile = substr(str_replace($dir, "", $errfile), 1);

	$logging->write(MOD_PHPERROR, "$errortype[$errno] in $errfile:$errline => $errstr");
}

function parse_cfg_file($file, $process_sections = false) {
  global $logging;

  $process_sections = ($process_sections !== true) ? false : true;

  $ini = file($file);
  if (count($ini) == 0) {return array();}

  $sections = array();
  $values = array();
  $result = array();
  $globals = array();
  $i = 0;
  $lineno = 0;
  foreach ($ini as $line) {
    $lineno ++;
    $line = trim($line);
    $line = str_replace("\t", " ", $line);

    // Comments
    if (!preg_match('/^[a-zA-Z0-9[-]/', $line)) {
        if (!empty($line) && $line{0} != ";") { //Not a Comment
            $logging->write(MOD_ERROR, "Parse error in $file on line $lineno");
        }
        continue;
    }

    // Sections
    if ($line{0} == '[') {
      $tmp = explode(']', $line);
      $sections[] = trim(substr($tmp[0], 1));
      $i++;
      continue;
    }

    // Key-value pair
    $parts = explode('=', $line, 2);
    if (count($parts) != 2) {
        $logging->write(MOD_ERROR, "Parse error in $file on line $lineno");
    }
    list($key, $value) = $parts;
    $key = trim($key);
    $value = trim($value);

    if (strtolower($value) == "null") {
        $value = null;
    }
    else {
        if (strstr($value, ";")) {
          $tmp = explode(';', $value);
          if (count($tmp) == 2) {
            if ((($value{0} != '"') && ($value{0} != "'")) ||
                preg_match('/^".*"\s*;/', $value) || preg_match('/^".*;[^"]*$/', $value) ||
                preg_match("/^'.*'\s*;/", $value) || preg_match("/^'.*;[^']*$/", $value) ){
              $value = $tmp[0];
            }
          } else {
            if ($value{0} == '"') {
              $value = preg_replace('/^"(.*)".*/', '$1', $value);
            } elseif ($value{0} == "'") {
              $value = preg_replace("/^'(.*)'.*/", '$1', $value);
            } else {
              $value = $tmp[0];
            }
          }
        }
        $value = trim($value);
        $value = trim($value, "'\"");
    }

    if ($i == 0) {
      if (substr($line, -1, 2) == '[]') {
        $globals[$key][] = $value;
      } else {
        $globals[$key] = $value;
      }
    } else {
      if (substr($line, -1, 2) == '[]') {
        $values[$i-1][$key][] = $value;
      } else {
        $values[$i-1][$key] = $value;
      }
    }

  }

  for($j = 0; $j < $i; $j++) {
    if ($process_sections === true) {
      $result[$sections[$j]] = $values[$j];
    } else {
      $result[] = $values[$j];
    }
  }

  return $result + $globals;
}

function size($size)
{
	$sizes = Array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
	$ext = $sizes[0];
	for ($i=1; (($i < count($sizes)) && ($size >= 1024)); $i++) {
		$size = $size / 1024;
		$ext  = $sizes[$i];
	}
	$size = round($size, 2) . ' ' . $ext;
	return $size;
}

function config_merge($config1, $config2) {
    $configs = func_get_args();
    $result = array_shift($configs);

    foreach ($configs as $config) {
        foreach ($config as $sectionname => $section) {
            foreach ($section as $key => $value) {
                $result[$sectionname][$key] = $value;
                if ($value == null) {
                    unset($result[$sectionname][$key]);
                }
            }
        }
    }

    return $result;
}

function array_i_key_exists($needle, $stack) {
    $needle = strtolower($needle);
    $keys = array_keys($stack);
    $keys = array_map("strtolower", $keys);
    return (in_array($needle, $keys));
}

function parse_argv($possible) {

    global $argv, $argc;

    $parsed = array();

    for ($i = 1; $i < $argc; $i ++) {
        if ($argv[$i]{0} != "-" && $argv[$i]{0} != "/") {
            throw new Exception("Unrecognized part '$argv[$i]'");
        }

        $name = strtolower(substr($argv[$i], 1));
        if (!array_key_exists($name, $possible)) {
            throw new Exception("Unrecognized parameter '$argv[$i]'");
        }

        if (array_key_exists($name, $parsed) && !$possible[$name]["multiple"]) {
            throw new Exception("'$name' can't be set multiple times");
        }

        $values = array();
        for ($j = 1; $j <= $possible[$name]["count"]; $j++, $i++) {

            if (!isset($argv[$i + 1])) {
                throw new Exception("Wrong parameter count for '$name'");
            }

            if ($possible[$name]["count"] == 1) {
                $values = $argv[$i + 1];
            }
            else {
                $values[] = $argv[$i + 1];
            }
        }

        if ($possible[$name]["multiple"]) {
            if (!array_key_exists($name, $parsed)) {
                $parsed[$name] = array();
            }
            $parsed[$name][] = $values;
        }
        else {
            $parsed[$name] = $values;
        }

    }

    return $parsed;

}

?>