<?php

/**
 * Knihovní třída s různými funkcemi
 *
 * @author Milan Lempera
 * @package Classes
 * @copyright Web-systems.cz  2009
 *
 */
class Tools {

  private function __construct() {
    die("Třída Tools je statická, nelze vytvářet její instance");
  }

  public static function getVar() {
    echo '<pre>';
    foreach (func_get_args() AS $i => $v){
      if ( $v === 'DIE' )
      die('</pre><br />ukončen běh scriptu -> fce. getVar');
      if (is_array($v))
      print_r($v);
      else
      var_dump($v);
    }
    echo '</pre>';
  }

  public static function arrayRecount(array $array) {
    $ret = array();
    foreach( $array as $value ) {
      $ret[] = $value;
    }
    return $ret;
  }

  public static function umenuLink($row) {
    if (URL_REWRITE) {
      return (URL.$row['CONTROLLER'].DIRSEP.$row['AKCE']);
    }
    else {
      return (URL.'index.php?route='.$row['CONTROLLER'].DIRSEP.$row['AKCE']);
    }
  }
  
  public static function controllerlink($controller, $akce = '', array $args = array()) {
    $array = array();
    $array[] = $controller;
    $array[] = $akce;
    $array = array_merge($array,$args);
    
    if (URL_REWRITE) {
      $ret = (URL.implode(DIRSEP, $array));
    }
    else {
      $ret = (URL.'index.php?route='.implode(DIRSEP, $array));
    }
    
    if (substr($ret,-1) != DIRSEP) {
      $ret .= DIRSEP;
    }
    
    return $ret;
  }

  public static function categoryLink($link) {
    
    if (URL_REWRITE) {
      $ret = (URL.'kategorie'.DIRSEP.$link);
    }
    else {
      $ret = (URL.'index.php?route='.'kategorie'.DIRSEP.$link);
    }
    
    if (substr($ret,-1) != DIRSEP) {
      $ret .= DIRSEP;
    }
    
    return $ret;
  }
  
  public static function productLink($link) {
    
    if (URL_REWRITE) {
      $ret = (URL.'produkt'.DIRSEP.$link);
    }
    else {
      $ret = (URL.'index.php?route='.'produkt'.DIRSEP.$link);
    }
    
    if (substr($ret,-1) != DIRSEP) {
      $ret .= DIRSEP;
    }
    
    return $ret;
  }
  
  public static function productLinkId($id) {
    
  	$link = dibi::query('SELECT REWRITE_LINK FROM PRODUKT WHERE ID = %i',$id)->fetchSingle();

    if (URL_REWRITE) {
      $ret = (URL.'produkt'.DIRSEP.$link);
    }
    else {
      $ret = (URL.'index.php?route='.'produkt'.DIRSEP.$link);
    }
    
    if (substr($ret,-1) != DIRSEP) {
      $ret .= DIRSEP;
    }
    
    return $ret;
  }
  
  public static function addLink(&$item, $key, array $args = array()) {
  	foreach($args as $key=>$value) {
  	  if (isset($value['target'])) {
        $value['target'] = ' target="'.$value['target'].'"';
      }
      else {
        $value['target'] = '';
      }
      if (isset($value['key'])) {
      	$value['text'] = $item[$value['key']];
      }
  		if (isset($value['click'])) {
        $value['click'] = ' onclick="'.$value['click'].'"';
      }
      else {
        $value['click'] = '';
      }
      if (isset($value['link'])) {
    		$item[$key] = '<a'.@$value['target'].' '.$value['click'].' href="'.$value['link'].$item[$value['addindex']].'">'.$value['text'].'</a>';
      }
      else {
      	$item[$key] = $value['text'];
      }
    }
  }
  
  public static function addText(&$item, $key, array $args = array()) {
   	$item[$key] = $value['text'];
  }

  public static function redirect($url){
    if (!headers_sent()) {
      header("HTTP/1.1 301 Moved Permanently");
      header('Location: '.$url);
      die;
    }
    else {
      echo '<script language="JavaScript" type="text/javascript">window.location.replace("'.$url.'");</script>';
      exit;
    }
  }

