Files
zurawik.pl/core/class/Utils.class.php
2026-05-15 20:23:25 +02:00

1529 lines
39 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
*
* Klasa statyczna z funkcjami pomocniczymi
*
*/
class Utils {
public function __construct() {
}
/**
* Funkcja do wyświetlania tablic asocjacyjnych, obiektów itd.
* Zastępuje funkcje array_display
*
* @param array, object $p_array Tablica lub obiekt do wyświetlenia
* @param src, object $src - comment/line/file itp. "comment: ".__FILE__.' - '.__LINE__
*/
public static function ArrayDisplay($p_array, $src = "comment: ".__FILE__.' - '.__LINE__) {
$mtime = microtime();
$mtime = explode(" ", $mtime);
$id = (double)($mtime[1]) + (double)($mtime[0]);
print "<div id='$id' style='background-color: white; color: black; text-align:left;position: sticky;z-index: 100000;' onclick=''>$id - $src<pre>";
print_r($p_array);
print "</pre></div>";
}
/**
* Stara funkcja array_display - działa prawidłowo w wersji PHP 4
*
* @param array, object $p_array Tablica lub obiekt do wyświetlenia
* @param int $user_defined I don't know ;)
*/
public static function ArrayDisplayOld($array_name, $user_defined = 0 ) {
$indexBreak = 0;
if (!isset($array_name)) {
print("<P><B>TABLICA JEST PUSTA</B><P>\n");
}
else {
print("<table border=1 cellspacing=1 style=\"font-family: Verdana; font-size: 10 pt;\" width=\"100%\">\n");
print("<tr><th colspan=2 bgcolor=\"#DDDDDD\">".$array_name."</TR>\n");
// for (reset($array_name); (strcmp(($key=key($array_name)) ,"")); next($array_name)){
foreach ($array_name as $key => $value) {
if (strcmp($key,"GLOBALS") == 0) $user_defined = 0;
if ($user_defined == 1) continue;
if ((is_array($value) || is_object($value)) && (strcmp($key,"GLOBALS") != 0)) {
print("<tr><td bgcolor=\"#66ccff\" width=10><font style=\"font-size:9;\">".substr(gettype($key),0,3)."</font>&gt;".str_replace(" ","&nbsp;",$key)."&lt;<font style=\"font-size:9;\">".(is_object($array_name) ? 'b.d.' : count($array_name[$key]))."</font><td bgcolor=\"#66ccff\">");
Utils::ArrayDisplayOld($value);
print ("</tr>\n");
}
else {
print("<tr><td bgcolor=\"#66bbff\" width=10><font style=\"font-size:9;\">".substr(gettype($key),0,3)."</font>&gt;".str_replace(" ","&nbsp;",$key)."<font>&lt;</font>");
print("<td bgcolor=\"#f5a5e8\"><font style=\"font-size:9;\">".substr(gettype($value),0,3)."</font>&gt;".str_replace(" ","&nbsp;",$value)."&lt;</TR>\n");
}
if (++$indexBreak>1000) {
break;
}
}
print("</TABLE >\n");
@reset($array_name);
}
}
/**
*
* @param string $search
* @param string $replace
* @param string $subject
* @return string
*/
public static function ReplaceFirstString($search, $replace, $subject) {
$search = '/'.preg_quote($search, '/').'/';
return preg_replace($search, $replace, $subject, 1);
}
/**
* Przeszukiwanie tablicy na podstawie zadanych tekst<73>w
*
* @param Array $array
* @param string $keySearchStart
* @param string $keySearchEnd
* @return int
*/
public static function GetArrayKeyNumberDifference($array, $keySearchStart, $keySearchEnd) {
$index = 0;
foreach ($array as $key => $value) {
if ($key==$keySearchStart) {
$indexStart = $index;
}
if ($key==$keySearchEnd) {
$indexEnd = $index;
break; // przerywamy bo nie mamy czego szukac
}
$index++;
}
$difference = $indexEnd-$indexStart;
return $difference;
}
/**
* Zwraca rozszerzenie pliku na podstawie nazwy
*
* @param string $fileName
* @return string
*/
public static function FileExtFromName($fileName) {
$array = explode('.', $fileName);
$ext = $array[count($array)-1];
return $ext;
}
/**
* Zwraca nazwe pliku bez rozszerzenia
*
* @param string $fileName
* @return string
*/
public static function FileNameFromName($fileName) {
$array = explode('.', $fileName);
unset($array[count($array)-1]);
$fileName = implode('.', $array);
return $fileName;
}
/**
* Wykonuje redirect
*
* @param string $url
*/
public static function Redirect($url,$error =false) {
$url = str_replace('&amp;', '&', $url);
header( "HTTP/1.1 $error");
header("Location: ".$url);
exit();
}
/**
* Porz<72>dkuje entery (zwaraca tekst z enterami w zadanej postaci)
*
* @param string $p_text
* @param string $p_enter
* @return string
*/
function GetSaveEnterInText($p_text, $p_enter = null) {
$enter = is_null($p_enter) ? chr(13) : $p_enter;
$text = $p_text;
$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "", $text);
$text = str_replace("\n", $enter, $text);
return $text;
}
/**
* Wy<57>wietla zapytania (funcja do debugowania)
*
*/
function DisplayQueries() {
echo count($_SESSION['queries']).'<br>';
sort($_SESSION['queries']);
Utils::ArrayDisplayOld($_SESSION['queries']);
unset($_SESSION['queries']);
}
public static function RemovePolish($string)
{
$letters = array('ę'=>'e', 'ó'=>'o', 'ą'=>'a', 'ś'=>'s', 'ł'=>'l', 'ź'=>'z', 'ż'=>'z', 'ć'=>'c', 'ń'=>'n', 'Ę'=>'e', 'Ó'=>'O', 'Ą'=>'A', 'Ś'=>'S', 'Ł'=>'L', 'Ż'=>'Z', 'Ź'=>'Z', 'Ć'=>'C', 'Ń'=>'N');
$string = strtr($string, $letters);
foreach($letters as $letters=>$replacement) {
$string = str_replace($letters, $replacement, $string);
}
return strtolower($string);
}
public static function RemovePolishNoToLower($string)
{
$letters = array('ę'=>'e', 'ó'=>'o', 'ą'=>'a', 'ś'=>'s', 'ł'=>'l', 'ź'=>'z', 'ż'=>'z', 'ć'=>'c', 'ń'=>'n', 'Ę'=>'e', 'Ó'=>'O', 'Ą'=>'A', 'Ś'=>'S', 'Ł'=>'L', 'Ż'=>'Z', 'Ź'=>'Z', 'Ć'=>'C', 'Ń'=>'N');
$string = strtr($string, $letters);
foreach($letters as $letters=>$replacement) {
$string = str_replace($letters, $replacement, $string);
}
return $string;
}
public static function TextToUrl($string) {
$letters = array('-'=> '_',' '=> '_', '/'=> '_', 'ę'=>'e', 'ó'=>'o', 'ą'=>'a', 'ś'=>'s', 'ł'=>'l', 'ź'=>'z', 'ż'=>'z', 'ć'=>'c', 'ń'=>'n', 'Ę'=>'e', 'Ó'=>'O', 'Ą'=>'A', 'Ś'=>'S', 'Ł'=>'L', 'Ż'=>'Z', 'Ź'=>'Z', 'Ć'=>'C', 'Ń'=>'N');
$string = strtr($string, $letters);
foreach($letters as $letters=>$replacement) {
$string = str_replace($letters, $replacement, $string);
}
return urlencode(strtolower(strip_tags($string)));
}
public static function AddSlashes($string) {
return $string;
}
public static function TextToTitle($string) {
$string = str_replace('"', '', (strip_tags($string)));
return $string;
}
/**
* Zamienia polskie znaki zakodowane utf pobrane z adresu url(param) na polskie znaki :)
*
*/
function url2pl($text) {
// $text = str_replace("", '/', $text);
$text = str_replace("%2F", '/', $text);
$text = str_replace("\xC4\x85", 'ą', $text);
$text = str_replace("\xC4\x84", 'Ą', $text);
$text = str_replace("\xC4\x87", 'ć', $text);
$text = str_replace("\xC4\x86", 'Ć', $text);
$text = str_replace("\xC4\x99", 'ę', $text);
$text = str_replace("\xC4\x98", 'Ę', $text);
$text = str_replace("\xC5\x82", 'ł', $text);
$text = str_replace("\xC5\x81", 'Ł', $text);
$text = str_replace("\xC3\xB3", 'ó', $text);
$text = str_replace("\xC3\x93", 'Ó', $text);
$text = str_replace("\xC5\x9B", 'ś', $text);
$text = str_replace("\xC5\x9A", 'Ś', $text);
$text = str_replace("\xC5\xBC", 'ż', $text);
$text = str_replace("\xC5\xBB", 'Ż', $text);
$text = str_replace("\xC5\xBA", 'ż', $text);
$text = str_replace("\xC5\xB9", 'Ż', $text);
$text = str_replace("\xc5\x84", 'ń', $text);
$text = str_replace("\xc5\x83", 'Ń', $text);
return $text;
}
function specjalSearchSing($text)
{
$text = str_replace("%2F", '%252F', $text);
$text = str_replace("/", '%252F', $text);
return $text;
}
public static function cleanUrl($text)
{
$text=strtolower($text);
$code_entities_match = array(' ','--','&quot;','!','@','#','$','%','^','&','*','(',')','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','*','+','~','`','=');
$code_entities_replace = array('-','-','','','','','','','','','','','','','','','','','','','','','','','');
$text = str_replace($code_entities_match, $code_entities_replace, $text);
return $text;
}
public function cleanUrlSpaces($text)
{
$text=strtolower($text);
$code_entities_match = array(' ','--','&quot;','!','@','#','$','%','^','&','*','(',')','_','+','{','}','|',':','"','<','>','?','[',']','\\',';',"'",',','.','/','*','+','~','`','=');
$code_entities_replace = array(' ','-','','','','','','','','','','','','','','','','','','','','','','','','');
$text = str_replace($code_entities_match, $code_entities_replace, $text);
return $text;
}
/**
* Pomocnicza f sortuj<75>ca
*
*/
public static function sortIt($objA, $objB, $key = 'count'){
if ($objA[$key] == $objB[$key]) return 0;
return ($objA[$key] > $objB[$key]) ? -1 : 1;
}
public function MakeImageUrlFromHeader($headerTitle) {
$exp = explode(" ", $headerTitle);
$imgUrl = '';
foreach ($exp as $e) {
$imgUrl .= ucfirst(strtr(strtolower($e), "žążśźęćńółĄŻŚŹĘĆŃÓŁ?!.,:", "zazszecnolAZSZECNOL_____"));
}
return $imgUrl;
}
/**
* Pomocnicza f sortuj<75>ca
*
*/
public static function sortByQO($objA, $objB){
self::sortIt($objA, $objB, 'queue_order');
}
/**
* Rozpoczyna mpomiar czasu
*
*/
public static function TimerStart() {
// Rozpoczynamy pomiar czasu wykonywania skryptu
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
// -->
}
/**
* Konczy pomiar czasu
*
* @return string
*/
public static function TimerEnd() {
// Konczymy pomiar czasu wykonywania skryptu
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
return $totaltime;
}
/**
* Zapisuje sortowanie dla podanej tabeli
*
* @param array $p_arraySort tablica id'k<>w
* @param string $sortColumn kolumna sortowania
* @param string $table tabla sortowania
* @param string $idColumn po jakim id'ku sorujemy
*/
public static function SaveSort($arraySort, $sortColumn, $table, $idColumn) {
$db = Registry::Get('db');
if (count($arraySort)) {
foreach ($arraySort as $id => $value) {
$sql = 'UPDATE '.$table.' SET '.$sortColumn.'='.$value.' WHERE '.$idColumn.' = '.$id;
//Utils::ArrayDisplay($sql);
$db->execute($sql);
}
}
}
/**
* Filtr danych XSS
*
* @param string $val
* @return string
*/
public static function RemoveXss($val) {
// $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
if(Config::Get('site')!='Admin') {
$search = 'aąbcćdeęfghijklłmnoópqrsśtuvwxyzżź';
$search .= 'AĄBCĆDEĘFGHIJKLŁMNOÓPQRSŚTUVWXYZŻŹ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);
$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val);
}
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound');
$ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
$htmlStart = '/\"\s*>/';
$ra = array_merge($ra1, $ra2);
$found = true;
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(&#0{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2);
$val = preg_replace($pattern, $replacement, $val);
$val = preg_replace($htmlStart, "", $val);
if ($val_before == $val) {
$found = false;
}
}
}
}
return $val;
}
/**
* Zwraca sliczna date
*
* @param string $datetime
* @return string
*/
public static function NiceDate($datetime, $noShort = false, $format = null, $time_format = null) {
$date = strtotime($datetime);
if (!$date) {
$date = (int)$datetime;
}
$now = time();
$out = '';
if($format == null)
$format = Registry::Get('DATE_SHORT_FORMAT');
if($time_format == null)
$time_format = Registry::Get('TIME_DEFAULT_FORMAT');
if (!$noShort)
{
if(date(Registry::Get('DATE_SHORT_FORMAT'), $date) == date(Registry::Get('DATE_SHORT_FORMAT'), $now)) {
$out = "Dzisiaj, " . strftime($time_format, $date);
} else if(date(Registry::Get('DATE_SHORT_FORMAT'), $date) == date(Registry::Get('DATE_SHORT_FORMAT'), $now - 86400)) {
$out = "Wczoraj, " . strftime($time_format, $date);
} else if(stristr(PHP_OS, "WIN")) {
$out = ucfirst(iconv("CP1250", "ISO-8859-2", strftime($format, $date)));
} else {
$out = ucfirst(strftime($format, $date));
}
} else {
if(stristr(PHP_OS, "WIN")) {
$out = ucfirst(iconv("CP1250", "ISO-8859-2", strftime($format, $date)));
} else {
$out = ucfirst(strftime($format, $date));
}
}
return $out;
}
/**
* Pod<6F>wietla s<>owa wyst<73>puj<75>ce w tytule i tre<72>ci.
* Nale<6C>y przekaza<7A> mu DataObject.
* Fields - pola po przecinku, w kt<6B>rych ma by<62> wyr<79>nione slowo wyszukania.
* $hlBegin - tekst wstawiony przed szukabym s<>owem
* $hlEnd - tekst wstawiony po szukabym s<>owie
*
* @param DataObject $array
* @param string $search
* @param string $fields
* @param string $hlBegin
* @param string $hlEnd
*/
public static function HighlightText(&$array, $search, $fields = 'Title,Text,Tag', $hlBegin = HL_BEGIN, $hlEnd = HL_END) {
$search = strtolower($search);
$replace = "$hlBegin$search$hlEnd";
$field = explode(',', $fields);
if (is_array($array)){
foreach ($array as $obj) {
for ($i = 0 ; $i < count($field) ; $i++) {
if($field[$i]=='Tag'){
$methodGet = "Get" . trim($field[$i]);
$methodSet = "Set" . trim($field[$i]);
$value = $obj->$methodGet();
$arrayValue = explode(',', $value);
$done = array();
foreach ($arrayValue as $tagObj) {
if(strtolower($tagObj) == strtolower($search)){
$tagObj = $replace;
array_unshift($done, $tagObj);
}
else {
$done[] = $tagObj;
}
}
$value = implode(',', $done);
$obj->$methodSet($value);
}
else {
$methodGet = "Get" . trim($field[$i]);
$methodSet = "Set" . trim($field[$i]);
$value = $obj->$methodGet();
$obj->$methodSet(str_ireplace($search, $replace, $value));
}
}
}
}
else{
for ($i = 0 ; $i < count($field) ; $i++) {
if($field[$i]=='Tag'){
$methodGet = "Get" . trim($field[$i]);
$methodSet = "Set" . trim($field[$i]);
$value = $obj->$methodGet();
$arrayValue = explode(',', $value);
$done = array();
foreach ($arrayValue as $tagObj) {
if(strtolower($tagObj) == strtolower($search)){
$tagObj = $replace;
array_unshift($done, $tagObj);
}
else {
$done[] = $tagObj;
}
}
$value = implode(',', $done);
$obj->$methodSet($value);
}
else {
$methodGet = "Get" . trim($field[$i]);
$methodSet = "Set" . trim($field[$i]);
$value = $obj->$methodGet();
$obj->$methodSet(str_ireplace($search, $replace, $value));
}
}
}
}
/**
* Zwraca dat<61> - miesi<73>c za kt<6B>ry przyznana zosta<74>a nagroda.
*
*/
public static function AwardDate() {
$month = (int)date('m');
$year = (int)date('Y');
//Od 21 nagrody przyznajemy za obecny miesiac, wcze<7A>niej za miniony
if ((int)date('d') < 21) {
$month --;
if ($month == 0) {
$month = 12;
$year --;
}
}
return $year.$month."01";
}
/**
* counts elements of an multidimensional array
*
* @param array $array Input Array
* @param int $limit dimensions that shall be considered (-1 means no limit )
* @return int counted elements
*/
public static function Multicount ($array, $limit = -1)
{
$cnt = 0;
$limit = $limit > 0 ? (int) $limit : -1;
$arrs[] = $array;
for ($i=0; isset($arrs[$i]) && is_array($arrs[$i]); ++$i)
{
foreach ($arrs[$i] as $value)
{
if (!is_array($value) ) ++$cnt;
elseif( $limit==-1 || $limit>1 )
{
if( $limit>1 ) --$limit;
$arrs[] = $value;
}
}
}
return $cnt;
}
/**
* Konwertuje tablicę do formatu jSon'a.
*
* @param array $array
* @return string
*/
public static function Array2Json($array) {
$output = "{";
foreach ($array as $key=>$val) {
if (is_array($val)) {
$output .= "\"".$key."\" : [" . Array2Json($val) ."],";
} else {
$output .= "\"".$key."\" : \"".$val."\",";
}
}
$output .= "}";
return $output;
}
/**
* funkcja wypisujaca js wypisujacego adres email
*
* @param <type> $email - adres email
* @param <type> $cssClass - klasa css dla linka
*/
public static function jsEmail($email,$cssClass = null)
{
$s = '<script type="text/javascript">';
$emailArray = explode("@", $email);
if($cssClass != null)
$s .= 'document.write(\'<a class="' . $cssClass . '" href="mai\');';
else
$s .= 'document.write(\'<a href="mai\');';
$s .= 'document.write(\'lto:' . $emailArray[0] . '\');';
$s .= 'document.write(\'@\');';
$s .= 'document.write(\''. $emailArray[1] . '\');';
$s .= 'document.write(\'">\');';
$s .= 'document.write(\'' . $emailArray[0] . '\');';
$s .= 'document.write(\'@\');';
$s .= 'document.write(\''. $emailArray[1] . '\');';
$s .= 'document.write(\'</a>\');';
$s .= '</script>';
return $s;
}
/**
* funkcja przypisuje cyfrom z lancucha wartosci literowe (na potrzeby LUCENE)
* @param string $var
* @return string
*/
public static function codeIntToChar($var) {
$out = null;
//var_dump($var);
$lenght = strlen($var);
$var = (string)$var;
for($i = 0; $i < $lenght; $i++) {
if(in_array($var[$i], array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))) {
$out .= chr(107 + $var[$i]);
} else {
$out .= $var[$i];
}
}
//var_dump($out);
//if($lenght < 3) {
// $out = 'zxc'.$out;
//}
return $out;
}
public static function codeCharToInt($var) {
$out = null;
$lenght = strlen($var);
$var = (string)$var;
for($i = 0; $i < $lenght; $i++) {
$ord = ord($var[$i]) - 107;
$out .= $ord;
}
//TODO - obsluga dla mniejszych liczb niz 3 cyfry
if($lenght < 3) {
$out = 'zxc'.$out;
}
return $out;
}
/**
* Metoda tworzy katalogi
*
* @param string $dir sciezka katalog<6F>w
* @param int $mode prawa zapisu
* @param bool $recursive czy ma tworzy<7A> katalogi rekursywnie
* @return bool
*/
public static function Mkdirs($dir, $mode = 0777, $recursive = true) {
if( is_null($dir) || $dir === "" ){
return FALSE;
}
if( is_dir($dir) || $dir === DIRECTORY_SEPARATOR ){
return TRUE;
}
if( PhotoDAL::mkdirs(dirname($dir), $mode, $recursive) ){
return mkdir($dir, $mode);
}
return FALSE;
}
public static function dateDiff($date1, $date2)
{
//$date1 today, or any other day
//$date2 date to check against
$d1 = explode(" ", $date1);
$y1 = $d1[0];
$m1 = $d1[1];
$d1 = $d1[2];
$d2 = explode(" ", $date2);
$y2 = $d2[0];
$m2 = $d2[1];
$d2 = $d2[2];
$date1_set = mktime(0,0,0, $m1, $d1, $y1);
$date2_set = mktime(0,0,0, $m2, $d2, $y2);
return(round(($date2_set-$date1_set)/(60*60*24)));
}
public static function MultiImplode($glue, $pieces, $multiGlue = null) {
$first = array_shift($pieces);
if (!$multiGlue) {
$multiGlue = $glue;
}
$ret = (is_array($first) ? self::MultiImplode($glue, $first, $multiGlue) : $first);
foreach ($pieces as $item) {
if (is_array($item)) {
$ret .= $multiGlue . '' . self::MultiImplode($glue, $item);
} else {
$ret .= $glue . $item;
}
}
return $ret;
}
public static function CleanString($str) {
return str_replace(array('\"', "R11;", "R22;", "R21;", "R30;", "R17;"), array('"', '-', '&rdquo;', '&bdquo;', '', ''), $str);
}
public static function DisplayBackTrace($backtrace) {
$backtrace = array_map(function ($a) { return array($a["line"], $a["file"], $a["function"]); }, $backtrace);
var_dump($backtrace);
}
/*
* Zamienia " na &quot;, < na &lt; , > &gt;
*/
public static function SaveInput($string, $type = 'input') {
$patterns = array('/"/');
$replacements = array('&quot;');
if($type == 'textarea') {
$patterns = array('/"/', '/<textarea>/', '/<\/textarea>/');
$replacements = array('&quot;', '&lt;textarea&gt;', '&lt;/textarea&gt;');
}
$str = preg_replace($patterns, $replacements, $string);
return $str;
}
/*
* Sortowanie
*
* array $param
* array $fields - para 'nazwa z bazy' => 'nazwa wyswietlana'
* string $session - identyfikacja zmiennych w sesji
* string $defaultField
* string $defaultOrder
*
*/
public static function SortList($param, $fields, $session, $defaultField = 'kolejnosc', $defaultOrder = 'DESC') {
$field = $fields[$defaultField];
$order = $defaultOrder;
//Utils::ArrayDisplay($_SESSION);
if(isset($param['sortuj'])) {
foreach($fields as $dbfield => $appfield) {
if($dbfield == $param['sortuj']) {
$field = $appfield;
}
}
$oorder = SessionProxy::GetValue('__sort_'.$session.'_index_order__');
//Utils::ArrayDisplay($oorder);
if($oorder == 'ASC') {
$order = 'DESC';
} else {
$order = 'ASC';
}
SessionProxy::SetValue('__sort_'.$session.'_index_order__', $order);
SessionProxy::SetValue('__sort_'.$session.'_index_field__', $field);
} else {
$oorder = SessionProxy::GetValue('__sort_'.$session.'_index_order__');
if(!empty($oorder)) {
$order = $oorder;
}
$ofield = SessionProxy::GetValue('__sort_'.$session.'_index_field__');
if(!empty($ofield)) {
$field = $ofield;
}
}
$smarty = Registry::Get('smarty');
$smarty->assign('tableSort', array($field, $order));
return sprintf(' %s %s ', $field, $order);
}
/**
*
* @param string $base - zadany ciag
* @param string $string - szukany ciag na poczatku zadanego ciagu
*/
public static function TrimString($base, $string) {
$cutLen = strlen($string);
$trim = true;
$done = $base;
while($trim) {
$begStr = substr($done, 0, $cutLen);
if($string == $begStr) {
$done = substr($done, $cutLen);
} else {
$trim = false;
}
}
return $done;
}
function charset_utf_fix($string )
{
$utf_iso = array(
"\xc4\x85" => "\xb1",
"\xc4\x84" => "\xa1",
"\xc4\x87" => "\xe6",
"\xc4\x86" => "\xc6",
"\xc4\x99" => "\xea",
"\xc4\x98" => "\xca",
"\xc5\x82" => "\xb3",
"\xc5\x81" => "\xa3",
"\xc3\xb3" => "\xf3",
"\xc3\x93" => "\xd3",
"\xc5\x9b" => "\xb6",
"\xc5\x9a" => "\xa6",
"\xc5\xba" => "\xbc",
"\xc5\xb9" => "\xac",
"\xc5\xbc" => "\xbf",
"\xc5\xbb" => "\xaf",
"\xc5\x84" => "\xf1",
"\xc5\x83" => "\xd1",
// xmlhttprequest uses different encoding
"%u0104" => "\xA1",
"%u0106" => "\xC6",
"%u0118" => "\xCA",
"%u0141" => "\xA3",
"%u0143" => "\xD1",
"%u00D3" => "\xD3",
"%u015A" => "\xA6",
"%u0179" => "\xAC",
"%u017B" => "\xAF",
"%u0105" => "\xB1",
"%u0107" => "\xE6",
"%u0119" => "\xEA",
"%u0142" => "\xB3",
"%u0144" => "\xF1",
"%u00D4" => "\xF3",
"%u015B" => "\xB6",
"%u017A" => "\xBC",
"%u017C" => "\xBF"
);
//$utf_iso = array_flip($utf_iso);
//return strtr($string, $utf_iso);
return str_replace(array_keys($utf_iso), array_values($utf_iso), $string);
}
/**
* Funkcja przekazuje do smarty informacje o aktualnej stronie i ilo<6C>ci stron, oraz
* zwraca limit dla aktualenej strony.
*
*
* @param <type> $smarty
* @param <type> $strona
* @param <type> $ilosc
* @param <type> $perPage
*/
public static function PageConfigure(&$smarty, $param, $ilosc, $perPage = 10) {
$iloscStron = ceil((int)$ilosc / $perPage);
if (!isset($param['p'])) {
$strona = 0;
} else {
$strona = (int)$param['p'] - 1;
}
if ($strona < 0) {
$strona = 0;
} else if ($strona > $iloscStron - 1) {
$strona = $iloscStron - 1;
}
if ($strona < 0) {
$strona = 0;
}
$offset = ($strona * $perPage);
$limit = "$offset, $perPage";
$smarty->assign('strona', $strona);
$smarty->assign('iloscStron', $iloscStron);
return $limit;
}
/**
* Wycina polskie znaki
*
* @param string $string
* @return string
*/
public static function CleanStringQuery($string) {
$letters = array(
"ą"=>"a",
"ę"=>"e",
"ś"=>"s",
"ć"=>"c",
"ł"=>"l",
"ń"=>"n",
"ż"=>"z",
"ź"=>"z",
"ó"=>"o",
"Ą"=>"A",
"Ę"=>"E",
"Ś"=>"S",
"Ć"=>"C",
"Ł"=>"L",
"Ń"=>"N",
"Ż"=>"Z",
"Ź"=>"Z",
"Ó"=>"O",
"Ä"=>"A",
"ä"=>"a",
"Ö"=>"O",
"ö"=>"o",
"Ü"=>"U",
"ü"=>"u",
"Ë"=>"E",
"ë"=>"e",
"ß"=>"ss"
);
foreach($letters as $letter=>$replacement) {
$string = str_replace($letter, $replacement, $string);
}
return $string;
}
public static function GetNowDate() {
return date("Y-m-d H:i:s");
}
/**
* +1 day");
" +1 week");
" +2 week");
" +1 month");
" +30 days")
*
* @param date $period
*/
public static function GetDate($period = '') {
$date = date("Y-m-d H:i:s");
$date = strtotime($date);
$date = date("Y-m-d H:i:s", strtotime($period, $date));
return $date;
}
function ClearSearch($string){
$letters = Array( 0xC0=>'A',
0xE0=>'a',
0xC1=>'A',
0xE1=>'a',
0xC2=>'A',
0xE2=>'a',
0xC3=>'A',
0xE3=>'a',
0xC4=>'A',
0xE4=>'a',
0xC5=>'A',
0xE5=>'a',
0xC6=>'E',
0xE6=>'e',
0xC7=>'C',
0xE7=>'c',
0xC8=>'E',
0xE8=>'e',
0xC9=>'E',
0xE9=>'e',
0xCA=>'E',
0xEA=>'e',
0xCB=>'E',
0xEB=>'e',
0xCC=>'I',
0xEC=>'i',
0xCD=>'I',
0xED=>'i',
0xCE=>'I',
0xEE=>'i',
0xCF=>'I',
0xEF=>'i',
0xD0=>'D',
0xF0=>'d',
0xD1=>'N',
0xF1=>'n',
0xD2=>'O',
0xF2=>'o',
0xD3=>'O',
0xF3=>'o',
0xD4=>'O',
0xF4=>'o',
0xD5=>'O',
0xF5=>'o',
0xD6=>'O',
0xF6=>'o',
0xD7=>'*',
0xF7=>'*',
0xD8=>'?',
0xF8=>'?',
0xD9=>'U',
0xF9=>'u',
0xDA=>'U',
0xFA=>'u',
0xDB=>'U',
0xFB=>'u',
0xDC=>'U',
0xFC=>'u',
0xDD=>'Y',
0xFD=>'y',
0xDF=>'B',
0xFF=>'y'
);
foreach($letters as $letter=>$replacement) {
$string = str_replace($letter, $replacement, $string);
}
return $string;
}
function win2utf(){
$tabela = Array(
"\xb9" => "\xc4\x85", "\xa5" => "\xc4\x84", "\xe6" => "\xc4\x87", "\xc6" => "\xc4\x86",
"\xea" => "\xc4\x99", "\xca" => "\xc4\x98", "\xb3" => "\xc5\x82", "\xa3" => "\xc5\x81",
"\xf3" => "\xc3\xb3", "\xd3" => "\xc3\x93", "\x9c" => "\xc5\x9b", "\x8c" => "\xc5\x9a",
"\x9f" => "\xc5\xba", "\xaf" => "\xc5\xbb", "\xbf" => "\xc5\xbc", "\xac" => "\xc5\xb9",
"\xf1" => "\xc5\x84", "\xd1" => "\xc5\x83", "\x8f" => "\xc5\xb9");
return $tabela;
}
function iso2utf(){
$tabela = Array(
"\xb1" => "\xc4\x85", "\xa1" => "\xc4\x84", "\xe6" => "\xc4\x87", "\xc6" => "\xc4\x86",
"\xea" => "\xc4\x99", "\xca" => "\xc4\x98", "\xb3" => "\xc5\x82", "\xa3" => "\xc5\x81",
"\xf3" => "\xc3\xb3", "\xd3" => "\xc3\x93", "\xb6" => "\xc5\x9b", "\xa6" => "\xc5\x9a",
"\xbc" => "\xc5\xbc", "\xac" => "\xc5\xbb", "\xbf" => "\xc5\xba", "\xaf" => "\xc5\xb9",
"\xf1" => "\xc5\x84", "\xd1" => "\xc5\x83");
return $tabela;
}
function ISO88592_2_UTF8($tekst){
return strtr($tekst, self::iso2utf());
}
function UTF8_2_ISO88592($tekst){
return strtr($tekst, array_flip(self::iso2utf()));
}
function WIN1250_2_UTF8($tekst){
return strtr($tekst, self::win2utf());
}
function UTF8_2_WIN1250($tekst){
return strtr($tekst, array_flip(self::win2utf()));
}
function ISO88592_2_WIN1250($tekst){
return strtr($tekst, "\xa1\xa6\xac\xb1\xb6\xbc", "\xa5\x8c\x8f\xb9\x9c\x9f");
}
function WIN1250_2_ISO88592($tekst){
return strtr($tekst, "\xa5\x8c\x8f\xb9\x9c\x9f", "\xa1\xa6\xac\xb1\xb6\xbc");
}
/**
* Pobiera idików
*
* @param string $table tabla
* @param string $column nazwa kolumny
*/
public static function GetIdsList($table, $idName, $lang = null, $where = '', $orderBy = '') {
$array = array();
$db = Registry::Get('db');
$sql = " CHECK TABLE $table FAST QUICK";
//Utils::ArrayDisplay($sql);
$stmt = $db->execute($sql);
$row = $stmt->FetchArray();
//Utils::ArrayDisplay($row);
if (strtolower($row['Msg_type']) != 'error') {
$sql = 'SELECT '.$idName.' FROM '.$table.' WHERE 1=1 '.
( $lang ? "AND lang = '$lang' " : " ") . $where;
$order = ( $orderBy ? " ORDER BY $orderBy " : " ORDER BY id_$table ");
$sql .= $order;
//Utils::ArrayDisplay($sql);
$stmt = $db->execute($sql);
$ids = '';
$returnArray = array();
while(($row = $stmt->FetchArray())) {
$returnArray[] = $row[$idName];
}
if (count($returnArray) > 0) {
$ids .= implode(',', $returnArray);
} else {
$ids .= '-1';
}
$ids .= '';
return $ids;
}
}
/**
* Pobiera dane dla dropdown
*
* @param string $table tabla
* @param string $column nazwa kolumny
*/
public static function GetArrayList($table, $idName, $column, $lang = null, $where = '', $orderBy = '') {
$array = array();
$db = Registry::Get('db');
$sql = " CHECK TABLE $table FAST QUICK";
//Utils::ArrayDisplay($sql);
$stmt = $db->execute($sql);
$row = $stmt->FetchArray();
//Utils::ArrayDisplay($row);
if (strtolower($row['Msg_type']) != 'error') {
$sql = 'SELECT '.$idName.', '.$column.' FROM '.$table.' WHERE 1=1 '.
( $lang ? "AND lang = '$lang' " : " ") . $where;
$order = ( $orderBy ? " ORDER BY $orderBy " : " ORDER BY id_$table ");
$sql .= $order;
//Utils::ArrayDisplay($sql, __FILE__." - ".__LINE__);
$stmt = $db->execute($sql);
while(($row = $stmt->FetchArray())) {
$array[$row[$idName]] = $row[$column];
}
//Utils::ArrayDisplay($array);
return $array;
}
}
/**
* Pobiera dane dla dropdown
*
* @param string $table tabla
* @param string $column nazwa kolumny
*/
public static function GetArrayListDISTINCT($table, $idName, $column, $lang = null, $where = '', $orderBy = '') {
$array = array();
$db = Registry::Get('db');
$sql = " CHECK TABLE $table FAST QUICK";
//Utils::ArrayDisplay($sql);
$stmt = $db->execute($sql);
$row = $stmt->FetchArray();
//Utils::ArrayDisplay($row);
if (strtolower($row['Msg_type']) != 'error') {
$sql = 'SELECT DISTINCT '.$column.' FROM '.$table.' WHERE 1=1 '.
( $lang ? "AND lang = '$lang' " : " ") . $where;
$order = ( $orderBy ? " ORDER BY $orderBy " : " ORDER BY id_$table ");
$sql .= $order;
//Utils::ArrayDisplay($sql);
$stmt = $db->execute($sql);
while(($row = $stmt->FetchArray())) {
$array[] = $row[$column];
}
//Utils::ArrayDisplay($array);
return $array;
}
}
/**
* wyciena polskie znaki i spacje
* mienia nazwę na lower
*
* @param string $string
* @return string
*/
public static function ClearString($string) {
$letters = array(" "=>"_",
"ą"=>"a",
"ę"=>"e",
"ś"=>"s",
"ć"=>"c",
"ł"=>"l",
"ń"=>"n",
"ż"=>"z",
"ź"=>"z",
"ó"=>"o",
"Ą"=>"A",
"Ę"=>"E",
"Ś"=>"S",
"Ć"=>"C",
"Ł"=>"L",
"Ń"=>"N",
"Ż"=>"Z",
"Ź"=>"Z",
"Ó"=>"O");
foreach($letters as $letter=>$replacement) {
$string = str_replace($letter, $replacement, $string);
}
$string = strtolower($string);
return $string;
}
//TODO: dorobić sprawdzenie daty
public static function CheckPublication($id, $table, $column) {
$db = Registry::Get('db');
$sql = "SELECT
$column
FROM $table WHERE $column = $id AND publication = 1";
$stmt = $db->prepare($sql)
->execute($sql);
if ($stmt->NumRows() > 0) {
return true;
} else {
return false;
}
}
public static function SetPublication($id, $table, $column, $value) {
$db = Registry::Get('db');
$sql = "SELECT
$column
FROM $table WHERE $column = $id AND publication = $value";
$sql = 'UPDATE '.$table.' SET publication'."='".$value."' WHERE $column = $id";
//Utils::ArrayDisplay($sql);
$db->execute($sql);
}
/**
*
*/
public static function UpdateField($table, $field, $whereName, $whereValue, $value, $showSqlNotDo = false) {
$db = Registry::Get('db');
$sql = 'UPDATE '.$table.' SET '.$field."='".$value."' WHERE ".$whereName." = '".$whereValue."'";
if ($showSqlNotDo) {
Utils::ArrayDisplay($sql);
//$db->execute($sql);
} else {
//Utils::ArrayDisplay($sql);
$db->execute($sql);
}
}
public static function TextToUpper($string) {
$search = 'a.ą.b.c.ć.d.e.ę.f.g.h.i.j.k.l.ł.m.n.o.ó.p.q.r.s.ś.t.u.v.w.x.y.z.ż.ź';
$searchUpper = 'A.Ą.B.C.Ć.D.E.Ę.F.G.H.I.J.K.L.Ł.M.N.O.Ó.P.Q.R.S.Ś.T.U.V.W.X.Y.Z.Ż.Ź';
$array = explode('.',$search);
$arrayUpper = explode('.',$searchUpper);
foreach ($array as $key => $value ) {
$data[$value] = $arrayUpper[$key];
}
$string = strtr($string, $data);
foreach($data as $data=>$replacement) {
$string = str_replace($data, $replacement, $string);
}
return $string;
}
public static function ClearStringToTitle($string) {
$letters = array(
"ą"=>"a",
"ę"=>"e",
"ś"=>"s",
"ć"=>"c",
"ł"=>"l",
"ń"=>"n",
"ż"=>"z",
"ź"=>"z",
"ó"=>"o",
"Ą"=>"A",
"Ę"=>"E",
"Ś"=>"S",
"Ć"=>"C",
"Ł"=>"L",
"Ń"=>"N",
"Ż"=>"Z",
"Ź"=>"Z",
"Ó"=>"O");
foreach($letters as $letter=>$replacement) {
$string = str_replace($letter, $replacement, $string);
}
return $string;
}
public static function FraceUpper($string) {
$letters = array(
"é"=>"É",
);
foreach($letters as $letter=>$replacement) {
$string = str_replace($letter, $replacement, $string);
}
return $string;
}
public static function TextToUpperArray($string, $lang) {
$arrayLangToCode = array('pl' => 'iso8859-2','en' => 'iso8859-1', 'de' => 'iso8859-1', 'ua' => 'Windows-1251', 'fr' => 'iso8859-1');
if ($lang != 'pl') {
$string = Utils::ClearStringToTitle($string);
}
//Utils::ArrayDisplay($string);
$line = iconv("UTF-8", $arrayLangToCode[$lang], $string); // convert to
if ($lang != 'pl') {
$line = strtoupper($line);
}
$line1 = substr($line,0,1);
$line2 = substr($line,1);
$line1 = iconv($arrayLangToCode[$lang], "UTF-8", $line1); // convert back to utf-8
$line2 = iconv($arrayLangToCode[$lang], "UTF-8", $line2); // convert back to utf-8
if ($lang == 'pl') {
$line1 = Utils::TextToUpper($line1);
$line2 = Utils::TextToUpper($line2);
}
$line1 = Utils::FraceUpper($line1);
$line2 = Utils::FraceUpper($line2);
$line = array($line1, $line2);
return $line;
}
public static function Truncate($string, $max = 20, $rep = '')
{
if (strlen($string) <= ($max + strlen($rep)))
{
return $string;
}
$leave = $max - strlen ($rep);
return substr_replace($string, $rep, $leave);
}
public static function Filter() {
if (Request::IsPost()) {
$post = Request::GetAllPost();
$filter = $post['filter'];
SessionProxy::GetAndSetValue('filter', $post['filter']);
} else {
if (SessionProxy::IsSetValue('filter')) {
$filter = SessionProxy::GetValue('filter');
} else {
$filter = 3;
}
}
return $filter;
}
public static function PerPage(&$smarty = null) {
if (Request::IsPost()) {
$post = Request::GetAllPost();
$perPage = $post['perPage'];
SessionProxy::GetAndSetValue('perPage', $post['perPage']);
} else {
if (SessionProxy::IsSetValue('perPage')) {
$perPage = SessionProxy::GetValue('perPage');
} else {
$perPage = 10;
}
}
if ($smarty != null)
$smarty->assign('perPage', $perPage);
return $perPage;
}
public static function Sort(&$param, &$smarty = null) {
if (isset($param[ROUTER_SORT_LABEL]) && isset($param[ROUTER_DIR_LABEL])) {
$sortBy = $param[ROUTER_SORT_LABEL];
$sortDir = $param[ROUTER_DIR_LABEL];
$sortByArray = explode('-', $sortBy);
$sortDirArray = explode('-', $sortDir);
if ($smarty != null) {
$smarty->assign('_sortBy', $sortByArray);
$smarty->assign('_sortDir', $sortDirArray);
}
if (count($sortByArray) >= 1 && count($sortDirArray) == count($sortByArray)) {
$sortBy = $sortByArray;
$sortDir = $sortDirArray;
} else {
throw new CoreException('Sortowanie: błędna ilość parametrów');
}
} else {
$sortBy = array();
$sortDir = array();
$param[ROUTER_SORT_LABEL] = "";
$param[ROUTER_DIR_LABEL] = "";
}
return array($sortBy, $sortDir);
}
public static function Page(&$param, &$smarty = null) {
if (isset($param[ROUTER_PAGE_LABEL])) {
$pageNum = $param[ROUTER_PAGE_LABEL];
$page = explode('-', $pageNum);
array_filter($page, function ($x) { if ((int)$x <= 0) { throw new UserException("Strona poza zakresem"); } });
if ($smarty != null)
$smarty->assign('_page', $page);
} else {
$page = array();
$param[ROUTER_PAGE_LABEL] = "";
}
return $page;
}
public static function CheckDescLang($id, $table, $lang) {
$db = Registry::Get('db');
$strId = str_replace('_description', '', $table);
$sql = "SELECT
id_$table
FROM $table WHERE id_$strId = $id AND lang NOT IN ('$lang')";
$stmt = $db->prepare($sql)
->execute($sql);
//Utils::ArrayDisplay('dd');
//Utils::ArrayDisplay($sql);
// Utils::ArrayDisplay($stmt->fetchAllAssoc());
if ($stmt->NumRows() > 0) {
return true;
} else {
return false;
}
}
/**
* Z nazwy pola tabeli generuje nazwÄ™ zmiennej php
*
* @param string
*/
public static function SQLName2PHPName($name) {
$wordsArray = explode('_', $name);
//od 1 bo pierwszy element zostaje z maĹÄ… literÄ…
for ($i = 1; $i < count($wordsArray); $i++) {
$wordsArray[$i] = ucfirst($wordsArray[$i]);
}
return implode('', $wordsArray);
}
public static function NumFormat($number) {
$number_format = number_format($number, 2, ',', ' ');
return $number_format;
}
}
?>