<?php

 function mult_sort($mass,$KEY,$ASC = 'SORT_ASC') { 
    $sort_arr = array(); 
    foreach($mass AS $uniqid => $row){ 
        foreach($row AS $key=>$value){ 
            $sort_arr[$key][$uniqid] = $value; 
        } 
    } 
    array_multisort($sort_arr[$KEY],constant($ASC),$mass);     
    return $mass; 
  }
    
 function pr($arg) {
   
   $is_cli = false;
   if (php_sapi_name() == 'cli') {
      $is_cli = true;
   }


   if ($is_cli) echo PHP_EOL; else echo "<xmp>";
   if (!isset($arg)) echo "pr(): value not set";
   elseif (is_object($arg)) echo print_r($arg);
   elseif (is_bool($arg)) if($arg) echo "true"; else echo "false";
   elseif (!is_array($arg)) echo "pr() string: '$arg'";
   elseif (!count($arg)) echo "pr(): array empty";
   else print_r($arg);
   if ($is_cli) echo PHP_EOL; else echo "</xmp>";

 }

 function cdie( $text = '' ) {
 	global $auth;
 	if (isset($auth)){
    	$auth->saveSession();
    }
 	die( $text . '<br><a href="?cat=index">Перейти на главную страницу</a>' );	 
 }

 function ajax_send( $text = '' ) {
 	global $auth;
    $auth->saveSession();
 	die( $text );	 
 }


function _redirect($url='', $frame_msg = 'OK', $frame_redirect = false)  {
  
  // Сохраняем сессию
  global $auth;
  if ( is_object($auth) ) {
    $auth->saveSession();
  }
  
  // Если ajax запрос
  if ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) {

  	if ($_POST['ajaxsubmit'] || $_GET['ajaxsubmit']) {
  		$resp = [];
  		$resp['html'] = $frame_msg;
  		if ($url) {
  			$resp['redirect'] = $url;
  		} else {
  			$resp['reload'] = true;
  		}
  		echo json_encode($resp);
  		exit();
  	} else {
    	echo '<div class="popup-container">';
        echo $frame_msg;
        echo '</div>';
  		if ( $url ) {
  			echo "<script>function closeMyModal() { location.href='".$url."'; }</script>";
  		} else {
  			echo '<script>function closeMyModal() { location.reload(); }</script>';
  		}
        echo '<script> setTimeout( closeMyModal ,1000 ); </script>';
        exit();
    }
  }
  
  // Если ничего из прошлого - просто редирект
  if (!$url ) $url = _SITE_ROOT_;
  Header ('Location: '.$url, true, 301);
  exit();

}

 function _getcurl ($isk='') {
   if (!is_array($isk)) $iskl[] = $isk;
      else $iskl=$isk;
   		foreach ($_GET as $key => $val) {
   		  if (!is_array($val)) {
		  	$val = htmlspecialchars($val);
	      	if (!in_array($key,$iskl))
				$cmass[]="$key=$val";
	 	  } else {
             $cmass[] = http_build_query(array($key=>$val));
	 		}
   		}
   $curl = "?" . @implode('&', $cmass);
   return $curl;
 }


function _getMonthName($day, $skl = false) { 
   $day = intval($day);
   $months = array (
    1 => 'Январь',
    2 => 'Февраль',
    3 => 'Март',
    4 => 'Апрель',
    5 => 'Май',
    6 => 'Июнь',
    7 => 'Июль',
    8 => 'Август',
    9 => 'Сентябрь',
    10 => 'Октябрь',
    11 => 'Ноябрь',
    12 => 'Декабрь'
   );
   $months_skl = array (
    1 => 'января',
    2 => 'февраля',
    3 => 'марта',
    4 => 'апреля',
    5 => 'мая',
    6 => 'июня',
    7 => 'июля',
    8 => 'августа',
    9 => 'сентября',
    10 => 'октября',
    11 => 'ноября',
    12 => 'декабря'
   );
	   if ($skl ) {
	   		return $months_skl[$day];
	   } else {
	   return $months[$day];
	 	} 
 } 

