Index: /add.php
===================================================================
--- /add.php	(revision 1)
+++ /add.php	(revision 1)
@@ -0,0 +1,18 @@
+<?
+include('stat_functions.php');
+include('db.php');
+DB_Init('localhost', 'stat', '', 'statistic');
+
+if(array_key_exists('MeasureId', $_GET) and array_key_exists('Value', $_GET))
+{
+  $MeasureId = addslashes($_GET['MeasureId']);
+  $Value = addslashes($_GET['Value']);
+  $Measure = GetMeasureById($MeasureId);
+  if(gethostbyaddr($_SERVER['REMOTE_ADDR']) == $Measure['permission_add']) 
+  {
+    AddValue($Measure, $Value);
+    echo('Hodnota '.$Value.' ulo¾ena');
+  } else echo('Nemáte oprávnìní k aktualizaci zadané velièiny!<br>Vae adresa: '.gethostbyaddr($_SERVER['REMOTE_ADDR']).'('.$_SERVER['REMOTE_ADDR'].')');
+} else echo('Nebyly zadány potøebné parametry');
+
+?>
Index: /code.php
===================================================================
--- /code.php	(revision 1)
+++ /code.php	(revision 1)
@@ -0,0 +1,561 @@
+<?
+/*
+  ISO8859-2 <-> UTF-8 conversion functions designed for use in PHP-GTK apps
+  Adam Rambousek - rambousek@volny.cz
+
+  version history:
+  1.03 --- 12/02/2002
+   * added Win1257 support
+  1.02 --- 30/11/2001
+   * added ISO8859-1 support
+  1.01
+   * added Win1250 support
+  1.00
+
+  string to_utf8(string string [, string charset])
+  string from_utf8(string string [, string charset])
+
+  supported charsets: name of charset you must use in script
+  ISO8859-2: iso2   (this is the default charset, you don't have to specify it)
+  Windows1250: win1250
+  ISO8859-1: iso1
+  Windows1257: win1257
+  
+  example:  $new_string=to_utf8($some_string,"win1250");
+*/
+
+
+/*
+  translation table - actually, it's array where key is hexadecimal number of
+  character in ISO8859-2/Windows1250 and value is its two byte representation in UTF-8 
+*/
+
+$iso2_utf8 = array(
+	0x80=>"\xc2\x80",
+	0x81=>"\xc2\x81",
+	0x82=>"\xc2\x82",
+	0x83=>"\xc2\x83",
+	0x84=>"\xc2\x84",
+	0x85=>"\xc2\x85",
+	0x86=>"\xc2\x86",
+	0x87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xc3\xb6",
+	0xF7=>"\xc3\xb7",
+	0xF8=>"\xc5\x99",
+	0xF9=>"\xc5\xaf",
+	0xFA=>"\xc3\xba",
+	0xFB=>"\xc5\xb1",
+	0xFC=>"\xc3\xbc",
+	0xFD=>"\xc3\xbd",
+	0xFE=>"\xc5\xa3",
+	0xFF=>"\xcb\x99"
+);
+
+$win1250_utf8 = array(
+	0x80=>"\xc2\x80",
+	0x81=>"\xc2\x81",
+	0x82=>"\x140\x9a",
+	0x83=>"\xc2\x83",
+	0x84=>"\x140\x9e",
+	0x85=>"\x140\xa6",
+	0x86=>"\x140\xa0",
+	0x87=>"\x140\xa1",
+	0x88=>"\xc2\x88",
+	0x89=>"\x140\xb0",
+	0x8a=>"\xc5\xa0",
+	0x8b=>"\x140\xb9",
+	0x8c=>"\xc5\x9a",
+	0x8d=>"\xc5\xa4",
+	0x8e=>"\xc5\xbd",
+	0x8f=>"\xc5\xb9",
+	0x90=>"\xc2\x90",
+	0x91=>"\x140\x98",
+	0x92=>"\x140\x99",
+	0x93=>"\x140\x9c",
+	0x94=>"\x140\x9d",
+	0x95=>"\x140\xa2",
+	0x96=>"\x140\x93",
+	0x97=>"\x140\x94",
+	0x98=>"\xc2\x98",
+	0x99=>"\x144\xa2",
+	0x9a=>"\xc5\xa1",
+	0x9b=>"\x140\xba",
+	0x9c=>"\xc5\x9b",
+	0x9d=>"\xc5\xa5",
+	0x9e=>"\xc5\xbe",
+	0x9f=>"\xc5\xba",
+	0xa0=>"\xc2\xa0",
+	0xa1=>"\xcb\x87",
+	0xa2=>"\xcb\x98",
+	0xa3=>"\xc5\x81",
+	0xa4=>"\xc2\xa4",
+	0xa5=>"\xc4\x84",
+	0xa6=>"\xc2\xa6",
+	0xa7=>"\xc2\xa7",
+	0xa8=>"\xc2\xa8",
+	0xa9=>"\xc2\xa9",
+	0xaa=>"\xc5\x9e",
+	0xab=>"\xc2\xab",
+	0xac=>"\xc2\xac",
+	0xad=>"\xc2\xad",
+	0xae=>"\xc2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\xc3\xb3",
+	0xF4=>"\xc3\xb4",
+	0xF5=>"\xc3\xb5",
+	0xF6=>"\xc3\xb6",
+	0xF7=>"\xc3\xb7",
+	0xF8=>"\xc3\xb8",
+	0xF9=>"\xc3\xb9",
+	0xFA=>"\xc3\xba",
+	0xFB=>"\xc3\xbb",
+	0xFC=>"\xc3\xbc",
+	0xFD=>"\xc3\xbd",
+	0xFE=>"\xc3\xbe"
+);
+
+$win1257_utf8 = array(
+	0x80=>"\x142\xac",
+	0x81=>"\xc0\x4",
+	0x82=>"\x140\x9a",
+	0x83=>"\xc0\x4",
+	0x84=>"\x140\x9e",
+	0x85=>"\x140\xa6",
+	0x86=>"\x140\xa0",
+	0x87=>"\x140\xa1",
+	0x88=>"\xc0\x4",
+	0x89=>"\x140\xb0",
+	0x8A=>"\xc0\x4",
+	0x8B=>"\x140\xb9",
+	0x8C=>"\xc0\x4",
+	0x8D=>"\xc2\xa8",
+	0x8E=>"\xcb\x87",
+	0x8F=>"\xc2\xb8",
+	0x90=>"\xc0\x4",
+	0x91=>"\x140\x98",
+	0x92=>"\x140\x99",
+	0x93=>"\x140\x9c",
+	0x94=>"\x140\x9d",
+	0x95=>"\x140\xa2",
+	0x96=>"\x140\x93",
+	0x97=>"\x140\x94",
+	0x98=>"\xc0\x4",
+	0x99=>"\x144\xa2",
+	0x9A=>"\xc0\x4",
+	0x9B=>"\x140\xba",
+	0x9C=>"\xc0\x4",
+	0x9D=>"\xc2\xaf",
+	0x9E=>"\xcb\x9b",
+	0x9F=>"\xc0\x4",
+	0xA0=>"\xc2\xa0",
+	0xA1=>"\xc0\x4",
+	0xA2=>"\xc2\xa2",
+	0xA3=>"\xc2\xa3",
+	0xA4=>"\xc2\xa4",
+	0xA5=>"\xc0\x4",
+	0xA6=>"\xc2\xa6",
+	0xA7=>"\xc2\xa7",
+	0xA8=>"\xc3\x98",
+	0xA9=>"\xc2\xa9",
+	0xAA=>"\xc5\x96",
+	0xAB=>"\xc2\xab",
+	0xAC=>"\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\x87",
+	0xE4=>"\xc3\xa4",
+	0xE5=>"\xc3\xa5",
+	0xE6=>"\xc4\x99",
+	0xE7=>"\xc4\x93",
+	0xE8=>"\xc4\x8d",
+	0xE9=>"\xc3\xa9",
+	0xEA=>"\xc5\xba",
+	0xEB=>"\xc4\x97",
+	0xEC=>"\xc4\xa3",
+	0xED=>"\xc4\xb7",
+	0xEE=>"\xc4\xab",
+	0xEF=>"\xc4\xbc",
+	0xF0=>"\xc5\xa1",
+	0xF1=>"\xc5\x84",
+	0xF2=>"\xc5\x86",
+	0xF3=>"\xc3\xb3",
+	0xF4=>"\xc5\x8d",
+	0xF5=>"\xc3\xb5",
+	0xF6=>"\xc3\xb6",
+	0xF7=>"\xc3\xb7",
+	0xF8=>"\xc5\xb3",
+	0xF9=>"\xc5\x82",
+	0xFA=>"\xc5\x9b",
+	0xFB=>"\xc5\xab",
+	0xFC=>"\xc3\xbc",
+	0xFD=>"\xc5\xbc",
+	0xFE=>"\xc5\xbe",
+	0xFF=>"\xcb\x99"
+);
+
+/*
+  function to convert to UTF-8
+  because characters numbered 0-127 are standard ASCII characters and are same in Unicode,
+  we have to recode only higher characters
+  function pass through the string and when it finds such character, it is replaced with
+  UTF-8 two byte representation
+*/
+function to_utf8($string,$charset="iso2") {
+    eval("global \$".$charset."_utf8;");
+    eval("\$coding=\$".$charset."_utf8;");
+
+    for ($i=0;$i<strlen($string);$i++) {
+        if (ord($string[$i])>127) {
+            $string=substr($string,0,$i).$coding[ord($string[$i])].substr($string,++$i);
+        }
+    }
+    return $string;   
+}
+
+/*
+  reverse function to convert from UTF-8
+  and again it pass through the string and when the two following bytes correspond to
+  two byte combination given in translation array, these two characters are replaced with
+  one character from given coding
+    it takes the key returned by array_search() and since the key is the number of specific
+    character, we can use chr()
+*/
+function from_utf8($string,$charset="iso2") {
+    eval("global \$".$charset."_utf8;");
+    eval("\$coding=\$".$charset."_utf8;");
+
+    for ($i=0;$i<strlen($string)-1;$i++) {
+        if ($code=array_search($string[$i].$string[($i+1)],$coding))
+            $string=substr($string,0,$i).chr($code).substr($string,$i+2);
+    }
+    return $string;
+}
+?>
Index: /config.sample.php
===================================================================
--- /config.sample.php	(revision 1)
+++ /config.sample.php	(revision 1)
@@ -0,0 +1,15 @@
+<?php
+
+$Config = array(
+  'database' => array(
+    'host' => 'localhost',
+    'user' => 'stat',
+    'password' => 'serepes',
+    'database' => 'statistic',
+    'prefix' => '',
+    'charset' => 'latin2',
+  ),
+  'add_url' => 'http://localhost/statistic/new/add.php',
+);
+
+?>
Index: /create_groups.php
===================================================================
--- /create_groups.php	(revision 1)
+++ /create_groups.php	(revision 1)
@@ -0,0 +1,18 @@
+<?
+
+include('error.php');
+include('stat_functions.php');
+include('db.php');
+DB_Init('localhost', 'root', '', 'statistic');
+
+$Measures = array();
+DB_Select('stat_measure', '*');
+while($Measures[] = DB_Row());
+array_pop($Measures);
+
+foreach($Measures as $Measure)
+{
+  echo('Velicina '.$Measure['name']."\n");
+  for($Level=)         
+}
+?>
Index: stom/convert_data.php
===================================================================
--- /custom/convert_data.php	(revision 95)
+++ 	(revision )
@@ -1,37 +1,0 @@
-<?php
-
-include('../global.php');
-
-$Database->select_db('measure');
-$Result = $Database->select('measure', '*', 'DataTable != "data"');
-while($Measure = $Result->fetch_array())
-{
-  echo($Measure['Description'].'<br>');
-  
-  $Database->query("
-CREATE TABLE IF NOT EXISTS `".$Measure['DataTable']."` (
-  `time` datetime NOT NULL default '0000-00-00 00:00:00',
-  `measure` smallint(11) NOT NULL default '0',
-  `min` ".$Measure['DataType']." NOT NULL default '0',
-  `avg` ".$Measure['DataType']." NOT NULL default '0',
-  `max` ".$Measure['DataType']." NOT NULL default '0',
-  `continuity` tinyint(1) NOT NULL default '0',
-  `level` tinyint(4) NOT NULL default '0',
-  KEY `time` (`time`)
-) ENGINE=MyISAM DEFAULT CHARSET=latin2;
-");
-  $Database->query('TRUNCATE TABLE `'.$Measure['DataTable'].'`');
-  
-  $Database->query('INSERT INTO '.$Measure['DataTable'].' SELECT * FROM data WHERE measure='.$Measure['Id']);
-  $Database->query('INSERT INTO '.$Measure['DataTable'].' SELECT * FROM data_cache WHERE measure='.$Measure['Id']);
-  if($Measure['Divider'] == 100)
-  {
-    $Database->query('UPDATE '.$Measure['DataTable'].' SET min=min / '.$Measure['Divider'].', avg=avg /'.$Measure['Divider'].', max=max /'.$Measure['Divider']);
-  }
-  if($Measure['Divider'] == 1000000000)
-  {
-    $Database->query('UPDATE '.$Measure['DataTable'].' SET min=min * 1000000, avg=avg *1000000, max=max * 1000000');
-  }
-}
-
-?>
Index: stom/rebuild_finance.php
===================================================================
--- /custom/rebuild_finance.php	(revision 95)
+++ 	(revision )
@@ -1,41 +1,0 @@
-<?php
-
-include('../global.php');
-
-$MeasureId = 21;
-//print_r(GetMeasureById($MeasureId));
-$Database->query('TRUNCATE TABLE data_finance');
-$Database->select_db('wow');
-$DbRows = array();
-$DbResult = $Database->query('SELECT (SELECT IFNULL(SUM( money ), 0) FROM finance AS fin WHERE fin.time <= f.time ) AS money, time FROM finance AS f ORDER BY f.time ASC');
-echo($Database->error);
-while($DbRows[] = $DbResult->fetch_assoc());
-
-$DbRows[count($DbRows) - 1] = $DbRows[count($DbRows) - 2];
-
-//print_r($DbRows);
-$Measure = GetMeasureById($MeasureId);
-
-$LastTime = 0;
-$Database->select_db('statistic');
-foreach($DbRows as $Index => $DbRow)
-{
-  if($Index < (count($DbRows) - 1))
-  {
-    $TimeEnd = MysqlDateTimeToTime($DbRows[$Index + 1]['time']);
-    $TimeStart = MysqlDateTimeToTime($DbRows[$Index]['time']);
-    $TimeDiff = ($TimeEnd - $TimeStart) / $Measure['Period'];
-    echo('Period:'.$Measure['Period'].'   Diff:'.$TimeDiff.' '.($TimeEnd - $TimeStart)."\n");
-    for($I = 0; $I < $TimeDiff; $I++)
-    {
-      echo('*');
-      $Value = $DbRows[$Index]['money'];
-      //echo(TimeToMysqlDateTime($TimeStart + $Measure['Period'] * $I)." ".$DbRows[$Index]['money']."      \n");
-      AddValue($Measure, array('min' => $Value, 'avg' => $Value, 'max' => $Value), 0, $TimeStart + $Measure['Period'] * $I);
-    }
-    echo('#');
-  }
-}
-echo("\n");
-
-?>
Index: /database.php
===================================================================
--- /database.php	(revision 1)
+++ /database.php	(revision 1)
@@ -0,0 +1,71 @@
+<?
+
+// Extended database class
+// Date: 2007-07-19
+
+class Database extends mysqli
+{
+  var $Prefix = '';
+  
+  function select($Table, $What = '*', $Condition = 1)
+  {
+    return($this->query("SELECT ".$What." FROM ".$this->Prefix.$Table." WHERE ".$Condition));  
+  }
+
+  function delete($Table, $Condition)
+  {
+    $this->query("DELETE FROM ".$this->Prefix.$Table." WHERE ".$Condition);  
+  }
+  
+  function insert($Table, $Data)
+  {
+    $Name = '';
+    $Values = '';
+    foreach($Data as $Key => $Value)
+    {
+      $Value = strtr($Value, '"', '\"');
+      $Name .= ','.$Key;
+	    if($Value == 'NOW()') $Values .= ",".$Value;
+	      else $Values .= ",'".$Value."'";
+    }
+    $Name = substr($Name, 1);
+    $Values = substr($Values, 1);
+    $this->query('INSERT INTO '.$this->Prefix.$Table-' ('.$Name.') VALUES('.$Values.')');  
+  }
+  
+  function update($Table, $Condition, $Data)
+  {
+    foreach($Data as $Key => $Value)
+    {
+	    $Value = strtr($Value, '"', '\"');
+      if($Value != 'NOW()') $Value = "'".$Value."'";
+      $Values .= ", ".$Key."=".$Value;
+    }
+    $Values = substr($Values, 2);  
+    $this->query('UPDATE '.$this->Prefix.$Table.' SET '.$Values.' WHERE ('.$Condition.')');
+  }
+  
+  function replace($Table, $Data)
+  {
+    $Name = '';
+    $Values = '';
+    foreach($Data as $Key => $Value)
+    {
+      $Value = strtr($Value, '"', '\"');
+      $Name .= ",".$Key;
+      if($Value == 'NOW()') $Values .= ",".$Value;
+        else $Values .= ',"'.$Value.'"';
+    }
+    $Name = substr($Name, 1);
+    $Values = substr($Values, 1);
+    $this->query('REPLACE INTO '.$this->Prefix.$Table.' ('.$Name.') VALUES('.$values.')');
+  }
+  
+  function charset($Charset)
+  {
+    $this->query('SET CHARACTER SET '.$Charset);
+  }
+
+}
+
+?>
Index: /database.sql
===================================================================
--- /database.sql	(revision 1)
+++ /database.sql	(revision 1)
@@ -0,0 +1,67 @@
+-- phpMyAdmin SQL Dump
+-- version 2.6.1
+-- http://www.phpmyadmin.net
+-- 
+-- Poèítaè: localhost
+-- Vygenerováno: Pátek 16. bøezna 2007, 20:55
+-- Verze MySQL: 4.1.9
+-- Verze PHP: 4.3.10
+-- 
+-- Databáze: `statistic`
+-- 
+
+-- --------------------------------------------------------
+
+-- 
+-- Struktura tabulky `stat_data`
+-- 
+
+CREATE TABLE `stat_data` (
+  `time` datetime NOT NULL default '0000-00-00 00:00:00',
+  `measure` smallint(11) NOT NULL default '0',
+  `min` int(11) NOT NULL default '0',
+  `avg` int(11) NOT NULL default '0',
+  `max` int(11) NOT NULL default '0',
+  `continuity` tinyint(1) NOT NULL default '0',
+  `level` tinyint(4) NOT NULL default '0',
+  `group` smallint(6) NOT NULL default '0',
+  KEY `time` (`time`),
+  KEY `time_2` (`time`,`measure`)
+) ENGINE=MyISAM DEFAULT CHARSET=latin1;
+
+-- --------------------------------------------------------
+
+-- 
+-- Struktura tabulky `stat_data_cache`
+-- 
+
+CREATE TABLE `stat_data_cache` (
+  `time` datetime NOT NULL default '0000-00-00 00:00:00',
+  `measure` smallint(6) NOT NULL default '0',
+  `min` int(11) NOT NULL default '0',
+  `avg` int(11) NOT NULL default '0',
+  `max` int(11) NOT NULL default '0',
+  `continuity` tinyint(1) NOT NULL default '0',
+  `level` smallint(6) NOT NULL default '0',
+  KEY `time` (`time`)
+) ENGINE=MyISAM DEFAULT CHARSET=latin2 COLLATE=latin2_czech_cs;
+
+-- --------------------------------------------------------
+
+-- 
+-- Struktura tabulky `stat_measure`
+-- 
+
+CREATE TABLE `stat_measure` (
+  `id` int(11) NOT NULL auto_increment,
+  `name` varchar(255) collate latin2_czech_cs NOT NULL default '',
+  `description` varchar(255) collate latin2_czech_cs NOT NULL default '',
+  `divider` int(11) NOT NULL default '1',
+  `unit` varchar(16) collate latin2_czech_cs NOT NULL default '',
+  `continuity` tinyint(1) NOT NULL default '0',
+  `period` int(11) NOT NULL default '60',
+  `old_name` varchar(32) collate latin2_czech_cs NOT NULL default '',
+  `privileged_hosts` varchar(255) collate latin2_czech_cs NOT NULL default 'localhost',
+  PRIMARY KEY  (`id`)
+) ENGINE=MyISAM DEFAULT CHARSET=latin2 COLLATE=latin2_czech_cs;
+        
Index: /db.php
===================================================================
--- /db.php	(revision 1)
+++ /db.php	(revision 1)
@@ -0,0 +1,145 @@
+<?
+
+// Modul pro práci s databází //
+
+// Pøedpona pøed názvem tabulek
+if(!isset($DB_Prefix)) $DB_Prefix = '';
+
+//echo('Tuto stránku nelze zobrazit pøímo!');
+$DB_LastResults = array();  // Doèasné uchování výsledkù
+
+// Database selection
+function DB_Change($name)
+{
+  mysql_select_db($name);
+  if(mysql_errno() == 1049) db_query("CREATE DATABASE $name");  
+}
+
+// Inicializace databáze //
+function DB_Init($host,$user,$password,$name)
+{
+  global $DB_Tables;
+  $password = 'serepes';
+  $link = mysql_connect($host,$user, $password);
+  //echo(mysql_errno());
+  if(mysql_errno() != FALSE) die('Problém s databázi!');
+  DB_Change($name);
+  
+  // Load table list
+  $Tables = mysql_list_tables($name);
+  $DB_Tables = array();
+  for($I=0; $I<mysql_num_rows($Tables); $I++) 
+  {
+    $DB_Tables[$I] = mysql_tablename($Tables, $I);
+  }
+} 
+// Dotaz na databázi //
+function DB_Query($query)
+{
+  global $db_result,$DB_LastResults;
+  //echo('DB: Po¾adavek('.$query.')<br>');
+  //$DB_LastResults[0] = mysql_query($query);
+  //System_ShowArray($DB_LastResults);
+  $db_result = mysql_query($query);
+  if(mysql_error()) echo('DB: Chyba po¾adavku èíslo '.mysql_errno().'!('.mysql_error().')<br>Po¾adavek: '.$query.'<br>');
+}
+
+// Výbìr dal¹ího øádku //
+function DB_Row()
+{
+  global $db_result;
+  return(mysql_fetch_array($db_result));
+}
+
+// Poèet vrácených øádkù //
+function DB_NumRows()
+{
+  global $db_result;
+  return(mysql_num_rows($db_result));
+}
+
+// Uschová výsledek
+function DB_Save()
+{
+  global $db_result,$DB_LastResults;
+  array_push($DB_LastResults,$db_result);
+  //System_ShowArray($DB_LastResults);
+}
+
+// Naète pøedchozí výsledek
+function DB_Load()
+{
+  global $db_result,$DB_LastResults;
+  $db_result = array_pop($DB_LastResults);
+}
+
+// SELECT
+function DB_Select($Table,$What,$Condition = 1)
+{
+  global $DB_Prefix;
+  DB_Query("SELECT ".$What." FROM ".$DB_Prefix.$Table." WHERE ".$Condition);  
+}
+
+// DELETE
+function DB_Delete($Table,$Condition)
+{
+  global $DB_Prefix;
+  DB_Query("DELETE FROM ".$DB_Prefix.$Table." WHERE ".$Condition);  
+}
+
+// Vlo¾ení nového øádku do databáze //
+function DB_Insert($table,$data)
+{
+  global $DB_Prefix;
+  $name = '';
+  $values = '';
+  foreach($data as $key => $value)
+  {
+    $value = addslashes($value);
+    $name .= ",".$key;
+    if($value=='NOW()') $values .= ",".$value;
+    else $values .= ',"'.$value.'"';
+  }
+  $name = substr($name,1);
+  $values = substr($values,1);
+  db_query("INSERT INTO ".$DB_Prefix."$table ($name) VALUES($values)");
+  //echo("INSERT INTO $table ($name) VALUES($values)");
+}
+
+// Pøepis øádku za nový //
+function DB_Replace($table,$data)
+{
+  global $DB_Prefix;
+  $name = '';
+  $values = '';
+  foreach($data as $key => $value)
+  {
+    $value = addslashes($value);
+    $name .= ",".$key;
+    if($value=='NOW()') $values .= ",".$value;
+    else $values .= ',"'.$value.'"';
+  }
+  $name = substr($name,1);
+  $values = substr($values,1);
+  db_query("REPLACE INTO ".$DB_Prefix."$table ($name) VALUES($values)");
+  //echo("INSERT INTO $table ($name) VALUES($values)");
+}
+
+// Vlo¾ení nového øádku do databáze //
+function DB_Update($table,$condition,$data)
+{
+  global $DB_Prefix;
+  $name = '';
+  $values = '';
+  foreach($data as $key => $value)
+  {
+    $value = addslashes($value);
+    if($value!='NOW()') $value = '"'.$value.'"';
+    $values .= ", ".$key."=".$value;
+  }
+  $values = substr($values,2);
+  DB_Query("UPDATE ".$DB_Prefix."$table SET $values WHERE ($condition)");
+  //echo("UPDATE $table WHERE($condition) SET ($values)");
+}
+
+?>
Index: /error.log
===================================================================
--- /error.log	(revision 1)
+++ /error.log	(revision 1)
@@ -0,0 +1,9 @@
+1
+# 2007-07-15 22:30:10 : Undefined variable: III
+ /var/www/html/statistic/new/stat_functions.php(307)	GetValues
+ /var/www/html/statistic/new/graph.php(42)	GetValues('8','Undefined variable: III','/var/www/html/statistic/new/stat_functions.php','307','a:7:{s:7:"Measure";a:23:{i:0;s:1:"2";s:2:"id";s:1:"2";i:1;s:7:"inet_up";s:4:"name";s:7:"inet_up";i:2;s:17:"Internet odesláno";s:11:"description";s:17:"Internet odesláno";i:3;s:4:"1288";s:7:"divider";s:4:"1288";i:4;s:6:"kbit/s";s:4:"unit";s:6:"kbit/s";i:5;s:1:"0";s:10:"continuity";s:1:"0";i:6;s:2:"60";s:6:"period";s:2:"60";i:7;s:7:"inet_up";s:8:"old_name";s:7:"inet_up";i:8;s:9:"localhost";s:16:"privileged_hosts";s:9:"localhost";i:9;s:0:"";s:4:"info";s:0:"";i:10;s:1:"1";s:7:"enabled";s:1:"1";s:17:"ContinuityEnabled";i:0;}s:8:"TimeFrom";s:10:"1183925682";s:6:"TimeTo";s:10:"1184530482";s:5:"Level";d:0;s:13:"DivisionCount";i:500;s:5:"Debug";i:0;s:6:"Values";a:0:{}}')
+
+# 2007-07-15 22:30:10 : Undefined variable: Row
+ /var/www/html/statistic/new/stat_functions.php(307)	GetValues
+ /var/www/html/statistic/new/graph.php(42)	GetValues('8','Undefined variable: Row','/var/www/html/statistic/new/stat_functions.php','307','a:7:{s:7:"Measure";a:23:{i:0;s:1:"2";s:2:"id";s:1:"2";i:1;s:7:"inet_up";s:4:"name";s:7:"inet_up";i:2;s:17:"Internet odesláno";s:11:"description";s:17:"Internet odesláno";i:3;s:4:"1288";s:7:"divider";s:4:"1288";i:4;s:6:"kbit/s";s:4:"unit";s:6:"kbit/s";i:5;s:1:"0";s:10:"continuity";s:1:"0";i:6;s:2:"60";s:6:"period";s:2:"60";i:7;s:7:"inet_up";s:8:"old_name";s:7:"inet_up";i:8;s:9:"localhost";s:16:"privileged_hosts";s:9:"localhost";i:9;s:0:"";s:4:"info";s:0:"";i:10;s:1:"1";s:7:"enabled";s:1:"1";s:17:"ContinuityEnabled";i:0;}s:8:"TimeFrom";s:10:"1183925682";s:6:"TimeTo";s:10:"1184530482";s:5:"Level";d:0;s:13:"DivisionCount";i:500;s:5:"Debug";i:0;s:6:"Values";a:0:{}}')
+
Index: /error.php
===================================================================
--- /error.php	(revision 1)
+++ /error.php	(revision 1)
@@ -0,0 +1,63 @@
+<?php
+
+// Obsluha chyb v1.1.1 //
+
+$Error_Email = 'robie@centrum.cz';						// Adresa, kam budou chyby odesílány
+$Error_Subject = 'Chybové hlá¹ení';		// Název zpráv o chybách
+$Error_ShowDetails = 1;									// Zobrazit detajly o chybì
+
+//error_reporting(0);					// Vypni interní obsluhu chyb
+
+function obsluha_chyb($errno,$errmsg,$filename,$linenum,$vars)
+{
+  global $Error_ShowDetails;
+  $dt = date("Y-m-d H:i:s");		// èasové razítko polo¾ky
+  $errortype = array (
+    1 => "Error",
+    2 => "Warning",
+    4 => "Parsing Error",
+    8 => "Notice",
+    16 => "Core Error",
+    32 => "Core Warning",
+    64 => "Compile Error",
+    128 => "Compile Warning",
+    256 => "User Error",
+    512 => "User Warning",
+    1024 => "User Notice"
+  );
+  $user_errors = E_ALL;  //E_ERROR | E_WARNING | E_PARSE;
+  
+  if($user_errors & $errno)
+  {
+	  $err = '# '.$dt.' : '.$errmsg."\n";
+    $Backtrace = debug_backtrace();
+    array_shift($Backtrace);
+    //array_shift($Backtrace);
+    foreach($Backtrace as $Item)
+    {
+      $err .= ' '.$Item['file'].'('.$Item['line'].")\t".$Item['function'];
+      $arguments = '';
+      if(array_key_exists('args', $Item) and is_array($Item['args']))
+      foreach($Item['args'] as $Arg)
+      {
+        if(is_array($Arg)) $arguments .= "'".serialize($Arg)."',";
+        else $arguments .= "'".$Arg."',";
+      }
+      if(strlen($arguments)>0) $err .= '('.substr($arguments,0,-1).")";
+      $err .= "\n";
+      
+    }
+    $err .= "\n";
+    //echo('Uvnitø'.$errno);
+    error_log($err,3,'error.log');				// Ulo¾ do chybového protokolu
+	  //$err = "Datum: ".$dt."\nHlá¹ení: ".$errmsg."\nSkript: ".$filename."\nØádek: ".$linenum;
+    //mail($Error_Email,$Error_Subject,$err);		// Po¹li mi zprávu (pokud je to kritická chyba)
+	  echo('Do¹lo k vnitøní chybì!<br> O chybì byl uvìdomnìn správce webu a chybu brzy odstraní.<br><br>');
+  	if($Error_ShowDetails==1) echo('<pre>'.$err.'</pre><br>');			// V pøípadì ladìní chybu i zobraz
+    if((E_ERROR | E_PARSE) & $errno) die(); 
+  }// else echo($errmsg.'<br>');
+}
+
+set_error_handler('obsluha_chyb');				// Aktivuj novou obsluhu chyb
+
+?>
Index: /graph.php
===================================================================
--- /graph.php	(revision 1)
+++ /graph.php	(revision 1)
@@ -0,0 +1,201 @@
+<?php
+include('error.php');
+include('stat_functions.php');
+include('db.php');
+include('code.php');
+DB_Init('localhost', 'stat', '', 'statistic');
+DB_Query('SET CHARACTER SET latin2');
+  
+if(array_key_exists('Debug', $_GET)) $Debug = $_GET['Debug']; 
+  else $Debug = 0;
+  
+$DefaultWidth = 750;
+$DefaultHeight = 200;
+$K = 0.9;   // Coeficient for decreasing graph height 
+$FontFile = 'arial.ttf';
+$FontSize = 10;
+
+if(!array_key_exists('From',$_GET)) die('Musíte zadat èas poèátku');
+$StartTime = addslashes($_GET['From']);
+if(!array_key_exists('To',$_GET)) die('Musíte zadat èas konce');
+$EndTime = addslashes($_GET['To']);
+if($EndTime < $StartTime) $EndTime = $StartTime + 60;
+$TimeDifference = $EndTime - $StartTime;
+if(!array_key_exists('Measure',$_GET)) die('Musíte zadat mìøenou velièinu');
+$MeasureId = addslashes($_GET['Measure']);
+if(!array_key_exists('Width', $_GET)) $Width = $DefaultWidth; 
+else $Width = addslashes($_GET['Width']);
+if(!array_key_exists('Height', $_GET)) $Height = $DefaultHeight;
+else $Height = addslashes($_GET['Height']);
+$VerticalLinesCount = round($Height / ($FontSize + 4));
+
+$StopWatchStart = GetMicrotime();
+
+$Measure = GetMeasureById($MeasureId);
+
+$Level = floor(log(($EndTime - $StartTime) / $DivisionCount / 60) / log($LevelReducing)) - 1;
+if($Level < 0) $Level = 0;
+if($Level > $MaxLevel) $Level = $MaxLevel;
+//$Level = 0;
+
+
+$Points = GetValues($Measure, $StartTime, $EndTime, $Level);
+
+if($Debug) echo('Points count: '.count($Points).'<br>'); 
+//if($Debug) foreach($Points as $Index => $Item) 
+//  echo($Index.': '.$Item['min'].'<br>');
+
+// Calculate total max, avg, min value
+$MaxValue = -1000000000;
+$AvgValue = 0;
+$MinValue = 1000000000;
+foreach($Points as $Index => $Item)
+{
+  $Points[$Index]['min'] =  $Points[$Index]['min'] / $Measure['display_divider'];
+  $Points[$Index]['avg'] =  $Points[$Index]['avg'] / $Measure['display_divider'];
+  $Points[$Index]['max'] =  $Points[$Index]['max'] / $Measure['display_divider'];
+  if($Points[$Index]['avg'] > $MaxValue) $MaxValue = $Points[$Index]['avg'];
+  if($Points[$Index]['avg'] < $MinValue) $MinValue = $Points[$Index]['avg'];
+  if($Points[$Index]['max'] > $MaxValue) $MaxValue = $Points[$Index]['max'];
+  if($Points[$Index]['min'] < $MinValue) $MinValue = $Points[$Index]['min'];
+  $AvgValue = $AvgValue + $Points[$Index]['avg'];
+}
+$MinValue = round($MinValue * $Measure['display_divider']) / $Measure['display_divider'];
+$MaxValue = round($MaxValue * $Measure['display_divider']) / $Measure['display_divider'];
+$AvgValue = round($AvgValue / count($Points) * $Measure['display_divider']) / $Measure['display_divider'];
+
+// Generate polygon and recalculate y values to fit graph height 
+$PointsMin = array(0, $Height-1);
+$PointsAvg = array(0, $Height-1);
+$PointsMax = array(0, $Height-1);
+if(($MaxValue - $MinValue) == 0) $MaxValue = $MinValue + 1;
+{ 
+  foreach($Points as $Index => $Item)
+  {
+    $PointsMin[] = $Index*$Width/$DivisionCount;
+    $PointsMin[] = $Height - 1 - ($Points[$Index]['min'] - $MinValue) / ($MaxValue - $MinValue) * $Height * $K;
+    $PointsAvg[] = $Index*$Width/$DivisionCount;
+    $PointsAvg[] = $Height - 1 - ($Points[$Index]['avg'] - $MinValue) / ($MaxValue - $MinValue) * $Height * $K;
+    $PointsMax[] = $Index*$Width/$DivisionCount;
+    $PointsMax[] = $Height - 1 - ($Points[$Index]['max'] - $MinValue) / ($MaxValue - $MinValue) * $Height * $K;
+    //echo($Index.' - '.$Item.' '.$Points[$Index].'<br>');
+  }
+}
+$PointsMin[] = $Width-1;
+$PointsMin[] = $Height-1;
+$PointsAvg[] = $Width-1;
+$PointsAvg[] = $Height-1;
+$PointsMax[] = $Width-1;
+$PointsMax[] = $Height-1;
+$PointsMin[] = $Width-1;
+$PointsMin[] = $Height-1;
+$PointsAvg[] = $Width-1;
+$PointsAvg[] = $Height-1;
+$PointsMax[] = $Width-1;
+$PointsMax[] = $Height-1;
+
+
+array_unshift($Points, $Height - 1);
+array_unshift($Points, 0);
+$Points[] = $Width - 1;
+$Points[] = $Height - 1;
+
+// Generate image
+if(!$Debug) 
+{
+  header("Content-type: image/png");
+  header("Cache-Control: no-cache");	// Dynamic graph - no cache 
+  $Image = @imagecreate($Width, $Height + 14);
+  $BackgroundColor = imagecolorallocate($Image, 255, 255, 255);
+  $Black = imagecolorallocate($Image, 0, 0, 0);
+  $White = imagecolorallocate($Image, 255, 255, 255);
+  $Gray = imagecolorallocate($Image, 200, 200, 200);
+  $DarkGray = imagecolorallocate($Image, 100, 100, 100);
+  $LightBlue = imagecolorallocate($Image, 150, 150, 255);
+  $Blue = imagecolorallocate($Image, 0, 0, 255);
+  $LightRed = imagecolorallocate($Image, 255, 150, 150);
+  $Red = imagecolorallocate($Image, 255, 0, 0);
+  $Green = imagecolorallocate($Image, 0, 200, 0);
+  $LightGreen = imagecolorallocate($Image, 150, 255, 150);
+
+  imagefilledpolygon($Image, $PointsMax, count($PointsMax) / 2, $LightRed);
+  imagefilledpolygon($Image, $PointsAvg, count($PointsAvg) / 2, $LightGreen);
+  imagefilledpolygon($Image, $PointsMin, count($PointsMin) / 2, $LightBlue);
+  
+  $TimeMarks = array(1, 60, 60*60, 60*60*24, 60*60*24*7, 60*60*24*30, 60*60*24*365, 60*60*24*365*10);
+  
+  $TimeRange = $EndTime - $StartTime;
+  $TimeMarksIndex = 0;
+  while(($TimeRange / $TimeMarks[$TimeMarksIndex]) > 1) $TimeMarksIndex += 1;
+  if($TimeMarksIndex < 2) $TimeMarksIndex = 2;
+  $MajorTimeMarks = $TimeMarks[$TimeMarksIndex - 1];
+  $MinorTimeMarks = $TimeMarks[$TimeMarksIndex - 2];  
+   
+  $TimeShift = AlignTime($StartTime, $MajorTimeMarks) - $StartTime; 
+  //imagestring($Image, 10, 40, 50, $TimeShift, $Black);
+  
+  // Zobraz mìøítko Y
+  $VerticalLinesDistance = $Height / $VerticalLinesCount;
+  for($I=1; $I<=$VerticalLinesCount; $I++)
+  {
+    $Y = $Height - 1 - ($VerticalLinesDistance * $I);
+    for($X=1; $X < $Width; $X = $X + 3) imagesetpixel($Image, $X, $Y, $Gray);
+    //imageline($Image, 30, $Y, $Width-1, $Y, IMG_COLOR_STYLED);
+  } 
+
+  $TimeShift = AlignTime($StartTime, $MinorTimeMarks) - $StartTime; 
+
+  /*
+  if(($MinorTimeMarks / $TimeRange * $Width) > 3)
+  for($Time = $StartTime; $Time < $EndTime; $Time += $MinorTimeMarks)
+  {
+    $X = round(($Time - $StartTime + $TimeShift) / $TimeRange * $Width) % $Width; 
+    for($Y=0; $Y < $Height; $Y = $Y + 3) imagesetpixel($Image, $X, $Y, $Gray);
+    //imageline($Image, 30, $Y, $Width-1, $Y, IMG_COLOR_STYLED);
+    //imagestring($Image, 2, 2, $Y - 6, round(($I * $VerticalLinesDistance + $MinValue)*$Measure['divider']) / $Measure['divider'], $Black);
+  } 
+  */
+  
+  // Zobraz mìøítko X
+  $LastTextEnd = 0;
+  for($Time = $StartTime; $Time < $EndTime; $Time += $MajorTimeMarks)
+  {
+    $X = round(($Time - $StartTime + $TimeShift) / $TimeRange * $Width) % $Width; 
+    //imageline($Image, 30, $Y, $Width-1, $Y, IMG_COLOR_STYLED);
+    if(($MajorTimeMarks > 60*60*24)) $Text = date('j.n.Y', $Time + $TimeShift);
+      else $Text = date('j.n.Y G:i', $Time + $TimeShift);
+    $BoundBox = imagettfbbox($FontSize, 0, $FontFile, $Text);
+    if($LastTextEnd < ($X - ($BoundBox[2] - $BoundBox[0] + 20) / 2))
+    {
+      for($Y=0; $Y < $Height; $Y = $Y + 1) imagesetpixel($Image, $X, $Y, $Gray);
+      imagettftext($Image, $FontSize, 0, $X - ($BoundBox[2] - $BoundBox[0]) / 2,  $Height - 2, $Black, $FontFile, $Text);
+      $LastTextEnd = $X + ($BoundBox[2] - $BoundBox[0]) / 2;
+    }
+    else for($Y=0; $Y < $Height; $Y = $Y + 3) imagesetpixel($Image, $X, $Y, $Gray);
+  } 
+  
+  // Popisky osy Y
+  for($I=1; $I<=$VerticalLinesCount; $I++)
+  {
+    $Y = $Height - 1 - ($VerticalLinesDistance * $I);
+    //$Y = $Height - 1 - ($VerticalLinesDistance * $I / ($MaxValue - $MinValue) * $K * $Height);
+    $Text = round(($I * $VerticalLinesDistance / $Height / $K * ($MaxValue - $MinValue) + $MinValue));
+    $BoundBox = imagettfbbox($FontSize, 0, $FontFile, $Text);
+    if(($Y - ($BoundBox[5] - $BoundBox[1]) / 2) > 10)
+      imagettftext($Image, $FontSize, 0, 2,  $Y - ($BoundBox[5] - $BoundBox[1]) / 2, $Black, $FontFile, $Text);
+  } 
+  $GenerationTime = floor((GetMicrotime() - $StopWatchStart) * 1000  ) / 1000;
+
+  imagettftext($Image, $FontSize, 0, $Width-94, 14, $Red, $FontFile, "Max. ".$MaxValue.' '.$Measure['unit']);
+  imagettftext($Image, $FontSize, 0, $Width-194, 14, $Green, $FontFile, "Avg.  ".$AvgValue.' '.$Measure['unit']);
+  imagettftext($Image, $FontSize, 0, $Width-294, 14, $Blue, $FontFile, "Min.  ".$MinValue.' '.$Measure['unit']);
+  imagestring($Image, 2, 50, 20, 'Vygenerováno za '.$GenerationTime.' sekund', $Black);
+  //imagestring($Image, 2, 50, 30, 'Level: '.$Level, $Black);
+
+  imagettftext($Image, $FontSize, 0, 50, 14, $Black, $FontFile, to_utf8($Measure['description']));
+  imagerectangle($Image, 0, 0, $Width - 1, $Height - 1, $Black);   // Frame border
+  imagepng($Image);
+  imagedestroy($Image);
+}
+
+?>
Index: /index.php
===================================================================
--- /index.php	(revision 1)
+++ /index.php	(revision 1)
@@ -0,0 +1,233 @@
+<?
+include('stat_functions.php');
+include('db.php');
+DB_Init('localhost', 'stat', '', 'statistic');
+DB_Query('SET CHARACTER SET latin2');
+
+$Debug = 0;
+
+function EditTime($Time)
+{
+      global $Months;
+      
+      $Output = '<form style="display: inline;" action="?Operation=SetTime&amp;Time='.$Time.'" method="post">';
+      
+      $TimeParts = getdate($_SESSION[$Time]);
+      //print_r($TimeParts); 
+          
+      // Day selection
+      $Output .= '<select name="Day">';
+      for($I = 1; $I < 32; $I++)
+      {
+        if($I == $TimeParts['mday']) $Selected = ' selected="1"'; else $Selected = ''; 
+        $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
+      }
+      $Output .= '</select>. ';
+      
+      // Month selection
+      $Output .= '<select name="Month">';
+      foreach($Months as $Index => $Month)
+      { 
+        if($Index == $TimeParts['mon']) $Selected = ' selected="1"'; else $Selected = ''; 
+        if($Index > 0) $Output .= '<option value="'.$Index.'"'.$Selected.'>'.$Month.'</option>';
+      }
+      $Output .= '</select>. ';
+      
+      // Day selection
+      $Output .= '<select name="Year">';
+      for($I = 2000; $I < 2010; $I++)
+      { 
+        if($I == $TimeParts['year']) $Selected = ' selected="1"'; else $Selected = ''; 
+        $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
+      }
+      $Output .= '</select> &nbsp;&nbsp; ';
+      
+      
+      // Hour selection
+      $Output .= '<select name="Hour">';
+      for($I = 0; $I < 24; $I++)
+      { 
+        if($I == $TimeParts['hours']) $Selected = ' selected="1"'; else $Selected = ''; 
+        $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
+      }
+      $Output .= '</select> : ';
+
+      // Minute selection
+      $Output .= '<select name="Minute">';
+      for($I = 0; $I < 60; $I++) 
+      {
+        if($I == $TimeParts['minutes']) $Selected = ' selected="1"'; else $Selected = ''; 
+        $Output .= '<option value="'.$I.'"'.$Selected.'>'.$I.'</option>';
+      }
+      $Output .= '</select> ';
+      $Output .= '<input type="submit" value="Nastavit">';     
+      $Output .= '</form>';
+
+      $Output .= ' <form style="display: inline;" action="?Operation=SetTimeNow&amp;Time='.$Time.'" method="post">';
+      $Output .= '<input type="submit" value="Aktuální èas">';     
+      $Output .= '</form>';
+      
+      return($Output);
+}
+
+$Months = array('', 'Leden', 'Únor', 'Bøezen', 'Duben', 'Kvìten', 'Èerven', 'Èervenec', 'Srpen', 'Záøí', 
+  'Øíjen', 'Listopad', 'Prosinec'); 
+
+$GrafTimeRanges = array(
+  'hour' => array(
+    'caption' => 'Hodina', 
+    'period' => 3600,
+  ),
+  'day' => array(
+    'caption' => 'Den',
+    'period' => 3600*24,
+  ),
+  'week' => array(
+    'caption' => 'Týden',
+    'period' => 3600*24*7,
+  ),
+  'month' => array(
+    'caption' => 'Mìsíc',
+    'period' => 3600*24*30,
+  ),
+  'year' => array(
+    'caption' => 'Rok',
+    'period' => 3600*24*365,
+  ),
+  'years' => array(
+    'caption' => 'Desetiletí',
+    'period' => 3600*24*365*10,
+  ),
+); 
+
+session_start();
+
+$Variables = array(
+  'TimeStart' => time() - 3600*24,
+  'TimeEnd' => time(),
+  'Measure' => 1,
+  'Period' => 'day',
+  'TimeSpecify' => 0,
+);
+
+foreach($Variables as $Index => $Variable)
+{
+  if(!array_key_exists($Index, $_SESSION)) $_SESSION[$Index] = $Variable;
+  if(array_key_exists($Index, $_GET)) $_SESSION[$Index] = $_GET[$Index];
+  if(array_key_exists($Index, $_POST)) $_SESSION[$Index] = $_POST[$Index];
+  //$$Index = $_SESSION[$Index];
+} 
+
+if($_SESSION['TimeSpecify'] == 0) 
+{
+  $_SESSION['TimeEnd'] = time() - 60;
+  $_SESSION['TimeStart'] = $_SESSION['TimeEnd'] - $GrafTimeRanges[$_SESSION['Period']]['period'];
+}
+
+echo('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html><head>
+  <meta http-equiv="Content-Language" content="cs">
+  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">
+  <title>Statistika</title>
+  <LINK REL="StyleSheet" HREF="style.css" TYPE="text/css" MEDIA="all">
+  </head><body style="font-family: sans-serif;">');
+  echo('<div class="Title">Statistiky</div>');
+
+if(!array_key_exists('Operation', $_GET)) $_GET['Operation'] = ''; 
+switch($_GET['Operation'])
+{
+  case 'SetTime':
+    if(array_key_exists('Time', $_GET) and array_key_exists('Month', $_POST) and array_key_exists('Day', $_POST) and
+      array_key_exists('Year', $_POST) and array_key_exists('Hour', $_POST) and array_key_exists('Minute', $_POST))  
+      {
+        if(($_GET['Time'] == 'TimeStart') or ($_GET['Time'] == 'TimeEnd'))
+        {
+          $_SESSION[$_GET['Time']] = mktime($_POST['Hour'], $_POST['Minute'], 0, $_POST['Month'], 
+            $_POST['Day'], $_POST['Year']);
+          $$_GET['Time'] = $_SESSION[$_GET['Time']];
+        }
+      }
+    break; 
+  case 'SetTimeNow':
+    if(array_key_exists('Time', $_GET)) 
+    {
+      if(($_GET['Time'] == 'TimeStart') or ($_GET['Time'] == 'TimeEnd'))
+      {
+        $_SESSION[$_GET['Time']] = time();
+        $$_GET['Time'] = $_SESSION[$_GET['Time']];
+      }
+    }
+    break; 
+  
+    }
+    /*
+    echo('<strong>Mìøené velièiny:</strong><br>');
+    DB_Select('stat_measure', '*', 'enabled=1 ORDER BY description');
+    while($Row = DB_Row())
+      echo('<a href="?Measure='.$Row['id'].'">'.$Row['description'].'</a> ');
+    echo('<br><br>');
+    */
+    echo('<strong>Èasový úsek:</strong><br>');
+    // Show graf time range menu
+    if($_SESSION['TimeSpecify'] == 0)
+    {
+      echo('Délka úseku: ');
+      foreach($GrafTimeRanges as $Index => $Item)
+        echo('<a href="?Period='.$Index.'">'.$Item['caption'].'</a>&nbsp;'); 
+      echo('<br>');
+      echo('<a href="?TimeSpecify=1">Pøesnìj¹í nastavení...</a><br>');  
+    } else {
+      echo('<table cellspacing="0" cellpadding="2" border="0">');
+      echo('<tr><td>Poèátek:</td><td>'.EditTime('TimeStart').'</td></tr>');
+      echo('<tr><td>Konec:</td><td>'.EditTime('TimeEnd').'</td></tr>');
+      echo('</table>');
+      echo('<a href="?TimeSpecify=0">Jednoduché nastavení...</a><br>');  
+    }
+echo('<br>');
+
+echo('<strong>Graf:</strong><br>');
+echo('<img alt="Graf" src="graph.php?Measure='.$_SESSION['Measure'].'&amp;From='.$_SESSION['TimeStart'].'&amp;To='.$_SESSION['TimeEnd'].'&amp;Width=750&amp;Height=200" width="750" height="214"><br>');
+//print_r(GetValues($Measure, $TimeStart, $TimeEnd));
+ 
+echo('<br>');
+
+echo('<table border="1" cellspacing="0" cellpadding="2" style="font-size: small;">');
+echo('<tr><th>Mìøená velièina</th><th>Èas posledního mìøení</th><th>Poslední hodnota</th><th>Interpolace</th><th>Poznámky</th></tr>');
+DB_Select('stat_measure', '*', 'enabled=1 AND permission_view="all" OR permission_view="'.gethostbyaddr($_SERVER['REMOTE_ADDR']).'" ORDER BY description');
+while($Measure = DB_Row())
+{
+  DB_Save();
+  $StopWatchStart = GetMicrotime();
+//  DB_Select('stat_data', 'COUNT(*)', 'measure='.$Measure['id']);
+//  $RowCount = DB_Row();
+//  $RowCount = $RowCount[0];
+//  $RowCount = 0;
+  DB_Select('stat_data', 'time, avg', 'measure='.$Measure['id'].' ORDER BY time DESC LIMIT 1');
+  if(DB_NumRows() > 0)
+  {
+    $Row = DB_Row();
+    $LastMeasureTime = date('j.n.Y G:i:s', MysqlDateTimeToTime($Row['time']));
+    $LastMeasureValue = round($Row['avg'] / $Measure['display_divider']);
+  } else {
+    $LastMeasureTime = '&nbsp;';
+    $LastMeasureValue = '&nbsp;';
+  }
+  if($Measure['continuity'] == 1) $Interpolate = 'Ano'; else $Interpolate = 'Ne';
+  if($Measure['info'] == '') $Measure['info'] = '&nbsp;';
+  $GenerationTime = floor((GetMicrotime() - $StopWatchStart) * 1000  ) / 1000;
+  echo('<tr><td><a href="?Measure='.$Measure['id'].'">'.$Measure['description'].'</a></td><td align="center">'.$LastMeasureValue.' '.$Measure['display_unit'].'</td><td align="center">'.$LastMeasureTime.'</td><td align="center">'.$Interpolate.'</td><td>'.$Measure['info'].'</td>');
+  //<td>'.$RowCount.'</td><td>'.$GenerationTime.'</td></tr>');
+  flush();
+  DB_Load();
+}
+echo('</table>');
+echo('<br><a href="development/">Sekce vývoje systému</a>');
+//echo(time());
+//print_r(gd_info());
+echo('<br><div style="font-size: small;">Kontakt: robie@centrum.cz</div>');
+echo('</body></html>');
+//print_r($_SESSION);
+
+
+
+?>
Index: /measure_scripts/system_disk_free.php
===================================================================
--- /measure_scripts/system_disk_free.php	(revision 1)
+++ /measure_scripts/system_disk_free.php	(revision 1)
@@ -0,0 +1,9 @@
+<?php
+include('../config.php');
+$MeasureId = 5;
+
+$Value = round(disk_free_space('/') / 1024);
+
+file_get_contents($TargetUrl.'?MeasureId='.$MeasureId.'&Value='.$Value);
+
+?>
Index: /rebuild.php
===================================================================
--- /rebuild.php	(revision 1)
+++ /rebuild.php	(revision 1)
@@ -0,0 +1,11 @@
+<?
+
+include('error.php');
+include('stat_functions.php');
+include('db.php');
+DB_Init('localhost', 'stat', '', 'statistic');
+
+//$Measure = GetMeasureById(12);
+RebuildAllMeasuresCache();
+
+?>
Index: /stat_functions.php
===================================================================
--- /stat_functions.php	(revision 1)
+++ /stat_functions.php	(revision 1)
@@ -0,0 +1,450 @@
+<?
+
+$DivisionCount = 500;
+$ReferenceTime = 0;
+$LevelReducing = 5;
+$MaxLevel = 4;
+
+$ValueTypes = array('min', 'avg', 'max');
+
+function GetMicrotime()
+{
+    list($Usec, $Sec) = explode(" ",microtime());
+    return ((float)$Usec + (float)$Sec);
+}
+
+function MysqlDateTimeToTime($Time)
+{
+  $Parts = explode(' ', $Time);
+  $DateParts = explode('-', $Parts[0]); 
+  $TimeParts = explode(':', $Parts[1]);
+  $Result = mktime($TimeParts[0], $TimeParts[1], $TimeParts[2], $DateParts[1], $DateParts[2], $DateParts[0]); 
+  return($Result);  
+}
+
+function TimeToMysqlDateTime($Time)
+{
+  return(date('Y-m-d H:i:s', $Time));  
+}
+
+function TimeSegment($Level)
+{
+  global $LevelReducing;
+  return(pow($LevelReducing, $Level) * 60);
+}
+
+function StatTableName($Level)
+{
+  if($Level == 0) return('stat_data');
+    else return('stat_data_cache');
+}
+
+function AlignTime($Time, $TimeSegment)
+{
+  global $ReferenceTime, $LevelReducing;
+  return(round(($Time - $ReferenceTime) / $TimeSegment) * $TimeSegment + $ReferenceTime);
+}
+
+function GetMeasureById($Id)
+{
+  DB_Select('stat_measure', '*', 'id='.$Id);
+  if(DB_NumRows() > 0) 
+  {
+    $Measure = DB_Row();
+    if($Measure['continuity'] == 0) $Measure['ContinuityEnabled'] = 0;  // non continuous
+      else $Measure['ContinuityEnabled'] = 2;    // continuous graph  
+  } else die('Mìøená velièina nenalezena');
+  return($Measure); 
+}
+
+function AddValue($Measure, $Value)
+{
+  global $LevelReducing, $MaxLevel;
+  
+  $Time = time();
+  $Value = round($Measure['divider']*$Value);
+
+  DB_Select('stat_data', '*', 'measure='.$Measure['id'].' AND level=0 ORDER BY time DESC LIMIT 2');
+  if(DB_NumRows() == 0) DB_Insert('stat_data', array('min' => $Value, 'avg' => $Value, 'max' => $Value, 'level' => 0, 'measure' => $Measure['id'], 'time' => TimeToMysqlDateTime($Time),
+    'continuity' => 0));
+  else if(DB_NumRows() == 1) DB_Insert('stat_data', array('min' => $Value, 'avg' => $Value, 'max' => $Value, 'level' => 0, 'measure' => $Measure['id'], 'time' => TimeToMysqlDateTime($Time),
+    'continuity' => 1));
+  else {
+    $LastValue = DB_Row();
+    $NextToLastValue = DB_Row();
+    if(($Time - MysqlDateTimeToTime($LastValue['time'])) < 0.75 * $Measure['period']) 
+    {
+    }
+    else 
+    {
+      if(($Time - MysqlDateTimeToTime($LastValue['time'])) < 1.25 * $Measure['period']) $Continuity = 1; 
+        else $Continuity = 0;
+      if(($LastValue['avg'] == $NextToLastValue['avg']) and ($LastValue['avg'] == $Value) and 
+        ($LastValue['continuity'] == 1) and ($Continuity == 1)) 
+      {
+        echo('s');
+        DB_Update('stat_data', 'time="'.$LastValue['time'].'" AND level=0 AND measure='.$Measure['id'], array('time' => 'NOW()'));
+      } else 
+      {
+        DB_Insert('stat_data', array('min' => $Value, 'avg' => $Value, 'max' => $Value, 'level' => 0, 'measure' => $Measure['id'], 'time' => TimeToMysqlDateTime($Time),
+          'continuity' => $Continuity));        
+      }
+    }
+  } 
+    
+    // Update levels
+    //echo($Time."<br>\n");
+    for($Level = 1; $Level <= $MaxLevel; $Level++)
+    {
+      //echo('Level '.$Level."<br>\n");
+      $TimeSegment = TimeSegment($Level);
+      $EndTime = AlignTime($Time, $TimeSegment);
+      //if($EndTime < $Time) $EndTime = $EndTime + $TimeSegment;
+      $StartTime = $EndTime - $TimeSegment;
+      
+      //echo(" ".$TimeSegment." ".$StartTime.'-'.$EndTime."<br>\n");
+      //flush();
+  
+      // Load values in time range
+      $Values = array();
+      DB_Select(StatTableName($Level-1), '*', 'time > "'.TimeToMysqlDateTime($StartTime).'" AND time < "'.
+        TimeToMysqlDateTime($EndTime).'" AND measure='.$Measure['id'].' AND level='.($Level-1).' ORDER BY time');
+      while($Row = DB_Row())
+      {
+        $Row['time'] = MysqlDateTimeToTime($Row['time']);
+        $Values[] = $Row;
+      }
+      //print_r($Values);
+      //array_pop($Values);      
+
+      // Load subsidary values
+      array_unshift($Values, LoadLeftSideValue($Level-1, $Measure, $StartTime));
+      array_push($Values, LoadRightSideValue($Level-1, $Measure, $EndTime));
+
+      $Point = ComputeOneValue($StartTime, $EndTime, $Values, $Measure, $Level);
+      //print_r($Point);
+      
+      DB_Delete(StatTableName($Level), '(time > "'.TimeToMysqlDateTime($StartTime).'") AND 
+        (time < "'.TimeToMysqlDateTime($EndTime).'") AND measure='.$Measure['id'].' AND level='.$Level);
+      $Continuity = $Values[1]['continuity'];   
+      DB_Insert(StatTableName($Level), array('level' => $Level, 'measure' => $Measure['id'], 'min' => $Point['min'], 
+        'avg' => $Point['avg'], 'max' => $Point['max'], 'continuity' => $Continuity, 'time' => TimeToMysqlDateTime($StartTime+($EndTime-$StartTime)/2)));
+
+    }
+}
+
+function Interpolation($X1, $Y1, $X2, $Y2, $X)
+{
+  $Y = ($Y2 - $Y1) / ($X2 - $X1) * ($X - $X1) + $Y1;
+  //echo($Y1.'-'.$Y.'-'.$Y2.' '.$X1.'-'.$X.'-'.$X2.'<br>');
+  return($Y);
+}
+
+function ComputeOneValue($LeftTime, $RightTime, $Values, $Measure, $Level)
+{
+  global $ValueTypes;
+  
+  $NewValue = array('min' => +10000000000, 'avg' => 0, 'max' => -10000000000); 
+  
+  // Trim outside parts
+  foreach($ValueTypes as $ValueType)
+  {
+    $Values[0][$ValueType] = Interpolation($Values[0]['time'], $Values[0][$ValueType], $Values[1]['time'], $Values[1][$ValueType], $LeftTime);
+  }
+  $Values[0]['time'] = $LeftTime;
+  foreach($ValueTypes as $ValueType)
+  {   
+    $Values[count($Values)-1][$ValueType] = Interpolation($Values[count($Values)-2]['time'], $Values[count($Values)-2][$ValueType], 
+      $Values[count($Values)-1]['time'], $Values[count($Values)-1][$ValueType], $RightTime);
+  }
+  $Values[count($Values)-1]['time'] = $RightTime;
+  
+  // Perform computation 
+  foreach($ValueTypes as $ValueType)
+  { 
+    // Compute new value
+    for($I = 0; $I < (count($Values) - 1); $I++)
+    {      
+      if($ValueType == 'avg') 
+      {
+        if($Values[$I+1]['continuity'] == $Measure['ContinuityEnabled']) ;
+          else $NewValue[$ValueType] = $NewValue[$ValueType] + ($Values[$I+1]['time'] - $Values[$I]['time']) *
+            (($Values[$I+1][$ValueType] - $Values[$I][$ValueType]) / 2 + $Values[$I][$ValueType]);
+      }
+      else if($ValueType == 'max') 
+      {
+        if($Values[$I+1]['continuity'] == $Measure['ContinuityEnabled'])
+        {
+          if(0 > $NewValue[$ValueType]) $NewValue[$ValueType] = 0;
+        }
+        else 
+        {
+          //if($Values[$I][$ValueType] > $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I][$ValueType];
+          if($Values[$I+1][$ValueType] > $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I+1][$ValueType];
+        }
+      }
+      else if($ValueType == 'min') 
+      {
+        //echo($Values[$I+1]['continuity'].'=='.$Measure['ContinuityEnabled'].'<br>'); 
+        if($Values[$I+1]['continuity'] == $Measure['ContinuityEnabled'])
+        {
+          if(0 < $NewValue[$ValueType]) $NewValue[$ValueType] = 0;
+        }
+        else 
+        {
+          //if($Values[$I][$ValueType] < $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I][$ValueType];
+          if($Values[$I+1][$ValueType] < $NewValue[$ValueType]) $NewValue[$ValueType] = $Values[$I+1][$ValueType];
+        }
+      }
+           
+    }  
+    $NewValue[$ValueType] = $NewValue[$ValueType]; 
+  }
+  //if(($RightTime - $LeftTime) > 0) 
+  if($Measure['cumulative'] == 0) $NewValue['avg'] = $NewValue['avg'] / ($RightTime - $LeftTime);  
+  return($NewValue);
+  //echo($NewValue['avg'].'<br>');
+  //return(array('min' => rand(0,1), 'avg' => $NewValue['avg'], 'max' => rand(0,1)));
+}
+
+function GetTimeRange($Measure, $Level)
+{
+  global $Debug;
+  
+  // Get first and last time
+  echo($Measure['id'].','.$Level.','.StatTableName($Level)."\n"); 
+  DB_Select(StatTableName($Level), '*', 'measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time LIMIT 1');
+  if(DB_NumRows() > 0)
+  {
+    $Row = DB_Row();
+    $AbsoluteLeftTime = MysqlDateTimeToTime($Row['time']);
+  } else $AbsoluteLeftTime = 0;
+
+  DB_Select(StatTableName($Level), '*', 'measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time DESC LIMIT 1');
+  if(DB_NumRows() > 0)
+  {
+    $Row = DB_Row();
+    $AbsoluteRightTime = MysqlDateTimeToTime($Row['time']);
+  } else $AbsoluteRightTime = 0;
+
+  if($Debug) 
+  {
+    echo('AbsoluteLeftTime: '.$AbsoluteLeftTime.'('.TimeToMysqlDateTime($AbsoluteLeftTime).')<br>');
+    echo('AbsoluteRightTime: '.$AbsoluteRightTime.'('.TimeToMysqlDateTime($AbsoluteRightTime).')<br>');
+  }
+  return(array('left' => $AbsoluteLeftTime, 'right' => $AbsoluteRightTime));
+}
+
+function LoadRightSideValue($Level, $Measure, $Time)
+{ 
+  global $Debug;
+  $Result = array();
+  DB_Select(StatTableName($Level), '*', 'time > "'.TimeToMysqlDateTime($Time).'" AND measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time ASC LIMIT 1');
+  if(DB_NumRows() > 0) 
+  {
+    $Row = DB_Row();
+    $Row['time'] = MysqlDateTimeToTime($Row['time']);
+    return(array($Row));
+  } 
+  else 
+  {
+    //$Time = $Values[count($Values)-1]['time'] + 60;
+    //array_push($Values, array('time' => $Time, 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0));
+    $Result[] = array('time' => ($Time + TimeSegment($Level)), 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0);
+    DB_Select(StatTableName($Level), '*', 'time < "'.TimeToMysqlDateTime($Time).'" AND measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time DESC LIMIT 1');
+    if(DB_NumRows() > 0)
+    {
+      $Row = DB_Row();
+      array_unshift($Result, array('time' => (MysqlDateTimeToTime($Row['time'])+10), 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0)); 
+    } 
+   // if($Debug) print_r($Result);
+    return($Result);
+  }
+}  
+
+function LoadLeftSideValue($Level, $Measure, $Time)
+{
+  global $Debug;
+  $Result = array();
+  //echo('SELECT * FROM '.StatTableName($Level). ' WHERE '. 'time < "'.TimeToMysqlDateTime($Time).'" AND measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time DESC LIMIT 1'."<br>\n");
+  DB_Select(StatTableName($Level), '*', 'time < "'.TimeToMysqlDateTime($Time).'" AND measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time DESC LIMIT 1');
+  if(DB_NumRows() > 0) 
+  {
+    $Row = DB_Row();
+    $Row['time'] = MysqlDateTimeToTime($Row['time']);
+    return(array($Row));
+  }  
+  else 
+  {
+    //$Time = $Values[0]['time'] - 60;
+    //array_unshift($Values, array('time' => $Time, 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0));
+    $Result[] = array('time' => ($Time - TimeSegment($Level)), 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0);
+    
+    DB_Select(StatTableName($Level), '*', 'time > "'.TimeToMysqlDateTime($Time).'" AND measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time ASC LIMIT 1');
+    if(DB_NumRows() > 0)
+    {
+      $Row = DB_Row();
+      array_push($Result, array('time' => (MysqlDateTimeToTime($Row['time'])-10), 'min' => 0, 'avg' => 0, 'max' => 0, 'continuity' => 0)); 
+    } 
+//    if($Debug) print_r($Result);
+    return($Result);
+  }
+}
+
+function GetValues($Measure, $TimeFrom, $TimeTo, $Level)
+{
+  global $DivisionCount, $Debug;
+  
+  if($Debug) echo('TimeFrom: '.$TimeFrom.'('.TimeToMysqlDateTime($TimeFrom).')<br>');
+  if($Debug) echo('TimeTo: '.$TimeTo.'('.TimeToMysqlDateTime($TimeTo).')<br>');
+
+  //$AbsoluteTime = GetTimeRange($MeasureId);
+  
+//  if(($TimeFrom > $AbsoluteLeftTime) and ($TimeStart < $AbsoluteRightTime) and 
+//    ($TimeTo > $AbsoluteLeftTime) and ($TimeTo < $AbsoluteRightTime))
+//  {
+
+  // Load values in time range
+  DB_Select(StatTableName($Level), 'time, min, avg, max, continuity', 'time > "'.TimeToMysqlDateTime($TimeFrom).'" AND time < "'.
+    TimeToMysqlDateTime($TimeTo).'" AND measure='.$Measure['id'].' AND level='.$Level.' ORDER BY time');
+//  echo($Level.' '.TimeToMysqlDateTime($TimeFrom).' '.TimeToMysqlDateTime($TimeTo));
+  $Values = array();
+//  echo(DB_NumRows());
+//  $III = 0;
+  while($Row = DB_Row())
+  {
+//    echo($III.' '.$Row['time'].' '.memory_get_usage().',');
+//    $III++;
+    $Values[] = array('time' => MysqlDateTimeToTime($Row['time']), 'min' => $Row['min'], 'avg' => $Row['avg'], 'max' => $Row['max'], 'continuity' => $Row['continuity']);
+  }
+ // array_pop($Values);
+//  echo('abc');
+//  die();
+  if($Debug) echo('Item count: '.count($Values));
+  
+  $Points = array();
+  if(count($Values) > 0)
+  {
+    $Values = array_merge(LoadLeftSideValue($Level, $Measure, $TimeFrom), $Values, LoadRightSideValue($Level, $Measure, $TimeTo));
+    
+    //echo(count($Values).'<br>');
+    //echo($TimeFrom.','.$TimeTo.'<br>');
+    //echo($Values[0]['time'].'<br>');
+    $StartIndex = 0;
+    $Points = array();
+    for($I = 0; $I < $DivisionCount; $I++)
+    {
+      $TimeStart = $TimeFrom + (($TimeTo - $TimeFrom) / $DivisionCount) * $I;
+      //if($Debug) echo('TimeStart '.$I.': '.$TimeStart.'('.TimeToMysqlDateTime($TimeStart).')<br>');
+      $TimeEnd = $TimeFrom + (($TimeTo - $TimeFrom) / $DivisionCount) * ($I+1);
+      //if($Debug) echo('TimeEnd '.$I.': '.$TimeEnd.'('.TimeToMysqlDateTime($TimeEnd).')<br>');
+      //echo($TimeStart.','.$TimeEnd.'<br>');
+
+      $EndIndex = $StartIndex;
+      while($Values[$EndIndex]['time'] < $TimeEnd) $EndIndex = $EndIndex + 1;
+      $SubValues = array_slice($Values, $StartIndex, $EndIndex - $StartIndex + 1);
+      //echo($StartIndex.','.$EndIndex.' '.count($SubValues).'<br>');
+      //print_r($SubValues);
+      $Points[] = ComputeOneValue($TimeStart, $TimeEnd, $SubValues, $Measure, $Level);
+      $StartIndex = $EndIndex - 1;  
+    }
+  } else $Points[] = array('min' => 0, 'avg' => 0, 'max' => 0);
+  return($Points);
+}
+
+function RebuildMeasureCache($Measure)
+{
+  global $MaxLevel, $LevelReducing;
+
+  echo('Velicina '.$Measure['name']."\n");
+  if($Measure['continuity'] == 0) $Measure['ContinuityEnabled'] = 0;  // non continuous
+    else $Measure['ContinuityEnabled'] = 2;    // continuous graph
+
+  // Clear previous items
+  DB_Select('stat_data_cache', 'COUNT(*)', 'level>0 AND measure='.$Measure['id']);
+  $Row = DB_Row();
+  echo("Mazu starou cache (".$Row[0]." polozek)...");
+  DB_Delete('stat_data_cache', 'level>0 AND measure='.$Measure['id']);
+  echo("\n");
+
+  for($Level=1; $Level <= $MaxLevel; $Level++)
+  {
+    echo('Uroven '.$Level."\n");
+    $TimeRange = GetTimeRange($Measure, $Level-1);
+    //echo($Measure['id'].','.($Level-1)."\n");
+    //echo(TimeToMysqlDateTime($TimeRange['left']).'-'.TimeToMysqlDateTime($TimeRange['right'])."\n");
+    $TimeSegment = TimeSegment($Level);
+    $StartTime = AlignTime($TimeRange['left'], $TimeSegment) - $TimeSegment;
+    $EndTime = AlignTime($TimeRange['right'], $TimeSegment);
+    $BurstCount = 500; 
+    echo('For 0 to '.round(($EndTime - $StartTime) / $TimeSegment / $BurstCount)."\n");
+    for($I = 0; $I <= round(($EndTime - $StartTime) / $TimeSegment / $BurstCount); $I++)
+    {
+      echo($I.' ');
+      $StartTime2 = $StartTime + $I * $BurstCount * $TimeSegment;
+      $EndTime2 = $StartTime + ($I+1) * $BurstCount * $TimeSegment;
+      $Values = array();
+      DB_Select(StatTableName($Level-1), '*', 'time > "'.TimeToMysqlDateTime($StartTime2).'" AND time < "'.
+        TimeToMysqlDateTime($EndTime2).'" AND measure='.$Measure['id'].' AND level='.($Level-1).' ORDER BY time');
+      while($Row = DB_Row())
+      {
+        $Row['time'] = MysqlDateTimeToTime($Row['time']);
+        $Values[] = $Row;
+      }
+      
+      if(count($Values) > 0)
+      {        
+        $Values = array_merge(LoadLeftSideValue($Level-1, $Measure, $StartTime2), $Values, LoadRightSideValue($Level-1, $Measure, $EndTime2));
+ 
+        $StartIndex = 0;
+        for($B = 0; $B < $BurstCount; $B++)
+        {          
+          echo('.');
+          $StartTime3 = $StartTime2 + (($EndTime2 - $StartTime2) / $BurstCount) * $B;
+          $EndTime3 = $StartTime2 + (($EndTime2 - $StartTime2) / $BurstCount) * ($B+1);
+          
+          $EndIndex = $StartIndex;
+          while($Values[$EndIndex]['time'] < $EndTime3) $EndIndex = $EndIndex + 1;
+          $SubValues = array_slice($Values, $StartIndex, $EndIndex - $StartIndex + 1);
+          //echo($StartIndex.','.$EndIndex.' '.count($SubValues).'<br>');
+          //print_r($SubValues);
+          if(count($SubValues) > 2)
+          {        
+            $Point = ComputeOneValue($StartTime3, $EndTime3, $SubValues, $Measure, $Level);
+            $Continuity = $SubValues[1]['continuity'];   
+            DB_Insert(StatTableName($Level), array('level' => $Level, 'measure' => $Measure['id'], 'min' => $Point['min'], 
+              'avg' => $Point['avg'], 'max' => $Point['max'], 'continuity' => $Continuity, 'time' => TimeToMysqlDateTime($StartTime3+($EndTime3-$StartTime3)/2)));
+          }        
+          $StartIndex = $EndIndex - 1;  
+        }
+      }
+      // Load values in time range
+      //array_pop($NextValues);
+    }  
+    echo("Uroven dokoncena\n");         
+    DB_Select('stat_data', 'COUNT(*)', 'level='.$Level.' AND measure='.$Measure['id']);
+    $Row = DB_Row();
+    echo("Vlozeno ".$Row[0]." polozek.\n");
+  } 
+}   
+
+function RebuildAllMeasuresCache()
+{
+  global $ReferenceTime, $LevelReducing, $MaxLevel;
+  
+  
+//  echo("Vytvarim novou cache...\n");
+    // Load measures
+  $Measures = array();
+  DB_Select('stat_measure', '*');
+  while($Measures[] = DB_Row());
+  array_pop($Measures);
+
+  foreach($Measures as $Measure)
+  {
+    RebuildMeasureCache($Measure);  
+    echo('Velicina dokoncena<br>');         
+  }
+}
+
+?>
Index: /style.css
===================================================================
--- /style.css	(revision 1)
+++ /style.css	(revision 1)
@@ -0,0 +1,295 @@
+body {
+	font-family: Arial, Helvetica, sans-serif;
+}
+
+li.Tree {
+	list-style: outside url(images/blank.png);
+	margin-left: -20px;
+	padding: 0px 0px 0px -10px;
+	cursor: pointer;
+}
+
+li.Open {
+	list-style: outside url(images/open.png);
+	margin-left: 0px;
+	padding: 0px 0px 0px -10px;
+	cursor: pointer;
+}
+
+li.Close {
+	list-style: outside url(images/close.png);
+	margin-left: 0px;
+}
+
+ul.NoEnd {
+	margin-left: 20px;
+	padding-left: 20px;
+	background-repeat: repeat-y;
+	background-image: url(images/line1.png);
+}
+
+ul.End {
+	margin-left: 20px;
+	padding-left: 20px;
+}
+
+div.NewsItem {
+	
+}
+
+div.NewsItemContent {
+}
+
+div.NewsItemLink {
+	display: inline;
+	padding-right: 5px;
+}
+
+div.NewsTreeItem {
+	
+}
+
+#MainTitle {
+	background-color: #F08080;
+	padding: 1px 10px 0px 10px;
+	margin-top: 0px;
+	margin-left: 0px;
+	border-bottom-style: dotted;
+	border-bottom-width: thin;
+	color: White;
+}
+
+#MainTitleText {
+	margin: 2px 0px 2px 0px;
+	padding: 0px 0px 0px 0px;
+	background-repeat: no-repeat;
+}
+
+#MainMenu {
+	background-color: #F5F5F5;
+	padding: 2px 5px 2px 5px;
+	margin-top: 0px;
+	border-bottom-style: dotted;
+	border-bottom-width: thin;
+}
+
+form {
+	padding: 0px 0px 0px 0px;
+	margin: 0px 0px 0px 0px;
+}
+
+.MenuItem {
+	padding: 2px 3px 1px 3px;
+	float: left;
+}
+
+.MenuItem2 {
+	padding: 0px 3px 0px 3px;
+	margin-top: 0px;
+	text-align: right;
+	width: 100%;	
+}
+
+#Online {
+	padding: 1px 3px 2px 3px;
+	display: inline;
+	right: 10px;
+}
+
+#Content {
+	padding: 4px 10px 10px 10px;
+	margin-left: 0px;
+}
+
+div.NewsItem {
+	border: thin dotted #97ADFF;
+	background: #F6F7FF;
+	margin-top: 5px;
+	padding: 0px 5px 5px 5px;
+}
+
+h4.NewsItemTitle {
+	border-bottom-width: thin;
+	border-bottom-style: solid;
+	margin-top: 0px;
+	margin-bottom: 0px;
+}
+
+#NewsGroupTree {
+	margin-left: -20px;
+}
+
+#NewsGroupTreeSection {
+	float: left;
+	width: 50%;
+}
+
+#NewsGroupTreeTitle {
+	padding: 0px;
+	border-bottom-color: Silver;
+	border-bottom-style: solid;
+	border-bottom-width: thin;
+}
+
+#NewsSection {
+	margin: 0px 0px 0px 50%;
+	}
+	
+#NewsSection {
+	
+}
+
+#AddNewsForm {
+	
+}
+
+div.Form {
+	border: thin solid;
+	background: #F0F8FF;
+	padding: 0px;
+	width: 450px;
+	padding: 5px 5px 5px 5px;
+}
+
+#AdminInfo {
+	clear: both;
+	border-top-style: dotted;
+	border-top-width: thin;
+	text-align: center;
+	font-size: smaller;
+	margin-top: 0px;
+	padding-top: 0px;
+}
+
+table.Table {
+	border: thin dotted;
+}
+
+table.Table tr td {
+	font-size: smaller;
+	border: thin dotted;
+	padding: 1px 3px 1px 3px;
+	margin: 0px 0px 0px 0px;
+}
+
+table.Table tr th {
+	background: #F6F6F6;
+	font-size: smaller;
+	border: thin dotted;
+	padding: 1px 3px 1px 3px;
+	margin: 0px 0px 0px 0px;
+}
+
+h3 {
+	font-size: large;
+	padding: 0px 0px 0px 0px;
+	margin: 0px 0px 0px 0px;
+}
+
+li a img {
+	padding: 0px 0px 0px 0px;
+	border: none;
+}
+
+#rsslink
+{
+	text-align: right;
+}
+
+#NewsList table
+{
+}
+
+#NewsList h3
+{
+	border-bottom-color: Silver;
+	border-bottom-style: solid;
+	border-bottom-width: thin;
+	margin-bottom: 5px;
+}
+
+div.sysmessage
+{
+	background: #ffe0e0;
+	border-left-width: 10;
+	border-left-color: Red;
+	border-left-style: solid;
+	padding: 5px 5px 5px 5px;
+	font-size: medium;
+	color: Maroon;
+	margin-top: 5px;
+	margin-bottom: 5px;
+}
+
+div.Title
+{
+	border-bottom-color: Silver;
+	border-bottom-style: solid;
+	border-bottom-width: thin;
+	font-size: large;
+	font-weight: bold;
+	margin-bottom: 5px;
+}
+
+#odber {
+	font-size: small;
+	font-style: italic;
+}
+
+Table2 {
+	border: 0px;
+}
+
+Table2 tr {
+	background-color: #d9dCFF;
+}
+
+Table2 th {
+	background-color: #897CFF;
+	color: White;
+}
+
+Table2 td {
+  padding: 3 3 3 3;
+}
+
+.StatTable {
+	font-size: small;
+	margin-left: auto;
+	margin-right: auto;
+	margin-bottom: 16px;
+	border-left: thin solid Black;
+	border-top: thin solid Black;
+}
+
+.StatTable th {
+	background-color: #e8e8ff;
+	border-right: thin solid Black;
+	border-bottom: thin solid Black;
+}
+
+.StatTable td {
+	border-right: thin solid Black;
+	border-bottom: thin solid Black;
+	padding: 3px 3px 3px 3px;
+}
+
+.StatTable tr {
+	border: thin solid Black;
+}
+
+.StatList {
+	text-align: center;
+	margin-bottom: 16px;
+}
+
+.SourceCode {
+	font-family: monospace;
+	font-size: larger;
+	border: solid #dddddd 1px;
+	background-color: #FFFFF0;
+	padding: 6px;
+	float: none;
+	page: auto;
+	width: auto;
+}
