$count) { $pos=$count; $tag=false; for ($i=$pos;$i>=$pos - 50;$i--) { if (mb_substr($str1,$i,1,"UTF-8")=="<") {$tag=true;$pos=$i-1;} } if (!$tag) while (mb_substr($str1,$pos,1,"UTF-8")!=" " && mb_substr($str1,$pos,1,"UTF-8")!="." && $pos>0) $pos--; $rez=mb_substr($str1,0,$pos,"UTF-8")."..."; } else $rez=$str1; return $rez; } function correctHref($str1) { if (substr($str1,0,8)=="https://") return $str1; return (substr($str1,0,7)=="http://" ? $str1 : "http://".$str1); } function echo_POST() { echo "--POST--
"; foreach ($_POST as $key=>$value) echo $key." = ".$value."
"; echo "--POST--
"; } function translit($string) { $rus = array('ё','ж','ц','ч','ш','щ','ю','я','Ё','Ж','Ц','Ч','Ш','Щ','Ю','Я','ъ','ь','Ъ','Ь'); $lat = array('yo','zh','tc','ch','sh','sh','yu','ya','Yo','Zh','Tc','Ch','Sh','Sch','Yu','Ya','','','',''); $string = str_replace($rus,$lat,$string); $rus1=array("А","Б","В","Г","Д","Е","З","И","Й","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ъ","Ы","Ь","Э","а","б","в","г","д","е","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ъ","ы","ь","э"); $eng1=array("A","B","V","G","D","E","Z","I","J","K","L","M","N","O","P","R","S","T","U","F","H","`","I","`","E","a","b","v","g","d","e","z","i","j","k","l","m","n","o","p","r","s","t","u","f","h","`","i","`","e"); $extended_latin=array("Ç","ç","Ğ","ğ","Ö","ö","Ş","ş","Ü","ü","I","ı"); $base_latin=array("C","c","G","g","O","o","S","s","U","u","I","i"); /*$string = strtr($string, "АБВГДЕЗИЙКЛМНОПРСТУФХЪЫЬЭабвгдезийклмнопрстуфхъыьэ", "ABVGDEZIJKLMNOPRSTUFH`I`Eabvgdezijklmnoprstufh`i`e");*/ $string=str_replace($rus1,$eng1,$string); $string=str_replace($extended_latin,$base_latin,$string); $string=str_replace("`","",$string); return($string); } function removeRestricted($str,$utf8=true) { $what=array(" ","'","+","%","&","?","\"","`","№","#","@"); //return str_replace($what,"",$str); $allowed="ABCDEFGHIJGKLMNOPQRSTUVWXYZabcdefghijgklmnopqrstuvwxyz0123456789._-()"; $remove=array(); $ln=$utf8 ? mb_strlen($str,"UTF-8") : strlen($str); for ($i=0;$i<$ln;$i++) { $c=$utf8 ? mb_substr($str,$i,1,"UTF-8") : substr($str,$i,1); if(strpos($allowed,$c)===false) $remove[]=$c; } return str_replace($remove,"",$str); } function redirect($page) { $base=""; header("Location: ".$base.$page); die(); } function redirect301($page) { $base=""; header("Location: ".$base.$page,true,301); die(); } function CheckPassword($password) { $digit=0; $upper=0; $lower=0; //---- check password size if(strlen($password)<5) return(false); //---- check password for($i=0;$i=3); } //создание пароля function generatePassword($length=6) { $alfabet="abcdefghigkmnopqrstuvwxyzABCDEFGHGKLMNPQRSTUVWXYZ123456789"; $ln=strlen($alfabet)-1; while (!CheckPassword($pass)) { $pass=""; for ($i=1;$i<=$length;$i++) $pass.=substr($alfabet,mt_rand(0,$ln),1); } return $pass; } //-------------------------постраничка------------------- function getPage($num_name="n") { return (isset($_GET[$num_name]) && is_numeric($_GET[$num_name]) ? $_GET[$num_name] : 1); } function pagenavigation($query,$pagenews=15,$num_name="n",$not_cpu=false) { global $db; $use_cpu=getSystemOption("use_cpu")==1; if (strpos($_SERVER['REQUEST_URI'],"/admin/")!==false || $not_cpu) $use_cpu=false; if (isset($_GET['search'])) $use_cpu=false; global $request_params; $pagenavigationstring=$rows=""; $cp=6; if ($use_cpu) $nav=ALIAS_URL.$request_params; else { $nav="?".$_SERVER['QUERY_STRING']; //$nav=ereg_replace("&".$num_name."=[[:digit:]]+", "", $nav); $nav=preg_replace("|&".$num_name."=(\d+)|i", "", $nav); } $page=getPage($num_name); if (is_numeric($query)) $r1[0]=$query; else { $result=$db->select($query); list($key,$value)=each($result[0]); $r1[0]=$value; } if ($r1[0]>$pagenews) { $pagenum=ceil($r1[0]/$pagenews); if ($page<=$cp) { $start=1; $end=($pagenum<$cp ? $pagenum : $cp); } else if ($page>=$pagenum - $cp) { $start=$pagenum - $cp; $end=$pagenum; } else { $start=$page - round($cp/2); $end=$page + round($cp/2); } $pagenavigationstring=LoadTemplate("pager"); $row=LoadTemplate("pager_row"); $currow=LoadTemplate("pager_currow"); $url1=($page==1 ? "javascript:void(0)" : ($use_cpu ? $nav."page/1/" : $nav."&".$num_name."=1")); $url2=($page==1 ? "javascript:void(0)" : ($use_cpu ? $nav."page/".($page-1)."/" : $nav."&".$num_name."=".($page-1))); $url3=($page==$pagenum ? "javascript:void(0)" : ($use_cpu ? $nav."page/".($page+1)."/" : $nav."&".$num_name."=".($page+1))); $url4=($page==$pagenum ? "javascript:void(0)" : ($use_cpu ? $nav."page/".$pagenum."/" : $nav."&".$num_name."=".$pagenum)); if ($start>1) $rows.=str_replace(array("[:url:]","[:num:]"),array(($use_cpu ? $nav."page/".($start-1)."/" : $nav."&".$num_name."=".($start - 1)),"..."),$row); for($j=$start;$j<=$end;$j++) { $tpl=($page==$j ? $currow : $row); $rows.=str_replace(array("[:url:]","[:num:]"),array(($use_cpu ? $nav."page/".$j."/" : $nav."&".$num_name."=".$j),$j),$tpl); } if ($end<$pagenum) $rows.=str_replace(array("[:url:]","[:num:]"),array(($use_cpu ? $nav."page/".($end+1)."/" : $nav."&".$num_name."=".($end+1)),"..."),$row); $pagenavigationstring=str_replace(array("[:url1:]","[:url2:]","[:url3:]","[:url4:]","[:rows:]"),array($url1,$url2,$url3,$url4,$rows),$pagenavigationstring); } return $pagenavigationstring; } //-------------------------!постраничка------------------ //-------------------------работа с файлами------------------- function getFileList($path,$tip,$ext="",$name="") { $dir=opendir($path); $ar=array(); while ($curfile=readdir($dir)) { switch($tip) { case 0:$ar[sizeof($ar)]=$curfile;break; //все без разбору case 1:if ($curfile!="." && $curfile!="..") $ar[sizeof($ar)]=$curfile;break; // все кроме . и .. case 2:if ($curfile!="." && $curfile!=".." && is_dir(($path[strlen($path)-1]=="/" ? $path : $path."/").$curfile) &&($name=="" || !(strpos($curfile,$name)===false))) $ar[sizeof($ar)]=$curfile;break; // только папки case 3:if ($curfile!="." && $curfile!=".." && !is_dir(($path[strlen($path)-1]=="/" ? $path : $path."/").$curfile) &&($name=="" || !(strpos($curfile,$name)===false)) &&($ext=="" || getExtension($curfile)==$ext)) $ar[sizeof($ar)]=$curfile;break; // только файлы } } return $ar; } function changeExtension($filename,$ext) { if (strlen($filename)>0) { $pos=strlen($filename)-1; while ($filename[$pos]!="." && $pos>=0) $pos--; return substr($filename,0,$pos+1).$ext; } else return ""; } function getFileName($filename) { $pos=strlen($filename)-1; while ($filename[$pos]!="/" && $filename[$pos]!="\\") $pos--; return substr($filename,$pos+1); } function getExtension($filename) { $pos=strlen($filename)-1; while ($filename[$pos]!="." && $pos>=0) $pos--; return substr($filename,$pos+1); } function addPostfix($filename,$postfix) { if (strlen($filename)>0) { if(strpos($filename,'.')!==false) { $pos=strlen($filename)-1; while ($filename[$pos]!=".") $pos--; } else { $pos = strlen($filename); } $res = substr($filename,0,$pos).$postfix; if($pos != strlen($filename)) { $res .= substr($filename,$pos - strlen($filename)); } return $res; } else return $postfix; } function stringToFile($path,$string) { file_put_contents($path,$string); //$newfile=@fopen($path,"w+") or die("Unable to create file $path - $string!"); //@fwrite($newfile,$string) or die("Couldn't write to file $path - $string."); //fclose($newfile); } //-------------------------!работа с файлами------------------ //-------------------------SQL------------------- function sql($query,$die=false) { global $db; $res=$db->sql($query); if ($res===false && $die) die($db->error); return $res; } function ArrayToUpdate($mas) { if (sizeOf($mas)==0) return ""; $res=""; foreach ($mas as $field=>$value) $res.=",`".$field."`='".mysql_escape_string(trim($value))."'"; return substr($res,1); } function arrayToInsert($mas,$table) { if (sizeOf($mas)==0 || trim($table)=="") return ""; $query="insert into [:table:] ([:fields:])values([:values:])"; $res['table']=trim($table); $res['fields']=""; $res['values']=""; foreach ($mas as $field=>$value) { $res['fields'].=",`".$field."`"; $res['values'].=",'".mysql_escape_string(trim($value))."'"; } $res['fields']=substr($res['fields'],1); $res['values']=substr($res['values'],1); return arrayToTemplate($res,$query); } //-------------------------!SQL------------------ //-------------------------грабберы------------------- function grabURL($source) { $handle=fopen($source, "rb"); if ($handle) { $contents=''; while (!feof($handle)) $contents.=fread($handle, 8192); return $contents; } else return false; } function getTag($start,$end,$str,$include=false) { $res=$str; $pos_start=@strpos($res,$start); $pos_end=@strpos($res,$end,$pos_start+strlen($start)); $cond=!($pos_start===false || $pos_end===false); if($cond) { $pos_start+=($include ? 0 : strlen($start)); $pos_end+=($include ? strlen($end) : 0); $res=substr($res,$pos_start,$pos_end-$pos_start); } return $res; } function removeTag($start,$end,$str,$include=true) { $res=$str; do { if ($include) { $pos_start=strpos($res,$start); $pos_end=strpos($res,$end,$pos_start); $cond=!($pos_start===false || $pos_end===false); } else { $prev_end=0; $continue=false; do { $pos_start=strpos($res,$start,$prev_end); $pos_end=strpos($res,$end,$pos_start); $cond=!($pos_start===false || $pos_end===false); if ($pos_start!==false && $pos_end!==false && $pos_end==$pos_start+strlen($start)) { $continue=true; $prev_end=$pos_end; } else $continue=false; } while ($continue); } if($cond) { $res=substr($res,0,$pos_start+($include ? 0 : strlen($start))).substr($res,$pos_end+($include ? strlen($end) : 0)); } } while ($cond); return $res; } //-------------------------!грабберы------------------ function getNav($page="") { $nav="?".$_SERVER['QUERY_STRING']; $nav=ereg_replace("&order=[[:alpha:]]+", "", $nav); $nav=($page!="" ? $page.".php" : "").ereg_replace("\?order=[[:alpha:]]+", "", $nav); return $nav; } //-------------------------E-mail---------------------------------- function isCorrectEmail($email) { if (preg_match("%^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z])+$%", $email)) { return true; } return false; } function sendEmail($from,$to,$subject,$text,$attachments="") { if (!class_exists("PHPMailer")) include ABSPATH."tools/phpmailer/PHPMailerAutoload.php"; $mail = new PHPMailer; $mail->CharSet = 'UTF-8'; $mail->setFrom($from,$_SERVER['HTTP_HOST']); $mail->addAddress($to); $mail->Subject = $subject; $mail->AltBody = $text; $mail->MsgHTML(nl2br($text)); if (is_array($attachments)) foreach ($attachments as $file) { $mail->addAttachment($file); } //add DKIM if present if (defined('DKIM_PRIVATE_KEY_PATH') && file_exists(DKIM_PRIVATE_KEY_PATH)) { $siteurl=$_SERVER['HTTP_HOST']; $siteurl=str_replace(array("http://","https://","www."),'',$siteurl); $mail->DKIM_domain = $siteurl; $mail->DKIM_private = DKIM_PRIVATE_KEY_PATH; $mail->DKIM_selector = 'phpmailer'; $mail->DKIM_identity = $mail->From; $mail->DKIM_copyHeaderFields = false; } $res=$mail->send(); return $res; } //-------------------------!E-mail---------------------------------- function upload($fieldname,$path="",$extensions="",$name="",$force_not_folderize=false) { if (is_uploaded_file($_FILES[$fieldname]['tmp_name'])) { if ($path=="") $path=ABSPATH."uploads/images/"; $orig_name=$_FILES[$fieldname]['name']; $encoding=mb_detect_encoding($orig_name,array("UTF-8","cp1251")); if ($encoding!="UTF-8") $orig_name=mb_convert_encoding($orig_name,"UTF-8",$encoding); $fname=removeRestricted(translit($orig_name)); if (!defined("ADD_UPLOAD_UNIQATOR") || ADD_UPLOAD_UNIQATOR) $fname=addPostfix($fname,date("YmdHis")); if ($extensions!="") //установлены ограничения на расширения { $allowed=explode(",",$extensions); $ext=strtolower(getExtension($fname)); if (!in_array($ext,$allowed)) return ""; } $fname=$name=="" ? $fname : $name; if (!$force_not_folderize && defined("UPLOADS_BY_MONTH") && UPLOADS_BY_MONTH) { //need to put file in month folder $folder_name=date("Y-m"); if (!file_exists($path.$folder_name)) mkdir($path.$folder_name); $fname=$folder_name."/".$fname; } if (file_exists($path.$fname)) { $i="1"; while (file_exists($path.addPostfix($fname,$i))) $i++; $fname=addPostfix($fname,$i); } $filename=$fname; $copy_res=copy($_FILES[$fieldname]['tmp_name'],$path.$filename); } else $filename=""; return $filename; } //Массовая загрузка файлов function uploadMulti($fieldname,$num,$lang,$path="",$extensions="",$name="",$force_not_folderize=false) { if (is_uploaded_file($_FILES[$fieldname]['tmp_name'][$num][$lang])) { if ($path=="") $path=ABSPATH."uploads/images/"; $orig_name=$_FILES[$fieldname]['name'][$num][$lang]; $encoding=mb_detect_encoding($orig_name,array("UTF-8","cp1251")); if ($encoding!="UTF-8") $orig_name=mb_convert_encoding($orig_name,"UTF-8",$encoding); $fname=removeRestricted(translit($orig_name)); if (!defined("ADD_UPLOAD_UNIQATOR") || ADD_UPLOAD_UNIQATOR) $fname=addPostfix($fname,date("YmdHis")); if ($extensions!="") //установлены ограничения на расширения { $allowed=explode(",",$extensions); $ext=strtolower(getExtension($fname)); if (!in_array($ext,$allowed)) return ""; } $fname=$name=="" ? $fname : $name; if (!$force_not_folderize && defined("UPLOADS_BY_MONTH") && UPLOADS_BY_MONTH) { //need to put file in month folder $folder_name=date("Y-m"); if (!file_exists($path.$folder_name)) mkdir($path.$folder_name); $fname=$folder_name."/".$fname; } if (file_exists($path.$fname)) { $i="1"; while (file_exists($path.addPostfix($fname,$i))) $i++; $fname=addPostfix($fname,$i); } $filename=$fname; $copy_res=copy($_FILES[$fieldname]['tmp_name'][$num][$lang],$path.$filename); } else $filename=""; return $filename; } function format($number) { return number_format($number,2,".",""); } function getPrevFrom($format) { return date($format,mktime(0, 0, 0, date("m")-1, 1, date("Y"))); } function getPrevTo($format) { return date($format,mktime(0, 0, 0, date("m"), 0, date("Y"))); } function getNextFrom($format) { return date($format,mktime(0,0,0,date("m")+1,1,date("Y"))); } function writeLog($log,$file="") { if ($file=="") $file="log/pagelog_".date("Y-m-d").".tsv"; $line=date("Y.m.d H:i:s")."\t".$_SERVER['REMOTE_ADDR']."\t".(isset($_SESSION['login']) ? $_SESSION['login'] : "unknown")."\t".$log."\n"; $handle=fopen($file,"a"); fwrite($handle,$line); fclose($handle); } function flipTable($mas) { $n=sizeOf($mas); $m=sizeOf($mas[0]); $res=array(); for ($i=0;$i<$m;$i++) { $res[]=array(); for ($j=0;$j<$n;$j++) $res[$i][]=$mas[$j][$i]; } return $res; } function letterNum($numb,$gender,$valuta,$printNull) { $hundreds=Array("","one hundred","two hundred","three hundred","four hundred","five hundred","six hundred","seven hundred","eight hundred","nine hundred"); $decimals=Array("","","twenty","thirty","fourty","fifty","sixty","seventy","eighty","ninety"); $teens=Array("ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"); $ones_male=Array("","one","two","three","four","five","six","seven","eight","nine"); $ones_female=Array("zero","one","two","three","four","five","six","seven","eight","nine"); $rez=$hundreds[floor($numb/100)]; $decim=$numb % 100; if ($decim>=10 && $decim<20) $rez.=" ".$teens[$decim-10]; else $rez.=" ".$decimals[floor($decim / 10)]." ".($gender=="male" ? $ones_male[$decim % 10] : $ones_female[$decim % 10]); //if (num==0 && printNull) rez="ноль"; $edin=$numb % 10; $decim=$numb % 100; if ($decim>10 && $decim<20) $padej=2; else if ($edin==1) $padej=0; else if ($edin >=2 && $edin<=4) $padej=1; else $padej=2; return $rez." ".($numb!=0 || $printNull ? $valuta[$padej] : ""); } function numToString($number,$val,$sex) { $result=""; $gender=Array('','female','male','male'); $gender[0]=$sex; $valuta=Array(Array('','',''),Array('thousand','thousand','thousand'),Array('million','million','million'),Array('billion','billion','billion')); $valuta[0]=$val; for ($i=0;strlen($number)>0;$i++) { if (strlen($number)<=3) { $num=$number; $number=""; } else { $num=substr($number,strlen($number)-3); $number=substr($number,0,strlen($number)-3); } $result=letterNum($num,$gender[$i],$valuta[$i],($i>0 ? false : true))." ".$result; } return $result; } function currencyToString($currency,$val1,$sex1,$subval,$subsex) { if ($currency<1) $str_cur=numToString(round($currency*100),$subval,$subsex); else { $currencyArray=explode(".",$currency); $str_cur=numToString($currencyArray[0],$val1,$sex1); if (sizeOf($currencyArray)>1) { if (sizeOf($currencyArray[1])>2) $currencyArray[1]=substr($currencyArray[1],0,2); else if (strlen($currencyArray[1])==1) $currencyArray[1]=$currencyArray[1]."0"; if ($currencyArray[1]>0) $str_cur.=" ".numToString($currencyArray[1],$subval,$subsex); } } return $str_cur; } //-------------------функции для мобильника ---------- function isMobile() { $agent=strtolower($_SERVER["HTTP_USER_AGENT"]); $mobile=false || isset($_GET['mobile_view']); $signs=array("symbian","opera mini","j2me"); foreach ($signs as $sign) $mobile=$mobile || (strpos($agent,$sign)!==false); return $mobile; } //-------------------!функции для мобильника --------- function refresh() { $isHttps = !empty($_SERVER['HTTPS']) && 'off' !== strtolower($_SERVER['HTTPS']); $host=($isHttps ? "https://" : "http://").$_SERVER['HTTP_HOST']; if (isset($_SERVER['REQUEST_URI'])) $url=$host.$_SERVER['REQUEST_URI']; else { $url=$host.(substr($_SERVER['PHP_SELF'],0,1)=="/" ? "" : "/").$_SERVER['PHP_SELF'].($_SERVER['QUERY_STRING']=="" ? "" : "?".$_SERVER['QUERY_STRING']); } redirect($url); //redirect(basename($_SERVER['PHP_SELF'])."?".$_SERVER['QUERY_STRING']); } //накладывает на иконку текст (расширение файла) function get_file_icon($filename,$default_icon="../img/report.png") { $path="../img/file_icons/"; $exts=array("document-excel.png"=>array("xls","xlsx"), "document-film.png"=>array("mp4","avi","3gp","rmvb","wmv","mkv","mpg","mov","vob","flv"), "document-flash-movie.png"=>array("swf","fla"), "document-music.png"=>array("mp3","wma","flac","aac","mmf","amr","m4a","m4r","ogg","mp2","wav"), "document-pdf.png"=>array("pdf"), "document-photoshop.png"=>array("psd"), "document-word.png"=>array("doc","docx","rtf"), "document-illustrator.png"=>array("ai"), "document-image.png"=>array("jpg","png","ico","bmp","gif","tif","pcx","tga","cdr","eps"), "document-rar.png"=>array("rar","zip"), "document-txt.png"=>array("txt"), "application.png"=>array("exe")); $tip=strtolower(getExtension($filename)); foreach($exts as $icon=>$ext) if(in_array($tip,$ext)) return $path.$icon; return $default_icon; } function correctDateFormat($date) { $tmp=explode(".",trim($date)); if (strlen($tmp[0])==4) return $date; else return implode(".",array_reverse($tmp)); } function getMinutesBetween($from,$to) { if ($from=="" || $to=="") return 0; //echo substr($from,0,2)." ".substr($from,3,2)."
"; $min1=60*(substr($from,0,2))+ substr($from,3,2); $min2=60*(substr($to,0,2))+ substr($to,3,2); $res=$min2-$min1; if ($res<0) $res=0; return $res; } function chislitelnoe($num,$words) //возвращает нужную форму числительного { $ost100=$num % 100; $ost10=$num % 10; if ($ost10==1 && $ost100!=11) $word=$words[0]; else if ($ost10>=2 && $ost10<=4 && ($ost100<10 || $ost100>20)) $word=$words[1]; else $word=$words[2]; return $word; } function floatMicrotime() { list($msec,$sec)=explode(" ",microtime()); return ((float)$msec + (float)$sec); } $system_options_cache=array(); function getSystemOption_OLD($name,$raw=false) //получает значение системной настройки { global $system_options_cache; $sign=$name.'@!!!@'.($raw ? '1' : '0'); if (isset($system_options_cache[$sign])) return $system_options_cache[$sign]; global $db; $res=$db->select("select `default` from `".db_prefix."options` where `name`='".$db->escape($name)."' and `type`=0"); if (sizeOf($res)==0) { $system_options_cache[$sign]=''; return ""; } else { $value=$res[0]['default']; if (IS_MULTILINGUAL && !$raw) $value=multilang($value); $system_options_cache[$sign]=$value; return $value; } } function getSystemOption($name,$raw=false) //получает значение системной настройки { global $system_options_cache; $sign=$name.'@!!!@'.($raw ? '1' : '0'); if (isset($system_options_cache[$sign])) return $system_options_cache[$sign]; global $db; global $memcached; $memcached_sign='SO_'.$name; $ttl=3600; $raw_value=$memcached->get($memcached_sign); if ($raw_value===false) { $res=$db->select("select `default` from `".db_prefix."options` where `name`='".$db->escape($name)."' and `type`=0"); if (sizeOf($res)==0) { $system_options_cache[$sign]=''; $memcached->set($memcached_sign,'',$ttl); return ""; } else { $raw_value=$res[0]['default']; $memcached->set($memcached_sign,$raw_value,$ttl); } } $value=(IS_MULTILINGUAL && !$raw) ? multilang($raw_value) : $raw_value; $system_options_cache[$sign]=$value; return $value; } function setSystemOption($name,$value) { global $db; $data=$db->select("select `id` from `".db_prefix."options` where `name`='".$db->escape($name)."' and `type`=0"); if (sizeOf($data)==0) { $o=array("name"=>$name,"default"=>$value,"type"=>0); $res=$db->insert(db_prefix."options",$o); } else { $o=array("default"=>$value); $res=$db->update(db_prefix."options",$o," `id`='".$data[0]['id']."' limit 1"); } if ($res!==false) { global $memcached; $memcached_sign='SO_'.$name; $ttl=3600; $memcached->set($memcached_sign,$value,$ttl); } return $res; } function getCategoryOption($name,$category="",$raw=false) //получает значение настройки категории { if ($category=="") return ""; global $db; $res=$db->select("select `value` from `".db_prefix."category_options` co,`".db_prefix."options` o where id_option=o.id and o.name='".$db->escape($name)."' and id_category='".$db->escape($category)."' and `type`=3"); if (sizeOf($res)==0) return ""; else { $value=$res[0]['value']; if (IS_MULTILINGUAL && !$raw) $value=multilang($value); return $value; } } function getCategoryOptions($category,$raw=false) //получает все настройки категории { if ($category=="" || !is_numeric($category)) return ""; global $db; $options=array(); $res=$db->select("select o.name,co.`value` from `".db_prefix."options` o,`".db_prefix."category_options` co where o.`type`=3 and co.id_option=o.id and id_category='".$db->escape($category)."'"); foreach ($res as $r) { if (IS_MULTILINGUAL && !$raw) $r['value']=multilang($r['value']); $options[$r['name']]=$r['value']; } return $options; } function setCategoryOption($cid,$option,$value) { if (!is_numeric($cid)) return false; global $db; //check option existence $data=$db->select("select id from `".db_prefix."options` where `name`='".$db->escape($option)."' and `type`=3 limit 1"); if (sizeOf($data)==0) { $o=array("name"=>$option,"type"=>3); $oid=$db->insert(db_prefix."options",$o); } else $oid=$data[0]['id']; //update/insert $ov=$db->select("select `value` from `".db_prefix."category_options` where `id_option`='".$db->escape($oid)."' and `id_category`='".$db->escape($cid)."' limit 1"); if (sizeOf($ov)==0) { $co=array("id_option"=>$oid,"id_category"=>$cid,"value"=>$value); $db->insert(db_prefix."category_options",$co); } else $db->update(db_prefix."category_options",array("value"=>$value)," `id_option`='".$db->escape($oid)."' and `id_category`='".$db->escape($cid)."' limit 1"); return true; } function getPageOption($name,$page="",$raw=false) //получает значение настройки страницы { if ($page=="") return ""; global $db; $res=$db->select("select `value` from `".db_prefix."page_options` po,`".db_prefix."options` o where id_option=o.id and o.name='".$db->escape($name)."' and id_page='".$page."' and `type`=2"); //echo "select `value` from `".db_prefix."page_options` po,`".db_prefix."options` o where id_option=o.id and o.name='".mysql_escape_string($name)."' and id_page='".$page."' and `type`=2"; if (sizeOf($res)==0) return ""; else { $value=$res[0]['value']; if (IS_MULTILINGUAL && !$raw) $value=multilang($value); return $value; } } function getPageOptions($page,$raw=false) { if ($page=="" || !is_numeric($page)) return ""; global $db; $options=array(); //$res=$db->select("select o.name,po.`value` from `".db_prefix."options` o,`".db_prefix."page_options` po where o.`type`=2 and id_option=o.id and id_page='".$page."'"); $res=$db->select("select o.name,po.`value` from `".db_prefix."options` o,`".db_prefix."page_options` po where po.`id_option`=o.`id` and po.`id_page`='".$page."'"); foreach ($res as $r) { if (IS_MULTILINGUAL && !$raw) $r['value']=multilang($r['value']); $options[$r['name']]=$r['value']; } return $options; } function setPageOption($pid,$option,$value) { if (!is_numeric($pid)) return false; global $db; //check option existence $data=$db->select("select id from `".db_prefix."options` where `name`='".$db->escape($option)."' and `type`=2 limit 1"); if (sizeOf($data)==0) { $o=array("name"=>$option,"type"=>2); $oid=$db->insert(db_prefix."options",$o); } else $oid=$data[0]['id']; //update/insert $ov=$db->select("select `value` from `".db_prefix."page_options` where `id_option`='".$db->escape($oid)."' and `id_page`='".$db->escape($pid)."' limit 1"); if (sizeOf($ov)==0) { $po=array("id_option"=>$oid,"id_page"=>$pid,"value"=>$value); $db->insert(db_prefix."page_options",$po); } else $db->update(db_prefix."page_options",array("value"=>$value)," `id_option`='".$db->escape($oid)."' and `id_page`='".$db->escape($pid)."' limit 1"); return true; } function getUserOption($name,$user="") //получает значение свойства пользователя { if ($user=="") return ""; global $db; $res=$db->select("select `value` from `".db_prefix."user_options` uo,`".db_prefix."options` o where id_option=o.id and o.name='".$db->escape($name)."' and id_user='".$user."' and `type`=1"); if (sizeOf($res)==0) return ""; else return $res[0]['value']; } function setUserOption($uid,$option,$value) { if (!is_numeric($uid)) return false; global $db; //check option existence $data=$db->select("select id from `".db_prefix."options` where `name`='".$db->escape($option)."' and `type`=1 limit 1"); if (sizeOf($data)==0) { $o=array("name"=>$option,"type"=>1); $oid=$db->insert(db_prefix."options",$o); } else $oid=$data[0]['id']; //update/insert $ov=$db->select("select `value` from `".db_prefix."user_options` where `id_option`='".$db->escape($oid)."' and `id_user`='".$db->escape($uid)."' limit 1"); if (sizeOf($ov)==0) { $uo=array("id_option"=>$oid,"id_user"=>$uid,"value"=>$value); $db->insert(db_prefix."user_options",$uo); } else $db->update(db_prefix."user_options",array("value"=>$value)," `id_option`='".$db->escape($oid)."' and `id_user`='".$db->escape($uid)."' limit 1"); return true; } function defineLanguageParams() { global $db; $use_cpu=getSystemOption("use_cpu")==1; if ($use_cpu) { $url_parts=parse_url($_SERVER['REQUEST_URI']); $parts=explode("/",$url_parts['path']); foreach ($parts as $key=>$part) if (substr($part,0,1)=="?" || substr($part,0,1)=="&") unset($parts[$key]); if ($parts[sizeOf($parts)-1]=="") unset($parts[sizeOf($parts)-1]); if (isset($parts[0]) && $parts[0]=="") $parts=array_slice($parts,1); if (sizeOf($parts)==0) $lang_url=""; else $lang_url=$parts[0]; } else $lang_url=$_GET['lang']; $lang_id=0; $langs=array(); $res=$db->select("select * from `".db_prefix."languages` where `active`=1"); foreach ($res as $r) { $langs[$r['id']]=$r; if ($lang_url==$r['url']) $lang_id=$r['id']; if ($r['default']==1) $default=$r; } if ($lang_id==0) $lang_id=$default['id']; //не смогли определить или не указан язык define("LANG_ID",$lang_id,true); define("LANG",$langs[$lang_id]['code'],true); define("DEFAULT_LANG",$langs[$default['id']]['code'],true); define("LANG_URL",$langs[$lang_id]['url'],true); define("IS_DEFAULT_LANG",$lang_id==$default['id'],true); define("LANGS",serialize($langs),true); } function getPageIDnTypeByGet() { global $db; if(isset($_GET['p'])) { if (!is_numeric($_GET['p'])) error404(); else { $res=$db->select("select `id`,`type` from `".db_prefix."pages` where id='".intval($_GET['p'])."'"); if (sizeOf($res)==0) error404(); return array($res[0]['id'],$res[0]['type']); } } else //это индекс, ищем соответствующую в базе { $cond=""; if (IS_MULTISITE) $cond=" and id_category in ".CATEGORIES_COND; $res=$db->select("select id,`type` from `".db_prefix."pages` where `type`='index'".$cond); if (sizeOf($res)==0) error404(); return array($res[0]['id'],$res[0]['type']); } } class Request_URI{ //CONST MODE='fifo'; // CONST MODE='mfifo'; // //CONST MODE='multi'; // method is not prepared for multisite CONST AUTO_MODE=true; CONST DEBUG_MODE=LOCAL; private $_uri=[]; private $_db=null; public $use_cpu=true; public function __construct($db){ $this->setRequest(); $this->_db=$db; $this->use_cpu=getSystemOption("use_cpu")==1; $this->setMultiSite(); } private function setMultiSite(){ $this->need_merge=(defined('USE_ALIAS') && USE_ALIAS && defined("MERGE_MULTISITE_MISSING_PAGES") && MERGE_MULTISITE_MISSING_PAGES); if($this->need_merge){ global $root_cats; //получим список категорий основного домена (из файла multisite.php темы) if(is_array($root_cats) && sizeOf($root_cats)>0){ $this->root_cond="('".implode("','",$root_cats)."')"; }else{ $this->need_merge=false; } } } public function getPage(){ if($this->use_cpu && (!isset($_GET['p']) || !is_numeric($_GET['p'])) && sizeOf($this->_uri)>0){ return $this->getPageCPU(); }else{ return $this->getPageByQuery(); } return false; } public function getRequestString(){ return sizeOf($this->_uri)>0 ? "/".implode("/",$this->_uri)."/" : ""; } private function setRequest(){ $url_parts=parse_url($_SERVER['REQUEST_URI']); $parts=explode("/",$url_parts['path']); foreach($parts as $key=>$part) if(substr($part,0,1)=="?" || substr($part,0,1)=="&"){ unset($parts[$key]); } if($parts[sizeOf($parts)-1]==""){ unset($parts[sizeOf($parts)-1]); } if(isset($parts[0]) && $parts[0]==""){ $parts=array_slice($parts,1); } if(defined('IS_MULTILINGUAL') && IS_MULTILINGUAL && sizeOf($parts)>0){ // check first element is language $langs=defined('LANGS') ? unserialize(LANGS) : []; $is_lang=false; foreach($langs as $lang){ $is_lang=$is_lang || $lang['url']==$parts[0]; } if($is_lang){ $parts=array_slice($parts,1); } } foreach($parts as $key=>$value) if($value=="page" && is_numeric($parts[$key+1])){ $_GET['n']=$parts[$key+1]; unset($parts[$key]); unset($parts[$key+1]); } foreach($parts as $p){ $this->_uri[]=$p; } //$this->_uri=$parts; } private function getPageByQuery(){ return getPageIDnTypeByGet(); } private function getPageCPU(){ $this->trackTime('start_cpu'); $id=''; $type=''; $sign='cpu_'.$this::MODE.'_'.$this->getRequestString(); $cache=$this->storage($sign); if($cache===false){ if(sizeOf($this->_uri)==1){ list($id,$type)=$this->cpuSimple(); }else{ if(!$this::AUTO_MODE && $this::MODE=='fifo' || $this::AUTO_MODE && sizeOf($this->_uri)<3){ list($id,$type)=$this->cpuFIFO(); }elseif(!$this::AUTO_MODE && $this::MODE=='mfifo' || $this::AUTO_MODE && false){ list($id,$type)=$this->cpuModifiedFIFO(); }elseif($this::MODE=='multi' || $this::AUTO_MODE){ list($id,$type)=$this->cpuMulti(); } } $this->storageSet($sign,$id.'-'.$type); }else{ list($id,$type)=explode('-',$cache); } $this->trackTime('finish_cpu'); $this->getTrackTime('start_cpu','finish_cpu',false); return array($id,$type); } private function cpuSimple(){ $id=""; $type=""; if(!$this->_uri || sizeOf($this->_uri)!=1){ return [$id,$type]; } if(defined('IS_MULTISITE') && IS_MULTISITE){ $cond=" and `id_category` in ".CATEGORIES_COND; } $value=urldecode($this->_uri[0]); $q="select `id`,`type` from `".db_prefix."pages` where (`url`='".$this->_db->escape($value)."') and `publish`=1 and `id_parent`=0".$cond; $res=$this->_db->select($q); if(sizeOf($res)==0 && $this->need_merge){ $res=$this->_db->select(" select `id`,`type` from `".db_prefix."pages` where (`url`='".$this->_db->escape($value)."') and `publish`=1 and `id_parent`=0 and `id_category` in ".$this->root_cond ); } if(sizeOf($res)==0){ return $this->pageNotFound($id,$type); } return [$res[0]['id'],$res[0]['type']]; } private function pageNotFound($id,$type){ if($id=="" || (defined('CPU_NONEXISTENT_PARAMS') && CPU_NONEXISTENT_PARAMS==404)){ error404(); return ['','']; }elseif((defined('CPU_NONEXISTENT_PARAMS') && CPU_NONEXISTENT_PARAMS==301) && $id!=""){ redirect301(getPageLink($id).(is_numeric($_GET['n']) && $_GET['n']>1 ? "page/".$_GET['n']."/" : "")); return ['','']; } return [$id,$type]; } private function cpuFIFO(){ $id=""; $type=""; $parent=0; $parent_root=0; $cond=""; if(defined('IS_MULTISITE') && IS_MULTISITE){ $cond=" and `id_category` in ".CATEGORIES_COND; } for($i=0;$i_uri);++$i){ $value=urldecode($this->_uri[$i]); $res=$this->_db->select( "select `id`,`type` from `".db_prefix."pages` where (`url`='".$this->_db->escape($value)."') and `publish`=1 and `id_parent`=".$parent.$cond. " LIMIT 1" ); if(sizeOf($res)==0){ $merged=true; //если нужно, то пробуем найти в основном домене if($this->need_merge){ $res=$this->_db->select(" select `id`,`type` from `".db_prefix."pages` where (`url`='".$this->_db->escape($value)."') and `publish`=1 and `id_parent`=".$parent_root." and `id_category` in ".$this->root_cond. " LIMIT 1" ); } }else{ $merged=false; } if(sizeOf($res)==0){ return $this->pageNotFound($id,$type); }else{ $id=$res[0]['id']; $type=$res[0]['type']; $parent=$id; if($merged){ $parent_root=$id; }elseif($this->need_merge && !$merged){ $res=$this->_db->select(" select id,`type` from `".db_prefix."pages` where (`url`='".$this->_db->escape($value)."') and `publish`=1 and `id_parent`=".$parent_root." and `id_category` in ".$this->root_cond. " LIMIT 1" ); $parent_root=$res[0]['id']; } } } return [$id,$type]; } private function cpuModifiedFIFO(){ $id=""; $type=""; $parent=0; $parent_root=0; $cond=$cond2=""; if(defined('IS_MULTISITE') && IS_MULTISITE){ $cond=" and p.`id_category` in ".CATEGORIES_COND; $cond2=" and p.`id_category` in ".CATEGORIES_COND; } for($i=0;$i_uri);$i+=2){ $value=urldecode($this->_uri[$i]); $join=[]; $sel=[]; $has_child=isset($this->_uri[$i+1]); if($has_child){ $value2=urldecode($this->_uri[$i+1]); $join[]="`".db_prefix."pages` p2 ON (p2.`id_parent`=p.`id` and p2.`publish`=1 and p2.`url`='".$this->_db->escape($value2)."'".$cond2.")"; $sel[]="p2.`id` as `child_id`,p2.`type` as `child_type`"; } $q="select p.`id`,p.`type`".(sizeOf($sel)>0 ? ",".implode(",",$sel) : "")." from `".db_prefix."pages` p ".(sizeOf($join)>0 ? " LEFT JOIN ".implode(" LEFT JOIN ",$join) : '')." where (p.`url`='".$this->_db->escape($value)."') and p.`publish`=1 and p.`id_parent`=".$parent.$cond. " LIMIT 1"; $res=$this->_db->select($q); $is_found=sizeOf($res)!=0; if($is_found && $has_child){ if(!isset($res[0]['child_id']) || !$res[0]['child_id'] || !isset($res[0]['child_type']) || !$res[0]['child_type']){ $is_found=false; $id=$res[0]['id']; $type=$res[0]['type']; } } if(!$is_found){ $merged=true; //если нужно, то пробуем найти в основном домене if($this->need_merge){ $res=$this->_db->select(" select p.`id`,p.`type`".(sizeOf($sel)>0 ? ",".implode(",",$sel) : "")." from `".db_prefix."pages` p ".(sizeOf($join)>0 ? " LEFT JOIN ".implode(" LEFT JOIN ",$join) : '')." where (p.`url`='".$this->_db->escape($value)."') and p.`publish`=1 and p.`id_parent`=".$parent_root." and p.`id_category` in ".$this->root_cond. " LIMIT 1" ); } }else{ $merged=false; } if(!$is_found){ return $this->pageNotFound($id,$type); }else{ $id=$res[0]['id']; $type=$res[0]['type']; if($has_child){ $id=$res[0]['child_id']; $type=$res[0]['child_type']; } $parent=$id; if($merged){ $parent_root=$id; }elseif($this->need_merge && !$merged){ $res=$this->_db->select(" select p.`id`,p.`type`".(sizeOf($sel)>0 ? ",".implode(",",$sel) : "")." from `".db_prefix."pages` p ".(sizeOf($join)>0 ? " LEFT JOIN ".implode(" LEFT JOIN ",$join) : '')." where (`url`='".$this->_db->escape($value)."') and `publish`=1 and `id_parent`=".$parent_root." and `id_category` in ".$this->root_cond. " LIMIT 1" ); $parent_root=$res[0]['id']; if($has_child){ $parent_root=isset($res[0]['child_id']) && $res[0]['child_id'] ? $res[0]['child_id'] : ''; } } } } return [$id,$type]; } private function cpuMulti(){ $id=""; $type=""; $join=[]; $sel=[]; $par="p"; for($i=1;$i_uri);++$i){ $value=urldecode($this->_uri[$i]); $join[]="`".db_prefix."pages` p_".$i." ON (p_".$i.".`id_parent`=".$par.".`id` and p_".$i.".`publish`=1 and p_".$i.".`url`='".$this->_db->escape($value)."')"; $sel[]="p_".$i.".`id` as `child_".$i."_id`,p_".$i.".`type` as `child_".$i."_type`"; $par="p_".$i; } $value=urldecode($this->_uri[0]); $q="SELECT p.`id`,p.`type`".(sizeOf($sel)>0 ? ",".implode(",",$sel) : "")." FROM `".db_prefix."pages` p ".(sizeOf($join)>0 ? " LEFT JOIN ".implode(" LEFT JOIN ",$join) : '')." WHERE (p.`url`='".$this->_db->escape($value)."') and p.`publish`=1 and p.`id_parent`=0". " LIMIT 1"; $res=$this->_db->select($q); if($res===false || sizeOf($res)==0){ return $this->pageNotFound($id,$type); } $id=$res[0]['id']; $type=$res[0]['type']; if(!$id || !$type){ return $this->pageNotFound($id,$type); } $found=true; for($i=1;$i_uri);++$i){ if(isset($res[0]['child_'.$i.'_id']) && $res[0]['child_'.$i.'_id'] && isset($res[0]['child_'.$i.'_type']) && $res[0]['child_'.$i.'_type']){ $id=$res[0]['child_'.$i.'_id']; $type=$res[0]['child_'.$i.'_type']; }else{ $found=false; break; } } if(!$found){ return $this->pageNotFound($id,$type); } return [$id,$type]; } private function storage($key){ if(!defined('USE_MEMCACHED') || !USE_MEMCACHED){ return false; } global $memcached; if(!$memcached){ return false; } return $memcached->get($key); } private function storageSet($key,$value){ if(!defined('USE_MEMCACHED') || !USE_MEMCACHED){ return false; } global $memcached; if(!$memcached){ return false; } return $memcached->set($key,$value,300); } private function trackTime($key){ if(!$this::DEBUG_MODE || $this::DEBUG_MODE==='LOCAL'){ return false; } if(!isset($this->time_tracking)){ $this->time_tracking=[]; } $this->time_tracking[$key]=floatMicrotime(); } private function getTrackTime($key1,$key2,$echo=true,$log=true){ if(!$this::DEBUG_MODE || $this::DEBUG_MODE==='LOCAL' || !isset($this->time_tracking) || !isset($this->time_tracking[$key1]) || !isset($this->time_tracking[$key2])){ return false; } $time=$this->time_tracking[$key2] - $this->time_tracking[$key1]; if($echo){ echo 'Time spent ('.$key2.' - '.$key1.'): '.$time.'ms'; } if($log){ writeLog('Time spent ('.$key2.' - '.$key1.'): '.$time.'ms, with mode '.(sizeOf($this->_uri)==1 ? 'simple' : $this::MODE),'log/cpu_log['.date('Y-m-d').'].log'); } } } function getPageIDnType(){ global $request_params; global $db; $ru=new Request_URI($db); $request_params=$ru->getRequestString(); $page_data=$ru->getPage(); return $page_data; } function uploadImage($field,$type) //upload image and create theme thumbnails { $path=ABSPATH."uploads/images/"; $fname=upload($field,$path,"jpg,jpeg,gif,png"); if ($fname!="") { //check if it is an image if (@getimagesize($path.$fname)==false) { @unlink($path.$fname); return ""; } //creating thumbnails global $picture_sizes; if (is_array($picture_sizes)) foreach ($picture_sizes as $size) { list($width,$height)=explode("x",$size); @resize($path.$fname,$path.addPostfix($fname,"_".$size),$width,$height,"center",85); } $add_logo=true; if(defined('ADD_LOGO_TYPES') && ADD_LOGO_TYPES!=''){ if(is_numeric($type)){ global $db; $page=$db->select("SELECT `type` FROM `".db_prefix."pages` WHERE `id`='".$db->escape($type)."' LIMIT 1"); if(sizeOf($page)==1) $t=$page[0]['type']; }else $t=$type; $logo_types=explode(",",ADD_LOGO_TYPES); if(trim($t)=='' || !in_array($t,$logo_types)) $add_logo=false; } if (ADD_LOGO===true && LOGO_FILE!="" && file_exists(LOGO_FILE) && $add_logo) //adding logo if needed { @addLogoNew($path.$fname,LOGO_FILE); $logo_sizes=explode(",",ADD_LOGO_SIZES); foreach ($logo_sizes as $size) if (in_array($size,$picture_sizes)) @addLogoNew($path.addPostfix($fname,"_".$size),LOGO_FILE); } return $fname; } else return ""; } function getImageURL($fname,$size="",$skip_check=false) //получает URL изображения и проверяет/создает превью по заданному размеру в формате <ширина>x<высота> { $base_url=ALIAS_URL."/uploads/images/"; if ($size=="") return $base_url.$fname; else if ($skip_check) return $base_url.addPostfix($fname,"_".$size); list($width,$height)=explode("x",$size); if (is_numeric($width) && is_numeric($height)) { //ширина и высота заданы верно $path=ABSPATH."uploads/images/"; $preview=addPostfix($fname,"_".$size); if (!file_exists($path.$preview)) { //такого размера нет, создаем @resize($path.$fname,$path.$preview,$width,$height,"center",85); if (ADD_LOGO===true && LOGO_FILE!="" && file_exists(LOGO_FILE)) //adding logo if needed { $logo_sizes=explode(",",ADD_LOGO_SIZES); if (in_array($size,$logo_sizes)) @addLogoNew($path.$preview,LOGO_FILE); } } return $base_url.$preview; } else return $base_url.$fname; } $page_links_cache=array(); $page_parents_cache=array(); function getPageLink_OLD($id,$base=true,$alias=true,$page='') { global $page_links_cache; global $page_parents_cache; $sign=$id.'_'.($base ? '1' : '0').'_'.($alias ? '1' : '0'); if (isset($page_links_cache[$sign])) return $page_links_cache[$sign]; global $db; $parent=''; $use_cpu=getSystemOption("use_cpu")==1; if ($use_cpu) //это ЧПУ { $url=array(); do { if (isset($page_parents_cache[$id])) $res=$page_parents_cache[$id]; else { if ($parent==='' && is_array($page)) $res=array(array('id'=>$page['id'],'url'=>$page['url'],'id_parent'=>$page['id_parent'],'type'=>$page['type'])); else $res=$db->select("select id,`url`,id_parent,`type` from `".db_prefix."pages` where id='".intval($id)."'"); $page_parents_cache[$id]=$res; } if (sizeOf($res)==0) { $page_links_cache[$sign]=''; return ""; } $r=$res[0]; $parent=$id=$r['id_parent']; if ($r['type']=="index" && $r['id_parent']==0 && sizeOf($url)==0) { $page_links_cache[$sign]=ALIAS_URL; return ALIAS_URL; } else $url[]=$r['url']!="" ? $r['url'] : $r['id']; } while ($parent!=0); $url=array_reverse($url); //if (IS_MULTILINGUAL && !IS_DEFAULT_LANG) array_unshift($url,LANG_URL); $result=($base ? ($alias ? ALIAS_URL : SITE_URL)."/" : "").implode("/",$url).(defined("CPU_TRAILING_SLASH") && !CPU_TRAILING_SLASH ? "" : "/"); $page_links_cache[$sign]=$result; return $result; } else { $link="/index.php?p=".$id; if (IS_MULTILINGUAL && !IS_DEFAULT_LANG) $link.="&lang=".LANG_URL; $page_links_cache[$sign]=$link; return $link; } } function getPageLink($id,$base=true,$alias=true,$page=''){ $use_cpu=getSystemOption("use_cpu")==1; if ($use_cpu) //это ЧПУ { global $memcached; global $db; $ttl=3600; $sign=($use_cpu ? '1' : '0').'_URL_'.$id; $url=$memcached->get($sign); /*if ($url!==false) { $memcached->delete($sign); $url=false; }*/ if ($url===false) { if (is_array($page)) $pages=array(array('id'=>$page['id'],'url'=>$page['url'],'id_parent'=>$page['id_parent'],'type'=>$page['type'])); else $pages=$db->select("select id,`url`,id_parent,`type` from `".db_prefix."pages` where id='".intval($id)."'"); if (sizeOf($pages)==0) { $memcached->set($sign,null,$ttl); return ""; } $p=$pages[0]; if ($p['type']=="index" && $p['id_parent']==0) $url=''; else { $url=$p['url']!="" ? $p['url'] : $p['id']; $parent_url=getPageLink($p['id_parent'],false,false,''); $has_slash=($parent_url=='' || substr($parent_url,-1)=='/'); $url=$parent_url.($has_slash ? '' : '/').$url.(defined("CPU_TRAILING_SLASH") && !CPU_TRAILING_SLASH ? "" : "/"); } $memcached->set($sign,$url,$ttl); } else if ($url===null) return ''; $result=($base ? ($alias ? ALIAS_URL : SITE_URL)."/" : "").$url; return $result; } else { $link="/index.php?p=".$id; if (IS_MULTILINGUAL && !IS_DEFAULT_LANG) $link.="&lang=".LANG_URL; return $link; } } function clearUrlsCache($pid) { if (!USE_MEMCACHED) return true; global $memcached; global $db; $sign='1_URL_'.$pid; //echo $sign."
\n"; $memcached->delete($sign); $children=$db->select("select `id` from `".db_prefix."pages` where `id_parent`='".$db->escape($pid)."'"); foreach ($children as $c) clearUrlsCache($c['id']); } function checkCPUTrailingForm() //проверяет есть ли слеш в конце URL согласно настрокам и редиректит 301 на правльную форму { $url=parse_url($_SERVER['REQUEST_URI']); if (IS_MULTILINGUAL){ if (substr($url['path'],0,strlen(LANG_URL)+2)=="/".LANG_URL."/") $url['path']="/".substr($url['path'],strlen(LANG_URL)+2); if ($url['path']=="/".LANG_URL) $url['path']="/"; } if ($url['path']=="" || $url['path']=="/") return false; //no redirect for the home page $has_trailing_slash=(substr($url['path'],strlen($url['path'])-1)=="/"); $need_trailing_slash=(!defined("CPU_TRAILING_SLASH") || CPU_TRAILING_SLASH); if ($has_trailing_slash!=$need_trailing_slash) //reality and expectations don't match { if ($need_trailing_slash && !$has_trailing_slash) $url['path'].="/"; else $url['path']=substr($url['path'],0,strlen($url['path'])-1); $new_url=ALIAS_URL.$url['path'].($url['query']!="" ? "?".$url['query'] : ""); redirect301($new_url); die(); } } function slugize($str) //remove all unwanted charachters from URL-string { $allowed="abcdefghijklmnopqrstuvwxyz-_1234567890"; $str=mb_strToLower(translit($str),"utf-8"); $str=str_replace(" ","-",$str); $replaces=array(); for ($i=0;$i","

"); foreach ($spam_signs as $sign) if (strpos(strtolower($value),$sign)!==false || strip_tags($value)!=$value) return true; return false; } function getPageTags($pid,$get_links=false,$id_category="",$page_type="category") { global $db; $tags=array(); if (!is_numeric($pid)) return $tags; if ($get_links && $id_category===""){ //if need to get links to tag pages, we need category ID $res=$db->select("select id_category from `".db_prefix."pages` where id='".intval($pid)."' limit 1"); $id_category=$res[0]['id_category']; } $res=$db->select("select t.* from `".db_prefix."tag` t, `".db_prefix."page_tag` pt where pt.id_tag=t.id and pt.id_page='".intval($pid)."' order by t.`name`"); foreach ($res as $t) { if (IS_MULTILINGUAL) $t['name']=multilang($t['name']); $tags[$t['id']]=$t; if ($get_links) $tags[$t['id']]['link']=getTagPageLink($t['id'],$id_category,$page_type); } return $tags; } $tag_links_cache=array(); function getTagPageLink($tag_id,$category_id,$page_type="category") { if (!is_numeric($tag_id) || !is_numeric($category_id)) return ""; global $db; $sign=$tag_id."|".$category_id."|".$page_type; global $tag_links_cache; if (isset($tag_links_cache[$sign])) return $tag_links_cache[$sign]; //read cache $query="select p.id,(select count(*) as `cnt` from `".db_prefix."page_tag` pt2 where id_page=p.id) as tag_num from `".db_prefix."page_tag` pt,`".db_prefix."pages` p where p.id=pt.id_page and pt.id_tag='".intval($tag_id)."' and p.`type`='".$db->escape($page_type)."' and p.`id_category`='".intval($category_id)."' order by `tag_num`"; $res=$db->select($query); $page_id=sizeOf($res)>0 ? $res[0]['id'] : 0; $link=$page_id==0 ? "" : getPageLink($page_id); $tag_links_cache[$sign]=$link; return $link; } function getPageAttachments($pid,$raw=false) { $attachments=array(); global $db; $cond=""; if (!$raw) { $cond.=" and pa.`status`=1"; if (IS_MULTILINGUAL) $cond.=" and (pa.`id_lang`=0 or pa.`id_lang`='".$db->escape(LANG_ID)."')"; } if ($raw) $query="select pa.*,l.`name` as `language` from `".db_prefix."page_attachments` pa left join `".db_prefix."languages` l on pa.id_lang=l.id where pa.`id_page`='".$db->escape($pid)."' ".$cond." order by pa.`ord`"; else $query="select pa.* from `".db_prefix."page_attachments` pa where `id_page`='".$db->escape($pid)."' ".$cond." order by `ord`"; $attachments=$db->select($query); if (IS_MULTILINGUAL && !$raw) { foreach ($attachments as $key=>$a) $attachments[$key]['name']=multilang($a['name']); } return $attachments; } $global_multilang_cache=array(); $global_multilang_order=array(); function multilang($str,$lang="",$strict=false) { if ($lang=="") { global $language; if ($language=="" || $language=="LANG") $language=(string)LANG; } else $language=$lang; global $global_multilang_cache; if (isset($global_multilang_cache[$str])) //cache { if (isset($global_multilang_cache[$str][$language])) return $global_multilang_cache[$str][$language]; else return $strict ? "" : $global_multilang_cache[$str]['default']; } //no cache preg_match_all("~\{([A-Z]+)\}~",$str,$matches); //print_r($matches); global $global_multilang_order; if (!is_array($global_multilang_order) || sizeOf($global_multilang_order)<=0) { if (defined("MULTILINGUAL_ORDER") && MULTILINGUAL_ORDER!='') $global_multilang_order=explode(',',MULTILINGUAL_ORDER); if (!is_array($global_multilang_order) || sizeOf($global_multilang_order)<=0) $global_multilang_order=array('EN'); } if (sizeOf($matches[1])==0) { $data=array("default"=>$str); $value=$str; } else { $data=array(); $values=explode("{}",str_replace($matches[0],"{}",$str)); foreach ($matches[1] as $i=>$lng) $data[$lng]=$values[$i+1]; //$data['default']=isset($data['EN']) ? $data['EN'] : $values[1]; $data['default']=''; foreach ($global_multilang_order as $code) if (isset($data[$code]) && $data[$code]!='') { $data['default']=$code=='RU' && $language!='RU' ? translit($data[$code]) : $data[$code]; break; } if ($data['default']=='') $data['default']=$values[1]; $value=isset($data[$language]) ? $data[$language] : ($strict ? "" : $data['default']); } $global_multilang_cache[$str]=$data; return $value; } function get_name_file_multilang($str, $option='', $page_id='', $lang=''){ if($option!=''){ $str = getPageOption($option,$page_id, true); } if(trim($str)==''){ return ($option!=''?'':array()); } preg_match_all("~\{([A-Z]+)\}~",$str,$matches); if(count($matches[1])==0){ return ($option!=''?'':array()); } $values=explode("{}",str_replace($matches[0],"{}",$str)); foreach ($matches[1] as $i=>$lng) $data[$lng]=$values[$i+1]; if($option!=''){ if(isset($data[$lang]) && $data[$lang]!=''){ return $data[$lang]; }elseif(isset($data['EN']) && $data['EN']!=''){ return $data['EN']; }else{ return ''; } }else{ return $data; } } function set_name_file_multilang($array=array()){ if(count($array)==0){ return ''; } $str = ''; foreach($array AS $lang=>$value){ $str .= '{'.$lang.'}'.$value; } return $str; } function getPageMultilangData($pid,$default_data="",$fields="",$language_id="") { global $db; if ($language_id==="") $language_id=LANG_ID; //get default data if ($default_data=="") { $res=$db->select("select * from `".db_prefix."pages` where id='".intval($pid)."' limit 1"); if (sizeOf($res)==0) return "";// no such page $default_data=$res[0]; } $res=$db->select("select * from `".db_prefix."pages_translation` where `id_page`='".intval($pid)."' and `id_language`=".intval($language_id)." limit 1"); if (sizeOf($res)==0) { //no translation for language, should take default $data=array();//$default_data; } else $data=$res[0]; //translated data unset($data['id']); //now choose the output $no_auto_content=(defined('NO_MULTILINGUAL_AUTO_CONTENT') && NO_MULTILINGUAL_AUTO_CONTENT===true); if (!is_array($fields) && $fields!="") //one field { $result=$data[$fields]; if ($result=="" && !($no_auto_content && $fields=='content')) $result=$default_data[$fields]; } else //array of data { $all=$fields==""; $result=array(); foreach ($default_data as $key=>$value) if ($all || in_array($key,$fields)) $result[$key]=$data[$key]=="" && !($no_auto_content && $key=='content') ? $default_data[$key] : $data[$key]; } return $result; } function checkUserExists($field,$value,$exclude_user="") { $value=trim($value); if ($value=="") return false; $fields=array("login","email"); if (!in_array($field,$fields)) return false; if ($exclude_user===""){ global $user; $exclude_id=$user->id; } else $exclude_id=$exclude_user; global $db; $value=trim($value); $res=$db->select("select id from `".db_prefix."users` where `".$field."`='".$db->escape($value)."' and id<>'".$db->escape($exclude_id)."' limit 1"); return (sizeOf($res)>0); } function registerNewUser($login,$password,$email,$name,$custom_options,$force_email=false) { $login=trim($login); $password=trim($password); $email=trim($email); if (DEBUG && $login=="") writeLog("no login to register!"); if (DEBUG && $password=="") writeLog("no password to register!"); if (DEBUG && $force_email && $email=="") writeLog("no email to register!"); if ($login=="" || $password=="" || $force_email && $email=="") return false; if (checkUserExists("login",$login)) {writeLog("check login failed");return false;} if ($email!="" && checkUserExists("email",$email)) {if (DEBUG) writeLog("check email failed");return false;} global $db; $mas['login']=$login; $mas['password']=md5($password); $mas['email']=$email; $mas['name']=$name; $mas['status']=1; $mas['id_type']=SITE_USER_TYPE_ID; $uid=$db->insert(db_prefix."users",$mas); if($uid===false) return false; if (is_array($custom_options) && sizeOf($custom_options)>0) foreach ($custom_options as $param=>$value){ setUserOption($uid,$param,$value); /*$zap_op=$db->select("select id from `".db_prefix."options` where `name`='".$db->escape($param)."' and `type`=1"); if (sizeOf($zap_op)>0) { $o['id_option']=$zap_op[0]['id']; $o['id_user']=$uid; $o['value']=$value; $db->insert(db_prefix."user_options",$o); } */ } return $uid; } $options_type2_cache=null; function getPages($params) //get pages list with correct language by params { $total=0; $items=array(); global $db; //optimisation $optimize=isset($params['optimize']); //set conditions $cond=isset($params['condition']) ? $params['condition'] : ""; if (IS_MULTISITE) $cond.=" and p.`id_category` in ".CATEGORIES_COND; $from=""; $join=array(); $options_aliases=array(); $compare_types=array("=","<>","<",">","<=",">=","in","between","like","not in"); if (isset($params['type'])) $cond.=" and p.`type`='".$db->escape($params['type'])."'"; if (is_numeric($params['id_parent'])) $cond.=" and p.`id_parent`='".$db->escape($params['id_parent'])."'"; if (is_numeric($params['id_category'])) $cond.=" and p.`id_category`='".$db->escape($params['id_category'])."'"; //set tag conditions $distinct=false; if (is_array($params['tags']) && sizeOf($params['tags'])>0) { $tags=array(); foreach ($params['tags'] as $tag) if (is_numeric($tag)) $tags[]=$db->escape($tag); if (sizeOf($tags)>0) { $join[]=" left join `".db_prefix."page_tag` pt on p.`id`=pt.`id_page`"; $cond.=" and pt.`id_tag` in ('".implode("','",$tags)."')"; if (sizeOf($tags)>1) $distinct=true; } } //set options conditions if (is_array($params['options']) && sizeOf($params['options'])>0) { global $options_type2_cache; if (!is_array($options_type2_cache)) { $options=array(); //options IDs cache $data=$db->select("select * from `".db_prefix."options` where `type`=2"); foreach ($data as $o) $options[$o['name']]=$o['id']; $options_type2_cache=$options; } else $options=$options_type2_cache; foreach ($params['options'] as $i=>$o) if (isset($options[$o['name']])){ $options_aliases[$o['name']]="po_".$i; $join[]=" left join `".db_prefix."page_options` po_".$i." on p.`id`=po_".$i.".`id_page` and po_".$i.".`id_option`='".$db->escape($options[$o['name']])."'"; $compare=isset($o['compare']) && in_array($o['compare'],$compare_types) ? $o['compare'] : "="; if ($compare=="in") { if (!is_array($o['value'])) $o['value']=array_map("trim",explode(",",$o['value'])); $in=""; foreach ($o['value'] as $val) $in.=",'".$db->escape($val)."'"; $cond.=" and (po_".$i.".`value` in (".($in=="" ? "''" : substr($in,1)).")"; if($o['strict']!==true) $cond.=" or po_".$i.".`value` IS NULL"; $cond.=" )"; } else if ($compare=="not in") { if (!is_array($o['value'])) $o['value']=array_map("trim",explode(",",$o['value'])); $notin=""; foreach ($o['value'] as $val) $notin.=",'".$db->escape($val)."'"; $cond.=" and (po_".$i.".`value` not in (".($notin=="" ? "''" : substr($notin,1)).")"; if($o['strict']!==true) $cond.=" or po_".$i.".`value` IS NULL"; $cond.=" )"; } else if (is_array($o['value'])) { $subconds=""; foreach ($o['value'] as $val) { if ($compare=="between") { if (!is_array($val)) $val=array_map("trim",explode(",",$val)); if (sizeOf($val)<2) $subconds.=" or (po_".$i.".`value`='".$db->escape($val[0])."')"; else { $b_from=isset($val['from']) ? $val['from'] : $val[0]; $b_to=isset($val['to']) ? $val['to'] : $val[1]; $subconds.=" or (po_".$i.".`value`>='".$db->escape($b_from)."'".($o['compare_type']=="numeric" ? "+0" : "")." and po_".$i.".`value`<='".$db->escape($b_to)."'".($o['compare_type']=="numeric" ? "+0" : "").")"; } } else if ($compare=="like") $subconds.=" or (po_".$i.".`value` like '%".$db->escape($val)."%')"; else $subconds.=" or (po_".$i.".`value`".$compare."'".$db->escape($val)."'".($o['compare_type']=="numeric" ? "+0" : "").")"; } $cond.=" and ((".substr($subconds,4).")"; if($o['strict']!==true) $cond.=" or po_".$i.".`value` IS NULL"; $cond.=" )"; } else if ($compare=="like") $cond.=" and po_".$i.".`value` like '%".$db->escape($o['value'])."%'"; else{ $cond.=" and (po_".$i.".`value`".$compare."'".$db->escape($o['value'])."'".($o['compare_type']=="numeric" ? "+0" : ""); if($o['strict']!==true /*&& $compare=='<>'*/) $cond.=" or po_".$i.".`value` IS NULL"; $cond.=" )"; } } } //multilingual join if needed if (IS_MULTILINGUAL && !IS_DEFAULT_LANG && ($params['force_language']===true || $params['search']!="")) { $from.="`".db_prefix."pages_translation` ptr, "; $cond.=" and ptr.`id_page`=p.id and ptr.`id_language`=".LANG_ID; } //search if ($params['search']!="") { $srch="'%".$db->escape($params['search'])."%'"; if (IS_MULTILINGUAL && !IS_DEFAULT_LANG) $cond.=$params['search_title_only'] ? " and ptr.`name` like ".$srch : " and (ptr.`name` like ".$srch." or ptr.`content` like ".$srch.")"; else $cond.=$params['search_title_only'] ? " and p.`name` like ".$srch : " and (p.`name` like ".$srch." or p.`content` like ".$srch.")"; } //set order if ($optimize) { $order=''; if (!isset($params['optimize']['sort_by'])) $sort="CONCAT((1000000-p.`order`+0),p.`data_create`,LPAD(p.`id`,8,0))"; else $sort=$params['optimize']['sort_by']; $data_sort_order=(strtolower($params['optimize']['sort_order'])=="asc" ? "ASC" : "DESC"); $select='p.`id`'.($sort=='' ? '' : ','.$sort.' as `srt`'); } else { $order="p.`order` asc, p.`data_create` desc, p.`id` desc"; if ($params['sort_by']!=""){ if (is_array($params['sort_by'])){ if (isset($params['sort_by']['option'])) { //sort by given option value $order=$options_aliases[$params['sort_by']['option']].".`value`"; if ($params['sort_by']['compare_type']=="numeric") $order.="+0"; //compare as numbers } } else $order=$params['sort_by']; $order.=" ".(strtolower($params['sort_order'])=="asc" ? "ASC" : "DESC"); } $order=' order by '.$order; if ($params['sort_by']==='') $order=''; $select='p.*'; if (isset($params['select']) && $params['select']!='') $select=$params['select']; } //set limits if (!$optimize && is_numeric($params['per_page']) && $params['per_page']>0) { $page=is_numeric($params['page_number']) ? $params['page_number'] : getPage(); $limit=" limit ".($page-1)*$params['per_page'].",".$params['per_page']; } else $limit=""; $publish_cond=$params['publish']===false ? "p.`publish`>=0" : "p.`publish`=1"; $query="select ".($distinct ? 'distinct ' : '').$select." from ".$from."`".db_prefix."pages` p ".(sizeOf($join)>0 ? implode(" ",$join) : "")." where ".$publish_cond." ".$cond.$order."".$limit; //var_dump($query); //echo $query."

\n\n"; if ($optimize) { $rows=$db->select($query); $total=sizeOf($rows); $sort_params['order']=$data_sort_order=='ASC' ? 1 : -1; $sort_params['compare']=$params['optimize']['compare_type']=='numeric' ? 1 : 0; usort($rows,function($a,$b) use ($sort_params){ if ($sort_params['compare']==1) { if ($a['srt']<$b['srt']) $res=-1; else if ($a['srt']>$b['srt']) $res=1; else $res=0; } else $res=strcmp($a['srt'],$b['srt']); return $sort_params['order']*$res; }); //limits if (is_numeric($params['per_page']) && $params['per_page']>0) { $page=is_numeric($params['page_number']) ? $params['page_number'] : getPage(); $rows=array_slice($rows,($page-1)*$params['per_page'],$params['per_page']); } //get page IDs and perform real query $ids=''; foreach ($rows as $r) $ids.=','.$r['id']; $data=$db->select("select p.* from `".db_prefix."pages` p where p.`id` in (".substr($ids,1).") order by FIELD(p.`id`".$ids.")"); } else { $data=$db->select($query); if ($limit=='' || $params['skip_total']===true) $total=sizeOf($data); else { $query_count="select count(*) as `cnt` from ".$from."`".db_prefix."pages` p ".(sizeOf($join)>0 ? implode(" ",$join) : "")." where ".$publish_cond." ".$cond; $cnt=$db->select($query_count); $total=$cnt[0]['cnt']; } } foreach ($data as $p) { if (IS_MULTILINGUAL && !IS_DEFAULT_LANG) $p=getPageMultilangData($p['id'],$p); if ($params['get_options']===true) { $p['options_raw']=getPageOptions($p['id'],true); $p['options']=IS_MULTILINGUAL ? array() : $p['options_raw']; if (IS_MULTILINGUAL) foreach ($p['options_raw'] as $o_name=>$value) $p['options'][$o_name]=multilang($value); } $items[]=$p; } return array($items,$total); } function searchPages($keyphrase,$per_page=10,$exclude_types="") //search pages list by keyphrase { global $db; $params=array( "search"=>$keyphrase, "per_page"=>(is_numeric($per_page) ? $per_page : 10), "page_number"=>getPage(), ); //exclude types condition if (!is_array($exclude_types)) { /* build exclude types condition on XML settings */ $exclude_types=array(); $types_string=getSystemOption("xml_sitemap_exclude_types"); $variants=explode(",",$types_string); foreach ($variants as $key=>$value) { $value=trim($value); if ($value!=="") $exclude_types[]=$value; } } foreach ($exclude_types as $key=>$value) $exclude_types[$key]=$db->escape($value); if (sizeOf($exclude_types)>0) $params['condition']=" and p.`type` not in ('".implode("','",$exclude_types)."')"; //use common getPages function to get results return getPages($params); } function formatDate($date) { $hour=(int)(substr($date,11,2)); $minute=(int)(substr($date,14,2)); $month=(int)substr($date,5,2); $day=(int)substr($date,8,2); $year=(int)substr($date,0,4); $date_ts=mktime($hour,$minute,1,$month,$day,$year); $format=getSystemOption("date_format"); if ($format=="") $format=DEFAULT_DATE_FORMAT; return date($format,$date_ts); } //comments function getCommentsList($params) { $total=0; $items=array(); global $db; $opt_data=$db->select("select id from `".db_prefix."options` where `type`=1 and `name`='soc_params'"); $oid=$opt_data[0]['id']; //conditions $cond=""; if (IS_MULTILINGUAL) { if (!isset($params['language']) || !is_numeric($params['language'])) $cond.=" and (c.`id_lang`='0' or c.`id_lang`='".LANG_ID."')"; else if ($params['language']!=0) $cond.=" and c.`id_lang`='".$db->escape($params['language'])."'"; } if (is_numeric($params['id_page'])) $cond.=" and c.`id_page`='".$db->escape($params['id_page'])."'"; if (isset($params['publish']) && is_numeric($params['publish'])) $cond.=" and c.`publish`='".$db->escape($params['publish'])."'"; else $cond.=" and c.`publish`='1'"; if ($cond!="") $cond=substr($cond,4); //set order $order="c.`id` "; if ($params['sort_by']!=""){ $order=$params['sort_by']; $order.=" ".($params['sort_order']=="ASC" ? "ASC" : "DESC"); } //set limits if (is_numeric($params['per_page']) && $params['per_page']>0) { $page=is_numeric($params['page_number']) ? $params['page_number'] : getPage(); $limit=" limit ".($page-1)*$params['per_page'].",".$params['per_page']; } else $limit=""; $query="select c.*,u.`name`,uo.`value` as soc_params from `".db_prefix."comments` c left join `".db_prefix."user_options` uo on uo.`id_option`='".$oid."' and uo.`id_user`=c.`id_user` left join `".db_prefix."users` u on c.`id_user`=u.`id` where ".$cond." order by ".$order.$limit; $items=$db->select($query); foreach ($items as $key=>$comment) { $items[$key]['soc_params']=$comment['soc_params']=="" ? array() : unserialize($comment['soc_params']); if ($comment['name']=="") $items[$key]['name']=$comment['soc_name']; $items[$key]['avatar']=$items[$key]['soc_params']['avatar']!="" ? $items[$key]['soc_params']['avatar'] : ""; $items[$key]['user_link']=$items[$key]['soc_params']['uid']!="" ? $items[$key]['soc_params']['uid'] : "#"; } //get total if (sizeOf($items)==0) $total=0; else { $data=$db->select("select count(*) as `cnt` from `".db_prefix."comments` c where ".$cond); $total=$data[0]['cnt']; } return array($items,$total); } function commentsBlock($id_page,$pagination=0,$form_tpl="",$unlogged_tpl="",$list_tpl="",$item_tpl="") { if ($id_page=="" || !is_numeric($id_page)) return ""; if (!is_numeric($pagination)) $pagination=0; if ($form_tpl=="") $form_tpl="comments_form"; if ($unlogged_tpl=="") $unlogged_tpl="comments_unlogged"; if ($list_tpl=="") $list_tpl="comments_list"; if ($item_tpl=="") $item_tpl="comments_list_item"; $form=LoadTemplate($form_tpl); $unlogged=LoadTemplate($unlogged_tpl); $list=LoadTemplate($list_tpl); $item=LoadTemplate($item_tpl); global $db; $html=""; if (logged()) { global $user; $f['name']=$user->name; $html.=arrayToTemplate($f,$form); } else $html.=$unlogged; $opt_data=$db->select("select id from `".db_prefix."options` where `type`=1 and `name`='soc_params'"); $oid=$opt_data[0]['id']; $res['items']=""; $sort_setting=getSystemOption("comments_sort"); if ($sort_setting=="") $sort_setting=COMMENTS_SORT; $sort_order=strtolower($sort_setting); if ($sort_order!="asc") $sort_order="desc"; $params=array("id_page"=>$id_page); if ($pagination!=0) $params['per_page']=$pagination; $params['sort_by']="c.`data`"; $params['sort_order']=$sort_order; list($comments,$total)=getCommentsList($params); foreach ($comments as $comment) { if ($comment['avatar']!="") $comment['avatar']='

'; $comment['date']=formatDate($comment['data']); $comment['comment']=nl2br($comment['comment']); $res['items'].=arrayToTemplate($comment,$item); } $html.=arrayToTemplate($res,$list); if ($pagination!=0) $html.=pagenavigation($total,$pagination); return $html; } function registerComment($id_page,$comment) { if (!logged()) return "ERROR"; if (!is_numeric($id_page)) return "ERROR"; if (formSpamFilter($comment)) return "ERROR"; global $db; global $user; $data=$db->select("select id,name from `".db_prefix."pages` where `id`='".$db->escape($id_page)."' limit 1"); if (sizeOf($data)==0) return "ERROR"; $page_name=$data[0]['name']; $c=array(); $c['id_page']=$id_page; $c['id_user']=$user->id; $c['data']=date("Y.m.d H:i"); $c['comment']=$comment; $c['publish']="0"; $c['id_lang']=LANG_ID; $c['ip']=$_SERVER['REMOTE_ADDR']; $res=$db->insert(db_prefix."comments",$c); if ($res===false) return "ERROR"; //inform admin $inform_comment=getSystemOption("comments_inform_new"); $inform_email=getSystemOption("comments_inform_email"); if ($inform_comment==1 && $inform_email!="") { $from="noreply@".$_SERVER['HTTP_HOST']; $subject="New comment on ".ALIAS_URL; $message="Please review new comment for "".$page_name."" (".getPageLink($id_page).")"; $res=sendEmail($from,$inform_email,$subject,$message); } return "OK"; } //default multisite init function initDefaultMultisite() { global $db; $use_alias=false; $alias_url=SITE_URL; $alias=array(); $avail_cats=array(); $prt=explode("://",SITE_URL); $site_host=$prt[1]; if (IS_MULTILANG && !IS_DEFAULT_LANG) $site_host=str_replace("/".LANG_URL,"",$site_host); if (substr($site_host,0,4)=="www.") $site_host=substr($site_host,4); $host=$_SERVER['HTTP_HOST']; if (substr($host,0,4)=="www.") $host=substr($host,4); if ($host!=$site_host) //$site_host определен в конструкторе { $parts=explode(".",$host); $subdomain=$parts[0]; $domain=implode(".",array_slice($parts,1)); if ($domain==$site_host) { $subdomains=$db->select("select * from `".db_prefix."subdomains` where `domain`='".$db->escape($subdomain)."' and `active`=1"); if (sizeOf($subdomains)>0) { $use_alias=true; $alias=$subdomains[0]; $alias_url="http://".$subdomain.".".$site_host.(IS_MULTILANG && !IS_DEFAULT_LANG ? "/".LANG_URL : ""); } } } $avail_cats=getDefaultAvailCats($use_alias ? $alias['city'] : ""); return array($use_alias,$alias_url,$alias,$avail_cats); } function getDefaultAvailCats($city="",$parent=0) { global $db; $cat_ids=array(); if ($parent==0) { if ($city!="") $query="select id from `".db_prefix."category` where `name` like '%::".$db->escape($city)."'"; else { $query="select id from `".db_prefix."category` where `id_parent`=0 and `name` not like '%::%'"; $cat_ids[]=0; } } else $query="select id from `".db_prefix."category` where id_parent='".$parent."'"; $categories=$db->select($query); foreach ($categories as $cat) { $cat_ids[]=$cat['id']; $cat_ids=array_merge($cat_ids,getDefaultAvailCats($city,$cat['id'])); } return $cat_ids; } function logMemoryUsage() { $peak_memory_used=memory_get_peak_usage(true); $memory_used=memory_get_usage(true); $memory_log_file=ABSPATH.'log/memory/'.date("Y-m-d").'.log'; $str=date("Y-m-d H:i:s")."\t".$_SERVER['REMOTE_ADDR']."\t".$_SERVER['REQUEST_URI']."\t".convertBytesSize($memory_used)."\t".convertBytesSize($peak_memory_used); file_put_contents($memory_log_file,$str."\r\n",FILE_APPEND); } function convertBytesSize($size) { $unit=array('b','kb','mb','gb','tb','pb'); return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; } ?>