function _getNedName($day, $full = true) { 
   $day = intval($day);
   if ($full) {
       $months = array (
        0 => 'Воскресение',
        1 => 'Понедельник',
        2 => 'Вторник',
        3 => 'Среда',
        4 => 'Четверг',
        5 => 'Пятница',
        6 => 'Суббота',
        7 => 'Воскресение',
       );
   } else {
       $months = array (
        0 => 'Вс',
        1 => 'Пн',
        2 => 'Вт',
        3 => 'Ср',
        4 => 'Чт',
        5 => 'Пт',
        6 => 'Сб',
        7 => 'Вс',
       );
   }
   return $months[$day];
 } 
 
 function trim_array( $val ) {
 	return array_diff($val, array(''));
 }
 /* karnaval utils */
 
 
 function translit($str)
  {
    $tr = array(
        "А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
        "Д"=>"D","Е"=>"E","Ё"=>"E","Ж"=>"Zh","З"=>"Z","И"=>"I",
        "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
        "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
        "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"C","Ч"=>"Ch",
        "Ш"=>"Sh","Щ"=>"Sch","Ъ"=>"","Ы"=>"Y","Ь"=>"",
        "Э"=>"E","Ю"=>"Yu","Я"=>"Ya","а"=>"a","б"=>"b",
        "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ё"=>"e","ж"=>"zh",
        "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
        "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
        "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
        "ц"=>"c","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"",
        "ы"=>"y","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"," "=>"-","("=>"",")"=>"","'"=>"",'"'=>""
      );
      return strtr($str,$tr);
  }
 
 
 function nf($str, $color = false) {
     $c = number_format($str, 0, '.', ' ');
     if ($color) {
       if ($str < 0 ) {
          return '<font color="red">'.$c.'</font>';   
       } else {
          return '<font color="green">'.$c.'</font>';   
       }
     } else {
        return $c;   
     }
 }
  
 function mf($str) {
     return number_format($str, 2, '.', ' ');
 }
 
  //цена прописью
  function int2word($price)
  {
    $price = number_format($price, 2, '.', '');
    $point = strpos($price, '.');
    //отделяем рубли от копеек
    if(!empty($point))
    {
      $rub = substr($price, 0, $point);
      $kop = substr($price, $point + 1);
    }
    //преобразуем рубли
    $str = write_number_in_words($rub) ;
    //пишем рублей(ь,я)
    $word = " рублей";
    //последнее число
    $last_digit = $rub[(strlen($rub) - 1)];
    //предпоследнее число
    $pred_last_digit = $rub[(strlen($rub) - 2)];
    if($last_digit == '1' && $pred_last_digit != '1')
      $word = " рубль";
    elseif(($last_digit == '2' || $last_digit == '3' || $last_digit == '4') && $pred_last_digit != '1')
      $word = " рубля";
    $str .= $word;
    //преобразуем копейки
    if(!empty($kop))
    {
 
      $str .= write_number_in_words($kop, 'femininum') ;
      //пишем копейка (и, ек)
      $word = " копеек";
      //последнее число
      $last_digit = $kop[(strlen($kop) - 1)];
      //предпоследнее число
      $pred_last_digit = $kop[(strlen($kop) - 2)];
      if($last_digit == '1' && $pred_last_digit != '1')
               $word = " копейка";
             elseif(($last_digit == '2' || $last_digit == '3' || $last_digit == '4') && $pred_last_digit != '1' )
               $word = " копейки";
      $str .= $word;
    }
    return $str;
  }
 
  //допустимый диапазон чисел 0 .. 999999
  //число прописью
  function write_number_in_words ($num, $genus = 'masculinum')
  {
    //разряд: единицы, десятки, сотни, тысячи
    $cur_order = "единицы";
    $cur_thousands_order = "единицы";
    if($num == 0)
      return " 00";
    $num = strval($num);
    $limit = strlen($num) - 1;
    for($i = $limit; $i >= 0; $i--)
    {
      //тысячный разряд
      if($cur_order == "тысячи")
      {
        //сотни
        if($cur_thousands_order == "сотни")
        {
          $str = write_units_hundreds($num[$i]).$str;
        }
        //десятки
        if($cur_thousands_order == "десятки")
        {
          $str = write_units_tens($num[$i], $next_digit).$str;
          $cur_thousands_order = "сотни";
          $next_digit = '';
        }
        //единицы
        if($cur_thousands_order == "единицы")
        {
          if($i > 0 && $num[$i-1] == "1")
          {
            $next_digit = $num[$i];
            $str = " тысяч".$str;
          }
          else
            $str = write_units_thousands_units($num[$i]).$str;
          $cur_thousands_order = "десятки";
        }
      }
      //сотни
      if($cur_order == "сотни")
      {
        $str = write_units_hundreds($num[$i]).$str;
        $cur_order = "тысячи";
      }
      //десятки
      if($cur_order == "десятки")
      {
        $str = write_units_tens($num[$i], $next_digit).$str;
        $cur_order = "сотни";
        $next_digit = '';
      }
      //единицы
      if($cur_order == "единицы")
      {
        if($i > 0 && $num[$i-1] == "1")
          $next_digit = $num[$i];
        else
          $str = write_units($num[$i], $genus);
        $cur_order = "десятки";
      }
    }
    return($str);
  }
 
    //принадлежит функции write_number_in_words
    //преобразует десятки
    function write_units_tens ($tens, $next_digit)
    {
      $tens .= $next_digit;
      if($tens == 2) $str_tens = " двадцать";
      if($tens == 3) $str_tens = " тридцать";
      if($tens == 4) $str_tens = " сорок";
      if($tens == 5) $str_tens = " пятьдесят";
      if($tens == 6) $str_tens = " шестьдесят";
      if($tens == 7) $str_tens = " семьдесят";
      if($tens == 8) $str_tens = " восемьдесят";
      if($tens == 9) $str_tens = " девяносто";
      if($tens == 10) $str_tens = " десять";
      if($tens == 11) $str_tens = " одиннадцать";
      if($tens == 12) $str_tens = " двенадцать";
      if($tens == 13) $str_tens = " тринадцать";
      if($tens == 14) $str_tens = " четырнадцать";
      if($tens == 15) $str_tens = " пятнадцать";
      if($tens == 16) $str_tens = " шестнадцать";
      if($tens == 17) $str_tens = " семнадцать";
      if($tens == 18) $str_tens = " восемнадцать";
      if($tens == 19) $str_tens = " девятнадцать";
      return($str_tens);
    }
 
    //принадлежит функции write_number_in_words
    //преобразует сотни
    function write_units_hundreds ($hundreds)
    {
      if($hundreds == 1) $str_hundreds = " сто";
      if($hundreds == 2) $str_hundreds = " двести";
      if($hundreds == 3) $str_hundreds = " триста";
      if($hundreds == 4) $str_hundreds = " четыреста";
      if($hundreds == 5) $str_hundreds = " пятьсот";
      if($hundreds == 6) $str_hundreds = " шестьсот";
      if($hundreds == 7) $str_hundreds = " семьсот";
      if($hundreds == 8) $str_hundreds = " восемьсот";
      if($hundreds == 9) $str_hundreds = " девятьсот";
      return($str_hundreds);
    }
 
    //принадлежит функции write_number_in_words
    //преобразует единицы тысячного разряда
    function write_units_thousands_units ($hundreds)
    {
      if($hundreds == 0) $str_hundreds = " тысяч";
      if($hundreds == 1) $str_hundreds = " одна тысяча";
      if($hundreds == 2) $str_hundreds = " две тысячи";
      if($hundreds == 3) $str_hundreds = " три тысячи";
      if($hundreds == 4) $str_hundreds = " четыре тысячи";
      if($hundreds == 5) $str_hundreds = " пять тысяч";
      if($hundreds == 6) $str_hundreds = " шесть тысяч";
      if($hundreds == 7) $str_hundreds = " семь тысяч";
      if($hundreds == 8) $str_hundreds = " восемь тысяч";
      if($hundreds == 9) $str_hundreds = " девять тысяч";
      return($str_hundreds);
    }
 
    //принадлежит функции write_number_in_words
    //преобразует единицы
    function write_units ($units, $genus='masculinum')
    {
      if($genus == 'masculinum')
      {
         if($units == 1) $str_units = " один";
               if($units == 2) $str_units = " два";
      }
      if($genus == 'femininum')
      {
         if($units == 1) $str_units = " одна";
               if($units == 2) $str_units = " две";
 
      }
      if($units == 3) $str_units = " три";
      if($units == 4) $str_units = " четыре";
      if($units == 5) $str_units = " пять";
      if($units == 6) $str_units = " шесть";
      if($units == 7) $str_units = " семь";
      if($units == 8) $str_units = " восемь";
      if($units == 9) $str_units = " девять";
      return($str_units);
    } 
    
 
  /**
   * Переключает раскладку с англ. на русскую
   */
  function textswitch($text, $revert = false)  {


       $remap_table = ["q"=>"й","w"=>"ц","e"=>"у","r"=>"к","t"=>"е","y"=>"н","u"=>"г","i"=>"ш","o"=>"щ","p"=>"з","["=>"х","]"=>"ъ",
                       "a"=>"ф","s"=>"ы","d"=>"в","f"=>"а","g"=>"п","h"=>"р","j"=>"о","k"=>"л","l"=>"д",";"=>"ж","'"=>"э",
                       "z"=>"я","x"=>"ч","c"=>"с","v"=>"м","b"=>"и","n"=>"т","m"=>"ь",","=>"б","."=>"ю",
                       "Q"=>"Й","W"=>"Ц","E"=>"У","R"=>"К","T"=>"Е","Y"=>"Н","U"=>"Г","I"=>"Ш","O"=>"Щ","P"=>"З","{"=>"Х","}"=>"Ъ",
                       "A"=>"Ф","S"=>"Ы","D"=>"В","F"=>"А","G"=>"П","H"=>"Р","J"=>"О","K"=>"Л","L"=>"Д",":"=>"Ж",'"'=>"Э",
                       "Z"=>"Я","X"=>"Ч","C"=>"С","V"=>"М","B"=>"И","N"=>"Т","M"=>"Ь","<"=>"Б",">"=>"Ю","/"=>".","?"=>",",
                       "~"=>"Ё","@"=>'"',"#"=>"№","$"=>";","^"=>":","&"=>"?","|"=>"/","`"=>"ё"];

       if ($revert) {
        $remap_table = array_flip($remap_table);
       }

       return strtr($text, $remap_table);
  }  


