ACC SHELL

Path : /srv/www/vhosts/agroing/web/helpers/
File Upload :
Current File : /srv/www/vhosts/agroing/web/helpers/tools_helper.php

<?php
class Tools {

	protected static $instance;
	public static $db; // if is not defined, log is disabled

    public static function get_instance(){
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

	// escape data for DB
	public static function escape(&$data){
		if(is_array($data)){
			foreach($data as $i=>$d){
				if(is_array($d)){
					self::escape($data[$i]);
					continue;
				}
				$data[$i] = str_replace(array("\\","'","\""),array("\\\\","\\'","\\\""),$d);
			}
		}else{
			$data = str_replace(array("\\","'","\""),array("\\\\","\\'","\\\""),$data);
		}
		return $data;
	}

	// types used for flash messages and log
	private static $types = array("critical","alert","warn","succ","debug","log");

	/**
	 * Save message in session to later print (also in log)
	 *
	 * @param string $message
	 * @param string $type one of defined [succ|warn|alert|critical|debug|log]
	 * @return bool
	 */
    public static function flash ($message,$type = "alert") {
		$type = strtolower($type);
		self::write_log($message,$type);
        $_SESSION['flashMessages'][$type][] = $message;
	}
	public static function succ ($message) { self::flash($message,"succ"); }
	public static function warn ($message) { self::flash($message,"warn"); }
	public static function alert ($message) { self::flash($message,"alert"); }
	public static function critical ($message) { self::flash($message,"critical"); }
	public static function debug ($message) { self::flash($message,"debug"); }			// uvidí vždy programátor
	public static function log ($message) { self::flash($message,"log"); }	// uvidí programátor po nastavení

	/**
	 * prints (or return) html-list of errors
	 * @param bool $inline
	 */
	public static function printFlash($inline = true) {
		$result = "";
		if(!empty($_SESSION['flashMessages'])){
			$mail = "";
			foreach (self::$types as $type){
				$print = "";
				$printed = array();
				if(!empty($_SESSION['flashMessages'][$type])){
					$mail .= "\n".strtoupper($type).":\n";
					foreach ($_SESSION['flashMessages'][$type] as $i => $message) {
						if(!in_array($message,$printed)){
							$printed[] = $message;
							$print .= '<li>' . $message . '</li>';
							$mail .= "\n$message\n";
						}
						unset($_SESSION['flashMessages'][$type][$i]);
					}
				}
				if($print &&
					($type!="log" || SEE_LOG) &&
					($type!="debug" || !PRODUCTION) 
					){
					$result .= "<ul class='flash-all flash-". $type ."'>". $print ."</ul>\n\n";
				}
			}
			if(PRODUCTION && strpos($mail,"CRITICAL:")){ // mail criticals with context
				mail(CRITICALS_MAIL, "critical  from ". $_SERVER["SERVER_NAME"]  . $_SERVER["REQUEST_URI"], $mail);
			}
		}
		if($inline){
			echo $result;
		}else{
			return $result;
		}
    }

	private static function write_log($message,$type=""){
		static $log_file = false;
		if(!$log_file && !empty(Settings_model::$settings['name'])){
			$log_file = @fopen("./w/".Settings_model::$settings['name']."/log.log","a");
		}
		if(!empty($log_file)){
			$message = "\n[". date('Y-m-d H:i:s') . ']' . ($type?'['.$type.']':'') . ' ' . $message;
			fwrite($log_file,$message);
			return true;
		}
		// not using fclose() because of speed
		return false;
	}

	public static function rozmezi ($d1,$d2=""){
		if(!$d2 || $d2<=$d1) return date("j.n.Y",strtotime($d1));
		if(date("Y",strtotime($d1))!=date("Y",strtotime($d2))){
			$prvni = date("j.n.Y",strtotime($d1));
		}elseif(date("n",strtotime($d1))!=date("n",strtotime($d2))){
			$prvni = date("j.n.",strtotime($d1));
		}else{
			$prvni = date("j.",strtotime($d1));
		}
		return $prvni . " - " . date("j.n.Y",strtotime($d2));
	}
	
	public static function cz_date($db_date){
		if(strpos($db_date,date("Y-m-d"))!==false) return "dnes";
		if(strpos($db_date,date("Y-m-d",time()-3600*24))!==false) return "včera";
		return date("j. n. Y",strtotime($db_date));
	}

	public static function analytics($gid){
		if($gid) return "<script type=\"text/javascript\">\n  var _gaq = _gaq || [];\n  _gaq.push(['_setAccount', '".$gid."']);\n  _gaq.push(['_trackPageview']);\n  (function() {\n	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n})();\n</script>";
	}

	public static function str2url($text){
		if (is_string($text)){
			$prevodni_tabulka = Array( ' - '=>'-', ' '=>'-', "…"=>"", " "=>"-", "–"=>"", "“"=>"", '"'=>"", "'"=>"","/"=>"", "\\"=>"","&"=>"-","?"=>"",","=>"","("=>"",")"=>"","®"=>"","™"=>"",":"=>"","+"=>"","\n"=>"","\r"=>"",
				'ä'=>'a','Ä'=>'A','á'=>'a','Á'=>'A','à'=>'a','À'=>'A','ã'=>'a','Ã'=>'A','â'=>'a','Â'=>'A',	  'č'=>'c','Č'=>'C','ć'=>'c','Ć'=>'C','ď'=>'d','Ď'=>'D','ě'=>'e','Ě'=>'E','é'=>'e','É'=>'E','ë'=>'e','Ë'=>'E','è'=>'e','È'=>'E','ê'=>'e','Ê'=>'E','í'=>'i','Í'=>'I','ï'=>'i','Ï'=>'I','ì'=>'i','Ì'=>'I','î'=>'i','Î'=>'I','ľ'=>'l','Ľ'=>'L','ĺ'=>'l','Ĺ'=>'L','ń'=>'n','Ń'=>'N','ň'=>'n','Ň'=>'N','ñ'=>'n','Ñ'=>'N','ó'=>'o','Ó'=>'O','ö'=>'o','Ö'=>'O','ô'=>'o','Ô'=>'O','ò'=>'o','Ò'=>'O','õ'=>'o','Õ'=>'O','ő'=>'o','Ő'=>'O','ř'=>'r','Ř'=>'R','ŕ'=>'r','Ŕ'=>'R','š'=>'s','Š'=>'S','ś'=>'s','Ś'=>'S','ť'=>'t','Ť'=>'T','ú'=>'u','Ú'=>'U','ů'=>'u','Ů'=>'U','ü'=>'u','Ü'=>'U','ù'=>'u','Ù'=>'U','ũ'=>'u','Ũ'=>'U','û'=>'u','Û'=>'U','ý'=>'y','Ý'=>'Y','ž'=>'z','Ž'=>'Z','ź'=>'z','Ź'=>'Z'		);
			$r = strtolower(strtr($text, $prevodni_tabulka));
			$result = "";
			for($i=0;$i<strlen($r);$i++){
				$ord = ord($r[$i]);
				if ($ord > 44 && $ord < 123) {
					$result .=  $r[$i];
				}else{
					$result .=  "-";
				}
			}
			return $result;
		}
		return "";
	}

	public static function truncate($text,$lenght=150,$alias="..."){
		if (is_string($text))
		{
			$text = strip_tags($text);
			$result = mb_substr($text,0,$lenght-mb_strlen($alias));
			if(mb_strlen($result) == ($lenght-mb_strlen($alias))) $result .= $alias;
			return $result;
		}
		return "";
	}

	public static function truncate_span($text,$lenght=150,$alias="..."){
		$result = self::truncate($text,$lenght,$alias);
		$text = str_replace('"',"",  strip_tags($text));
		if(strlen($result)>=$lenght){
			return '<span title="'.$text.'">'.$result.'</span>';
		}else{
			return $result;
		}
	}

	public static function rand_str($len){
		// generování náhodného textu
		$pool = 'abcdefghijkmnopqrstuvwxyz23456789ABCDEFGHJKLMNPRSTUVWXYZ';
		$text = '';
		for ($i=0; $i < $len; $i++) {
			$text .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
		}
		return $text;
	}

	// generovani variabilniho symbolu z ID
	public static function vs($id){
		$_vs = strval($id);
		$length = strlen($_vs);
		$vs = date("y");
		for ($i=$length;$i<6;$i++)
			$vs .= "0";
		$vs .= $_vs;
		return $vs;
	}

	// TODO: smazat... všechny databázové úkony by měli být v modelech!
	private function db_connect(){
		mysql_pconnect(DB_HOST,DB_USER,DB_PASS);
		mysql_select_db(DB_DB);
	}

	/**
	 * vraci ip trochu dumyslnejsim zpusobem...
	 *
	 * @staticvar array $cache
	 * @param boolean $false_return [optional] kdyz je false tak v pripade ze nezjisti ip vrati "00.000.000.000", vychozi je true, takze vraci "false"
	 * @return string
	 */
	public static function ip_check($false_return=true) {
		static $cache=array('0'=>null,'1'=>null);
		$index=($false_return ? 1 : 0);
		$ip=false;
		if($cache[$index]===null){
			if (getenv('HTTP_CLIENT_IP')) {$ip = getenv('HTTP_CLIENT_IP');}
			elseif (getenv('HTTP_X_FORWARDED_FOR')) {$ip = getenv('HTTP_X_FORWARDED_FOR');}
			elseif (getenv('HTTP_X_FORWARDED')) {$ip = getenv('HTTP_X_FORWARDED');}
			elseif (getenv('HTTP_FORWARDED_FOR')) {$ip = getenv('HTTP_FORWARDED_FOR');}
			elseif (getenv('HTTP_FORWARDED')) {$ip = getenv('HTTP_FORWARDED');}
			else {$ip = $_SERVER['REMOTE_ADDR'];}
			// false, nebo 00.000.000.000?
			if(empty($ip) && !$false_return){$ip = '00.000.000.000';}
			$cache[$index]=$ip;
		}
		// vystup
		return $cache[$index];
	}


	/**
	 * formatuje datum do ceskeho tvaru
	 *
	 * @param string $datetime
	 * @return string
	 */
	public static function czech_datetime($datetime){
		$dt=new DateTime($datetime);
		return $dt->format('d. m. Y, H:i');
	}

}

ACC SHELL 2018