  public static function setMessage($message, $class = '', $persistent = 0, $toLog = false) {

    $registry = Registry::getInstance();

    if (empty($class)) {
      $class = CSS_MESS;
    }

    $class = (!empty($registry->to_message_class) ? $registry->to_message_class : $class);

    $message = $message.(!empty($registry->to_message) ? '<br />'.$registry->to_message : $registry->to_message);

    if ($persistent == 0) {
      $registry->add('message', $message);
      $registry->add('message_class', $class);
    }
    else {
      $registry->addPersistent('message', $message, $persistent );
      $registry->addPersistent('message_class', $class, $persistent );
    }
		Debug::addPoint('message',$message);

    if ($toLog) {
    	Logger::add($message);
    	Debug::addPoint('Logger::add',$message);
    }
    

  }

  public static function moveUploadedImage($item_name, $path, $file_name, $rewrite = false) {

    if (empty($file_name)) {
      return false;
    }
    
    if (substr($path,-1) != DIRSEP) {
      $path .= DIRSEP;
    }

    $nazev_obrazku = $path.$_FILES[$item_name]['name'];

    if (move_uploaded_file($_FILES[$item_name]['tmp_name'], $nazev_obrazku) ) {
    	chmod($nazev_obrazku, 0644);
      list($width, $height, $type, $atr) = getimagesize($nazev_obrazku);
      
      switch ( $type ) {
        case 1:
          $suffix = '.gif';
          break;

        case 2:
          $suffix = '.jpg';
          break;

        case 3:
          $suffix = '.png';
          break;

        default:
          throw new AppliException(1, 'Obrázek musí být typu JPG, GIF, nebo PNG !', '', 'Neplatný typ souboru');
          break;          
      }
      
      $novy_nazev = $path.$file_name.$suffix;

      if (file_exists($novy_nazev)) {
      	if ($rewrite) {

      		if (unlink($novy_nazev) == false) {
        		throw new AppliException(2, 'Chyba při mazání půvudního obrázku!', '', 'upload unlink error');
      		}

      		if (rename($nazev_obrazku,$novy_nazev) == false) {
        		throw new AppliException(2, 'Chyba při uploadu obrázku!', '', 'upload rename error');
      		}

      	}
      	else {
        	throw new AppliException(2, 'Chyba při uploadu obrázku - soubor již existuje!', '', 'upload rewrite disable');
      	}
      }
      else {

      	if (rename($nazev_obrazku,$novy_nazev) == false) {
        	throw new AppliException(2, 'Chyba při uploadu obrázku!', '', 'upload rename error');
      	}
      }

      return $file_name.$suffix;
      
    }
    else {
      throw new AppliException(2, 'Chyba při uploadu obrázku!', '', 'move uploaded error');
    }

  }