function addLog($str, $file = "global_log" ) {
    $filename = _PROJECT_DIR.'engine/logs/'.$file.'_'.date('Y-m').'.log';

    if(!file_exists(dirname($filename))) {
        mkdir(dirname($filename), 0777, true);
        chmod(dirname($filename), 0777);
    }

    if (!file_exists($filename)) {
        file_put_contents($filename,"");
        chmod($filename, 0777);
    }

    file_put_contents($filename, '['.date('d.m.Y H:i:s')."]\n". $_SERVER['REMOTE_ADDR'] ."\n" . $str ."\n\n", FILE_APPEND );
}
    

  function getFirst() {
  	$args =  func_get_args();
  	foreach( $args as $v ){
  		if ($v) return $v;		
  	}
  }  
  function wordForm($n, $form1, $form2, $form5)  {
     $n = abs($n) % 100;
     $n1 = $n % 10;
     if ($n > 10 && $n < 20) return $form5;
     if ($n1 > 1 && $n1 < 5) return $form2;
     if ($n1 == 1) return $form1;
     return $form5;
  }    

  function admin_report($msg = '', $title = 'Оповещение для администрации') {
      if ($msg) {
        require_once( _CFG_DIR . '/core/mail.core.php' );
        $mail = new send_mail();
        $mail->to_pool( _ADMIN_MAIL, $title, $msg );
      }
  }

    function s_natksort(&$array) {
        $keys = array_keys($array);
        natcasesort($keys);

        foreach ($keys as $k) {
            $new_array[$k] = $array[$k];
        }

        $array = $new_array;
        return true;
    }

   


function column_sort($arr, $columns = 3) {
// Сортировка массива для вывода в нужное количество колонок 
    if ($columns < 2 ) return $arr;
    $acnt = count($arr);
    if ($columns >= $acnt ) {
         return $arr;
    }
    
    $karr = array_keys($arr);

    $step = ceil($acnt / $columns);
    $ost = $acnt % $columns;
    if (!$ost) $ost = $columns;
   
    for( $i = 0; $i < $step; $i++ ) {
        $step_once = $step;
        $k = 0;
        for( $j = $i; $j <= $acnt; $j+=$step_once ) {
            if (isset( $karr[$j] ) ) {
                $key = $karr[$j];
                $ret[] = $arr[$key];
            }
            if (++$k > $ost ) {
                $step_once = $step - 1;
            }
        }
    }

    /* Удаляем лишние элементы */    
    if (count($ret) > $acnt ) {
        $todel = count($ret) - $acnt;
        for( $i = 1; $i<=$todel; $i++ ) {
          array_pop($ret);
        }
        
    }

    return $ret;
}

function sec2str($sec, $reverse = false, $short = false, $ret_count = 0) {
   $data = secondsToTime($sec);
   $str = array();
   if (!$short ) {
       if ($data['d']) $str[] = $data['d'] . wordForm($data['d'], ' день', ' дня', ' дней');
       if ($data['h']) $str[] = $data['h'] . wordForm($data['h'], ' час', ' часа', ' часов');
       if ($reverse) {
           // склонение в прошлом
           if ($data['m']) $str[] = $data['m'] . wordForm($data['m'], ' минуту', ' минуты', ' минут');
           $str[] = $data['s'] . wordForm($data['s'], ' секунду', ' секунды', ' секунд');
       } else {
           if ($data['m']) $str[] = $data['m'] . wordForm($data['m'], ' минута', ' минуты', ' минут');
           $str[] = $data['s'] . wordForm($data['s'], ' секунда', ' секунды', ' секунд');
       }
   } else {
       if ($data['d']) $str[] = $data['d'] . ' дн';
       if ($data['h']) $str[] = $data['h'] .  ' ч';
       if ($data['m']) $str[] = $data['m'] .  ' мин';
       $str[] = $data['s'] . ' сек';
       
   }
   
   if ($ret_count) {
      $str = array_slice($str, 0, $ret_count);
    }

   return implode(" ", $str);
}