  public static function pictureResize($file_name, $orig_dir, $mini_dir, $type = 2, $rezim = 1, $rewrite = false) {

    if (empty($file_name)) {
      return false;
    }
    
    if (substr($orig_dir,-1) != DIRSEP) {
      $orig_dir .= DIRSEP;
    }

  	if (substr($mini_dir,-1) != DIRSEP) {
      $mini_dir .= DIRSEP;
    }
	  
	  $mini_dir = $orig_dir.$mini_dir;

	  $orig = $orig_dir.$file_name;
	  $mini = $mini_dir.$file_name;

	  if ( file_exists($orig) == true){
      $pict_size = GetImageSize($orig);
      
		if ($rewrite == false AND file_exists($mini)) {
			throw new AppliException(1, 'Soubor nelze přepsat');
		}
		else {
			if (file_exists($mini)) {
				unlink($mini);
			}
		}
      
      if ( ( $pict_size[1] > MAX_PICT_WIDTH ) OR ( $pict_size[2] > MAX_PICT_HEIGHT ) )
      	throw new AppliException(2, 'Doslo k chybe pri zpracovani obrazku!
        <br />Jedná se o chybu Prekrocení povolené velikosti<br />
        Maximální povolená velikost: <br />
        sirka: '.MAX_PICT_WIDTH.'px<br />
        vyska: '.MAX_PICT_HEIGHT.'px<br /><br />
        Velikost nahrávaného obrázku:<br /> 
        sirka: '.$pict_size[1].'px<br />
        vyska: '.$pict_size[1].'px' );
        
      $typ = $pict_size[2];
      switch ($typ){
        case 1:
          $pict = ImageCreateFromGIF($orig);        
          break;
        case 2:
          $pict = ImageCreateFromJPEG($orig);
          break;
        case 3:
          $pict = ImageCreateFromPNG($orig);
          $COULEUR_BLANC=imagecolorallocate($pict,255,255,255) ;
          break;
        default: 
          throw new AppliException(2, 'Neznámý typ obrázku');
      }
      
      $result = dibi::query('SELECT IF(SIRKA != "*", SIRKA, VYSKA) AS SIZE FROM PARAMETRY_OBRAZKU AS PO WHERE PO.ID = %i', $type);
      $size = $result->fetchSingle();
      $param = Tools::getPictureParam($rezim,$pict_size[0],$pict_size[1],$size);
      $new_pict=ImageCreateTruecolor($param['dst_w'],$param['dst_h']);

      if ($typ == 3) {
				$red = imagecolorallocate($new_pict, 255, 255, 255);
				imagefill($new_pict, 0, 0, $red);
      }
      $ok = imagecopyresampled($new_pict,$pict,
        $param['dst_x'],$param['dst_y'],$param['src_x'],$param['src_y'],
        $param['dst_w'],$param['dst_h'],$param['src_w'],$param['src_h']);
	    switch ($typ){
        case 1:
          $ok2 = imagegif($new_pict,$mini);        
          break;
        case 2:
          $ok2 = imagejpeg($new_pict,$mini, '75');
          break;
        case 3:
					//imagesavealpha($new_pict, true);
          $ok2 = imagepng($new_pict,$mini, '7', 0); 
          break;
        default:
          throw new AppliException(2, 'Neznámý typ obrázku');
      }
      ImageDestroy($pict);
      ImageDestroy($new_pict);
      if (!$ok or !$ok2) {
        throw new AppliException(2, 'Chyba při zpracování obrázku');
      }
	  }
	  else {
	  	throw new AppliException(2, 'Soubor neexistuje');
	  }

  }
  
  public static function getPictureParam($rezim,$widht,$height,$size){
	  $ret = array(
        'dst_x' => 0,
        'dst_y' => 0,
        'src_x' => 0,
        'src_y' => 0,
        'dst_w' => 0,
        'dst_h' => 0,
        'src_w' => $widht,
        'src_h' => $height
	    );
	    
	  if ( $rezim == 3){
	    if( $widht > $height )
	      $rezim = 2;
	    else
	      $rezim = 1;
	  }
	  
	  if ( $rezim == 4){
	  	if( $widht < $height )
	      $rezim = 2;
	    else
	      $rezim = 1;
	  }
	  
	  switch($rezim){
	    case 1:
	        $mini_width  = $size;
	        $mini_height = -1;
	        $dopocet = true;
	      break;
	    case 2:
	        $mini_height = $size;
	        $mini_width  = -1;
	        $dopocet = true;
	      break;
	    case 5:
	      $cut_pr = 5;
	      if( $widht > $height ){
          $cut_y = Ceil( $height / $cut_pr );
          $cut_x = Ceil( ( $widht - ( $height - (2*$cut_y))) / 2 );
        }
        else{
          $cut_x = Ceil( $widht / $cut_pr );
          $cut_y = Ceil( ( $height - ( $widht- (2*$cut_x))) / 2 ); 
        }
        
        $cut2_x = $widht - (2*$cut_x);
        $cut2_y = $height - (2*$cut_y);
        
        $ret['src_x'] = $cut_x;
        $ret['src_y'] = $cut_y;
        $ret['dst_w'] = $size;
        $ret['dst_h'] = $size;
        $ret['src_w'] = $cut2_x;
        $ret['src_h'] = $cut2_y;
        
 	      $dopocet = false;
	      break;
	  }
	  if ($dopocet === true){
      if ($mini_height == -1)
        $mini_height=($height*$mini_width)/$widht;
	    elseif ($mini_width == -1)
	      $mini_width=($widht*$mini_height)/$height;
    
	    $ret['dst_w'] = $mini_width;
	    $ret['dst_h'] = $mini_height;
	  }
	  
	  return $ret;
	}

  public static function deleteFile($name, $path) {
  	if (file_exists($path.$name)) {
  		if (unlink($path.$name) == false) {
	    	throw new AppliException(2, 'Chyba při mazání souboru!', '', 'unlink error');
    	}
  	}
    else {
    	throw new AppliException(1, 'Soubor, který se pokoušíte smazat neexistuje!', '', 'file_exists false');
    }
  }

  public static function toURL($text) {

    $utf8table = array (
    		'ä'=>'a',
        'Ä'=>'A',
        'á'=>'a',
        'Á'=>'A',
        'č'=>'c',
        'Č'=>'C',
        'ć'=>'c',
        'Ć'=>'C',
        'ď'=>'d',
        'Ď'=>'D',
        'ě'=>'e',
        'Ě'=>'E',
        'é'=>'e',
        'É'=>'E',
        'ë'=>'e',
        'Ë'=>'E',
        'í'=>'i',
        'Í'=>'I',
        'ľ'=>'l',
        'Ľ'=>'L',
        'ń'=>'n',
        'Ń'=>'N',
        'ň'=>'n',
        'Ň'=>'N',
        'ó'=>'o',
        'Ó'=>'O',
        'ö'=>'o',
        'Ö'=>'O',
        'ř'=>'r',
        'Ř'=>'R',
        'ŕ'=>'r',
        'Ŕ'=>'R',
        'š'=>'s',
        'Š'=>'S',
        'ś'=>'s',
        'Ś'=>'S',
        'ť'=>'t',
        'Ť'=>'T',
        'ú'=>'u',
        'Ú'=>'U',
        'ů'=>'u',
        'Ů'=>'U',
        'ü'=>'u',
        'Ü'=>'U',
        'ý'=>'y',
        'Ý'=>'Y',
        'ž'=>'z',
        'Ž'=>'Z',
        'ź'=>'z',
        'Ź'=>'Z',
        ' '=>'_'
    );
    
    $text =  strtolower(strtr($text, $utf8table));

    if (ereg('^[a-z_0-9\-]*$',$text) != true) {
      $n = strlen($text);
      $out = '';
      for($i = 0; $i < $n; $i++) {
        $znak = substr($text,$i,1);
        $asci = ord($znak);
        if ( ($asci >= 97 AND $asci <=122) OR ($asci >= 48 AND $asci <=57) OR ($asci == 95) OR ($asci == 45) ) { // a - z OR _ OR -
          $out .= $znak;
        }
        else {
              // nepřidávat nic
        }
      }
      $text = $out;
    }

    return $text;
  }

  public function explodeDate($date){
    $pole = explode('-',$date);
    return array($pole[2], $pole[1], $pole[0]);
  }

  public static function dateToCZ($date, $time = true){
   	if (!empty($date)) {
      $pole = explode(' ',$date);
      $date = explode('-',$pole[0]);
      if ($time == true AND !empty($pole[1])) {
       	return @$date[2].'.'.@$date[1].'.'.@$date[0].' '.@$pole[1];
      }
      else {
      	return @$date[2].'.'.@$date[1].'.'.@$date[0];
      }
   	}
  }

  public static function dateToENG($date, $time = true){
   	if (!empty($date)) {
      $pole = explode(' ',$date);
      $date = explode('.',$pole[0]);
      if ($time == true AND !empty($pole[1])) {
      	return $date[2].'-'.$date[1].'-'.$date[0].' '.$pole[1];
      }
      else {
      	return $date[2].'-'.$date[1].'-'.$date[0];
      }
   	}
  }

   public static function getURL($url) {
  	if (!empty($url)) {
    	@$sub = substr($url,0,7);
    	if ($sub != 'http://') {
    		return 'http://'.$url;
    	}
    	else{
    		return $url;
    	}
  	}
  	return '';
  }

	public static function numberFromDE($number){
		return str_replace(',','.',$number);
	}

	 public static function numberToInput($number, $des = 2){
		return number_format($number,$des,',', '');
	}

	 public static function numberFromDb($number, $des = 2){
		return number_format($number,$des,',', ' ');
	}

}
?>