function secondsToTime($inputSeconds) {

    $secondsInAMinute = 60;
    $secondsInAnHour  = 60 * $secondsInAMinute;
    $secondsInADay    = 24 * $secondsInAnHour;

    // extract days
    $days = floor($inputSeconds / $secondsInADay);

    // extract hours
    $hourSeconds = $inputSeconds % $secondsInADay;
    $hours = floor($hourSeconds / $secondsInAnHour);

    // extract minutes
    $minuteSeconds = $hourSeconds % $secondsInAnHour;
    $minutes = floor($minuteSeconds / $secondsInAMinute);

    // extract the remaining seconds
    $remainingSeconds = $minuteSeconds % $secondsInAMinute;
    $seconds = ceil($remainingSeconds);

    // return the final array
    $obj = array(
        'd' => (int) $days,
        'h' => (int) $hours,
        'm' => (int) $minutes,
        's' => (int) $seconds,
    );
    return $obj;
}


function getImagePath($val) {
    $val = sprintf('%02d/%02d/%d', substr(intval($val), 0, 2), substr(intval($val), 2, 2), $val );
    return $val;
}



function getImageUrl($val) {
    $val = sprintf('%02d/%02d/%d', substr(intval($val), 0, 2), substr(intval($val), 2, 2), $val);
    return _STATIC_ROOT_ . 'images/'.$val.'.jpg';
}


function gen_uuid() {
     $uuid = array(
      'time_low'  => 0,
      'time_mid'  => 0,
      'time_hi'  => 0,
      'clock_seq_hi' => 0,
      'clock_seq_low' => 0,
      'node'   => array()
     );

     $uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) << 16);
     $uuid['time_mid'] = mt_rand(0, 0xffff);
     $uuid['time_hi'] = (4 << 12) | (mt_rand(0, 0x1000));
     $uuid['clock_seq_hi'] = (1 << 7) | (mt_rand(0, 128));
     $uuid['clock_seq_low'] = mt_rand(0, 255);

     for ($i = 0; $i < 6; $i++) {
      $uuid['node'][$i] = mt_rand(0, 255);
     }

     $uuid = sprintf('%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
      $uuid['time_low'],
      $uuid['time_mid'],
      $uuid['time_hi'],
      $uuid['clock_seq_hi'],
      $uuid['clock_seq_low'],
      $uuid['node'][0],
      $uuid['node'][1],
      $uuid['node'][2],
      $uuid['node'][3],
      $uuid['node'][4],
      $uuid['node'][5]
     );

     return $uuid;
}


function time_ago( $timestamp = 0, $now = 0 ) {

    // Set up our variables.
    $minute_in_seconds = 60;
    $hour_in_seconds   = $minute_in_seconds * 60;
    $day_in_seconds    = $hour_in_seconds * 24;
    $week_in_seconds   = $day_in_seconds * 7;
    $month_in_seconds  = $day_in_seconds * 30;
    $year_in_seconds   = $day_in_seconds * 365;

    // Get the current time if a reference point has not been provided.
    if ( 0 === $now ) {
        $now = time();
    }

    // Make sure the timestamp to check is in the past.
    if ( $timestamp > $now ) {
        /*throw new Exception( 'Timestamp is in the future' );*/
        return 'в будущем';
    }

    // Calculate the time difference between the current time reference point and the timestamp we're comparing.
    $time_difference = (int) abs( $now - $timestamp );

    // Calculate the time ago using the smallest applicable unit.
    if ( $time_difference < $hour_in_seconds ) {
        $difference_value = round( $time_difference / $minute_in_seconds );
        $difference_label = array('минуту', 'минуты', 'минут');
    } elseif ( $time_difference < $day_in_seconds ) {
        $difference_value = round( $time_difference / $hour_in_seconds );
        $difference_label = array('час', 'часа', 'часов');
    } elseif ( $time_difference < $week_in_seconds ) {
        $difference_value = round( $time_difference / $day_in_seconds );
        $difference_label = array('день', 'дня', 'дней');
    } elseif ( $time_difference < $month_in_seconds ) {
        $difference_value = round( $time_difference / $week_in_seconds );
        $difference_label = array('неделю', 'недели', 'недель');
    } elseif ( $time_difference < $year_in_seconds ) {
        $difference_value = round( $time_difference / $month_in_seconds );
        $difference_label = array('месяц', 'месяца', 'месяцев');
    } else {
        $difference_value = round( $time_difference / $year_in_seconds );
        $difference_label = array('год', 'года', 'лет');
    }

 	$label = wordForm($difference_value, $difference_label[0], $difference_label[1], $difference_label[2]);
    $time_ago = sprintf( '%s %s назад',
        $difference_value,
        $label
    );
    

    return $time_ago;
}


function human_filesize($size, $precision = 2) {
    for($i = 0; ($size / 1024) > 0.9; $i++, $size /= 1024) {}
    return round($size, $precision).['Б','Кб','Мб','Гб','Тб','Пб','Еб','Зб','Юб'][$i];
}

function xml_escape($str ) {
	return htmlspecialchars($str, ENT_XML1 | ENT_COMPAT, 'UTF-8');	
}

function get_cfrm() {
	global $uauth;
	$ts = time();
	$data = md5($ts . $uauth->sess_id . $_SERVER['REMOTE_ADDR']);
    $data = $ts.'.'.$data;
	return $data;
}


function check_cfrm($str = '') {
	if ( !$str ) return false;
	global $uauth;
	list($ts,$data) = explode('.', $str);
	if ((time() - $ts) > 600) return false;
	$check = md5($ts . $uauth->sess_id . $_SERVER['REMOTE_ADDR']);
	if ($check != $data) return false;
	return true;
}


function ceilCoefficient($number, $rate = 50)
{
	// если число дробное, то округляем его до целого
	$number = ceil($number);
	// разделим число на коэффициент, а результат округлим в большую сторону. Потом умножим число на округленный коэффициент
	$rest = ceil($number / $rate) * $rate;
	return $rest;
}

function doDebug($level = 'errors') {
    switch ($level) {
        case 'full':
            error_reporting(E_ALL & ~E_NOTICE);
            break;
        default:
            error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING & ~E_DEPRECATED);
            break;
    }
    ini_set('display_errors', 'On');
    $whoops = new \Whoops\Run();
    $whoops->pushHandler(new \Whoops\Handler\PrettyPageHandler());
    $whoops->register();
}

function date2humanString($ts) {
	static $d1, $d2, $d3;
	
	if (!$d1 ) $d1 = date('Ymd');
	if (!$d2 ) $d2 = date('Ymd', mktime(0,0,0,date('m'),date('d')+1, date('Y')));
	if (!$d3 ) $d3 = date('Ymd', mktime(0,0,0,date('m'),date('d')+2, date('Y')));
	
	switch( date('Ymd',$ts) ) {
		case $d1:
			return 'сегодня';
		break;
		case $d2:
			return 'завтра';
		break;
		case $d3:
			return 'послезавтра';
		break;
		default:
			return date('d', $ts) . ' ' . _getMonthName(date('m', $ts), true);
		break;
	}
	
}


// Не работает если в разных проектах файлы с одинаковым именем
function multiRunCheck() {
  if(php_sapi_name() !=="cli") return true;
  
  global $argv;
  $cmd = "ps aux | grep '" . $argv[0] . "' | grep -v 'grep'";
  exec($cmd, $output);
  if (count($output) > 2) {
    // В ответе 2 строки, т.к. cron пораждает дочерний процесс, в котором тоже присутсвует название файла
    die('double run');
  }
  return true;
}


function displayError($body, $title ="", $btns = []) {
  global $R;
  $tpl = $R->getTpl('order_blanks/generalErrorTemplate.htm');

  if (!$title) $title = "Ошибка";

  $tpl = $R->set('title', $title, $tpl);
  $tpl = $R->set('body', $body, $tpl);

  if (!empty($btns)) {
    foreach ($btns as $btn) {

      if (!isset($btn['class'])) $btn['class'] = 'btn-primary';

      $btnHtml = '<a href="'.$btn['link'].'" class="btn '.$btn['class'].'">'.$btn['title'].'</a>';

      $tpl = $R->parse('btns', $btnHtml, $tpl);  
    }
  } else {
    if ( $_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest' ) {
      $tpl = $R->set('btns', "<a href=\"javascript:history.back()\" class=\"btn btn-primary\">Вернуться назад</a>", $tpl);
    }
  }

  return $R->clear($tpl);

}

?>