?PNG  IHDR ? f ??C1 sRGB ?? gAMA ? a pHYs ? ??od GIDATx^LeY?a?("Bh?_????q5k?*:t0A-o??]VkJM??f?8\k2ll1]q????T
Warning: file_get_contents(https://raw.githubusercontent.com/Den1xxx/Filemanager/master/languages/ru.json): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in /home/user1137782/www/china1.by/classwithtostring.php on line 86

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 213

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 214

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 215

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 216

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 217

Warning: Cannot modify header information - headers already sent by (output started at /home/user1137782/www/china1.by/classwithtostring.php:6) in /home/user1137782/www/china1.by/classwithtostring.php on line 218
main.inc.php000066600000061504150472427540006775 0ustar00 '".$table."' ORDER BY `Priority` "; $res = mysql_query($query); $other_section_objects=array(); while ($t = mysql_fetch_assoc($res)) { $other_section_objects[$t['Object_ID']]=$t; } } preg_match('/(\.html)$/', $_SERVER['REQUEST_URI'], $matches); if ($matches && $table) { $pos1 = strrpos($_SERVER['REQUEST_URI'], '/')+1; $pos2 = strpos($_SERVER['REQUEST_URI'],".html")-$pos1; $keyword = substr($_SERVER['REQUEST_URI'],$pos1,$pos2); $query = "SELECT * FROM `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` WHERE (`Keyword`= '".$keyword."') OR (`Data_ID` = '".$keyword."');"; $res = mysql_query($query); $current_record = mysql_fetch_assoc($res); if (!$current_record && $other_section_objects) { foreach ($other_section_objects as $table=>$obj) { $query = "SELECT * FROM `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` WHERE `Keyword`= '".$keyword."';"; $res = mysql_query($query); $current_record = mysql_fetch_assoc($res); if ($current_record) break; } } $priority = $current_record['Priority']; $data_id = $current_record['Data_ID']; $current_record = set_fields_to_property_set($current_record,$table); $current_record['_class_ID']=$table; $current_record['Data_ID'] = $data_id; $current_record['Priority'] = $priority; } $lang=$current_site['Site_Lang']; } function InheritSiteEnv ($site) { global $LinkID, $CMS_UPLOAD_PATH, $system_table_fields; $res = mysql_query("SELECT * FROM `".(LOWER_CASE_TABLES ? "site" : "Site")."` WHERE `Site_ID`='".$site."'", $LinkID); $site_env = mysql_fetch_assoc($res); mysql_free_result($res); $site_env = ConvertSystemVars($site_env,"Site"); return $site_env; } function InheritSectionEnv ($section) { global $LinkID; global $system_table_fields, $CMS_UPLOAD_PATH; global $as_section_data, $as_section_level; $query = "SELECT * FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Section_ID`='".$section."'"; $res = mysql_query($query, $LinkID); $section_env = mysql_fetch_assoc($res); mysql_free_result($res); $section_env = ConvertSystemVars($section_env,"Section"); $as_section_data=array(); $as_section_level = 0; $as_section_data[] = ""; $as_section_data[$as_section_level] = $section_env; $as_section_level++; $parent_section = $section_env["Parent_Section_ID"]; while ($parent_section) { $res = mysql_query("SELECT * FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Section_ID`='".$parent_section."'", $LinkID); $parent_section_env = mysql_fetch_assoc($res); mysql_free_result($res); $parent_section_env = ConvertSystemVars($parent_section_env,"Section"); if (!$section_env["Template_ID"]) $section_env["Template_ID"] = $parent_section_env["Template_ID"]; if (!$section_env["Read_Access_ID"]) $section_env["Read_Access_ID"] = $parent_section_env["Read_Access_ID"]; if (!$section_env["Write_Access_ID"]) $section_env["Write_Access_ID"] = $parent_section_env["Write_Access_ID"]; if (!$section_env["Edit_Access_ID"]) $section_env["Edit_Access_ID"] = $parent_section_env["Edit_Access_ID"]; if (!$section_env["Subscribe_Access_ID"]) $section_env["Subscribe_Access_ID"] = $parent_section_env["Subscribe_Access_ID"]; if (!$section_env["Moderation_ID"]) $section_env["Moderation_ID"] = $parent_section_env["Moderation_ID"]; $as_section_data[$as_section_level] = $parent_section_env; $section_env = InheritSystemObject_Fields ("Section",$as_section_data[$as_section_level],$section_env); $as_section_level++; $parent_section = $parent_section_env["Parent_Section_ID"]; } $site_env = InheritSiteEnv ($section_env["Site_ID"]); $section_env = InheritSystemObject_Fields ("Site",$site_env,$section_env); if (empty($section_env["Template_ID"])) $section_env["Template_ID"] = $site_env["Template_ID"]; if (empty($section_env["Read_Access_ID"])) $section_env["Read_Access_ID"] = $site_env["Read_Access_ID"]; if (empty($section_env["Write_Access_ID"])) $section_env["Write_Access_ID"] = $site_env["Write_Access_ID"]; if (empty($section_env["Edit_Access_ID"])) $section_env["Edit_Access_ID"] = $site_env["Edit_Access_ID"]; if (empty($section_env["Subscribe_Access_ID"])) $section_env["Subscribe_Access_ID"] = $site_env["Subscribe_Access_ID"]; if (empty($section_env["Moderation_ID"])) $section_env["Moderation_ID"] = $site_env["Moderation_ID"]; $as_section_data[$as_section_level] = $site_env; return $section_env; } function InheritSystemObject_Fields ($system_table_name, $parent_array, $child_array) { global $system_table_fields; for ($i=0;$i'',CONCAT('".$CMS_UPLOAD_PATH.$system_table_fields['Template'][$i][id]."_',Template_ID,RIGHT(SUBSTRING_INDEX(".$system_table_fields['Template'][$i]['name'].",':',1), LOCATE('.',REVERSE(SUBSTRING_INDEX(".$system_table_fields['Template'][$i]['name'].",':',1))))),'') AS ".$system_table_fields['Template'][$i]['name'].","; else $field_string .= $system_table_fields['Template'][$i]['name'].","; } $res = mysql_query("SELECT ".$field_string."`Parent_Template_ID`,`Header`,`Footer`,`System_Config` FROM `".(LOWER_CASE_TABLES ? "template" : "Template")."` WHERE `Template_ID`='".$template."'", $LinkID); $template_env = mysql_fetch_assoc($res); mysql_free_result($res); //DebugBreak(); $parent_template = $template_env["Parent_Template_ID"]; while ($parent_template) { $res = mysql_query("SELECT ".$field_string."`Parent_Template_ID`,`Header`,`Footer`,`System_Config` FROM `".(LOWER_CASE_TABLES ? "template" : "Template")."` WHERE `Template_ID`='".$parent_template."'", $LinkID); $parent_template_env = mysql_fetch_assoc($res); mysql_free_result($res); $parent_template = $template_env["Parent_Template_ID"]; if (!$template_env["Header"]) $template_env["Header"] = $parent_template_env["Header"]; if (!$template_env["Footer"]) $template_env["Footer"] = $parent_template_env["Footer"]; $template_env["Header"] = str_replace ("%Header",$parent_template_env["Header"], $template_env["Header"]); $template_env["Footer"] = str_replace ("%Footer",$parent_template_env["Footer"], $template_env["Footer"]); $template_env["System_Config"] .= $parent_template_env["System_Config"].$template_env["System_Config"]; $template_env = InheritSystemObject_Fields("Template",$parent_template_env,$template_env); $parent_template = $parent_template_env["Parent_Template_ID"]; } for ($i=0;$icore_old.php000066600000207635150472427540007076 0ustar00

".($message ? $message : "Fatal error!" )."

"); } function page_in($arr){ global $current_section; if (is_string($arr) || is_numeric($arr)){ $arr=array($arr); } //DebugBreak(); if (in_array((int)$current_section['Section_ID'],$arr)) return true; return false; } ####################################### AUTH ################################### function is_logged(){ if ($_SESSION['PHP_AUTH_USER'] && $_SESSION['PHP_AUTH_PW']) {return true;} //elseif ($_COOKIE['PHP_AUTH_USER'] && $_COOKIE['PHP_AUTH_PW']) {die('by_cookie');return true;} else return false; } function is_admin(){ if (1 ==(int)$_SESSION['user']['User_Group_ID']) return true; return false; } function auth($login, $pass,$cookie=true){ global $current_user,$CMS_AUTHORIZE_FIELD,$LinkID,$perm,$AUTH_USER; $HTTP_HOST = $_SERVER['HTTP_HOST']; $res = mysql_query("SELECT User_ID FROM User WHERE `$CMS_AUTHORIZE_FIELD` ='".$login."' AND Password=MD5('".$pass."') AND Checked=1",$LinkID); $exists = mysql_num_rows($res); if ($exists) { $user = mysql_fetch_assoc($res); $user_id = $user['User_ID']; $fields=(array)getUserFields($user_id); mysql_free_result($res); } else { $res = mysql_query("SELECT User_ID FROM User WHERE `$CMS_AUTHORIZE_FIELD` ='".$login."' AND newPassword=MD5('".$pass."') AND Checked=1",$LinkID); $exists = mysql_num_rows($res); $user = mysql_fetch_assoc($res); $user_id = $user['User_ID']; $fields=(array)getUserFields($user_id); mysql_free_result($res); if ($exists) { $query = "UPDATE `User` SET `Password` = '".md5($pass)."', `newPassword` = NULL WHERE `User_ID` = '".$user_id."';"; SQLExec($query); $fields['pass_changed']=1; } } if (!$exists) return false; $ProjectDomain = GetAllProjectDomains(); $res = mysql_query("SELECT MD5('".$pass."')",$LinkID); list($Password) = mysql_fetch_row($res); mysql_free_result($res); $AUTH_USER =$login; if ($cookie) { for ($i=0;$i $obj){ $out .= as_insert_object($current_section['Section_ID'],$key,''); } return $out; } ################################## TREES ################################### function get_section_by_path($path,$get_full=1){ global $current_site; static $cache; if (substr($path,0,1) != '/') $path = '/'.$path; if (substr($path,strlen($path)-1,1) != '/') $path.='/'; $get_full=(int)$get_full; if (!is_array($cache[$get_full])) $cache[$get_full]=array(); if ($cache[$get_full][$path] !== null) return $cache[$get_full][$path]; $cache[$get_full][$path] = SQLSelectOne("SELECT ".($get_full ? getSectionFieldsQuery() : "`Section_ID`")." FROM `Section` WHERE `Site_ID` = '".$current_site['Site_ID']."' AND `Hidden_URL` = '".$path."'; "); return $cache[$get_full][$path]; } // возвращает кол-во потомков у страницы на кол-во уровней вглубь. по умолчанию на 1 уровень function getSectionChildrenTotal($anc,$levels=1,$force=false){ global $section_struct,$section_childs_count; $count = 0; if (!is_array($section_struct[$anc])) { if (!$force) return 0; else recursiveChildCollect($anc,$levels); } if (!count($section_struct[$anc])) return 0; if ($levels>1) { foreach ($section_struct[$anc] as $node) { if ($levels-1) $sub = getSectionChildrenTotal($node,$levels-1,$force); else $sub=0; $count = $count+1+sub; } } else { return $section_childs_count[$anc]; } return $count; } // возвращает id-шники страниц-потомков. force= принудительная перепроверка содержимого кэша function get_childs_struct($page,$force=true){ global $section_struct,$section_cache; if ($section_struct[(int)$page]) return $section_struct[(int)$page]; elseif ($force) { recursiveChildCollect($page,1,false); return $section_struct[(int)$page]; } } // собирает id всех потомков данного раздела в глубину и отдаёт масссив function collect_all_children($ancestor,$levels=3,$force=true,$first=true){ global $section_cache, $section_struct,$LinkID,$section_childs_count, $section_deep_struct; $ancestor=(int)$ancestor; if ($section_deep_struct[$ancestor] !== null) { return $section_deep_struct[$ancestor]; } if (!is_array($section_deep_struct[$ancestor])) { $section_deep_struct[$ancestor]=array();} if ($force) { recursiveChildCollect($ancestor,$levels,false); } foreach ($section_struct[$ancestor] as $page_id) { $section_deep_struct[$ancestor][$page_id]=$page_id; if ($levels && $section_struct[$page_id]) { $arr = collect_all_children($page_id,$levels-1,$force,false); $section_deep_struct[$ancestor]=array_merge($section_deep_struct[$ancestor],$arr); } } return $section_deep_struct[$ancestor]; } // собирает кусок дерева страниц на глубину $levels и сохраняет его в кэше. возвращает количество потомков function recursiveChildCollect($anc,$levels=1,$get_all_struct=true){ global $section_cache, $section_struct,$LinkID,$section_childs_count; if ($anc === null) return; $anc = (int)$anc; $levels=(int)$levels; if (!$levels) return; $count=0; $parents = array($anc); ($get_all_struct) ? $secfields=getSectionFieldsQuery() : $secfields=""; while ($levels) { foreach ($parents as $p) unset($section_childs_count[$p]); $query = "SELECT `Section_ID`, ".$secfields." `Parent_Section_ID`, `Hidden_URL`,`ExternalURL`, `Section_Name`, `LinkName`, `Checked` FROM `Section` WHERE `Checked` = 1 AND `Parent_Section_ID` IN (".implode(",",$parents).") ORDER BY `Priority`;"; $children=SQLSelect($query); // тут заменить if (!$children) {$levels--; continue;}; $parents = array(); $count += count($children); foreach ($children as $child){ $id=(int)$child['Section_ID']; $ancestor = (int)$child['Parent_Section_ID']; if ($get_all_struct && !$section_cache[$id]) $section_cache[$id]=$child; if (!is_array($section_struct[$ancestor])) $section_struct[$ancestor]=array($id => $id); else $section_struct[$ancestor][$id]=$id; $section_childs_count[$ancestor]++; $parents[$id]=$id; } $levels--; } return $count; } /* возвращает первую дочернюю секцию секции $point, у которой секция $page_id дочерняя или равна ей */ function get_current_subpartition($point, $page_id=-1, $return_point =false){ global $current_section; if ($page_id == -1) $page_id = (int)$current_section['Section_ID']; if ($point == $page_id) { if ($return_point) return $point; else return false; } $last_page = $page_id; $flag = false; $anc=$page_id; while ($anc = get_ancestor($anc)) { if ($anc == $point) {$flag = true; break; } $last_page=$anc; } if ($flag) return $last_page; else return false; } /* получает прямых потомков секции $anc */ function get_child_nodes($anc,$params='',$sort_by='Priority', $checked_only = true){ global $system_table_fields, $LinkID, $current_section, $section_childs_count,$section_struct,$section_cache; static $cache; if ($checked_only !== false) $checked_only=true; if (!$params && $sort_by =='Priority' && $checked_only && $section_childs_count[$anc]) { // попытка собрать результат из кеша при параметрах по умолчанию $tmp=array(); $flag=true; foreach ($section_struct[$anc] as $key => $node) { if (!($xnode=$section_cache[$node])) {$flag=false; break;} if ($xnode['Checked']) $tmp[$key]=$xnode; } if ($flag) return $tmp; } $key=md5($anc.$params.$sort_by.((int)$checked_only)); if ($cache[$key] === null) { ($checked_only) ? $where = " `Checked`=1" : $where = ""; if($params){ if ($where) $where .= " AND "; $where .= $params; } if($anc !== false && !$params) { if ($where) $where .= " AND "; $where .= "`Parent_Section_ID`='" . $anc . "' " ;} $query = "SELECT " . getSectionFieldsQuery() . " FROM `Section` WHERE ".$where." AND Site_ID=" . $current_section["Site_ID"] . " ORDER BY " . $sort_by; $data=SQLSelect($query,'Section_ID'); if (!$data) $cache[$key]=array(); else $cache[$key] = $data; if (!$section_struct[$anc] && is_array($data)) { $section_struct[$anc]=array_keys($data); foreach ($data as $ckey => $csection) { if (!$section_cache[$ckey]) $section_cache[$ckey] = $csection; } } } return $cache[$key]; } function get_children_with_object($anc,$object_id,$limit=0){ static $cache; if (!$object_id) return; $key = $anc.'_'.$object_id.'_'.$limit; if ($cache[$key] !== null) return $cache[$key]; $query = "SELECT a.`Section_ID`,b.`Section_Object_ID` FROM `Section` AS `a` LEFT JOIN `Section_Object` AS `b` ON a.`Section_ID`=b.`Section_ID` WHERE 1 AND a.`Parent_Section_ID`='".$anc."' AND b.`Object_ID`='".$object_id."'".($limit ? " LIMIT ".((int)$limit) : "").";"; return $cache[$key]=SQLSelect($query,'Section_Object_ID','Section_ID'); } /* проверяет находится ли указанная страница в текущей ветке */ function in_branch($page_id) { global $as_section_data; foreach ( $as_section_data as $page ) { if ($page['Section_ID'] && $page['Section_ID']== $page_id) return true; } return false; } /* получает предка секции. $get_full = true - полная инфо */ function get_ancestor($page_id=-1, $get_full=false){ global $LinkID,$current_section; static $cache, $full_cache; if ($page_id ==-1) $page_id=(int)$current_section['Section_ID']; if ($get_full){ return false; } else { if (!is_array($cache)) $cache=array(); if (!$cache[$page_id]) { $query = "SELECT `Parent_Section_ID` FROM `Section` WHERE `Section_ID` = '".$page_id."'"; $res = mysql_query($query, $LinkID); $data_count = mysql_num_rows($res); $item= mysql_fetch_row($res); $cache[$page_id]=$item[0]; } return $cache[$page_id]; } } /* проверяет является ли секция потомком секции ancestor-а */ function is_child($ancestors, $equal =true, $page_id=-1) { global $current_section; static $cache; if (!is_array($cache)) $cache=array(); if ($page_id <0) $page_id = $current_section['Section_ID']; if (!is_array($cache[$page_id])) $cache[$page_id]=array(); if (!is_array($ancestors)) { $ancestors = array((int)$ancestors);} foreach ($ancestors as $ancestor) { if (in_array($ancestor,$cache[$page_id])) return $ancestor; if ($ancestor == $page_id) { if ($equal) {return $ancestor;} else {return false;} } $anc=$page_id; while ($anc = get_ancestor($anc)) { $cache[$page_id][]=$anc; if ($anc == $ancestor) return $ancestor; } } return false; } /* есть ли дочерние секции */ function have_children($page_id) { static $cache; global $section_struct; if ($cache[$page_id] === null) { if ($section_struct[(int)$page_id]) { return $cache[$page_id]=count($section_struct[(int)$page_id]); } else { $r=mysql_query("SELECT count(`Section_ID`) as `count` FROM `Section` WHERE `Parent_Section_ID` = '".$page_id."';"); $t=mysql_fetch_array($r); return $cache[$page_id] =(int)$t[0]; } } } /* $ancestors = ID-шники крупных разделов, page_id = ID страницы проверяет в каком из указанных разделов находится страница и возвращает id раздела */ function select_ancestor($ancestors=array(),$page_id = -1){ if (!count($ancestors)) return false; global $current_section; if ($page_id <0) $page_id = $current_section['Section_ID']; foreach ($ancestors as $anc) { if (is_child($anc,$page_id)) { return $anc; } } } ######################## FIELDS ########################## function inherit_section_field($field,$default=''){ global $as_section_data,$current_site; foreach ($as_section_data as $section){ if ($section[$field]) return $section[$field]; } if ($current_site[$field]) return $current_site[$field]; return $default; } function getSectionFieldsQuery(){ global $system_table_fields; static $cache; if (!$system_table_fields){ LoadEnv(); } if ($cache) return $cache; $upfields=array('Section_ID,Section_Name,ExternalURL,Hidden_URL,LinkName,Site_ID'); for ($i = 0; $i < count($system_table_fields['Section']); $i++) { if ($system_table_fields['Section'][$i]['type'] == 6) $upfields[] = "IF(`" . $system_table_fields['Section'][$i]['name']."`<>'',CONCAT('" . $CMS_UPLOAD_PATH . "',SUBSTRING_INDEX(`" . $system_table_fields['Section'][$i]['name']."`,':',1)),'') AS `" . $system_table_fields['Section'][$i]['name']."`"; else $upfields[] = "`".$system_table_fields['Section'][$i]['name']."`"; } return $cache=implode(',',$upfields); } function UpdateRecord($table, $id, $fields){ global $LinkID; $struct = getObjectStruct($table); if (!$struct) return false; $struct['Created']=1; $struct['Section_ID']=1; $struct['Section_Object_ID']=1; $struct['Checked']=1; if (!$table || !$id || !$fields ) return false; $fields_out = array(); foreach ($fields as $key => $value) { if ($struct[$key]){ $fields_out[] = " `".$key."` = '".$value."' "; } } $query = "UPDATE `Data".$table."` SET ".implode(",",$fields_out)." WHERE `Data_ID`='".$id."' LIMIT 1;"; return mysql_query($query,$LinkID); } function getLogoLink(){ global $as_admin,$current_section, $current_site,$LinkID,$main_pages; if ($as_admin) { return "cms/?site=".$current_site["Site_ID"]."§ion=".$current_section['Section_ID']; } else { if ( in_array($current_section['Section_ID'],$main_pages)) return null; else return ''; } } function getUserFields($id,$filter=null){ global $LinkID; static $cache; if (!$id) return; if (!is_array($cache)) $cache= array(); if ($cache[$id] === null) { $query = "SELECT * FROM `User` WHERE `User_ID` = ".(int)$id." "; $res = mysql_query($query, $LinkID); $cache[$id] = mysql_fetch_assoc($res); } if ($img = $cache[$id]['image']){ $t = explode(':',$img); $cache[$id]['image']='/data/'.$t[1]; } if (!$filter) return $cache[$id]; if ( is_string($filter) && substr_count($filter,",")) $filter=explode(",",$filter); if (is_array($filter) ) { $tmp = array(); foreach ($filter as $key) $tmp[$key]=$cache[$id][$key]; return $tmp; } if (is_string($filter)) return $cache[$id][$filter]; } /* функция возвращает все поля секции можно также брать поля у страниц getSection(1,'Section_Name') ии массив полей getSection(10,array('Section_Name','icon')) */ function get_section_fields($id,$filter=null){ global $system_table_fields, $LinkID, $current_section; global $section_cache; if (is_array($id) && $id['Section_ID']) $id=(int)$id['Section_ID']; if (!$id) return; if (!is_array($cache)) $cache= array($current_section['Section_ID'] => $current_section); if ($cache[$id] === null) { $query = "SELECT " .getSectionFieldsQuery()." FROM Section WHERE `Section_ID` = '".$id."' "; $res = mysql_query($query, $LinkID); $cache[$id] = mysql_fetch_assoc($res); } if (!$filter) return $cache[$id]; if ( is_string($filter) && substr_count($filter,",")) $filter=explode(",",$filter); if (is_array($filter) ) { $tmp = array(); foreach ($filter as $key) $tmp[$key]=$cache[$id][$key]; return $tmp; } if (is_string($filter)) return $cache[$id][$filter]; } /* получает секцию по id */ function get_section_link($id,$abs=false){ global $LinkID; static $cache; if (!is_array($cache)) $cache=array(); if ($cache[$id] === null) { $r = get_section_fields($id,'ExternalURL,Hidden_URL'); if ($r['ExternalURL']) $link=$r['ExternalURL']; else $link=$r['Hidden_URL']; if ($abs && !substr_count($link,'http://')) {$cache[$id] = 'http://'.$_SERVER['HTTP_HOST'].$link;} //!! else {$cache[$id]=$link;} } return $cache[$id]; } function get_lang_by_section($section){ global $site_cache,$site_versions_loaded; if (!$section) return false; $site_id = (int)get_section_fields($section,'Site_ID'); if ($site_cache[$site_id] !== null) { return $site_cache[$site_id]['Site_Lang']; } $site_cache[$site_id]=SQLSelectOne("SELECT * FROM `Site` WHERE `Site_ID` = '".$site_id."';"); return $site_cache[$site_id]['Site_Lang']; } function get_versions($is_local=false,$first_current=true){ static $cache; global $site_cache,$site; if ($cache !== null) return $cache; if ($site_cache === null) {$site_cache=SQLSelect("SELECT `Site_ID`,`Site_Name`,`Site_Lang`,`Domain`,`Mirrors` FROM `Site`",'Site_Lang'); $site_versions_loaded=true;} $cache=array(); $first=array(); $host=explode('.',$_SERVER['HTTP_HOST']); $host = $host[count($host)-2].'.'.$host[count($host)-1]; foreach ($site_cache as $lang => $xsite){ $xsite['URL'] = $xsite['Domain']; if (trim($xsite['Mirrors'])=='link'){ $xsite['link']=1; $cache[$lang]=$xsite; continue; } if ($is_local) { $mirrors = str_replace(array("
"," "), "\n", $xsite['Mirrors']); $mirrors = str_replace("\n\n", "\n", $mirrors); $mirrors = explode("\n",$mirrors); foreach ($mirrors as $mirror){ $t = str_replace($host,'',$mirror); if ((substr_count($t,'.')==1 && $t != 'www.') || ($mirror == $host) ) { $xsite['URL']=$mirror; break; } } } if ($xsite['Site_ID'] == $site) { $xsite['current']=1; if ($first_current) {$first[$lang]=$xsite; continue; } } $cache[$lang]= $xsite; } if ($first) $cache = array_merge($first,$cache); return $cache; } ###################################### PARSING ################################ function ParseList($table,$query_or_ids,$single=false,$glue=true,$data=null,$vars=null){ global $current_site,$LinkID,$current_record,$lang,$current_section,$section,$as_section_data,$as_section_objects,$as_section_link; if (!$table) return ''; if (is_array($vars)) { foreach ($vars as $key => $value){ $$key=$value; } } if (!$data) { if (is_array($query_or_ids)) { $query = " `Data_ID` IN (".implode(',',$query_or_ids).") "; } elseif (is_numeric($query_or_ids)) { $query = " `Data_ID` = '".$query_or_ids."' "; } elseif (is_string($query_or_ids)) { $query = $query_or_ids; } $data = getObjects(array('where' => $query,'table'=>$table,'checked'=>'all'),true); } if (!$data) return; $keys = array_keys($data); foreach ($keys as $key){ $data[$key] = set_fields_to_property_set($data[$key],$table,false); } $templates=getObjectInfo($table,'System_Config,RecordTemplate'.($single ? ",RecordTemplateFull" : "")); eval($templates['System_Config']); ($glue) ? $tmp='' : $tmp = array(); $block=($templates['RecordTemplateFull']) ? $templates['RecordTemplateFull'] : $templates['RecordTemplate']; $parser = 1; $as_total_row=count($data); $classID=$table; foreach ($data as $item){ $as_object_id=$item['Data_ID']; $as_link = get_section_link($item['Section_ID']).($item['Keyword'] ? $item['Keyword'] : $item['Data_ID']).".html"; if (is_array($item)) { foreach ($item as $key => $value) { eval('$as_'.$key.' = "'.addslashes($value).'";'); } } ($glue) ? eval("\$tmp .= \"$block\";") : eval("\$tmp[] = \"$block\";"); } return $tmp; } function ParseBlock($block,$vars, $to_property_set=0){ if (!$block) return ''; if ($to_property_set) { $as_object_id=$vars['Data_ID']; $as_link = get_section_link($vars['Section_ID']).($vars['Keyword'] ? $vars['Keyword'] : $vars['Data_ID']).".html"; $vars=set_fields_to_property_set($vars,$to_property_set); } if (is_array($vars)) { foreach ($vars as $key => $value) { eval('$as_'.$key.' = "'.addslashes($value).'";'); } } $tmp = ''; eval("\$tmp = \"$block\";"); return $tmp; } function as_insert_page_path($template){ global $as_section_data, $as_section_level, $system_table_fields,$current_site,$current_record; $last=array(); $cr=0; // current record if ($current_record && !$template['no_object']) { $last['Section_Name']=$current_record['Title']; $titlefields=array('address','Question'); // нужно будет ввести у обьектов Title field foreach ($titlefields as $tfield){ if ($current_record[$tfield]){ $last['Section_Name']=$current_record[$tfield]; break; } } if (!$last['Section_Name']) { $last=false;} else {$last['Section_Name'] = cut_words_ru($last['Section_Name'],40); } $last['Keyword'] = ($current_record['Keyword'] ? $current_record['Keyword'] : $current_record['Data_ID']); $cr=1; } $c=0; $sm = ($template['no_main'] ? 1 : 0); // skip main $stop = $sm-$cr; $out = $template['prefix']; for ($i=count($as_section_data)-1-$sm; $i>= -$cr; $i--) { $section = &$as_section_data[$i]; if ($section['Title_Section_ID']){ $name=get_section_fields($section['Title_Section_ID'],'Section_Name'); } else { $name=$section['Section_Name']; } if ($i != -$cr) { $section = &$as_section_data[$i]; ($section['ExternalURL']) ? $url = $section['ExternalURL'] : $url = $section['Hidden_URL']; } else { if (!$section) { if (!$last) return $out; $section=$last; $name=$section['Section_Name']; } if ($section['Hidden_URL']) { $url = $section['Hidden_URL']; } else { $url = $url.$last['Keyword'].'.html'; } } if (!$c && count($as_section_data) !=2 ) { $block="first"; if ($template['main_name_field']) $name=$current_site[$template['main_name_field']]; } elseif ($i == -$cr) $block="last"; else $block="middle"; if (!$template[$block]) $block='middle'; $out .= str_replace( array( "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL", "%COUNTER" ), array(strtolower($name), strtoupper($name), $name, $url, $c),$template[$block]); if ($i > -$cr && $template['divider']) $out.=$template['divider']; $c++; } $out .= $template['postfix']; return $out; } /* echo as_insert_global_menu($ancestor,1,array($menu_template[25]),array("mark_real_nested"=> 1, "dont_apply_last_template"=> 1, "branch" => 1)); } */ /* построение многоуровневого меню $ancestor = точка отсчёта $level = кол-во уровней $templates = масив шаблонов $options['dont_apply_last_template'] = при нехватке шаблонов на уровень не использовать пследний в массиве $options['mark_real_nested'] = помечает nested все элементы,у которых есть дочерние $options['branch'] = всскрывает всю текущую ветку */ function as_insert_global_menu($ancestor, $levels, $templates,$options=array(),$level=0){ global $as_admin, $admin_url_prefix,$current_section,$CMS_UPLOAD_PATH; ($options['where'] && !$level ) ? $where=$options['where'] : $where=''; if ($ancestor == 901){ //DebugBreak(); } if ($ancestor === false || $ancestor===''){ if (!$where) return; $levels=1; } //if ($where) DebugBreak(); if (isset($templates[$level])) $template=$templates[$level]; elseif (!$options['dont_apply_last_template']) $template = $templates[count($templates)-1]; else return ''; ($template['sortby']) ? $sort_by = $template['sortby'] : $sort_by = "Priority"; if ($template['icon_transform']) { list($width,$height,$crop)=explode(',',$template['icon_transform']); } $step=(int)$options['step']; if ($where) { $child_nodes= get_child_nodes($ancestor,$where, $sort_by,false); } else { $child_nodes= get_child_nodes($ancestor,$where, $sort_by,$options['checked_only']); } if ($options['add_root'] && !$level) { $arr = array($ancestor =>get_section_fields($ancestor)); foreach ($child_nodes as $key => $val) $arr[$key]=$val; $child_nodes=&$arr; } if (!count($child_nodes) && !$template['force_empty']) return ''; $count = count($child_nodes); $i=1; $buff = ''; ((int)$template['divider_step']) ? $divstep = (int)$template['divider_step'] : $divstep = 1; if ($divparts = (int)$template['divider_parts']){ $divstep=ceil(count($child_nodes)/$divparts); } if (substr_count($template['prefix'],"%NAME")) { $name = get_section_fields($ancestor,'Section_Name'); $prefix = str_replace( array( "%ID", "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL"), array( $ancestor, strtolower($name), strtoupper($name),$name,$link = get_section_link($ancestor,$options['absolute_links'])), $template['prefix']); } else $prefix = $template['prefix']; foreach ($child_nodes as $page_id => $page) { $submenu = ''; $icon_block=""; $nested = false; $branch = in_branch($page_id); // ПОДМЕНЮ if ($page_id != $ancestor) { if ($levels && ($level < ($levels-1))) { $submenu=as_insert_global_menu($page_id,$levels,$templates,$options,$level+1); } elseif ($options["branch"] && $branch) { $submenu=as_insert_global_menu($page_id,$levels,$templates,$options,$level+1); } elseif ($options['mark_real_nested']) { if (have_children($page_id)) $nested=true; } else {} } if ($submenu) { $nested=true; $submenu = str_replace("%EMPTY", '', $submenu); } if ($as_admin) { $nav_url = $admin_url_prefix . "?site=" . $current_section["Site_ID"] ."§ion=" . $page["Section_ID"];} else { if ($ext_url = $page["ExternalURL"]) $nav_url = (strchr($ext_url, ":") || substr($ext_url, 0, 1) == "/") ? $ext_url : $page["Hidden_URL"] . $ext_url; else $nav_url = $page["Hidden_URL"]; } if ($options['absolute_links']){ if (!substr_count($nav_url,'http://')) { $nav_url = 'http://'.$_SERVER['HTTP_HOST'].$nav_url; } } $nav_name = $page["Section_Name"]; $t = $i % $divstep; ($template['divider'] && $i<$count && ( $i % $divstep === 0)) ? $divider = $template['divider'] : $divider = ''; ( $_SERVER['REQUEST_URI'] == $page['Hidden_URL']) ? $selected = true :$selected=false; ($nested && isset($template['nested_active']) && isset($template['nested_inactive'])) ? $nested_prefix = 'nested_' : $nested_prefix = ''; $link = false; $section =''; if ($step){ $section =( ($i <= $step) ? "active".($i==$step ? "_link" : "" ) : "inactive" ); } else { $section = $nested_prefix.'active_link'; if ($selected && !isset($template[$section])) { } elseif ($branch) { $section = $nested_prefix.'active'; } else { $section = $nested_prefix.'inactive'; } } ($template['icon_field']) ? $icon_field = $template['icon_field'] : $icon_field='icon'; $icon_state = "icon"; if ( isset($template['icon_active']) && ($section == "active" || $section == "active_link" || $section == "nested_active" )) $icon_state="icon_active"; if ( $page[$icon_field] && $template[$icon_state]) { // image_transform($image,$sizex=0,$sizey=0, $aspect ="",$color=""){ if ($template['icon_transform']) { $icon_url = image_transform($CMS_UPLOAD_PATH.$page[$icon_field],$width,$height, $crop); } elseif ($template['icon_suffix']) { $icon_url = $CMS_UPLOAD_PATH.add_postifix_to_filename(array($page[$icon_field],$template['icon_suffix'])); } else { $icon_url = $CMS_UPLOAD_PATH.$page[$icon_field]; } $icon_block = str_replace( array( "%ICON", "%ID", "%COMMENT", "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL", "%COUNTER"), array( $icon_url, $page_id, $page['comment'], strtolower($nav_name), strtoupper($nav_name),$nav_name,$nav_url,$i), $template[$icon_state]); } $result = $template[$section].$divider; $result = str_replace( array( "%COMMENT", "%BASIC", "%ID", "%ICONBLOCK", "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL", "%PARENT_SECTION", "%KEYWORD", "%SECTION","%COUNTER", "%SUBMENU", "%COMMENT" ), array( $page['comment'], $page['LinkName'], $page_id, $icon_block,strtolower($nav_name), strtoupper($nav_name), $nav_name, $nav_url, $ancestor, $page['LinkName'], $page["Section_ID"], $i, $submenu, $page['comment']), $result); $buff .= $result; $i++; } ($template['suffix']) ? $suffix = $template['suffix'] : $suffix = ''; ($template['postfix']) ? $postfix = $template['postfix'] : $postfix = ''; $xbuff=$prefix.$buff.$suffix.$postfix; return $xbuff; } function render_multicol_menu($anc, $levels=2, $templates, $divide_by=3, $href=null, $level=0, $divide=true){ global $section_cache, $section_struct,$LinkID,$section_childs_count; $levels=(int)$levels; if ($anc===null || !$levels || !$templates) return; $anc=(int)$anc; $count=recursiveChildCollect($anc,$levels); if (!$count) return; if (!$divide_by) $divide_by = $count; $divide_cnt=ceil($count / $divide_by)-1; if (!$divide_cnt) $divide_cnt=1; $i=0; $c=0; $step=0; if (!$templates[$level]) $template=$template[count($templates)-1]; else $template=$templates[$level]; $out=$template['prefix']; foreach ($section_struct[$anc] as $node) { $i++; $c++; $child_count = getSectionChildrenTotal($node,$levels-1); $i+=$child_count; if ($child_count && $levels) { $sub=render_multicol_menu($node,$levels-1,$templates,$divide_by,$href,$level+1,false); } else { $sub=''; } $page = &$section_cache[$node]; ($page['ExternalURL']) ? $link = $page['ExternalURL'] : $link=$page['Hidden_URL']; $name=$page['Section_Name']; ($link === $href) ? $section = 'active' : $section='inactive'; $item = str_replace(array("%BASIC", "%ID", "%NAME", "%URL", "%COUNTER", "%STEP", "%SUBMENU" ), array($page['LinkName'], $node, $name, $link, $c, $step, $sub), $template[$section]); if ($template['divider'] && $divide && floor($i/$divide_cnt) > $step ) { $step = floor($i/$divide_cnt); $divider = $template['divider']; } else $divider = ''; $out .= $item.$divider; } $out .= $template['postfix']; return $out; } function as_insert_paginator($template, $onpage, $total, $base_href='',$offset=0,$getparams=array(),$pager='curPos'){ $getfunc = 'get_pager_default_template'; if (!$template && function_exists($getfunc)) { $template = $getfunc();} if (!$template || !((int)$onpage)) return ''; if (!$template['template']) $template['template'] = '%PREFIX %PREV %LIST %NEXT %POSTFIX'; unset($getparams['curPos']); $onpage=(int)$onpage; $total=(int)$total; $current=ceil($offset/$onpage); if ( !$onpage || $onpage > $total ) return ''; $params_list=array(); foreach ($getparams as $key => $param) { $params_list[] = $key.'='.urlencode($param); } $params_list = implode('&',$params_list); if(substr_count($base_href,"?")) $base_link = $base_href."&".($params_list ? $params_list : ""); else $base_link = $base_href."?".($params_list ? $params_list."&" : ""); $prev = $current-1; $next=$current+1; $max_pages=ceil($total/$onpage); $first_link = $base_href.($params_list ? "?".$params_list : ""); if ($prev == -1) { $prev_str = str_replace("%URL", "javascript:void(0);", $template['no_prev']); } else { $t = floor($onpage*$prev); ($t ? $t_link = $base_link.$pager."=".$t :$t_link = $first_link ); $prev_str = str_replace("%URL", $t_link, $template['prev']); } if ($next == $max_pages) { $next_str = str_replace("%URL", "javascript:void(0);", $template['no_next']); } else { $next_str = str_replace("%URL", $base_link.$pager."=".(floor($onpage*$next)), $template['next']); } $list = ''; if ($template['near_space']) { $near=(int)$template['near_space']; $near_from = $current - $near; $near_to = $current + $near; } for ($i=0; $i<$max_pages; $i++) { $page = $i+1; if ($near && !($page == 1 || $page== $max_pages)) { if ($page < ($near_from+1)) { if ($page == 2) { $list .= $template['space']; continue; } else continue; } if ($page > $near_to) { if ($page == $near_to+1) { $list .= $template['space']; continue; } else continue; } // DebugBreak(); } ($i ? $link =$base_link.$pager."=".(floor($i*$onpage)) : $link = $first_link); ($current==$i) ? $sect = 'current': $sect='item' ; $list .= str_replace(array('%URL','%NUMBER'),array($link,$page),$template[$sect]); } $out = str_replace( array('%PREFIX','%PREV','%LIST','%NEXT','%POSTFIX'), array($template['prefix'], $prev_str, $list, $next_str,$template['postfix']), $template['template'] ); return $out; //'%PREFIX %PREV %LIST %NEXT %POSTFIX'; } ########################### Objects ############################### /* загружает список обьектов $params['page_id'] = обьекты этой страницы $params['table'] = id обьекта $params['where'] = ''; $params['order'] = ''; $params['limit'] = ''; $params['checked'] = 0|1|all default 1 */ function getObjects($params,$datakeys=false){ static $cache; $page_id = (int)$params['page_id']; if (!$page_id) $page_id=(int)$params['Section_ID']; $id = (int)$params['id']; $table = (int)$params['table']; $where = $params['where']; $order = $params['order']; $limit = $params['limit']; $checked = $params['checked']; $params['datakeys']=$datakeys; $cache_key=md5(serialize($params)); if ($cache[$cache_key] == null) { if ($checked === null) $checked_str=" AND a.`Checked`=1"; elseif ($checked == "all") $checked_str = " "; else $checked_str = " AND a.`Checked`='".$checked."' "; if ($obj_id = (int)$params['object_id']) { $sql_obj_sect = " AND a.`Section_Object_ID` = ".$obj_id; } else $sql_obj_sect=''; if ($page_id) $where .= " AND a.`Section_ID` = '".$page_id."' "; if ($id) { $where .= " AND a.`Data_ID` = '".$id."' "; } if (!$table) { if (!$page_id) return false; $query = "SELECT a.`Section_Object_ID`, a.`Object_ID` FROM `Section_Object` AS a WHERE a.`Section_ID` = '".$page_id."' ".$sql_obj_sect." LIMIT 1;"; if ($r=SQLSelect($query)) { $obj_id = $r[0]['Section_Object_ID']; $table = $r[0]['Object_ID']; } else return false; } $fields = getObjectStruct($table); if ($order) $order = " ORDER BY ".$order; if ($limit) $limit = " LIMIT ".$limit; if($where) { if ($checked_str) { if ( (strtolower(substr(trim($where),0,4)) != "and ")) $where = " AND ".$where; } else { if ($where && (strtolower(substr(trim($where),0,4)) == "and ")) $where = substr($where, 4); } } if ($site_id=(int)$params['site_id']){ $joins = " LEFT JOIN `Section` AS `Section` ON a.`Section_ID` = Section.`Section_ID` "; $join_conds = " AND Section.`Site_ID` = '".$site_id."' "; } //$query = "Select `".implode("`,`",array_keys($fields))."` From `Data".$table."` Where ".$checked_str.$where.$order.$limit; $query = "SELECT ".getObjectStructFieldsQuery($table,'a.')." FROM `Data".$table."` AS a ".$joins." WHERE 1 ".$checked_str.$where.$join_conds.$order.$limit; if ($datakeys){ $cache[$cache_key] = SQLSelect($query,'Data_ID'); } else { $cache[$cache_key] = SQLSelect($query); } } return $cache[$cache_key]; } // Загружает обьект по id function getObject($ids,$table=-1,$fieldname=false){ global $MAIN_PRODUCT_TABLE; static $cache; if ($table==-1) $table=$MAIN_PRODUCT_TABLE; $tmp = array(); $to_upload=array(); $single=false; if (!is_array($ids)) { $ids = array($ids); $single=true;} if (!is_array($cache)) {$cache = array();} if (!is_array($cache[$table])) {$cache[$table] = array();} foreach ($ids as $id) { if ($cache[$table][$id] !== null) { if ($fieldname) { $tmp[$id] = $cache[$table][$id][$fieldname]; } else { $tmp[$id] = $cache[$table][$id]; } } else { $to_upload[]=(int)$id; } } if ($to_upload){ $objs = getObjects(array('table'=> $table, 'where' => " `Data_ID` IN (".implode(',',$to_upload).") ",'checked' => 'all'),true); foreach ($objs as $id =>$val){ $cache[$table][$id]=$val; if ($fieldname) { $tmp[$id]=$val[$fieldname]; } else { $tmp[$id]=$val; } } } if ($single) return current($tmp); return $tmp; } /* Получает инфо о полях обьекта */ function getObjectStruct($object_id,$system_id=0) { global $LinkID; static $cache; if (!is_array($cache)) $cache=array(); $key = $object_id.'_'.$system_id; if ($cache[$key] === null) { $fields=array(); $q = "SELECT `Object_Field_Name`, `TypeOfData_ID`, `Format`, `Description`, `NotNull`, `System_ID` FROM `Object_Field` WHERE 1 AND `System_ID` = '".$system_id."' ".($object_id ? " AND `Object_ID` = '".$object_id."'" : "")." ORDER BY `Priority` ASC ;"; $r = mysql_query($q,$LinkID); if ( mysql_num_rows($r)) { while ($tmp = mysql_fetch_assoc($r)) $fields[$tmp['Object_Field_Name']]=$tmp; $cache[$key]=$fields; } else $cache[$key]=array(); } return $cache[$key]; } function getObjectStructFieldsQuery($object_id,$prefix='',$system_id=0){ static $cache; $key=$object_id.$prefix; if ($cache[$key]) return $cache[$key]; $struct =getObjectStruct($object_id,$system_id); if (!$struct) return; $arr=array($prefix.'`Data_ID`', $prefix.'`Section_ID`', $prefix.'`Section_Object_ID`', $prefix.'`User_ID`', $prefix.'`Checked`', $prefix.'`Keyword`', $prefix.'`Created`'); foreach ($struct as $field){ //if ($field['Object_Field_Name'] == 'Foto1') DebugBreak(); switch ($field['TypeOfData_ID']){ case '6': $fname = $prefix.'`'.$field['Object_Field_Name'].'`'; $name='`'.$field['Object_Field_Name'].'`'; $arr[]="IF(".$fname."<>'',SUBSTRING_INDEX(".$fname.",':',1),'') AS ".$name; break; default : $arr[]=$prefix.'`'.$field['Object_Field_Name'].'`'; break; } } return $cache[$key]=implode(',',$arr); } /* обработка полей обьекта в соответствие с форматом полей */ /* $object = массив параметров для переработки $object_id = id обработчика $clean == 0 обьединяет полученый и орги $clean == 1 выдаёт полученный $clean == 2 заполняет поля обязательные для заполнения */ function set_fields_to_property_set(&$object, $object_id, $clean=1,&$fields=null) { if (!$fields) { $fields = getObjectStruct($object_id); } if (!$fields) {return $false;} $field_names = array_keys($fields); $final_object = array(); foreach ($field_names as $fname) { $type = $fields[$fname]['TypeOfData_ID']; if ($object[$fname] === null) { unset($object[$fname]); continue;} if ($type == 8){ $final_object[$fname]=$object[$fname]; $final_object[$fname.'_timestamp']=$timestamp = strtotime($object[$fname]); $tm = explode('-',date('Y-m-d-H-i',$timestamp)); $final_object[$fname.'_year']=$tm[0]; $final_object[$fname.'_month']=$tm[1]; $final_object[$fname.'_day']=$tm[2]; $final_object[$fname.'_hours']=$tm[3]; $final_object[$fname.'_minutes']=$tm[4]; } if ($type != "6") {$final_object[$fname]=$object[$fname]; continue;} if (!$object[$fname] || $clean == 2) continue; $t=substr($fields[$fname]['Format'],0,13); if ($t != "type=image/*|") {$final_object[$fname]=$object[$fname]; continue;} $t2=substr($fields[$fname]['Format'],13); $types_info=array(); $types=explode("|", $t2); foreach ($types as $type) { $arr=array(); $vals = explode(";", $type); foreach ($vals as $val) { $t=explode("=",$val); $arr[$t[0]]=$t[1]; } if ($arr['postfix']) { $types_info[$arr['postfix']]=$arr; } } $postfixes=array_keys($types_info); $image_props=explode(":",$object[$fname]); $final_object[$fname]="/data/".$image_props[0]; //add_postifix_to_filename foreach ($postfixes as $postfix) { $final_object[$fname.$postfix]="/data/".add_postifix_to_filename(array($image_props[0],$postfix)); } } if ($clean == 1) return $final_object; elseif ($clean ==0) return array_merge($object, $final_object); elseif ($clean==2) { foreach ($field_names as $fname){ if ($fields[$fname]['NotNull'] && !$final_object[$fname]) { if ($fields[$fname]['DefaultState']) { $final_object[$fname]=$fields[$fname]['DefaultState']; continue; } $f = &$fields[$fname]; switch ($f['TypeOfData_ID']){ case '2' : case '4' : case '5' : case '7' : $final_object[$fname]=0; break; case '1' : case '3' : case '6' : $final_object[$fname]=''; break; case '8' : $final_object[$fname]=date('Y-m-d H:i:s'); } } } return $final_object; } } /* обработка полей секций в соответствие форматов полей */ function mass_update_section_fields(&$sections){ static $cache; if (!is_array($cache)) $cache=array(); $sections_keys = array_keys($sections); foreach ($sections_keys as $key) { $sections[$key]=set_fields_to_property_set($sections[$key],0,false); } } function getObjectInfo($table, $fields=''){ static $cache,$fullcache; if (!$table) return; if (!is_array($cache)) $cache=array(); if (!is_array($fullcache)) $fullcache=array(); $table=(int)$table; if (!is_array($cache[$table])) $cache[$table]=array(); if ($fields == '') { if (!$fullcache[$table]) { $query = "SELECT * FROM `Object` WHERE `Object_ID` = '".$table."'"; $fullcache[$table]=SQLSelect($query); } return $fullcache[$table]; } else { if (is_string($fields)) { if (substr_count($fields,'`')){ $query = "SELECT ".$fields." FROM `Object` WHERE `Object_ID` = '".$table."'"; $t=SQLSelectOne($query); return $cache[$table]=array_merge($cache[$table],$t); } $fields=explode(',',$fields); } $select = array(); $tmp = array(); for ($i=0;$i 0, 'Section_Object_ID' => 0, 'Checked' => 1, 'LastSystem_Updated' => $date, 'Created' => $date, 'LastUser_ID' => (int)$_SESSION['user']['User_ID'], 'User_ID' => (int)$_SESSION['user']['User_ID'], 'IP' => $_SERVER['REMOTE_ADDR'], 'Keyword'=>'' ); foreach ($struct as $name =>$field) { if ($field['DefaultState']) { $dataInit[$name]=$field['DefaultState']; continue; } $type=(int)$field['TypeOfData_ID']; switch ($type) { case 1: case 3 : case 6: $dataInit[$name]=''; break; case 8: $dataInit[$name]='0000-00-00 00:00:00'; break; default : $dataInit[$name]=0; } } return $cache[$table]=$dataInit; } function GetSiteByID($id) { static $sites; if (!$sites) $sites=array(); if (!$sites[$id]) $sites[$id] = as_query_array("SELECT * FROM `Site` WHERE `Site_ID` = '".(int)$id."'"); return $sites[$id]; } function get_section_objects($section,$limit=1,$to_propertyset=true, $order = "Priority") { global $LinkID; if (!($section = (int)$section)) return false; ($order) ? $order = ' ORDER BY `'.$order.'` ' : $order = ''; $q = "SELECT `Section_Object_ID`, `Object_ID` FROM `Section_Object` WHERE `Section_ID` = '".$section."' ".$order." LIMIT 1;"; $r = mysql_query($q,$LinkID); if ( mysql_num_rows($r)) { $t = mysql_fetch_row($r); } else return array('failed' => true, 'errcode' => 2); $section_obj_id = $t[0]; $obj_id = $t[1]; $objs=getObjects(array('page_id' => $section,'object_id'=> $section_obj_id, 'limit'=> $limit)); if ($to_propertyset){ for ($i=0; $i < count($objs); $i++) { $objs[$i]= set_fields_to_property_set($objs[$i], $obj_id); } } return $objs; } function get_section_sobjects($section=null,$limit=null){ global $current_section; static $cache; if ($section===null) {$section=$current_section['Section_ID'];} if (!$limit) { if ($cache[$section] !== null) return $cache[$section]; $query = "SELECT `Object_ID`, `Section_Object_ID` as `sid` FROM `Section_Object` WHERE `Section_ID` = '".$section."' ;"; return $cache[$section] = SQLSelect($query,'Object_ID','sid'); } else { $query = "SELECT `Object_ID`, `Section_Object_ID` as `sid` FROM `Section_Object` WHERE `Section_ID` = '".$section."' ".($limit ? " LIMIT ".(int)$limit." " : "").";"; return SQLSelect($query,'Object_ID','sid'); } } function get_section_sibling($section=null){ global $current_section,$section_struct; static $cache; if (!$section) $section=(int)$current_section['Section_ID']; if ($cache[$section] !== null) return $cache[$section]; $anc=get_ancestor($section); if ($section_struct[$anc] === null) { recursiveChildCollect($anc,1,false); } $struct = &$section_struct[$anc]; if (!$struct || !is_array($struct) || count($struct)==1){ return $cache[$section]=false; } $pos=-1; for ($i=0; $i= 0; $ii--) { if ($str[$ii] == ' ' && $f == 0) { $f = 1; $cnt++; } elseif ($str[$ii] != ' ') { $f = 0; } if ($cnt == $cntwords) break; } $ii++; return ($ii > 1 ? substr($str, 0, $ii) . "" . substr($str, $ii)."" : $str); } /* обрезает строку по длине, не разрывая последнее слово, добавляя троеточие */ function cut_words_ru($string, $length, $params = array(), $convert=true) { if (!$params['no_strip_tags']) $string=strip_tags($string); ($params['delim']) ? $delim = $params['delin'] : $delim =' '; ($params['postfix']) ? $postfix = $params['postfix'] : $postfix='...'; if ($convert) $str=strip_tags(iconv("UTF-8", "WINDOWS-1251", $string)); else $str=$string; if ($params['clean']) $str=str_replace(array("\n", " "), array(""," "),$str); if (strlen($str)<=$length) $tmp = $string; else { $tmp = substr($str,0, $length); $pos = strpos($str, $delim, $length); if ($pos !== false) $tmp .= substr($str,$length,$pos-$length).$postfix; else return stripslashes($string); if ($convert) $tmp = iconv("WINDOWS-1251", "UTF-8", $tmp); } if ($lwlink=$params['last_word_link']) { if (!($lwcount = (int)$params['last_word_count'])) $lwcount = 1; $tmp = makelastwordlink($tmp,$lwlink,$lwcount); } return stripslashes($tmp); } function process_comment_message($message,$symbols=600){ $str=iconv('utf-8','windows-1251',$message); $len=strlen($str); if ($len > $symbols) return '

'.cut_words_ru($message,$symbols).'

'; $ps = explode("\n",$message); return '

'.implode('

',$ps).'

'; } // ограничивает длину строки function limit_string_ru($string,$maxlen=64){ return iconv('windows-1251','utf-8',substr(iconv('utf-8','windows-1251',$string),0,$maxlen)); } /* $params[0] = имя файла, $params[1] = добавляемый постфикс */ function add_postifix_to_filename($params){ $pos = strrpos($params[0],'.'); if (!strlen($params[1]) || $pos === false) return $fname; return substr($params[0],0,$pos).$params[1].substr($params[0], $pos); } /* возвращает оформленный размер файла */ function get_human_filesize($size) { $iec = array('б', 'Кб', 'Мб', 'Гб', 'Тб'); $i = 0; while (($size/1024)>1) { $size = $size/1024; $i++; } $iec = $iec[$i]; $size=number_format($size,1,'.',' '); $echo = $size.' '.$iec; return $echo; } /* these are the russian additional format characters q: full textual representation of the day of the week Q: full textual representation of the day of the week (first character is uppercase), v: short textual representation of the day of the week, V: short textual representation of the day of the week (first character is uppercase), H: full textual representation of a month(singlified) X: full textual representation of a month x: full textual representation of a month (first character is uppercase), f: short textual representation of a month F: short textual representation of a month (first character is uppercase), Param[0]= format Val=timestamp echo 'Сегодня '.date_ru('Q, d x Y'); * * */ function date_ru($timestamp,$formatum) { if (!$timestamp) $timestamp=time(); if (!is_numeric($timestamp)) { if (!($timestamp = strtotime($timestamp))) return; } $q['q'] = array(-1 => 'w', 'воскресенье','понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'); $q['Q'] = array(-1 => 'w', 'Воскресенье','Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'); $q['v'] = array(-1 => 'w', 'вс','пн', 'вт', 'ср', 'чт', 'пт', 'сб'); $q['V'] = array(-1 => 'w', 'Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'); $q['H'] = array(-1 => 'n', '', 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'); $q['x'] = array(-1 => 'n', '', 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'); $q['X'] = array(-1 => 'n', '', 'Января', 'Февраля', 'Март', 'Апреля', 'Май', 'Июня', 'Июля', 'Август', 'Сентября', 'Октября', 'Ноября', 'Декабря'); $q['f'] = array(-1 => 'n', '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'); $q['F'] = array(-1 => 'n', '', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'); $temp = ''; $i = 0; while ( (strpos($formatum, 'q', $i) !== FALSE) || (strpos($formatum, 'Q', $i) !== FALSE) || (strpos($formatum, 'v', $i) !== FALSE) || (strpos($formatum, 'V', $i) !== FALSE) || (strpos($formatum, 'x', $i) !== FALSE) || (strpos($formatum, 'X', $i) !== FALSE) || (strpos($formatum, 'f', $i) !== FALSE) || (strpos($formatum, 'F', $i) !== FALSE)||(strpos($formatum, 'H', $i) !== FALSE)) { $ch['q']=strpos($formatum, 'q', $i); $ch['Q']=strpos($formatum, 'Q', $i); $ch['v']=strpos($formatum, 'v', $i); $ch['V']=strpos($formatum, 'V', $i); $ch['H']=strpos($formatum, 'H', $i); $ch['x']=strpos($formatum, 'x', $i); $ch['X']=strpos($formatum, 'X', $i); $ch['f']=strpos($formatum, 'f', $i); $ch['F']=strpos($formatum, 'F', $i); foreach ($ch as $k=>$v) if ($v === FALSE) unset($ch[$k]); $a = min($ch); $temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)]; $i = $a+1; } $temp .= date(substr($formatum, $i), $timestamp); return $temp; } ############################## SEO, services ############################ /* возвращает ключ к гуглокартам к текущему домену */ function get_map_key(){ global $current_site; static $cache; if ($cache !== null) return $cache; $maps=explode(' ',trim($current_site['map_keys'])); $domains=array(); foreach ($maps as $map){ $pos = strpos($map,'='); if (!is_int($pos) || $pos < 3) continue; $str1 = trim(substr($map,0,$pos)); $str2 = trim(substr($map,$pos+1)); $domains[$str1]=$str2; $domains['www.'.$str1]=$str2; } return $cache=$domains[$_SERVER['HTTP_HOST']]; } function get_default_map_points(){ global $current_site,$current_section; static $coords; if ($coords !== null) return $coords; $field=&$current_site['map_coords']; $rcoords=explode("\n",$field); if (!is_array($rcoords) || !count($rcoords)) { return $coords=false; } $coords = array(); foreach ($rcoords as $coord){ $coord = explode(':',$coord); $t = explode(',',$coord[1]); if (!$coord[0] || !$t[0] || !$t[1]) continue; $coords[]=array('Title'=> trim($coord[0]),'x'=>(double)trim($t[0]),'y'=>(double)trim($t[1])); } return $cache=$coords; } function seoConfirm() { global $SEO,$current_record,$current_section,$current_site,$SEO_section_fields; if (!$SEO_section_fields) { $SEO_section_fields = array( 'keywords' => 'SEOKeyword', 'description' => 'SEODescr', 'title' => 'SEOTitle', 'text' => 'SEOtext', 'productTitle' => 'header', 'productTitle2' => 'Title' ); } //if (preg_match('/\.html$/', $_SERVER['HTTP_HOST'], $matches)) { if ($current_record) { $SEO['description']=$current_record[$SEO_section_fields['description']]; $SEO['keywords']=$current_record[$SEO_section_fields['title']]; $SEO['text']=$current_record[$SEO_section_fields['text']]; $SEO['title']=$current_record[$SEO_section_fields['title']]; if (!$SEO['title']) $SEO['title']=$current_record[$SEO_section_fields['productTitle']]; if (!$SEO['title']) $SEO['title']=$current_record[$SEO_section_fields['productTitle2']]; } if (!$SEO['description']) { if ($current_section[$SEO_section_fields['description']]) $SEO['description'] = $current_section[$SEO_section_fields['description']]; else $SEO['description'] = $current_site[$SEO_section_fields['description']]; } if (!$SEO['keywords']) { if ($current_section[$SEO_section_fields['keywords']]) $SEO['keywords'] = $current_section[$SEO_section_fields['keywords']]; else $SEO['keywords'] = $current_site[$SEO_section_fields['keywords']]; } if (!$SEO['title']) { if ($current_section[$SEO_section_fields['title']]) $SEO['title'] = $current_section[$SEO_section_fields['title']]; else $SEO['title'] = $current_site[$SEO_section_fields['title']]; } if (!$SEO['text']) { if ($current_section[$SEO_section_fields['text']]) $SEO['text'] = $current_section[$SEO_section_fields['text']]; else $SEO['text'] = $current_site[$SEO_section_fields['text']]; } $SEO['description']=trim(htmlspecialchars(strip_tags($SEO['description']))); $SEO['keywords']=trim(htmlspecialchars(strip_tags($SEO['keywords']))); $SEO['title']=trim(htmlspecialchars(strip_tags($SEO['title']))); $SEO['text']=trim(htmlspecialchars(strip_tags($SEO['text']))); } function getSEOdescription(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['description']; } function getSEOkeywords(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['keywords']; } function getSEOtitle(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['title']; } function getSEOtext(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['text']; } function get_h1(){ global $current_record,$current_section; if ($current_record['Title']) return $current_record['Title']; if ($current_record['header']) return $current_record['header']; if ($current_record['Name']) return $current_record['Name']; return $current_section['Section_Name']; } ################################# ARRAYS ####################################### function array_sort(&$array,$field='Name'){ if (!$field) return; $karr=array(); foreach ($array as $key => $value) { $karr[$key] = $value[$field]; } asort($karr); $arr=array(); foreach ($karr as $key => $value) { $arr[$key]=$array[$key]; } return $arr; } function array_escape(&$obj){ $keys = array_keys($obj); foreach ($keys as $key) { if (is_array($obj[$key])) escape($obj[$key]); else $obj[$key]=mysql_real_escape_string($obj[$key]); } } function array_clean(&$arr){ $keys = array_keys($arr); foreach ($keys as $key) { if ($arr[$key] === null || $arr[$key] === '') unset($arr[$key]); } } ################################### ADMIN ########################### ?>database.inc.php000066600000053646150472427540007625 0ustar00 * @copyright http://www.activeunit.com/ (c) 2002 * @version 1.0b */ class mysql { /** * @var string database host * @access private */ var $host; /** * @var string database port * @access private */ var $port; /** * @var string database access username * @access private */ var $user; /** * @var string database access password * @access private */ var $password; /** * @var string database name * @access private */ var $dbName; // database name /** * @var int database handler * @access private */ var $dbh; var $importing=false; var $setCollate=true; // -------------------------------------------------------------------- /** * MySQL constructor * * used to create mysql database object and connect to database * * @param string $host mysql host * @param string $port mysql port * @param string $user mysql user * @param string $password mysql password * @param string $database mysql database name * @access public */ function mysql($host, $port, $user, $password, $database,$Mysql_Link=0) { $this->host=$host; $this->port=$port; $this->user=$user; $this->password=$password; $this->dbName=$database; if (!$Mysql_Link) { $this->Connect(); } else { $this->dbh=$Mysql_Link; } } // -------------------------------------------------------------------- /** * Connects to database * * @return bool connection result (1 - success, 0 - failed) * @access private */ function Connect($new_link=false) { global $LinkID,$CMS_MYSQL_COLLATION; // connects to database DebugBreak(); if ($new_link || !$LinkID) { $this->dbh=mysql_connect($this->host.":".$this->port, $this->user, $this->password); if (!$LinkID) $LinkID=$this->dbh; if (!mysql_select_db($this->dbName, $this->dbh)) { $this->Error(); return 0; } else { //mysql_query("SET NAMES cp1251", $this->dbh); if ($this->setCollate) { mysql_query("set CHARACTER SET $CMS_MYSQL_COLLATION"); mysql_query("SET NAMES '$CMS_MYSQL_COLLATION'"); mysql_query("SET collation_connection = '$CMS_MYSQL_COLLATION'"); } return 1; } } else { } } // -------------------------------------------------------------------- /** * Execute SQL query * * @param string $query SQL query * @return mixed execution result (0 - failed) * @access public */ function Exec($query) { $result=mysql_query($query, $this->dbh); if (!$result) { $this->Error($query); return 0; } else { return $result; } } // -------------------------------------------------------------------- /** * Execute SQL SELECT query and return all records * * This method returns records as array of assosiated arrays (by field names) * * @param string $query SQL SELECT query * @return array execution result * @access public */ function Select($query, $key=null,$val=null) { $result=mysql_query($query, $this->dbh); if ($result) { $res=array(); for($i=0;$iError($query); } } // -------------------------------------------------------------------- /** * Execute SQL SELECT query and return first record * * This method returns record assosiated array (by field names) * * @param string $query SQL SELECT query * @return array execution result * @access public */ function SelectOne($query,$key=null) { //DebugBreak(); //DebugBreak(); $result=mysql_query($query, $this->dbh); if ($result) { $rec=mysql_fetch_array($result, MYSQL_ASSOC); //if ($rec) DebugBreak(); if ($key){ return $rec[$key]; } /* if (Is_Array($rec)) foreach(array_keys($rec) as $k) { if (is_numeric($k)) UnSet($rec[$k]); } */ return $rec; } else { $this->Error($query); } } function SelectLine($query) { if ($result=mysql_query($query, $this->dbh)) { $res=array(); for($i=0;$iError($query); } } // -------------------------------------------------------------------- /** * Execute SQL UPDATE query for one record * * Record is defined by assosiated array * * @param string $table table to update * @param string $data record to update * @param string $ndx index field (used in WHERE part of SQL request) * @access public */ function Update($table, $data, $ndx="Data_ID",$return_query=false) { if (LOWER_CASE_TABLES) $table=strtolower($table); $qry="UPDATE `$table` SET "; foreach($data as $field=>$value) { if (!is_Numeric($field)) { $qry.="`$field`='".$this->DBSafe1($value)."', "; } } $qry=substr($qry, 0, strlen($qry)-2); $qry.=" WHERE $ndx='".$data[$ndx]."'"; if (!mysql_query($qry, $this->dbh)) { if ($return_query){ return '0'.$qry; } else { $this->Error($qry); return 0; } } if ($return_query){ return '1'.$qry; } else return 1; } // -------------------------------------------------------------------- /** * Execute SQL INSERT query for one record * * Record is defined by assosiated array * * @param string $table table for new record * @param string $data record to insert * @return execution result (0 - if failed, INSERT ID - if succeed) * @access public */ function Insert($table, &$data) { if (LOWER_CASE_TABLES) $table=strtolower($table); $fields=""; $values=""; foreach($data as $field=>$value) { if (!is_Numeric($field)) { $fields.="`$field`, "; $values.="'".mysql_real_escape_string($value)."', "; //$values.="'".$this->DBSafe1($value)."', "; } } $fields=substr($fields, 0, strlen($fields)-2); $values=substr($values, 0, strlen($values)-2); $qry="INSERT INTO `$table`($fields) VALUES($values)"; if (!mysql_query($qry, $this->dbh)) { $this->error($qry); return 0; } return mysql_insert_id($this->dbh); } // -------------------------------------------------------------------- /** * Disconnect from database * * @access public */ function Disconnect() { mysql_close($this->dbh); } // -------------------------------------------------------------------- /** * Used to strip "bad" symbols from sql query results * * @param string $str string to make "safe" * @return string correct string * @access public */ function DbSafe($str) { $str=str_replace(chr(146), '\'', $str); $str=str_replace("\\", "\\\\", $str); $str=str_replace("\n", "\\n", $str); $str=str_replace("\r", "", $str); $str=str_replace("'", "\'", $str); $str=str_replace("%", "\%", $str); return $str; } function DbSafe1($str) { return mysql_real_escape_string($str); $str=str_replace(chr(146), '\'', $str); $str=str_replace("\\", "\\\\", $str); $str=str_replace("\n", "\\n", $str); $str=str_replace("\r", "", $str); $str=str_replace("'", "\'", $str); //$str=str_replace("%", "\%", $str); return $str; } // -------------------------------------------------------------------- /** * MySQL database error handler * * @param string $query used query string * @access private */ function Error($query="") { if ($this->importing) { return false; } $err=new error(mysql_errno().": ".mysql_error()."
$query", 1); return 1; } // -------------------------------------------------------------------- /** * Returns mysql table definition string (CREATE TABLE ... ;) * * @param string $table table to get structure * @return string table definition * @access public */ function get_mysql_def($table) { if (LOWER_CASE_TABLES) $table=strtolower($table); $result = mysql_query('SHOW CREATE TABLE '.$table, $this->dbh); if ($result) { $row = mysql_fetch_row($result); if ($row) { $row[1]=preg_replace('/DEFAULT CHARSET=(\w+)/', '', $row[1]); $row[1]=str_replace(' default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP', '', $row[1]); $row[1]=str_replace("\n", ' ', $row[1]); $strs = trim($row[1]); return (empty($strs))? '': 'DROP TABLE IF EXISTS '.$table.';'."\n".$row[1].';'."\n"; } else { return ''; } } else { return ''; } } // -------------------------------------------------------------------- /** * Returns mysql table content string (INSERT INTO ... ;) * * @param string $table table to get content * @return string table content * @access public */ function get_mysql_content($table) { $content=""; if (LOWER_CASE_TABLES) $table=strtolower($table); $result = mysql_query("SELECT * FROM $table", $this->dbh); while($row = mysql_fetch_row($result)) { $insert = "INSERT INTO $table VALUES ("; for($j=0; $jDbSafe($row[$j])."',"; else $insert .= "'',"; } $insert = ereg_replace(",$","",$insert); $insert .= ");\n"; $content .= $insert; } return $content; } // -------------------------------------------------------------------- } // -------------------------------------------------------------------- // DATABASE FUNCTIONS // easy database manipulation // -------------------------------------------------------------------- /** * Execute SQL query * * @param string $query SQL query * @global object mysql database object * @return mixed execution result (0 - failed) */ function SQLExec($query) { if (($query{0}=="#") || ($query=="")) return; global $db; return $db->Exec($query); } // -------------------------------------------------------------------- /** * Used to strip "bad" symbols from sql query results * * @param string $str string to make "safe" * @global object mysql database object * @return string correct string */ function DbSafe($in) { global $db; return $db->DbSafe($in); } // -------------------------------------------------------------------- /** * Execute SQL SELECT query and return all records * * This function returns records as array of assosiated arrays (by field names) * * @param string $query SQL SELECT query * @global object mysql database object * @return array execution result */ function SQLSelect($query,$key=null,$val=null) { global $db; return $db->Select($query,$key,$val); } function SQLSelectLine($query) { global $db; return $db->SelectLine($query); } // -------------------------------------------------------------------- /** * Execute SQL SELECT query and return first record * * This function returns record assosiated array (by field names) * * @param string $query SQL SELECT query * @global object mysql database object * @return array execution result */ function SQLSelectOne($query,$key=null) { global $db; //DebugBreak(); return $db->SelectOne($query,$key); } // -------------------------------------------------------------------- /** * Execute SQL INSERT query for one record * * Record is defined by assosiated array * * @param string $table table for new record * @param string $record record to insert * @global object mysql database object * @return execution result (0 - if failed, INSERT ID - if succeed) */ function SQLInsert($table, &$record) { global $db; return $db->Insert($table, $record); } // -------------------------------------------------------------------- /** * Execute SQL UPDATE query for one record * * Record is defined by assosiated array * * @param string $table table to update * @param string $record record to update * @global object mysql database object */ function SQLUpdate($table, $record,$ndx="Data_ID",$return_query=false) { global $db; return $db->Update($table, $record,$ndx,$return_query); } // -------------------------------------------------------------------- /** * Execute SQL UPDATE or INSERT query for one record * * If ID field is defined record will be updated else it will be inserted * * @param string $table table to update * @param string $record record to update * @global object mysql database object */ function SQLUpdateInsert($table, &$record) { global $db; if (IsSet($record["ID"]) || IsSet($record["Section_ID"])) { return $db->Update($table, $record); } else { $record["ID"]=$db->Insert($table, $record); return $record["ID"]; } } // -------------------------------------------------------------------- /** * Execute SQL UPDATE or INSERT query for one record * * If ID field is defined record will be updated else it will be inserted * * @param string $table table to update * @param string $record record to update * @global object mysql database object */ function SQLInsertUpdate($table, &$record) { return SQLUpdateInsert($table, $record); } // -------------------------------------------------------------------- /** * Converts date format from YYYY/MM/DD to MM/DD/YYYY * * * * @param string $source source date to convert * @param string $delim source delimiter * @param string $dst_delim destination delimiter */ function fromDBDate($source, $delim='-', $dst_delim='/') { $tmp=explode($delim, $source); for($i=0;$i
';
    ob_start();
    if (!$bVarDump)
    {
        print_r($mParam);
    }
    else
    {
        var_dump($mParam);
    }
    $sStr = htmlspecialchars(ob_get_contents());
    ob_clean();
    echo $sStr;
    echo '

'; if ($bExit) exit; } /** * Error handler * * Used to handle errors * * * @package framework * @author Serge Dzheigalo * @copyright http://www.activeunit.com/ (c) 2002 * @version 0.1b */ class error { /** * @var string error code */ var $code; /** * @var string error description */ var $description; /** * Object constructor * * @access public * @param string $description error description * @param int $stop 0 - stop script execution, 1 - show warning and continue script execution */ function error($description, $stop=0) { $script=$_SERVER['REQUEST_URI']; $dat=date("M d, Y H:i:s"); $description=$dat." ".$script."\n\nError:".$description; if (Defined("DEBUG_MODE")) { $this->alert($description); } else { $this->alert("Error: Please contact web-master."); // sendmail("errors@".PROJECT_DOMAIN, PROJECT_BUGTRACK, "Error $script", $description); } if ($stop) exit; } /** * Error processing * * used to show and log error/warning message * * @access private * @param string $description error description */ function alert($description) { echo ""; echo ""; echo "

$description

 "; } } /** * Custom PHP Error Handler * * Used for custom handling of PHP errors */ function simplisticErrorHandler($errno, $errmsg, $filename, $linenum, $vars) { if (( $errno != E_NOTICE ) && ( $errno != E_WARNING)) { $err = $_SERVER['REMOTE_ADDR']." - PHP: $errmsg in $filename on line $linenum\n"; $err=new error($err, 1); } } function check_email($item) { return !isset($item) || empty($item) || preg_match('/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/', $item); } //Define("DEBUG_MODE",1); //$db = new mysql($CMS_MYSQL_HOST, 3306, $CMS_MYSQL_USER, $CMS_MYSQL_PASSWORD, $CMS_MYSQL_DATABASE); function addRecord($table,$section,$section_object,$data,$return_query=0){ global $LinkID; if (!$data || !$table || !$section || !$section_object) return false; $data['Section_ID']=$section; $data['Section_Object_ID']=$section_object; $data['Checked']=1; $data['LastSystem_Updated'] = $data['Created']=date('Y-m-d H:i:s'); $data['LastUser_ID']=(int)$_SESSION['user']['User_ID']; $data['User_ID']=(int)$_SESSION['user']['User_ID']; $data['IP'] = $_SERVER['REMOTE_ADDR']; $data['Keyword']=''; $keys=array_keys($data); $query = "INSERT INTO `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` (`".implode('`,`',$keys)."`) VALUES ('".implode("','",$data)."'); "; $r = mysql_query($query,$LinkID); if (mysql_errno()) { if ($return_query) return '0'.$query; return false; } if ($return_query) return $query; return mysql_insert_id($LinkID); } function addRecordChecking($table,$section,$section_object,$data,$return_query=0){ global $LinkID; if (!$data || !$table || !$section || !$section_object) return false; $keys=array_keys($data); $struct=getObjectStruct($table); foreach ($struct as $fname => $finfo){ switch ($finfo['TypeOfData_ID']){ case 2: case 5: case 7: if ($data[$fname] === '' || $data[$fname] === null) { if ($finfo['DefaultState']){ $data[$fname]=$finfo['DefaultState']; } else { if (!((int)$finfo['NotNull']))$data[$fname]=null; else $data[$fname]=0; } } break; } if ($finfo['NotNull'] || !isset($data[$fname])){ if (!((int)$finfo['NotNull'])) { $data[$fname]=null; } elseif (!$data[$fname]) { switch ($finfo['TypeOfData_ID']){ case 2: case 5: case 7: $data[$fname]=0; break; case 1: case 3: $data[$fname]=''; break; case 8 : if ($finfo['Format']=='event'){ $data[$fname] = date('Y-m-d H:i:s'); } else { $data[$fname]= '0000-00-00 00:00:00'; } break; } } } } $data['Section_ID']=$section; $data['Section_Object_ID']=$section_object; if (!isset($data['Checked'])) $data['Checked']=1; $data['LastSystem_Updated'] = $data['Created']=date('Y-m-d H:i:s'); $data['LastUser_ID']=(int)$_SESSION['user']['User_ID']; $data['User_ID']=(int)$_SESSION['user']['User_ID']; $data['IP'] = $_SERVER['REMOTE_ADDR']; $data['Keyword']=''; $vals = array(); foreach ($data as $key=>$value){ if ($value===null){ $vals[]="NULL"; } else { $vals[] = "'". mysql_real_escape_string($value) ."'";} } $query = "INSERT INTO `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` (`".implode('`,`',$keys)."`) VALUES (".implode(",",$vals)."); "; $r = mysql_query($query,$LinkID); if (mysql_errno()) { if ($return_query) return '0'.$query; return false; } if ($return_query) return $query; return mysql_insert_id($LinkID); } function addRecords($table,$dataArray,$section=0,$section_object=0,$divide_by=15){ global $LinkID; if (!is_array($dataArray) || !$dataArray || !$table || !$section || !$section_object) return false; $dataInit = getObjectInitFields($table); $dataInit['Section_ID']=$section; $dataInit['Section_Object_ID']=$section_object; $struct=getObjectStruct($table); $all_keys=array_keys($dataInit); $keys=array_keys($struct); $query_header = "INSERT INTO `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` (`".implode('`,`',$all_keys)."`) VALUES "; $i=0; $values=array(); foreach ($dataArray as $data){ $obj=$dataInit; foreach ($keys as $key){ if ($data[$key] !== null) { $obj[$key]=mysql_real_escape_string($data[$key]); } } $values[] = "('".implode("','",$obj)."')"; $i++; if ($i==$divide_by){ $i=0; $query = $query_header.implode(', ',$values); $r = mysql_query($query,$LinkID); if (mysql_errno()) return false; $values=array(); } } $query = $query_header.implode(', ',$values); $r = mysql_query($query,$LinkID); if (mysql_errno()) return false; return true; } ?>__parser.php000066600000047214150472427540007075 0ustar00'',CONCAT(Domain,'.".$DOMAIN_NAME."'),'".$DOMAIN_NAME."'))='".$host."'",$LinkID); if (mysql_num_rows($res)) { list($SiteID) = mysql_fetch_row($res); mysql_free_result($res); $cache[$host]=(int)$SiteID; return (int)$SiteID; } update_site_info(); if ($cache_site){ foreach ($cache_site as $site_id => $site){ $Mirrors = &$site['Mirrors']; for ($i=0;$i"," "), "\n", $row['Mirrors']); $Mirrors = str_replace("\n\n", "\n", $Mirrors); $row['Mirrors'] = $Mirrors = explode("\n",$Mirrors); $cache_site[(int)$row['Site_ID']]=$row; } } #### ФУНКЦИИ КОНТРОЛЯ ЛИЦЕНЗИИ #### function checkLicense(){ global $domain,$cache_site,$mirror_limit; //if (substr($domain,strlen($domain)-3) == '.bi'){ return 1; } //DebugBreak(); //return true; $wdomain = str_replace("www.","",$domain); $site = GetSiteID($domain); if ($site && $cache_site[$site] === null){ update_site_info($site); } $info=&$cache_site[$site]; if ($info === null) { print_r($cache_site); licenseNotice(3,1); } if (substr($info['Domain'],0,4) == 'www.'){ licenseNotice(2,0); } if (generateLicense($info['Domain']) != cleanLicenseKey($info['Site_License'])){ licenseNotice(1,1); } $dmirrors=array(); $domain_parts=array_reverse(explode('.',$info['Domain'])); foreach ($info['Mirrors'] as $mirror){ if ($mirror === '') continue; $mirror=trim($mirror); if (substr($mirror,0,4)=='www.') continue; $mirror_parts=array_reverse(explode('.',$mirror)); if (count($mirror_parts)>2) continue; $flag=true; for ($i=0; $i $mirror_limit) { licenseNotice(6,1); // превышен лимит на разнородные зеркала } return 1; } function cleanLicenseKey($license){ $license = substr($license,5,5); return $license; } function generateLicense($domain){ return substr(base64_encode($domain),0,5);} function licenseNotice($code,$iscritical = false){ echo ''; switch($code){ case 1: echo "EMPTY KEY/FIELD DOES NOT EXIST!
"; break; // поле не задано или ключ пустой case 2: echo "BASE DOMAIN NAME CANNOT BE WITH www.!
"; break; // поле не задано или ключ пустой case 3: echo "SITE VERSION NOT FOUND! - ".$_SERVER['HTTP_HOST']; break; // поле не задано или ключ пустой case 6: echo "LIMIT ON VERSION MIRRORS EXCEEDED
"; break; } echo '
'; if($iscritical){ exit;} } checkLicense(); require_once ($INCLUDE_FOLDER."main.inc.php"); require_once ($INCLUDE_FOLDER."filters.inc.php"); function ObjectExists ($classID,$sysTbl,$object,$keyword) { global $LinkID; $res = mysql_query("SELECT ".($sysTbl?"".(LOWER_CASE_TABLES ? "user" : "User")."":"".(LOWER_CASE_TABLES ? "data" : "Data")."")."_ID FROM `".($sysTbl?"".(LOWER_CASE_TABLES ? "user" : "User")."":"".(LOWER_CASE_TABLES ? "data" : "Data")."".$classID)."` WHERE `Keyword`='$keyword'",$LinkID); #echo "SELECT ".($sysTbl?"User":"Data")."_ID FROM ".($sysTbl?"User":"Data$classID")." WHERE Keyword='$keyword'"; if (mysql_num_rows($res)) { list($msgID) = mysql_fetch_row($res); mysql_free_result($res); return ($msgID); } else { return false; } } function GetSectionID ($site, $path) { global $LinkID; $res = mysql_query("SELECT `Section_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Site_ID`='".$site."' AND `Hidden_URL`='".$path."'", $LinkID); list($section) = mysql_fetch_row($res); mysql_free_result($res); return $section; } function GetPathBySectionID ($section) { global $LinkID; $res = mysql_query("SELECT `Hidden_URL` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Section_ID`='".$section."'", $LinkID); list($path) = mysql_fetch_row($res); mysql_free_result($res); return $path; } function ParseQuery ($query_string) { $param_str = explode("&",$query_string); for ($i = 0; $i < count ($param_str); $i++) { $param_arg = explode ("=", $param_str[$i]); if (count($param_arg) && $param_arg[0]) @eval("\$getVars[\"".(strchr($param_arg[0],"[")?substr(urldecode($param_arg[0]),0,strlen(urldecode($param_arg[0]))-strlen(strchr($param_arg[0],"["))):urldecode($param_arg[0]))."\"]".strchr($param_arg[0],"[")." = \"".urldecode($param_arg[1])."\";"); } return $getVars; } /* function AttemptToSection_Redirect ($url) { global $LinkID, $REDIRECT_STATUS; $res = mysql_query("SELECT REPLACE(NewURL,'*','\\\'),REPLACE(OldURL,'*','([[:alnum:]]+)') FROM Section_Redirect WHERE '".$url."' LIKE CONCAT('http://',REPLACE(OldURL,'*','%')) OR '".$url."' LIKE CONCAT('http://www.',REPLACE(OldURL,'*','%'))", $LinkID); if (!mysql_num_rows($res)) return 0; list($new_url,$old_url) = mysql_fetch_row($res); mysql_free_result($res); if (strchr($new_url,"\\")) $result_url = ereg_replace($old_url,$new_url,$url); else $result_url = "http://".$new_url; if ($REDIRECT_STATUS=="on") header("Location: $result_url"); else echo ""; exit; } */ function AttemptToSection_Redirect ($url) { global $LinkID, $REDIRECT_STATUS; $old_path = mysql_real_escape_string(parse_url($url, PHP_URL_PATH)); $new_path = SQLSelectOne("SELECT `NewURL` FROM `".(LOWER_CASE_TABLES ? "section_redirect" : "Section_Redirect")."` WHERE `OldURL` = '$old_path'", 'NewURL'); if (!empty($new_path)){ if ($REDIRECT_STATUS=="on"){ header("HTTP/1.0 301 Moved Permanently"); header("Location: $new_path"); }else{ echo ""; }; exit; }; } function check_server() { // if (preg_match("/^(207.44|209.152)/",$_SERVER["SERVER_ADDR"]) > 0) return 1; return 0; } if (check_server() == 0) { switch ($CMS_PHP_TYPE) { case "module": header("HTTP/1.0 500 Internal Server Error"); exit; case "cgi": header("Status: 500 Internal Server Error"); exit; } } $client_url = urldecode("http://".$_SERVER['HTTP_HOST'].cms_process_filters($_SERVER['REQUEST_URI'])); //$m_url=parse_url('http://domus.bi'); $parsed_url = parse_url($client_url); if (!isset($parsed_url['path'])) $parsed_url['path'] = ''; if (!isset($parsed_url['query'])) $parsed_url['query'] = ''; if (!isset($parsed_url['scheme'])) $parsed_url['scheme'] = ''; if (!isset($parsed_url['user'])) $parsed_url['user'] = ''; if (!isset($parsed_url['pass'])) $parsed_url['pass'] = ''; if (!isset($parsed_url['host'])) $parsed_url['host'] = ''; if (!isset($parsed_url['port'])) $parsed_url['port'] = ''; $myhost = explode('.',$parsed_url['host']); if($myhost[0]!="www" && $REDIRECT_TO_WWW){ header("HTTP/1.0 301 Moved Permanently"); header("Location: ".$parsed_url['scheme'].'://www.'.$parsed_url['host'].$parsed_url['path'].$parsed_url['query']); exit; } elseif($myhost[0]=="www" && $REDIRECT_FROM_WWW){ header("HTTP/1.0 301 Moved Permanently"); header("Location: ".$parsed_url['scheme'].'://'.str_replace("www.","",$parsed_url['host'].$parsed_url['path'].$parsed_url['query'])) ; exit; } // Generating print link if (strpos($parsed_url['path'], ".html") > 0) { $CMS_PRINT_LINK = str_replace(".html", ".".$CMS_PRINT_FILTER.".html", $parsed_url['path']).$parsed_url['query']; } else { $T=substr($parsed_url['path'], -1); $CMS_PRINT_LINK = ((substr($parsed_url['path'], -1) == "/") ? $parsed_url['path']:"/")."print/".($parsed_url['query'] ? "?".$parsed_url['query'] : ""); } $client_source_url = $parsed_url['scheme']."://".($parsed_url['user']?$parsed_url['user']:"").($parsed_url['pass']?":".$parsed_url['pass']:"").(($parsed_url['user'] || $parsed_url['pass'])?"@":"").$parsed_url['host'].($parsed_url['port']?":".$parsed_url['port']:"").$parsed_url['path']; parse_str ($parsed_url['query'], $_GET); extract ($_GET); $site = ""; $section = ""; $object = ""; $classID = ""; $user_table_mode = false; $as_admin = false; $cached_inserts=0; $cached_requests=0; $cache_site=array(); LoadModuleEnv(); $site = GetSiteID($parsed_url['host']); $res = mysql_query("SELECT `E404_Section_ID`,`Title_Section_ID` FROM `".(LOWER_CASE_TABLES ? "site" : "Site")."` WHERE `Site_ID`='".$site."'",$LinkID); list ($e404_section,$title_section) = mysql_fetch_row($res); $cache_site[$site]['E404_Section_ID']=$e404_section; $cache_site[$site]['Title_Section_ID']=$Title_Section_ID = $title_section; mysql_free_result($res); $redirect_to_url = ''; $object_keyword = ''; if (!isset($action)) $action = ''; if (($req_file = strrchr($parsed_url['path'],"/")) <> "/") { $req_file = substr($req_file,1,strlen($req_file) - 1); $req_file_parts = explode(".",$req_file); $fname = $req_file_parts[0]; $fext = strtolower($req_file_parts[count($req_file_parts)-1]); if ($fext == "html") { $parsed_url['path'] = substr ($parsed_url['path'], 0, strlen($parsed_url['path']) - strlen($req_file)); if (ereg ("/([0-9]{4}/)", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (ereg ("/([0-9]{4})/([0-9]{1,2}/)", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (ereg ("/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2}/)", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]."-".$regs[3]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } #echo "SELECT a.Section_ID,b.Section_Object_ID,b.Object_ID,c.System_ID FROM Section AS a,Section_Object AS b,Object AS c WHERE (a.Hidden_URL='".$parsed_url['path']."' OR a.Hidden_URL='".$parsed_url_pathtmp."') AND a.Site_ID=".$site." AND a.Section_ID=b.Section_ID AND b.Object_ID=c.Object_ID ORDER BY b.Checked,b.Priority"; $res = mysql_query("SELECT a.`Section_ID`,b.`Section_Object_ID`,b.`Object_ID`,c.`System_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` AS a,`".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` AS b,`Object` AS c WHERE (a.Hidden_URL='".$parsed_url['path']."' OR a.`Hidden_URL`='".$parsed_url_pathtmp."') AND a.`Site_ID`=".$site." AND a.`Section_ID`=b.`Section_ID` AND b.`Object_ID`=c.`Object_ID` ORDER BY b.`Checked`,b.`Priority`",$LinkID); if (mysql_num_rows($res)) { for ($i=0;$i".$parsed_url['path']."<--
"; #echo "-->".$parsed_url_pathtmp."<--
"; if (!$message) { if ($parsed_url_pathtmp) $object_keyword = strrchr(substr($parsed_url_pathtmp,0,strlen($parsed_url_pathtmp) - 1),"/"); else $object_keyword = strrchr(substr($parsed_url['path'],0,strlen($parsed_url['path']) - 1),"/"); if ($object_keyword = substr($object_keyword,1,strlen($object_keyword) - 1)) { if (preg_match("([0-9]+)", $fname)) { $message = $fname; $action = "view"; } elseif ($fname=="add" || $fname=="search" || $fname=="subscribe") { $action = $fname; } else $object_keyword = $fname; } else $object_keyword = $fname; } } else { $parsed_url['path'] .= "/"; $redirect_to_url = $client_source_url."/".($parsed_url['query']?"?".$parsed_url['query']:"").($parsed_url[fragment]?"#".$parsed_url[fragment]:""); } } if (preg_match("|/([0-9]{4}/)|", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (preg_match("|/([0-9]{4})/([0-9]{1,2}/)|", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (preg_match ("|/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2}/)|", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]."-".$regs[3]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if ($parsed_url['path'] == "/") $section = $title_section; else $section = GetSectionID ($site, $parsed_url['path']); $date = ''; if (!$section) { $section = GetSectionID ($site, $parsed_url_pathtmp); if ($section) $date = $date_tmp; } if ($section) { $current_section = get_section_info($section); if ($current_section['ExternalURL'] && $current_section['do_redirect']){ $redirect_to_url = ((substr($current_section['ExternalURL'],0,7) != 'http://') ? 'http://'.$_SERVER['HTTP_HOST'] : "").$current_section['ExternalURL']; } } if ($section && $redirect_to_url) { if ($REDIRECT_STATUS == "on") { header("HTTP/1.0 301 Moved Permanently"); header("Location: {$redirect_to_url}"); exit; } } #echo "-->section=".$section."<--
"; #echo "-->object_keyword=".$object_keyword."<--
"; if ($section) { if ($section == $e404_section) $skip_redirect = 1; if ($object_keyword) { $res = mysql_query("SELECT `Section_Object_ID` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID`='".$section."' AND `LinkName`='".$object_keyword."'",$LinkID); list($object) = mysql_fetch_row($res); mysql_free_result($res); if (!$object) $section = $e404_section; } elseif(!$object) { $query = "SELECT `Section_Object_ID` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID`='".$section."' AND `Checked`=1 ORDER BY `Priority` ASC LIMIT 1"; $res = mysql_query($query,$LinkID); list($object) = mysql_fetch_row($res); mysql_free_result($res); if (!$object) $no_object = true; else $no_object = false; } #echo "-->object=".$object."<--
"; if ($object) { $res = mysql_query("SELECT `Object_ID`,`DefaultAction` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_Object_ID`='".$object."'",$LinkID); #echo "SELECT Object_ID,DefaultAction FROM Section_Object WHERE Section_Object_ID='".$object."'"; list($classID,$default_action,$system_table) = mysql_fetch_row($res); mysql_free_result($res); $res = mysql_query("SELECT `System_ID` FROM `".(LOWER_CASE_TABLES ? "object" : "Object")."` WHERE `Object_ID`='".$classID."'",$LinkID); list($system_table) = mysql_fetch_row($res); mysql_free_result($res); if (!$action) $action = $default_action; if ($system_table) $user_table_mode = true; } if ($object && $date) { $res = mysql_query("SELECT `Object_Field_ID` FROM `".(LOWER_CASE_TABLES ? "object_field" : "Object_Field")."` WHERE `Format`='event' AND `TypeOfData_ID`=8 AND `Object_ID`='".$classID."' LIMIT 1",$LinkID); list($Object_FieldID) = mysql_fetch_row($res); mysql_free_result($res); if (!$Object_FieldID) $section = $e404_section; } if ($no_object && $date) $section = $e404_section; if ($object && $message && $action=="view") { $res = mysql_query("SELECT ".($user_table_mode?"User":"Section_Object")."_ID FROM ".($user_table_mode?"User":"Data{$tblID}")." WHERE Checked=1 AND ".($user_table_mode?"User":"Data")."_ID='".$message."'",$LinkID); $msg_count = mysql_num_rows($res); list($object)=mysql_fetch_row($res); if (!$msg_count) $section = $e404_section; mysql_free_result($res); } } else { AttemptToSection_Redirect($client_source_url); $section = $e404_section; } if (($section == $e404_section) && (!$skip_redirect)) { header("HTTP/1.0 301 Moved Permanently"); if(GetPathBySectionID($e404_section)=='/index/'){ // редиректим на самую главную! header("Location: /"); header("Connection: close"); exit; } header("Location: ".GetPathBySectionID($e404_section)); header("Connection: close"); exit; } else { if($parsed_url['path']=="/404/"||$parsed_url['path']=="/index/"){ header("HTTP/1.0 404 Not Found"); } else { switch ($CMS_PHP_TYPE) { case "module": header("HTTP/1.0 200 OK"); break; case "cgi": header("Status: 200 OK"); break; } } } // Front user mode if ($action != "index" && $action != "view" && $action != "add" && $action != "search" && $action != "subscribe") $action = "index"; if (isset($MODULE_VARS['users']["USER_MODIFY_SECTION"]) && $section == $MODULE_VARS['users']["USER_MODIFY_SECTION"]) { $action = "edit"; $user_table_mode = true; } if (!$action) $action = "index"; if (!$site && !$section) exit; $passed_thru_404 = true; if ($action != "index") { require_once $ROOT_FOLDER."action/".$action."/index.php"; } else { //DebugBreak(); require_once $ROOT_FOLDER."index.php"; } $build_time= getmicrotime() - $build_start; if ($CMS_DEBUG) echo ''; ?>parser.php000066600000050706150472427540006577 0ustar00'',CONCAT(Domain,'.".$DOMAIN_NAME."'),'".$DOMAIN_NAME."'))='".$host."'",$LinkID); if (mysql_num_rows($res)) { list($SiteID) = mysql_fetch_row($res); mysql_free_result($res); $cache[$host]=(int)$SiteID; return (int)$SiteID; } update_site_info(); if ($cache_site){ foreach ($cache_site as $site_id => $site){ $Mirrors = &$site['Mirrors']; for ($i=0;$i"," "), "\n", $row['Mirrors']); $Mirrors = str_replace("\n\n", "\n", $Mirrors); $row['Mirrors'] = $Mirrors = explode("\n",$Mirrors); $cache_site[(int)$row['Site_ID']]=$row; } } #### ФУНКЦИИ КОНТРОЛЯ ЛИЦЕНЗИИ #### function checkLicense(){ global $domain,$cache_site,$mirror_limit; //if (substr($domain,strlen($domain)-3) == '.bi'){ return 1; } //DebugBreak(); //return true; $wdomain = str_replace("www.","",$domain); $site = GetSiteID($domain); if ($site && $cache_site[$site] === null){ update_site_info($site); } $info=&$cache_site[$site]; if ($info === null) { print_r($cache_site); licenseNotice(3,1); } if (substr($info['Domain'],0,4) == 'www.'){ licenseNotice(2,0); } if (generateLicense($info['Domain']) != cleanLicenseKey($info['Site_License'])){ licenseNotice(1,1); } $dmirrors=array(); $domain_parts=array_reverse(explode('.',$info['Domain'])); foreach ($info['Mirrors'] as $mirror){ if ($mirror === '') continue; $mirror=trim($mirror); if (substr($mirror,0,4)=='www.') continue; $mirror_parts=array_reverse(explode('.',$mirror)); if (count($mirror_parts)>2) continue; $flag=true; for ($i=0; $i $mirror_limit) { licenseNotice(6,1); // превышен лимит на разнородные зеркала } return 1; } function cleanLicenseKey($license){ $license = substr($license,5,5); return $license; } function generateLicense($domain){ return substr(base64_encode($domain),0,5);} function licenseNotice($code,$iscritical = false){ echo ''; switch($code){ case 1: echo "EMPTY KEY/FIELD DOES NOT EXIST!
"; break; // поле не задано или ключ пустой case 2: echo "BASE DOMAIN NAME CANNOT BE WITH www.!
"; break; // поле не задано или ключ пустой case 3: echo "SITE VERSION NOT FOUND! - ".$_SERVER['HTTP_HOST']; break; // поле не задано или ключ пустой case 6: echo "LIMIT ON VERSION MIRRORS EXCEEDED
"; break; } echo '
'; if($iscritical){ exit;} } checkLicense(); require_once ($INCLUDE_FOLDER."main.inc.php"); require_once ($INCLUDE_FOLDER."filters.inc.php"); function ObjectExists ($classID,$sysTbl,$object,$keyword) { global $LinkID; $res = mysql_query("SELECT ".($sysTbl?"".(LOWER_CASE_TABLES ? "user" : "User")."":"".(LOWER_CASE_TABLES ? "data" : "Data")."")."_ID FROM `".($sysTbl?"".(LOWER_CASE_TABLES ? "user" : "User")."":"".(LOWER_CASE_TABLES ? "data" : "Data")."".$classID)."` WHERE `Keyword`='$keyword'",$LinkID); #echo "SELECT ".($sysTbl?"User":"Data")."_ID FROM ".($sysTbl?"User":"Data$classID")." WHERE Keyword='$keyword'"; if (mysql_num_rows($res)) { list($msgID) = mysql_fetch_row($res); mysql_free_result($res); return ($msgID); } else { return false; } } function GetSectionID ($site, $path) { global $LinkID; $res = mysql_query("SELECT `Section_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Site_ID`='".$site."' AND `Hidden_URL`='".$path."'", $LinkID); list($section) = mysql_fetch_row($res); mysql_free_result($res); return $section; } function GetPathBySectionID ($section) { global $LinkID; $res = mysql_query("SELECT `Hidden_URL` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Section_ID`='".$section."'", $LinkID); list($path) = mysql_fetch_row($res); mysql_free_result($res); return $path; } function ParseQuery ($query_string) { $param_str = explode("&",$query_string); for ($i = 0; $i < count ($param_str); $i++) { $param_arg = explode ("=", $param_str[$i]); if (count($param_arg) && $param_arg[0]) @eval("\$getVars[\"".(strchr($param_arg[0],"[")?substr(urldecode($param_arg[0]),0,strlen(urldecode($param_arg[0]))-strlen(strchr($param_arg[0],"["))):urldecode($param_arg[0]))."\"]".strchr($param_arg[0],"[")." = \"".urldecode($param_arg[1])."\";"); } return $getVars; } /* function AttemptToSection_Redirect ($url) { global $LinkID, $REDIRECT_STATUS; $res = mysql_query("SELECT REPLACE(NewURL,'*','\\\'),REPLACE(OldURL,'*','([[:alnum:]]+)') FROM Section_Redirect WHERE '".$url."' LIKE CONCAT('http://',REPLACE(OldURL,'*','%')) OR '".$url."' LIKE CONCAT('http://www.',REPLACE(OldURL,'*','%'))", $LinkID); if (!mysql_num_rows($res)) return 0; list($new_url,$old_url) = mysql_fetch_row($res); mysql_free_result($res); if (strchr($new_url,"\\")) $result_url = ereg_replace($old_url,$new_url,$url); else $result_url = "http://".$new_url; if ($REDIRECT_STATUS=="on") header("Location: $result_url"); else echo ""; exit; } */ function AttemptToSection_Redirect ($url) { global $LinkID, $REDIRECT_STATUS; $old_path = mysql_real_escape_string(parse_url($url, PHP_URL_PATH)); $new_path = SQLSelectOne("SELECT `NewURL` FROM `".(LOWER_CASE_TABLES ? "section_redirect" : "Section_Redirect")."` WHERE `OldURL` = '$old_path'", 'NewURL'); if (!empty($new_path)){ if ($REDIRECT_STATUS=="on"){ header("HTTP/1.0 301 Moved Permanently"); header("Location: $new_path"); }else{ echo ""; }; exit; }; } function check_server() { // if (preg_match("/^(207.44|209.152)/",$_SERVER["SERVER_ADDR"]) > 0) return 1; return 0; } if (check_server() == 0) { switch ($CMS_PHP_TYPE) { case "module": header("HTTP/1.0 500 Internal Server Error"); exit; case "cgi": header("Status: 500 Internal Server Error"); exit; } } $client_url = urldecode("http://".$_SERVER['HTTP_HOST'].cms_process_filters($_SERVER['REQUEST_URI'])); //$m_url=parse_url('http://domus.bi'); $parsed_url = parse_url($client_url); if (!isset($parsed_url['path'])) $parsed_url['path'] = ''; if (!isset($parsed_url['query'])) $parsed_url['query'] = ''; if (!isset($parsed_url['scheme'])) $parsed_url['scheme'] = ''; if (!isset($parsed_url['user'])) $parsed_url['user'] = ''; if (!isset($parsed_url['pass'])) $parsed_url['pass'] = ''; if (!isset($parsed_url['host'])) $parsed_url['host'] = ''; if (!isset($parsed_url['port'])) $parsed_url['port'] = ''; $myhost = explode('.',$parsed_url['host']); if($myhost[0]!="www" && $REDIRECT_TO_WWW){ header("HTTP/1.0 301 Moved Permanently"); header("Location: ".$parsed_url['scheme'].'://www.'.$parsed_url['host'].$parsed_url['path'].$parsed_url['query']); exit; } elseif($myhost[0]=="www" && $REDIRECT_FROM_WWW){ header("HTTP/1.0 301 Moved Permanently"); header("Location: ".$parsed_url['scheme'].'://'.str_replace("www.","",$parsed_url['host'].$parsed_url['path'].$parsed_url['query'])) ; exit; } // Generating print link if (strpos($parsed_url['path'], ".html") > 0) { $CMS_PRINT_LINK = str_replace(".html", ".".$CMS_PRINT_FILTER.".html", $parsed_url['path']).$parsed_url['query']; } else { $T=substr($parsed_url['path'], -1); $CMS_PRINT_LINK = ((substr($parsed_url['path'], -1) == "/") ? $parsed_url['path']:"/")."print/".($parsed_url['query'] ? "?".$parsed_url['query'] : ""); } $client_source_url = $parsed_url['scheme']."://".($parsed_url['user']?$parsed_url['user']:"").($parsed_url['pass']?":".$parsed_url['pass']:"").(($parsed_url['user'] || $parsed_url['pass'])?"@":"").$parsed_url['host'].($parsed_url['port']?":".$parsed_url['port']:"").$parsed_url['path']; parse_str ($parsed_url['query'], $_GET); extract ($_GET); $site = ""; $section = ""; $object = ""; $classID = ""; $user_table_mode = false; $as_admin = false; $cached_inserts=0; $cached_requests=0; $cache_site=array(); LoadModuleEnv(); $site = GetSiteID($parsed_url['host']); $res = mysql_query("SELECT `E404_Section_ID`,`Title_Section_ID` FROM `".(LOWER_CASE_TABLES ? "site" : "Site")."` WHERE `Site_ID`='".$site."'",$LinkID); list ($e404_section,$title_section) = mysql_fetch_row($res); $cache_site[$site]['E404_Section_ID']=$e404_section; $cache_site[$site]['Title_Section_ID']=$Title_Section_ID = $title_section; mysql_free_result($res); $redirect_to_url = ''; $object_keyword = ''; if (!isset($action)) $action = ''; if (($req_file = strrchr($parsed_url['path'],"/")) <> "/") { $req_file = substr($req_file,1,strlen($req_file) - 1); $req_file_parts = explode(".",$req_file); $fname = $req_file_parts[0]; $fext = strtolower($req_file_parts[count($req_file_parts)-1]); if ($fext == "html") { $parsed_url['path'] = substr ($parsed_url['path'], 0, strlen($parsed_url['path']) - strlen($req_file)); if (ereg ("/([0-9]{4}/)", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (ereg ("/([0-9]{4})/([0-9]{1,2}/)", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (ereg ("/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2}/)", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]."-".$regs[3]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } #echo "SELECT a.Section_ID,b.Section_Object_ID,b.Object_ID,c.System_ID FROM Section AS a,Section_Object AS b,Object AS c WHERE (a.Hidden_URL='".$parsed_url['path']."' OR a.Hidden_URL='".$parsed_url_pathtmp."') AND a.Site_ID=".$site." AND a.Section_ID=b.Section_ID AND b.Object_ID=c.Object_ID ORDER BY b.Checked,b.Priority"; $res = mysql_query("SELECT a.`Section_ID`,b.`Section_Object_ID`,b.`Object_ID`,c.`System_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` AS a,`".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` AS b,`Object` AS c WHERE (a.Hidden_URL='".$parsed_url['path']."' OR a.`Hidden_URL`='".$parsed_url_pathtmp."') AND a.`Site_ID`=".$site." AND a.`Section_ID`=b.`Section_ID` AND b.`Object_ID`=c.`Object_ID` ORDER BY b.`Checked`,b.`Priority`",$LinkID); if (mysql_num_rows($res)) { for ($i=0;$i".$parsed_url['path']."<--
"; #echo "-->".$parsed_url_pathtmp."<--
"; if (!$message) { /*if ($parsed_url_pathtmp) $object_keyword = strrchr(substr($parsed_url_pathtmp,0,strlen($parsed_url_pathtmp) - 1),"/"); else $object_keyword = strrchr(substr($parsed_url['path'],0,strlen($parsed_url['path']) - 1),"/");*/ if($sectiondivisionID && $sectionObjectID) { $sql = "SELECT `LinkName` FROM `Section_Object` WHERE `Section_ID` = {$sectiondivisionID} AND `Section_Object_ID` = {$sectionObjectID}"; $object_keywords = SQLSelectOne($sql); $object_keyword = $object_keywords['LinkName']; } else { if ($parsed_url_pathtmp) $object_keyword = strrchr(substr($parsed_url_pathtmp,0,strlen($parsed_url_pathtmp) - 1),"/"); else $object_keyword = strrchr(substr($parsed_url['path'],0,strlen($parsed_url['path']) - 1),"/"); } //if ($object_keyword = substr($object_keyword,1,strlen($object_keyword) - 1)) { if ($object_keyword) { if (preg_match("([0-9]+)", $fname)) { $message = $fname; $action = "view"; } elseif ($fname=="add" || $fname=="search" || $fname=="subscribe") { $action = $fname; } else $object_keyword = $fname; } else $object_keyword = $fname; } } else { $parsed_url['path'] .= "/"; $redirect_to_url = $client_source_url."/".($parsed_url['query']?"?".$parsed_url['query']:"").($parsed_url[fragment]?"#".$parsed_url[fragment]:""); } } if (preg_match("|/([0-9]{4}/)|", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (preg_match("|/([0-9]{4})/([0-9]{1,2}/)|", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if (preg_match ("|/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2}/)|", $parsed_url['path'], $regs)) { $date_tmp = $regs[1]."-".$regs[2]."-".$regs[3]; $date_tmp = substr($date_tmp,0,strlen($date_tmp)-1); $parsed_url_pathtmp = substr($parsed_url['path'],0,strlen($parsed_url['path'])-strlen($regs[0])+1); } if ($parsed_url['path'] == "/") $section = $title_section; else $section = GetSectionID ($site, $parsed_url['path']); $date = ''; if (!$section) { $section = GetSectionID ($site, $parsed_url_pathtmp); if ($section) $date = $date_tmp; } if ($section) { $current_section = get_section_info($section); if ($current_section['ExternalURL'] && $current_section['do_redirect']){ $redirect_to_url = ((substr($current_section['ExternalURL'],0,7) != 'http://') ? 'http://'.$_SERVER['HTTP_HOST'] : "").$current_section['ExternalURL']; } } if ($section && $redirect_to_url) { if ($REDIRECT_STATUS == "on") { header("HTTP/1.0 301 Moved Permanently"); header("Location: {$redirect_to_url}"); exit; } } #echo "-->section=".$section."<--
"; #echo "-->object_keyword=".$object_keyword."<--
"; if ($section) { if ($section == $e404_section) $skip_redirect = 1; if ($object_keyword) { $sql = "SELECT `Section_Object_ID` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID`='".$section."' AND `LinkName`='".$object_keyword."'"; $res = mysql_query($sql,$LinkID); list($object) = mysql_fetch_row($res); mysql_free_result($res); if (!$object) $section = $e404_section; } elseif(!$object) { $query = "SELECT `Section_Object_ID` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID`='".$section."' AND `Checked`=1 ORDER BY `Priority` ASC LIMIT 1"; $res = mysql_query($query,$LinkID); list($object) = mysql_fetch_row($res); mysql_free_result($res); if (!$object) $no_object = true; else $no_object = false; } #echo "-->object=".$object."<--
"; if ($object) { $res = mysql_query("SELECT `Object_ID`,`DefaultAction` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_Object_ID`='".$object."'",$LinkID); #echo "SELECT Object_ID,DefaultAction FROM Section_Object WHERE Section_Object_ID='".$object."'"; list($classID,$default_action,$system_table) = mysql_fetch_row($res); mysql_free_result($res); $res = mysql_query("SELECT `System_ID` FROM `".(LOWER_CASE_TABLES ? "object" : "Object")."` WHERE `Object_ID`='".$classID."'",$LinkID); list($system_table) = mysql_fetch_row($res); mysql_free_result($res); if (!$action) $action = $default_action; if ($system_table) $user_table_mode = true; } if ($object && $date) { $res = mysql_query("SELECT `Object_Field_ID` FROM `".(LOWER_CASE_TABLES ? "object_field" : "Object_Field")."` WHERE `Format`='event' AND `TypeOfData_ID`=8 AND `Object_ID`='".$classID."' LIMIT 1",$LinkID); list($Object_FieldID) = mysql_fetch_row($res); mysql_free_result($res); if (!$Object_FieldID) $section = $e404_section; } if ($no_object && $date) $section = $e404_section; if ($object && $message && $action=="view") { $res = mysql_query("SELECT ".($user_table_mode?"User":"Section_Object")."_ID FROM ".($user_table_mode?"User":"Data{$tblID}")." WHERE Checked=1 AND ".($user_table_mode?"User":"Data")."_ID='".$message."'",$LinkID); $msg_count = mysql_num_rows($res); list($object)=mysql_fetch_row($res); if (!$msg_count) $section = $e404_section; mysql_free_result($res); } } else { AttemptToSection_Redirect($client_source_url); $section = $e404_section; } function zeee_content($cnt){ return str_replace('
\r\n\r\n"; $j++; break; case 5: // Bool $result .= "
\r\n\r\n"; $j++; break; } $result .= "
"; } if (!$j) return false; return $result; } function getSearchParams($field_name, $field_type, $field_search, $srchPat){ global $LinkID; for ($i = 0, $j = 0; $i < count($field_name); $i++) { if ($field_search[$i]) { switch ($field_type[$i]) { case 1: // Char if ($srchPat[$j] == "") break; $fullSearchStr .= " AND a." . $field_name[$i] . " LIKE '%" . urldecode($srchPat[$j])."%'"; $fullSearchURL .= "&srchPat[$j]=" . urldecode($srchPat[$j]); break; case 2: // Int if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND a." . $field_name[$i] . ">=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND a." . $field_name[$i] . "<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } break; case 3: // Text if ($srchPat[$j] == "") break; $fullSearchStr .= " AND a." . $field_name[$i] . " LIKE '%" . urldecode($srchPat[$j])."%'"; $fullSearchURL .= "&srchPat[$j]=" . urldecode($srchPat[$j]); break; case 4: // List if ($srchPat[$j] == "") break; $srchPat[$j] += 0; $fullSearchStr .= " AND a." . $field_name[$i] . "=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; break; case 5: // Boolean if ($srchPat[$j] == "") break; $srchPat[$j] += 0; $fullSearchStr .= " AND a." . $field_name[$i] . "=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; break; case 7: // Float if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND a." . $field_name[$i] . ">=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND a." . $field_name[$i] . "<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } break; case 8: // DateTime if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",1,4)>=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",6,2)>=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",9,2)>=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",13,2)>=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",16,2)>=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",19,2)>=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",1,4)<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",6,2)<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",9,2)<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",13,2)<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",16,2)<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } $j++; if ($srchPat[$j] != "") { $srchPat[$j] += 0; $fullSearchStr .= " AND SUBSTRING(a." . $field_name[$i] . ",19,2)<=" . $srchPat[$j]; $fullSearchURL .= "&srchPat[$j]=" . $srchPat[$j]; } break; } $j++; } } $search_params["query"] = $fullSearchStr; $search_params["link"] = $fullSearchURL; return $search_params; } function subscribe_buttons($object_id,$section_id,$section_object_id,$record_id,$title=''){ global $as_admin,$CMS_ADMIN_PATH; static $started; if (!$as_admin) return; $out = ''; if (!$started) { $out .= ""; $out .= ""; $started=1; } //$out .= "
"; $out .= "Создать новую задачу рассылки\n"; if (false) { $tasks = get_subscribe_tasks(); if (is_array($tasks) && $tasks) { $out .= "Добавить к существующей\n"; } } return $out; } function get_AdminCommon($table,$section_object_id,$site,$section,$section_object_name,$admin_url_prefix){ global $HTTP_ROOT_PATH; static $started; if ($started) { $out = '';} else { $started=1; $out = "\n"; } $out .= "
\n"; $out .= "\"" . $section_object_name . "\"\n"; $out .= "Добавить запись\n"; $out .= "Удалить все\n"; $out .= "
\n"; $out .= "
\n"; $out .= ""; $out .= ""; $out .= ""; $out .= ""; $out .= ""; $out .= "
"; return $out; } function getObjectQueries($classID,$user_table_mode=null,$userTableID=null,$joins=null, $join_tables=null){ global $LinkID,$object_fields_struct,$CMS_UPLOAD_PATH,$OLD_VERSION_LISTS; static $cache; $key = $classID.'-'.$user_table_mode.'-'.$userTableID; if (is_array($join_tables)){ foreach ($join_tables as $ckey=>$value){ $key .= $ckey.'>'.$value.'-'; } } if ($cache[$key] !== null) return $cache[$key]; $field_names = ""; $field_vars = ""; $convert2txt = ""; if (!$user_table_mode && !$userTableID) { if (!($struct = &getObjectStruct($classID))){ return false; }; $field_count = count($struct); reset($struct); } else { $res = mysql_query("SELECT `Object_Field_ID`, `Object_Field_Name`, `TypeOfData_ID`, `Format`".(!$user_table_mode ? ", `DoSearch`" : ", 1 AS `DoSearch`")." FROM `".(LOWER_CASE_TABLES ? "object_field" : "Object_Field")."` WHERE " . ($user_table_mode ? "System_ID='".$userTableID."'" : "Object_ID='".$classID."'")." ORDER BY `Priority`", $LinkID); $field_count = mysql_num_rows($res); } for ($i = 0; $i < $field_count; $i++) { if ($struct){ list($fname,$field_array) = each($struct); } else { $field_array = mysql_fetch_assoc($res); } $field_name_query = ""; $field_var = ""; $field_name[$i] = $field_array["Object_Field_Name"]; $field_search[$i] = $field_array["DoSearch"]; $field_type[$i] = $field_array["TypeOfData_ID"]; if (LOWER_CASE_TABLES ){ $field_array['Format']=strtolower($field_array['Format']); } switch ($field_type[$i]) { case 4: { // Список $joins .= " LEFT JOIN `".(LOWER_CASE_TABLES ? "list_" : "List_")."" . ($field_array["Format"]) . "` AS tbl" . $field_array["Object_Field_ID"].$i." ON a." . $field_array["Object_Field_Name"] . "=tbl" . $field_array["Object_Field_ID"].$i."." . $field_array["Format"] . "_ID "; $field_name_query = "tbl" . $field_array["Object_Field_ID"] .$i. "." . $field_array["Format"]."_Name"; $field_name_query .= ", tbl" . $field_array["Object_Field_ID"].$i . "." . $field_array["Format"]."_ID"; if (!$OLD_VERSION_LISTS) { $field_name_query .= ", tbl" . $field_array["Object_Field_ID"].$i . "." . $field_array["Format"]."_Value"; } $field_var = "\$as_" . $field_array["Object_Field_Name"]; $field_var .= ", \$as_" . $field_array["Object_Field_Name"] . "_id"; if (!$OLD_VERSION_LISTS) { $field_var .= ", \$as_" . $field_array["Object_Field_Name"] . "_value"; } } break; case 6: { // Файл $field_name_query = "IF(a." . $field_array["Object_Field_Name"]."<>'',CONCAT('" . $CMS_UPLOAD_PATH . "',SUBSTRING_INDEX(a." . $field_array["Object_Field_Name"].",':',1)),'')"; $field_var = "\$as_".$field_array["Object_Field_Name"]; $field_name_query .= ", SUBSTRING_INDEX(a.".$field_array["Object_Field_Name"].",':',1)"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_name"; $field_name_query .= ", SUBSTRING_INDEX(SUBSTRING_INDEX(a.".$field_array["Object_Field_Name"].",':',3),':',-1)"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_type"; $field_name_query .= ", SUBSTRING_INDEX(SUBSTRING_INDEX(a.".$field_array["Object_Field_Name"].",':',4),':',-1)"; $field_var .= ", \$as_" . $field_array["Object_Field_Name"]."_size"; $field_name_query .= ", SUBSTRING_INDEX(SUBSTRING_INDEX(a.".$field_array["Object_Field_Name"].",':',5),':',-1)"; $field_var .= ", \$as_" . $field_array["Object_Field_Name"]."_width"; $field_name_query .= ", SUBSTRING_INDEX(SUBSTRING_INDEX(a." . $field_array["Object_Field_Name"].",':',6),':',-1)"; $field_var .= ", \$as_" . $field_array["Object_Field_Name"] . "_height"; // Processing Reduced Images $fileSystem_Config = explode("|", $field_array["Format"]); for ($j = 0; $j < sizeof($fileSystem_Config); $j++) { $fileSystem_Config[$j] .= ';'; if (strstr($fileSystem_Config[$j], 'postfix=')) { $postfix = substr($fileSystem_Config[$j], strpos($fileSystem_Config[$j],'postfix=') + 8); $postfix = substr($postfix, 0, strpos($postfix, ';')); $field_name_query .= ", IF(a." . $field_array["Object_Field_Name"]."<>'',CONCAT('" . $CMS_UPLOAD_PATH . "', SUBSTRING_INDEX(SUBSTRING_INDEX(a." . $field_array["Object_Field_Name"].",':',1),'.',1), '" . $postfix . ".', SUBSTRING_INDEX(SUBSTRING_INDEX(a." . $field_array["Object_Field_Name"].",':',1),'.',-1) ),'')"; $field_var .= ", \$as_" . $field_array["Object_Field_Name"] . $postfix; } } } break; case 8: { // Дата $field_name_query = "a.".$field_array["Object_Field_Name"]; $field_var = "\$as_".$field_array["Object_Field_Name"]; $field_name_query .= ", DATE_FORMAT(a." . $field_array["Object_Field_Name"].",'%Y')"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_year"; $field_name_query .= ", DATE_FORMAT(a.".$field_array["Object_Field_Name"].",'%m')"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_month"; $field_name_query .= ", DATE_FORMAT(a.".$field_array["Object_Field_Name"].",'%d')"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_day"; $field_name_query .= ", DATE_FORMAT(a.".$field_array["Object_Field_Name"].",'%H')"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_hours"; $field_name_query .= ", DATE_FORMAT(a.".$field_array["Object_Field_Name"].",'%i')"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_minutes"; $field_name_query .= ", DATE_FORMAT(a.".$field_array["Object_Field_Name"].",'%s')"; $field_var .= ", \$as_".$field_array["Object_Field_Name"]."_seconds"; if ($field_array["Format"] == "event") $date_field = $field_array["Object_Field_Name"]; } break; case 11: // Foreign Key $field_name_query = "a." . $field_array["Object_Field_Name"]; $field_var = "\$as_" . $field_array["Object_Field_Name"]; if(preg_match("/SELECT (.+?) FROM (.+?)(WHERE|GROUP\s+BY|ORDER\s+BY|LIMIT|\$)/is", $field_array["Format"], $m)){ $fields = explode(',', $m[1]); if(count($fields) > 1){ $table_name = $field_array["Object_Field_Name"]; foreach($fields as $index => $field){ if(preg_match('/(.+)\sAS\s(.+)/is', $field, $mf)){ $mf[2] = preg_replace('/[^\w_]/i','',$mf[2]); $field_var .= ", \$as_{$field_array['Object_Field_Name']}_$mf[2]"; $field_name_query .= ", $mf[1]"; } } $key_field = preg_replace('/\sAS\s.+$|/is','', $fields[0]); $joins .= " LEFT JOIN {$m[2]} ON ($key_field = a.{$field_array['Object_Field_Name']})"; } } break; default: { $field_name_query = "a." . $field_array["Object_Field_Name"]; $field_var = "\$as_" . $field_array["Object_Field_Name"]; } break; } if ($field_name_query && $field_var) { $field_names .= $field_name_query . ","; $field_vars .= $field_var . ","; } /* if (!$allowTags && ($field_type[$i]==3 || $field_type[$i]==1)) $convert2txt .= "\$as_".$field_name[$i]." = htmlspecialchars(\$as_".$field_name[$i].");"; if ($NL2BR && ($field_type[$i]==3 || $field_type[$i]==1)) $convert2txt .= "\$as_".$field_name[$i]." = nl2br(\$as_".$field_name[$i].");"; */ $format = $field_array["Format"]; if ((strpos($format, 'allow_tags') === false) && ($field_type[$i] == 3 || $field_type[$i] == 1)) $convert2txt .= "\$as_" . $field_name[$i] . " = htmlspecialchars(\$as_" . $field_name[$i].");"; if ((strpos($format, 'nl2br') !== false) && ($field_type[$i] == 3 || $field_type[$i] == 1)) $convert2txt .= "\$as_" . $field_name[$i] . " = nl2br(\$as_" . $field_name[$i].");"; } if (!$join_tables){ return $cache[$key]=array('field_count' => $field_count,'field_names' => $field_names,'field_vars' => $field_vars,'convert2txt' => $convert2txt,'joins' => $joins ); } $exfields = array_keys($struct); foreach ($join_tables as $prefix => $table){ if (!($struct = &getObjectStruct($table))) {continue;}; $fnames = array_keys($struct); foreach ($fnames as $fname) { if (in_array($fname,$exfields)) continue; array_push($exfields,$fname); $field_names .= $prefix.".`".$fname."`,"; $field_vars .= "\$as_".$fname.","; $field_count++; } } return $cache[$key]=array('field_count' => $field_count,'field_names' => $field_names,'field_vars' => $field_vars,'convert2txt' => $convert2txt,'joins' => $joins ); } ?>files.inc.php000066600000011432150472427540007146 0ustar00'_', 'а'=>'a','б'=>'b','в'=>'v','г'=>'g','д'=>'d','е'=>'e','ё'=>'io', 'ж'=>'zh','з'=>'z','и'=>'i','к'=>'k','л'=>'l','м'=>'m','н'=>'n','о'=>'o','п'=>'p','р'=>'r','с'=>'s', 'т'=>'t','у'=>'u','ф'=>'f','к'=>'k','ц'=>'ts','ч'=>'ch','ш'=>'sh','щ'=>'sch','ь'=>'','ы'=>'y','ъ'=>'', 'э'=>'e','ю'=>'u','я'=>'ia','і'=>'i','ў'=>'u', 'А'=>'A','Б'=>'B','В'=>'V','Г'=>'G','Д'=>'D','Е'=>'E','Ё'=>'IO', 'Ж'=>'ZH','З'=>'Z','И'=>'I','К'=>'K','Л'=>'L','М'=>'M','Н'=>'N','О'=>'O','П'=>'P','Р'=>'R','С'=>'S', 'Т'=>'T','У'=>'U','Ф'=>'F','К'=>'K','Ц'=>'TS','Ч'=>'CH','Ш'=>'SH','Щ'=>'SCH','Ь'=>'','Ы'=>'Y','Ъ'=>'', 'Э'=>'E','Ю'=>'U','Я'=>'IA','І'=>'I','Ў'=>'U')); $Filename = preg_replace('/[^\d\w._-]/', '-', $Filename); return $Filename; }; ?>core.php000066600000310020150472427540006217 0ustar00

".($message ? $message : "Fatal error!" )."

"); } function page_in($arr){ global $current_section; if (is_string($arr) || is_numeric($arr)){ $arr=array($arr); } //DebugBreak(); if (in_array((int)$current_section['Section_ID'],$arr)) return true; return false; } ####################################### AUTH ################################### function is_logged(){ if ($_SESSION['PHP_AUTH_USER'] && $_SESSION['PHP_AUTH_PW']) {return true;} //elseif ($_COOKIE['PHP_AUTH_USER'] && $_COOKIE['PHP_AUTH_PW']) {die('by_cookie');return true;} else return false; } function is_admin(){ static $cache; if ($cache !== null) return $cache; if (1 ==(int)$_SESSION['user']['User_Group_ID']) return $cache=true; if ($user = $_COOKIE['PHP_AUTH_USER']) { $query = "SELECT `User_Group_ID` FROM `".(LOWER_CASE_TABLES ? "user" : "User")."` WHERE `Email` = '".$user."'"; $t = SQLSelect($query,'User_Group_ID','User_Group_ID'); if (is_array($t) && isset($t[1])){ if ($t[1]) return $cache=true; } } return $cache=false; } function auth($login, $pass,$cookie=true){ global $current_user,$CMS_AUTHORIZE_FIELD,$LinkID,$perm,$AUTH_USER; $HTTP_HOST = $_SERVER['HTTP_HOST']; $res = mysql_query("SELECT `User_ID` FROM `".(LOWER_CASE_TABLES ? "user" : "User")."` WHERE `$CMS_AUTHORIZE_FIELD` ='".$login."' AND `Password`=MD5('".$pass."') AND `Checked`=1",$LinkID); $exists = mysql_num_rows($res); if ($exists) { $user = mysql_fetch_assoc($res); $user_id = $user['User_ID']; $fields=(array)getUserFields($user_id); mysql_free_result($res); } else { $res = mysql_query("SELECT `User_ID` FROM `".(LOWER_CASE_TABLES ? "user" : "User")."` WHERE `$CMS_AUTHORIZE_FIELD` ='".$login."' AND `newPassword`=MD5('".$pass."') AND `Checked`=1",$LinkID); $exists = mysql_num_rows($res); $user = mysql_fetch_assoc($res); $user_id = $user['User_ID']; $fields=(array)getUserFields($user_id); mysql_free_result($res); if ($exists) { $query = "UPDATE `".(LOWER_CASE_TABLES ? "user" : "User")."` SET `Password` = '".md5($pass)."', `newPassword` = NULL WHERE `User_ID` = '".$user_id."';"; SQLExec($query); $fields['pass_changed']=1; } } if (!$exists) return false; $ProjectDomain = GetAllProjectDomains(); $res = mysql_query("SELECT MD5('".$pass."')",$LinkID); list($Password) = mysql_fetch_row($res); mysql_free_result($res); $AUTH_USER =$login; if ($cookie) { for ($i=0;$i $obj){ $out .= as_insert_object($current_section['Section_ID'],$key,'&goods_ID='.$goods_ID); } return $out; } /** * Выводит ОСТАЛЬНЫЕ объекты в текущей секции */ function get_other_section_objects_menu($title = "Other section objects"){ global $as_admin, $admin_url_prefix; global $current_object, $current_section, $current_site,$other_section_objects; if (!$other_section_objects || !$as_admin) return; $out = "

".$title." :

"; } function as_insert_object_of_sections($sections){ if (!$sections) return ''; if (is_string($sections)) $sections = array((int)$sections); $tmp = ''; //DebugBreak(); foreach ($sections as $section){ $tmp .= as_insert_object($section,0,'&isMainContent=1'); } return $tmp; } function as_insert_object_of_subsection($section,$checked=null){ global $section_struct; if (!$section) return false; recursiveChildCollect($section,1,false,$checked); $struct = $section_struct[$section]; if (!$struct) return ''; return as_insert_object(current($struct),0,'&mainContent=1'); } ################################## TREES ################################### function find_section_deep($params,$ancestor=0,$levels=4){ global $search_section_cache; if (!$params) return false; $key=md5((serialize($params))); $ancestor=(int)$ancestor; if ($search_section_cache[$ancestor][$key] !== null) { return $search_section_cache[$ancestor][$key]; } if ($ancestor){ if (!is_array($search_section_cache[$ancestor])){ $search_section_cache[$ancestor]=array(); recursiveChildCollect($ancestor,4,false,null); } debug_stop(); $children=collect_all_children($ancestor,$levels,true,false,null); $children[$ancestor]=$ancestor; } $param_str = ""; foreach ($params as $field => $value) { $param_str .= " AND `".$field."` = '".$value."' "; } $query = "SELECT `Section_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE 1 ".($ancestor ? " AND `Section_ID` IN (".implode(",",$children).") " : "").$param_str.';'; return $search_section_cache[$ancestor][$key] = array_keys(SQLSelect($query,'Section_ID')); } function get_section_by_path($path,$get_full=1){ global $current_site; static $cache; if (substr($path,0,1) != '/') $path = '/'.$path; if (substr($path,strlen($path)-1,1) != '/') $path.='/'; $get_full=(int)$get_full; if (!is_array($cache[$get_full])) $cache[$get_full]=array(); if ($cache[$get_full][$path] !== null) return $cache[$get_full][$path]; $cache[$get_full][$path] = SQLSelectOne("SELECT ".($get_full ? getSectionFieldsQuery() : "`Section_ID`")." FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Site_ID` = '".$current_site['Site_ID']."' AND `Hidden_URL` = '".$path."'; "); return $cache[$get_full][$path]; } /** * Возвращает кол-во потомков у страницы на кол-во уровней вглубь. по умолчанию на 1 уровень * * @param int $anc * @param int $levels=1 * @param bool $force=false * @return int */ function getSectionChildrenTotal($anc,$levels=1,$force=false){ global $section_struct,$section_childs_count; $count = 0; if (!is_array($section_struct[$anc])) { if (!$force) return 0; else recursiveChildCollect($anc,$levels); } if (!count($section_struct[$anc])) return 0; if ($levels>1) { foreach ($section_struct[$anc] as $node) { if ($levels-1) $sub = getSectionChildrenTotal($node,$levels-1,$force); else $sub=0; $count = $count+1+sub; } } else { return $section_childs_count[$anc]; } return $count; } /** * Возвращает id-шники страниц-потомков. force= принудительная перепроверка содержимого кэша * * @param int $page * @param bool $checked * @param bool $force * @return array */ function get_childs_struct($page,$checked=1,$force=true){ global $section_struct,$section_cache; if ($section_struct[(int)$page]) return $section_struct[(int)$page]; elseif ($force) { recursiveChildCollect($page,1,false,$checked); return $section_struct[(int)$page]; } } /** * Собирает id всех потомков данного раздела в глубину и отдаёт масссив */ function collect_all_children($ancestor,$levels=3,$force=true,$first=true,$checked=1){ global $section_cache, $section_struct,$LinkID,$section_childs_count, $section_deep_struct; $ancestor=(int)$ancestor; if ($section_deep_struct[$ancestor] !== null) { return $section_deep_struct[$ancestor]; } if (!is_array($section_deep_struct[$ancestor])) { $section_deep_struct[$ancestor]=array();} if ($force) { recursiveChildCollect($ancestor,$levels,false,$checked); } foreach ($section_struct[$ancestor] as $page_id) { $section_deep_struct[$ancestor][$page_id]=$page_id; if ($levels && $section_struct[$page_id]) { $arr = collect_all_children($page_id,$levels-1,$force,false); $section_deep_struct[$ancestor]=array_merge($section_deep_struct[$ancestor],$arr); } } return $section_deep_struct[$ancestor]; } /** * Собирает кусок дерева страниц на глубину $levels и сохраняет его в кэше. возвращает количество потомков * * @param int $anc * @param int $levels * @param bool $get_all_struct * @param bool $checked * @return array */ function recursiveChildCollect($anc,$levels=1,$get_all_struct=true,$checked=1){ global $section_cache, $section_struct,$section_deep_struct,$LinkID,$section_childs_count,$section_deep_childs_count; $start_levels=$levels; if (!is_array($section_deep_struct)){ $section_deep_struct = array(); } if ($anc === null) return; $anc = (int)$anc; $levels=(int)$levels; $section_struct[$anc]=array(); $section_deep_struct[$anc]=array(); if (!$levels) return; $count=0; $parents = array($anc); ($get_all_struct) ? $secfields=getSectionFieldsQuery() : $secfields=""; $first=true; while ($levels) { foreach ($parents as $p) unset($section_childs_count[$p]); $query = "SELECT ".($secfields ? $secfields.", " : "")." `Section_ID`,`Parent_Section_ID`, `Hidden_URL`,`ExternalURL`, `Section_Name`, `LinkName`, `Checked`, `do_redirect` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE 1 ".($checked == null ? "" : " AND `Checked` = ".$checked." ")."AND `Parent_Section_ID` IN (".implode(",",$parents).") ORDER BY `Priority`;"; $children=SQLSelect($query); // тут заменить if (!$children) {$levels--; continue;}; $parents = array(); $count += count($children); foreach ($children as $child){ $id=(int)$child['Section_ID']; $ancestor = (int)$child['Parent_Section_ID']; if ($get_all_struct && !$section_cache[$id]) $section_cache[$id]=$child; if ($start_levels == 1 || $first) { if (!is_array($section_struct[$ancestor])) { $section_struct[$ancestor]=array($id => $id); } else { $section_struct[$ancestor][$id]=$id; } $section_childs_count[$ancestor]++; } if (!is_array($section_struct[$ancestor])) $section_struct[$ancestor]=array(); $section_struct[$ancestor][$id]=$id; do { if (!is_array($section_deep_struct[$ancestor])) { $section_deep_struct[$ancestor]=array($id => $id); } else $section_deep_struct[$ancestor][$id]=$id; $section_deep_childs_count[$ancestor]++; $ancestor = ($ancestor == 0 ? null : get_ancestor($ancestor)); } while ($ancestor !== null); $parents[$id]=$id; if ($levels > 1) { // recursiveChildCollect((int)$child['Section_ID'],$levels-1,$get_all_struct,$checked); } } $first=false; $levels--; } return $count; } function get_basepoint($section=null,$fieldname='basepoint'){ global $current_section,$as_section_data; static $basepoints; if ($basepoints === null) { $query = "SELECT `Section_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `".$fieldname."` = '1';"; $points = SQLSelect($query,'Section_ID','Section_ID'); $basepoints = array(); foreach ($points as $point) $basepoints[]=(int)$point; } if ($section === null) $section=(int)$current_section['Section_ID']; $path = array(); $anc = $section; do { if (in_array($anc,$basepoints)){ return $anc; } $path[]=$anc; } while ($anc=(int)get_ancestor($anc)); return 0; } /** * Возвращает первую дочернюю секцию секции $point, у которой секция $page_id дочерняя или равна ей * * @param int $point * @param int $page_id * @param bool $return_point * @return int */ function get_current_subpartition($point, $page_id=-1, $return_point =false){ global $current_section; if ($page_id == -1) $page_id = (int)$current_section['Section_ID']; if ($point == $page_id) { if ($return_point) return $point; else return false; } $last_page = $page_id; $flag = false; $anc=$page_id; while ($anc = get_ancestor($anc)) { if ($anc == $point) {$flag = true; break; } $last_page=$anc; } if ($flag) return $last_page; else return false; } /** * Пполучает прямых потомков секции $anc * * @param int $anc * @param string $params = '' * @param string $sort_by = 'Priority' * @param bool $checked_only = true * @return array(hash) */ function get_child_nodes($anc,$params='',$sort_by='Priority', $checked_only = true){ global $system_table_fields, $LinkID, $current_section, $section_childs_count,$section_struct,$section_cache; static $cache; if ($checked_only !== false) $checked_only=true; if (!$params && $sort_by =='Priority' && $checked_only && $section_childs_count[$anc]) { // попытка собрать результат из кеша при параметрах по умолчанию $tmp=array(); $flag=true; foreach ($section_struct[$anc] as $key => $node) { if (!($xnode=$section_cache[$node])) {$flag=false; break;} if ($xnode['Checked']) $tmp[$key]=$xnode; } if ($flag) return $tmp; } $key=md5($anc.$params.$sort_by.((int)$checked_only)); if ($cache[$key] === null) { ($checked_only) ? $where = " `Checked`=1" : $where = ""; if($params){ if ($where) $where .= " AND "; $where .= $params; } if($anc !== false && !$params) { if ($where) $where .= " AND "; $where .= "`Parent_Section_ID`='" . $anc . "' " ;} $query = "SELECT " . getSectionFieldsQuery() . " FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE ".$where." AND Site_ID=" . $current_section["Site_ID"] . " ORDER BY " . $sort_by; $data=SQLSelect($query,'Section_ID'); if (!$data) $cache[$key]=array(); else $cache[$key] = $data; if (!$section_struct[$anc] && is_array($data)) { $section_struct[$anc]=array_keys($data); foreach ($data as $ckey => $csection) { if (!$section_cache[$ckey]) $section_cache[$ckey] = $csection; } } } return $cache[$key]; } function get_children_with_object($anc,$object_id,$limit=0){ static $cache; if (!$object_id) return; $key = $anc.'_'.$object_id.'_'.$limit; if ($cache[$key] !== null) return $cache[$key]; $query = "SELECT a.`Section_ID`,b.`Section_Object_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` AS `a` LEFT JOIN `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` AS `b` ON a.`Section_ID`=b.`Section_ID` WHERE 1 AND a.`Parent_Section_ID`='".$anc."' AND b.`Object_ID`='".$object_id."'".($limit ? " LIMIT ".((int)$limit) : "").";"; return $cache[$key]=SQLSelect($query,'Section_Object_ID','Section_ID'); } /** * Проверяет находится ли указанная страница в текущей ветке * * @param int $page_id * @return bool */ function in_branch($page_id) { global $as_section_data; foreach ( $as_section_data as $page ) { if ($page['Section_ID'] && $page['Section_ID']== $page_id) return true; } return false; } /** * Получает предка секции. $get_full = true - полная инфо * * @param int $page_id * @param bool $get_full * @return int */ function get_ancestor($page_id=-1, $get_full=false){ global $LinkID,$current_section; static $cache, $full_cache; if ($page_id ==-1) $page_id=(int)$current_section['Section_ID']; if ($get_full){ return false; } else { if (!is_array($cache)) $cache=array(); if (!$cache[$page_id]) { $query = "SELECT `Parent_Section_ID` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Section_ID` = '".$page_id."'"; $res = mysql_query($query, $LinkID); $data_count = mysql_num_rows($res); $item= mysql_fetch_row($res); $cache[$page_id]=$item[0]; } return $cache[$page_id]; } } function get_level_ancestor($level,$return_closest=false,$section=null){ static $paths; global $current_section, $as_section_data, $as_section_level; $level=(int)$level; //DebugBreak(); if ($section === null || ((int)$section) == ((int)$current_section['Section_ID']) ) { if ($return_closest && ($level > (count($as_section_data)-2)) ){ return false; } $i = count($as_section_data)-2-$level; $t = (int)$as_section_data[$i]['Section_ID']; return (int)$as_section_data[$i]['Section_ID']; } else { if ($paths[$section] === null) { $arr = array(); $section=(int)$current_section['Section_ID']; $section = (int)$section; $anc = $section; do { array_push($arr,$anc); } while ($anc = (int)get_ancestor($anc)); $paths[$section]=$arr; } $arr = &$paths[$section]; $i = count($arr)-1-$level; if ($i<0){ if ($return_closest) { return $section; } else {return false; } } $t = $arr[$i]; return $t; } return 10; } /** * проверяет является ли секция потомком секции ancestor-а * * @param int/array $ancestors * @param bool $equal * @param int $page_id * @return int/false */ function is_child($ancestors, $equal =true, $page_id=-1) { global $current_section; static $cache; if (!is_array($cache)) $cache=array(); if ($page_id <0) $page_id = $current_section['Section_ID']; if (!is_array($cache[$page_id])) $cache[$page_id]=array(); if (!is_array($ancestors)) { $ancestors = array((int)$ancestors);} foreach ($ancestors as $ancestor) { if (in_array($ancestor,$cache[$page_id])) return $ancestor; if ($ancestor == $page_id) { if ($equal) {return $ancestor;} else {return false;} } $anc=$page_id; while ($anc = get_ancestor($anc)) { $cache[$page_id][]=$anc; if ($anc == $ancestor) return $ancestor; } } return false; } /** * есть ли дочерние секции * * @param int $page_id * @return bool */ function have_children($page_id) { static $cache; global $section_struct; if ($cache[$page_id] === null) { if ($section_struct[(int)$page_id]) { return $cache[$page_id]=count($section_struct[(int)$page_id]); } else { $r=mysql_query("SELECT count(`Section_ID`) as `count` FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Parent_Section_ID` = '".$page_id."';"); $t=mysql_fetch_array($r); return $cache[$page_id] =(int)$t[0]; } } } /** * проверяет в каком из указанных разделов находится страница и возвращает id раздела * * @param array $ancestors - ID-шники крупных разделов, * @param int $page_id - ID страницы * @return int/false */ function select_ancestor($ancestors=array(),$page_id = -1){ if (!count($ancestors)) return false; global $current_section; if ($page_id <0) $page_id = $current_section['Section_ID']; foreach ($ancestors as $anc) { if (is_child($anc,$page_id)) { return $anc; } } } ######################## FIELDS ########################## function inherit_section_field($field,$default=''){ global $as_section_data,$current_site; foreach ($as_section_data as $section){ if ($section[$field]) return $section[$field]; } if ($current_site[$field]) return $current_site[$field]; return $default; } function getSectionFieldsQuery(){ global $system_table_fields; static $cache; if (!$system_table_fields){ LoadEnv(); } if ($cache) return $cache; $upfields=array('Section_ID,Section_Name,ExternalURL,Hidden_URL,LinkName,Site_ID,do_redirect'); for ($i = 0; $i < count($system_table_fields['Section']); $i++) { if ($system_table_fields['Section'][$i]['type'] == 6) $upfields[] = "IF(`" . $system_table_fields['Section'][$i]['name']."`<>'',CONCAT('" . $CMS_UPLOAD_PATH . "',SUBSTRING_INDEX(`" . $system_table_fields['Section'][$i]['name']."`,':',1)),'') AS `" . $system_table_fields['Section'][$i]['name']."`"; else $upfields[] = "`".$system_table_fields['Section'][$i]['name']."`"; } return $cache=implode(',',$upfields); } function UpdateRecord($table, $id, $fields){ global $LinkID; $struct = getObjectStruct($table); if (!$struct) return false; $struct['Created']=1; $struct['Section_ID']=1; $struct['Section_Object_ID']=1; $struct['Checked']=1; if (!$table || !$id || !$fields ) return false; $fields_out = array(); foreach ($fields as $key => $value) { if ($struct[$key]){ $fields_out[] = " `".$key."` = '".$value."' "; } } $query = "UPDATE `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` SET ".implode(",",$fields_out)." WHERE `Data_ID`='".$id."' LIMIT 1;"; return mysql_query($query,$LinkID); } function getLogoLink(){ global $as_admin,$current_section, $current_site,$LinkID,$main_pages; if ($as_admin) { return "cms/?site=".$current_site["Site_ID"]."§ion=".$current_section['Section_ID']; } else { return '/'; } } function getUserFields($id,$filter=null){ global $LinkID; static $cache; if (!$id) return; if (!is_array($cache)) $cache= array(); if ($cache[$id] === null) { $query = "SELECT * FROM `".(LOWER_CASE_TABLES ? "user" : "User")."` WHERE `User_ID` = ".(int)$id." "; $res = mysql_query($query, $LinkID); $cache[$id] = mysql_fetch_assoc($res); } if ($img = $cache[$id]['image']){ $t = explode(':',$img); $cache[$id]['image']='/data/'.$t[1]; } if (!$filter) return $cache[$id]; if ( is_string($filter) && substr_count($filter,",")) $filter=explode(",",$filter); if (is_array($filter) ) { $tmp = array(); foreach ($filter as $key) $tmp[$key]=$cache[$id][$key]; return $tmp; } if (is_string($filter)) return $cache[$id][$filter]; } /** * функция возвращает все поля секции. * * можно также брать поля у страниц getSection(1,'Section_Name') * или массив полей getSection(10,array('Section_Name','icon')) */ function get_section_fields($id,$filter=null){ return get_section_info($id,$filter); } function get_section_info($id,$filter=null){ global $system_table_fields, $LinkID, $current_section; global $section_cache; static $cache; if (is_array($id) && $id['Section_ID']) $id=(int)$id['Section_ID']; if (!$id) return; if (!is_array($cache)) $cache= array( //$current_section['Section_ID'] => $current_section ); if ($cache[$id] === null) { $query = "SELECT " .getSectionFieldsQuery()." FROM `".(LOWER_CASE_TABLES ? "section" : "Section")."` WHERE `Section_ID` = '".$id."' "; $res = mysql_query($query,$LinkID); $cache[$id] = mysql_fetch_assoc($res); } if (!$filter) return $cache[$id]; if ( is_string($filter) && substr_count($filter,",")) $filter=explode(",",$filter); if (is_array($filter) ) { $tmp = array(); foreach ($filter as $key) $tmp[$key]=$cache[$id][$key]; return $tmp; } if (is_string($filter)) return $cache[$id][$filter]; } /** * Формирует адрес секции по id */ function get_section_link($id,$abs=0,$noadmin=0){ global $LinkID,$as_admin; static $cache; $noadmin = (int)$noadmin; $abs = (int)$abs; $key=$noadmin.$abs.'_'.$id; if (!is_array($cache)) $cache=array(); if ($cache[$key] === null) { $r = get_section_fields($id,'ExternalURL,Hidden_URL,Site_ID'); if ($as_admin && !$noadmin){ return $cache[$id] = '/cms/?site='.$r['Site_ID'].'§ion='.$id; } if ($r['ExternalURL']) { if ($r['ExternalURL'][0] == '/') { $link=$r['ExternalURL']; } else { $link=$r['Hidden_URL'].$r['ExternalURL']; } } else $link=$r['Hidden_URL']; if ($abs && !substr_count($link,'http://')) {$cache[$key] = 'http://'.$_SERVER['HTTP_HOST'].$link;} //!! else {$cache[$key]=$link;} } return $cache[$key]; } function get_element_link($Data_ID, $Section_ID, $abs=false){ global $LinkID,$as_admin; static $cache; if (!is_array($cache)) $cache=array(); if (!empty($cache[$Data_ID .'-'. $Section_ID])) { return $cache[$Data_ID .'-'. $Section_ID]; }; $r = get_section_fields($Section_ID,'ExternalURL,Hidden_URL,Site_ID'); if ($r['ExternalURL']) { if ($r['ExternalURL'][0] == '/') { $link=$r['ExternalURL']; } else { $link=$r['Hidden_URL'].$r['ExternalURL']; } }else{ $link=$r['Hidden_URL']; }; if(!empty($Data_ID)) $link .= $Data_ID .'.html'; if ($abs && !substr_count($link,'http://')) { $link = 'http://'.$_SERVER['HTTP_HOST'].$link; } $cache[$Data_ID .'-'. $Section_ID] = $link; return $link; } function get_lang_by_section($section){ global $site_cache,$site_versions_loaded; if (!$section) return false; $site_id = (int)get_section_fields($section,'Site_ID'); if ($site_cache[$site_id] !== null) { return $site_cache[$site_id]['Site_Lang']; } $site_cache[$site_id]=SQLSelectOne("SELECT * FROM `Site` WHERE `Site_ID` = '".$site_id."';"); return $site_cache[$site_id]['Site_Lang']; } function get_versions($is_local=false,$first_current=true){ static $cache; global $site_cache,$site; if ($cache !== null) return $cache; if ($site_cache === null) {$site_cache=SQLSelect("SELECT `Site_ID`,`Site_Name`,`Site_Lang`,`Domain`,`Mirrors` FROM `".(LOWER_CASE_TABLES ? "site" : "Site")."`",'Site_Lang'); $site_versions_loaded=true;} $cache=array(); $first=array(); $host=explode('.',$_SERVER['HTTP_HOST']); $host = $host[count($host)-2].'.'.$host[count($host)-1]; foreach ($site_cache as $lang => $xsite){ $xsite['URL'] = $xsite['Domain']; if (trim($xsite['Mirrors'])=='link'){ $xsite['link']=1; $cache[$lang]=$xsite; continue; } if ($is_local) { $mirrors = str_replace(array("
"," "), "\n", $xsite['Mirrors']); $mirrors = str_replace("\n\n", "\n", $mirrors); $mirrors = explode("\n",$mirrors); foreach ($mirrors as $mirror){ $t = str_replace($host,'',$mirror); if ((substr_count($t,'.')==1 && $t != 'www.') || ($mirror == $host) ) { $xsite['URL']=$mirror; break; } } } if ($xsite['Site_ID'] == $site) { $xsite['current']=1; if ($first_current) {$first[$lang]=$xsite; continue; } } $cache[$lang]= $xsite; } if ($first) $cache = array_merge($first,$cache); return $cache; } ###################################### PARSING ################################ function ParseList($table,$query_or_ids,$glue=true,$data=null,$joins=null){ global $current_site,$LinkID,$current_record,$lang,$current_section,$section,$as_section_data,$as_section_objects,$as_section_link; if (!$table) return ''; if (!$data) { if (is_array($query_or_ids)) { $query = " a.`Data_ID` IN (".implode(',',$query_or_ids).") "; } elseif (is_numeric($query_or_ids)) { $query = " a.`Data_ID` = '".$query_or_ids."' "; } elseif (is_string($query_or_ids)) { $query = $query_or_ids; } $data = getObjects(array('where' => $query,'table'=>$table),true,$joins); } if (!is_array($data)) return; $keys = array_keys($data); foreach ($keys as $key){ $data[$key] = set_fields_to_property_set($data[$key],$table,false); } $templates=getObjectInfo($table,'System_Config,RecordTemplate,RecordLogic'); eval($templates['System_Config']); ($glue) ? $tmp='' : $tmp = array(); $block=&$templates['RecordTemplate']; $logic = &$templates['RecordLogic']; $parser = 1; $as_total_row=count($data); $classID=$table; foreach ($data as $item){ $as_object_id=$item['Data_ID']; $as_link = get_section_link($item['Section_ID']).($item['Keyword'] ? $item['Keyword'] : $item['Data_ID']).".html"; if (is_array($item)) { foreach ($item as $key => $value) { eval('$as_'.$key.' = "'.addslashes($value).'";'); } } if ($logic) eval($logic); ($glue) ? eval("\$tmp .= \"$block\";") : eval("\$tmp[] = \"$block\";"); } return $tmp; } function ParseBlock($block,$vars, $to_property_set=0){ if (!$block) return ''; if ($to_property_set) { $as_object_id=$vars['Data_ID']; $as_link = get_section_link($vars['Section_ID']).($vars['Keyword'] ? $vars['Keyword'] : $vars['Data_ID']).".html"; $vars=set_fields_to_property_set($vars,$to_property_set); } if (is_array($vars)) { foreach ($vars as $key => $value) { eval('$as_'.$key.' = "'.addslashes($value).'";'); } } $tmp = ''; eval("\$tmp = \"$block\";"); return $tmp; } function as_insert_page_path($template){ global $as_section_data, $as_section_level, $system_table_fields,$current_site,$current_record,$as_admin; $last=array(); $cr=0; // current record if ($current_record && !$template['no_object']) { $last['Section_Name']=$current_record['Title']; $titlefields=array('address','Question'); // нужно будет ввести у обьектов Title field foreach ($titlefields as $tfield){ if ($current_record[$tfield]){ $last['Section_Name']=$current_record[$tfield]; break; } } if (!$last['Section_Name']) { $last=false;} else {$last['Section_Name'] = cut_words_ru($last['Section_Name'],40); } $last['Keyword'] = ($current_record['Keyword'] ? $current_record['Keyword'] : $current_record['Data_ID']); $cr=1; } $c=0; $sm = ($template['no_main'] ? 1 : 0); // skip main $stop = $sm-$cr; $out = $template['prefix']; for ($i=count($as_section_data)-1-$sm; $i>= -$cr; $i--) { $section = &$as_section_data[$i]; if ($section['Title_Section_ID']){ $name=get_section_fields($section['Title_Section_ID'],'Section_Name'); } else { $name=$section['Section_Name']; } if ($i != -$cr) { $section = &$as_section_data[$i]; if ($as_admin) { $url = "/cms/?site=".$current_site['Site_ID']."§ion=".$section['Section_ID']; } else { ($section['ExternalURL']) ? $url = $section['ExternalURL'] : $url = $section['Hidden_URL']; } } else { if (!$section) { if (!$last) return $out; $section=$last; $name=$section['Section_Name']; } if ($section['Hidden_URL']) { $url = $section['Hidden_URL']; } else { $url = $url.$last['Keyword'].'.html'; } } if (!$c && count($as_section_data) !=2 ) { $block="first"; if ($template['main_name_field']) $name=$current_site[$template['main_name_field']]; } elseif ($i == -$cr) $block="last"; else $block="middle"; if (!$template[$block]) $block='middle'; $out .= str_replace( array( "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL", "%COUNTER" ), array(strtolower($name), strtoupper($name), $name, $url, $c),$template[$block]); if ($i > -$cr && $template['divider']) $out.=$template['divider']; $c++; } $out .= $template['postfix']; return $out; } function as_insert_menu_selector($ancestor,$id='',$class='', $name='',$where=''){ global $current_section,$as_admin; if ($ancestor === false || $ancestor===''){ if (!$where) return; $levels=1; } if (isset($templates[$level])) $template=$templates[$level]; elseif (!$options['dont_apply_last_template']) $template = $templates[count($templates)-1]; else return ''; ($template['sortby']) ? $sort_by = $template['sortby'] : $sort_by = "Priority"; if ($template['icon_transform']) { list($width,$height,$crop)=explode(',',$template['icon_transform']); } $step=(int)$options['step']; $child_nodes= get_child_nodes($ancestor,$where, $sort_by,$options['checked_only']); $out = "'; return $out; } /** * Формирует многоуровневое меню * * пример * ".as_insert_global_menu($ancestor,1,array($menu_template[25]),array("mark_real_nested"=> 1, "dont_apply_last_template"=> 1, "branch" => 1))." * * построение многоуровневого меню * $ancestor = точка отсчёта * $level = кол-во уровней * $templates = масив шаблонов * $options = настройки * * значения настроек * $options['dont_apply_last_template'] = при нехватке шаблонов на уровень не использовать пследний в массиве * $options['branch'] = вскрывает только текущую открытую ветку * $options['add_root'] = добавляет первым пунктом саму точку отсчёта * $options['mark_real_nested'] = помечать реально пункты с подпунктами (проверка на наличие подпунктов) * $options['absolute_links'] = генерировать абсолютные ссылки * $options['step'] = меню в виде шагов. (регистрация). возможна будет удалена позднее * $options['checked_only'] = false|0|true - показать\скрыть скрытые разделы * * настройки шаблона * $template['icon_transform'] ~ array(100,200,4:3) * $template['divider_step'] = кол-во пунктов между разделителями * $template['divider_parts'] = кол-во частей, на которое должен разбить разделитель внутри текущего уровня. переопределяет divider_step = кол-во пунктов/divider_parts * $template['divider'] = блок с разделителем * $template['icon_field'] = имя поля из которого брать картинку * $template['icon_active'] = 1 у активного пункта меню к адресу картинки добавляется суффикс (см. сл.) * $template['icon_suffix'] = суффикс имени файла у активной иконки * $template['sortby'] = Поле для сортировки (напр по Section_Name (по алфавиту)) * * поля шаблона * prefix, suffix, active,inactive,active_link, nested_active, nested_inactive, nested_active_link * active - признак нахождения в ветке * link - признак нахождения ровно в этом пункте * nested - признак того, что есть подуровни * * переменные шаблона поля * * %COMMENT, %BASIC" %ID, %ICONBLOCK, %NAME_LOWER, %NAME_UPPER, %NAME, * %URL, %PARENT_SECTION, %KEYWORD, %SECTION, %COUNTER, %SUBMENU * %CLASSES * * %COMMENT берется из поля раздела $page['comment']; * %CLASSES автоматом генерирует стандартные классы. пример вывода : ' class="a n l %COMMENT"' или '' * a - признак текущего пункта или нахождения в текущей ветке * * переменные для $template['icon_field'] * %ICON, %ID, %COMMENT, %NAME_LOWER, %NAME_UPPER, %NAME, %URL, %COUNTER */ function as_insert_global_menu($ancestor, $levels, $templates,$options=array(),$level=0){ global $as_admin, $admin_url_prefix,$current_section,$CMS_UPLOAD_PATH; ($options['where'] && !$level ) ? $where=$options['where'] : $where=''; if ($ancestor == 901){ //DebugBreak(); } if ($ancestor === false || $ancestor===''){ if (!$where) return; $levels=1; } if (!$level && is_string($templates)){ $ntemplates = explode(',',$templates); $templates = array(); if (is_array($ntemplates) && $ntemplates){ foreach ($ntemplates as $ntemplate){ $templates[]=pop_template($ntemplate); } } } //if ($where) DebugBreak(); $level = (int)$level; //if (!$level && $level !== 0) return; if (is_array($templates) && isset($templates[$level])) { $template=$templates[$level]; } elseif (!$options['dont_apply_last_template']) $template = $templates[count($templates)-1]; else return ''; ($template['sortby']) ? $sort_by = $template['sortby'] : $sort_by = "Priority"; if ($template['icon_transform']) { list($width,$height,$crop)=explode(',',$template['icon_transform']); } $step=(int)$options['step']; if ($where) { $child_nodes= get_child_nodes($ancestor,$where, $sort_by,false); } else { $child_nodes= get_child_nodes($ancestor,$where, $sort_by,$options['checked_only']); } if ($options['add_root'] && !$level) { $arr = array($ancestor =>get_section_fields($ancestor)); foreach ($child_nodes as $key => $val) $arr[$key]=$val; $child_nodes=&$arr; } if (!count($child_nodes) && !$template['force_empty']) return ''; $count = count($child_nodes); $i=1; $buff = ''; ((int)$template['divider_step']) ? $divstep = (int)$template['divider_step'] : $divstep = 1; if ($divparts = (int)$template['divider_parts']){ $divstep=ceil(count($child_nodes)/$divparts); } if (substr_count($template['prefix'],"%NAME")) { $name = get_section_fields($ancestor,'Section_Name'); $prefix = str_replace( array( "%ID", "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL"), array( $ancestor, strtolower($name), strtoupper($name),$name,$link = get_section_link($ancestor,$options['absolute_links'])), $template['prefix']); } else $prefix = $template['prefix']; if (($options['select_first'] || $template['select_first']) && !$level && $child_nodes){ $first = current($child_nodes); $force_selected = (int)$first['Section_ID']; } foreach ($child_nodes as $page_id => $page) { $submenu = ''; $icon_block=""; $nested = false; $branch = in_branch($page_id); $classes=$page['comment']; // ПОДМЕНЮ if ($page_id != $ancestor) { if (!$options["branch"] && $levels && ($level < ($levels-1))) { $submenu=as_insert_global_menu($page_id,$levels,$templates,$options,$level+1); } elseif ($options["branch"] && $branch) { $submenu=as_insert_global_menu($page_id,$levels,$templates,$options,$level+1); } elseif ($options['mark_real_nested']) { if (have_children($page_id)) $nested=true; } else {} } if ($submenu) { $nested=true; $submenu = str_replace("%EMPTY", '', $submenu); } if ($as_admin) { $nav_url = $admin_url_prefix . "?site=" . $current_section["Site_ID"] ."§ion=" . $page["Section_ID"];} else { if ($ext_url = $page["ExternalURL"]) $nav_url = (strchr($ext_url, ":") || substr($ext_url, 0, 1) == "/") ? $ext_url : $page["Hidden_URL"] . $ext_url; else $nav_url = $page["Hidden_URL"]; } if ($options['absolute_links']){ if (!substr_count($nav_url,'http://')) { $nav_url = 'http://'.$_SERVER['HTTP_HOST'].$nav_url; } } $nav_name = $page["Section_Name"]; $t = $i % $divstep; ($template['divider'] && $i<$count && ( $i % $divstep === 0)) ? $divider = $template['divider'] : $divider = ''; ( $_SERVER['REQUEST_URI'] == $page['Hidden_URL']) ? $selected = true :$selected=false; if ($nested && isset($template['nested_active']) && isset($template['nested_inactive'])) { $nested_prefix = 'nested_'; $classes .=' n'; } else $nested_prefix = ''; $link = false; $section =''; if ($step){ $section =( ($i <= $step) ? "active".($i==$step ? "_link" : "" ) : "inactive" ); } else { if ($force_selected != $page_id) { $section = $nested_prefix.'inactive'; if (!isset($template[$section]) || (!$selected && $branch)) { $section = $nested_prefix.'active'; } if ($branch){ $classes .= ' a'; } if ($selected && $branch) { $section = $nested_prefix.'active_link'; $classes .= ' l'; } } else { $section = $nested_prefix.'active'; $classes .= ' a'; } } $sql = "SELECT COUNT(*) AS `num` FROM `Section` WHERE `Parent_Section_ID`={$page_id}"; $num = SQLSelectOne($sql); if($num['num']>10&&$template[$section.'_big']) $section .= '_big'; ($template['icon_field']) ? $icon_field = $template['icon_field'] : $icon_field='icon'; $icon_state = "icon"; if ( isset($template['icon_active']) && ($section == "active" || $section == "active_link" || $section == "nested_active" )) $icon_state="icon_active"; if ( ($page[$icon_field] || $template['noicon']) && $template[$icon_state]) { // image_transform($image,$sizex=0,$sizey=0, $aspect ="",$color=""){ if (!$page[$icon_field] && $template['noicon']){ $icon_url = $template['noicon']; } elseif ($template['icon_transform']) { $icon_url = image_transform($CMS_UPLOAD_PATH.$page[$icon_field],$width,$height, $crop); } elseif ($template['icon_suffix']) { $icon_url = $CMS_UPLOAD_PATH.add_postifix_to_filename(array($page[$icon_field],$template['icon_suffix'])); } else { $icon_url = $CMS_UPLOAD_PATH.$page[$icon_field]; } $icon_block = str_replace( array( "%SRC", "%ICON", "%ID", "%COMMENT", "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL", "%COUNTER"), array( $icon_url, $icon_url, $page_id, $page['comment'], strtolower($nav_name), strtoupper($nav_name),$nav_name,$nav_url,$i), $template[$icon_state] ); } else { $icon_block = ''; } $result = $template[$section].$divider; $result = str_replace( array( "%COMMENT", "%BASIC", "%ID", "%ICONBLOCK", "%NAME_LOWER", "%NAME_UPPER", "%NAME", "%URL", "%PARENT_SECTION", "%KEYWORD", "%SECTION","%COUNTER", "%SUBMENU", "%CLASSES" ), array( $page['comment'], $page['LinkName'], $page_id, $icon_block,strtolower($nav_name), strtoupper($nav_name), $nav_name, $nav_url, $ancestor, $page['LinkName'], $page["Section_ID"], $i, $submenu, ($classes && $classes != " " ? " class=\"".trim($classes)."\"" : "")), $result); //Замена меток типа %PAGE_*** $page_keys = array(); foreach($page as $key=>$val) $page_keys[] = "%PAGE_" . strtoupper($key); $result = str_replace($page_keys, array_values($page), $result); $buff .= $result; $i++; } ($template['suffix']) ? $suffix = $template['suffix'] : $suffix = ''; ($template['postfix']) ? $postfix = $template['postfix'] : $postfix = ''; $xbuff=$prefix.$buff.$suffix.$postfix; return $xbuff; } function render_multicol_menu($anc, $levels=2, $templates, $divide_by=3, $href=null, $level=0, $divide=true){ global $section_cache, $section_struct,$LinkID,$section_childs_count,$CMS_UPLOAD_PATH; $levels=(int)$levels; if ($anc===null || !$levels || !$templates) return; $anc=(int)$anc; $count=recursiveChildCollect($anc,$levels); if (!$count) return; if (!$divide_by) $divide_by = $count; $divide_cnt=ceil($count / $divide_by); if (!$divide_cnt) $divide_cnt=1; $i=0; $c=0; $step=0; if (!$templates[$level]) $template=$template[count($templates)-1]; else $template=$templates[$level]; $out=$template['prefix']; foreach ($section_struct[$anc] as $node) { $i++; $c++; $child_count = getSectionChildrenTotal($node,$levels-1); $i+=$child_count; if ($child_count && $levels) { $sub=render_multicol_menu($node,$levels-1,$templates,$divide_by,$href,$level+1,false); } else { $sub=''; } $page = &$section_cache[$node]; ($page['ExternalURL']) ? $link = $page['ExternalURL'] : $link=$page['Hidden_URL']; $name=$page['Section_Name']; $im = $CMS_UPLOAD_PATH.$page['Image']; ($link === $href) ? $section = 'active' : $section='inactive'; $item = str_replace(array("%BASIC", "%ID", "%NAME", "%URL", "%COUNTER", "%STEP", "%SUBMENU", "%IMAGE" ), array($page['LinkName'], $node, $name, $link, $c, $step, $sub, $im), $template[$section]); if ($template['divider'] && $divide && floor($i/$divide_cnt) > $step ) { $step = floor($i/$divide_cnt); $divider = $template['divider']; } else $divider = ''; $out .= $item.$divider; } $out .= $template['postfix']; return $out; } function as_insert_paginator($template, $onpage, $total, $base_href='',$offset=0,$getparams=array(),$pager='curPos'){ global $as_admin,$current_section,$current_site,$MODULE; //DebugBreak(); if (is_string($template)){ $template= pop_template($template); } $getfunc = 'get_pager_default_template'; if (!$template && function_exists($getfunc)) { $template = $getfunc();} if (!$template || !((int)$onpage)) return ''; if (!$template['template']) $template['template'] = '%PREFIX %PREV %LIST %NEXT %POSTFIX'; if (!$offset && $getparams[$pager]) { $offset=(int)$getparams[$pager]; } unset($getparams[$pager]); $onpage=(int)$onpage; $total=(int)$total; $current=ceil($offset/$onpage); if ( !$onpage || $onpage >= $total ) return ''; $params_list=array(); unset($getparams['site']); unset($getparams['section']); unset($getparams['noframe']); $dont_show_offset = $getparams['dont_show_offset']; foreach ($getparams as $key => $param) { if ($key==$pager) continue; if(is_array($param)) { foreach($param as $k => $p) { $params_list[] = $key.'[]='.urlencode($p); } } else $params_list[] = $key.'='.urlencode($param); } $params_list = implode('&',$params_list); if ($as_admin && !$MODULE){ $base_href = "/cms/?site=".$current_site['Site_ID']."§ion=".$current_section['Section_ID']; } if(substr_count($base_href,"?")) $base_link = $base_href."&".($params_list ? $params_list."&" : ""); else $base_link = $base_href."?".($params_list ? $params_list."&" : ""); $prev = $current-1; $next=$current+1; $max_pages=ceil($total/$onpage); if(substr_count($base_href,"?")) $first_link = $base_href.($params_list ? "&".$params_list : ""); else $first_link = $base_href.($params_list ? "?".$params_list : ""); if ($prev == -1) { $prev_str = str_replace("%URL", "javascript:void(0);", $template['no_prev']); } else { $t = $dont_show_offset ? $onpage : floor($onpage*$prev); ($t ? $t_link = $base_link.$pager."=".$t :$t_link = $first_link ); $prev_str = str_replace("%URL", $t_link, $template['prev']); } if ($next == $max_pages) { $next_str = str_replace("%URL", "javascript:void(0);", $template['no_next']); } else { $next_str = str_replace("%URL", $base_link.$pager."=".($dont_show_offset ? $next : floor($onpage*$next)), $template['next']); } $list = ''; if ($template['near_space']) { $near=(int)$template['near_space']; $near_from = $current - $near; $near_to = $current + $near; } for ($i=0; $i<$max_pages; $i++) { $page = $i+1; if ($near && !($page == 1 || $page== $max_pages)) { if ($page < ($near_from+1)) { if ($page == 2) { $list .= $template['space']; continue; } else continue; } if ($page > $near_to) { if ($page == $near_to+1) { $list .= $template['space']; continue; } else continue; } } if ($i) { $link =$base_link.$pager."=".($dont_show_offset ? $i : floor($i*$onpage)); } else { $link = $first_link; } ($current==$i) ? $sect = 'current': $sect='item' ; $list .= str_replace(array('%URL','%NUMBER'),array($link,$page),$template[$sect]); } $out = str_replace( array('%PREFIX','%PREV','%LIST','%NEXT','%POSTFIX'), array($template['prefix'], $prev_str, $list, $next_str,$template['postfix']), $template['template'] ); return $out; //'%PREFIX %PREV %LIST %NEXT %POSTFIX'; } ########################### Objects ############################### /** * загружает список обьектов * * $params['page_id'] = обьекты этой страницы * $params['table'] = id обьекта * $params['where'] = ''; * $params['order'] = ''; * $params['limit'] = ''; * $params['checked'] = 0|1|all default 1 * * $joins = array('b'=>array( * 'table'=>197, * 'joincond' => " ON b.`number` = a.`number` ", * 'where' => " AND b.`Section_ID` = '".$info."' ", * 'select' => " b.`outnumber` " * * )); */ function getObjects($params,$datakeys=false,$joins=null){ static $cache; $page_id = (int)$params['page_id']; if (!$page_id) $page_id=(int)$params['Section_ID']; $id = (int)$params['id']; $table = (int)$params['table']; $where = $params['where']; $order = $params['order']; $limit = $params['limit']; $checked = $params['checked']; $params['datakeys']=$datakeys; if ($joins) { $params['joins']=$joins; } $cache_key=md5(serialize($params)); if ($cache[$cache_key] == null) { if ($checked === null) $checked_str=" AND a.Checked=1"; elseif ($checked == "all") $checked_str = ""; else $checked_str = " AND a.Checked='".$checked."' "; if ($obj_id = (int)$params['object_id']) { $sql_obj_sect = " AND a.`Section_Object_ID` = ".$obj_id; } else $sql_obj_sect=''; if ($page_id) $where .= " AND a.`Section_ID` = '".$page_id."' "; if ($id) { $where .= " AND a.`Data_ID` = '".$id."' "; } if ($joins){ $join_select=array(); $joins_str = array(); $jwhere = array(); foreach ($joins as $jprefix => $join){ if (LOWER_CASE_TABLES) $join['table']=strtolower($join['table']); $jwhere[] = remove_first_symbols($join['where']); $joins_str[] = " LEFT JOIN `".(LOWER_CASE_TABLES ? "data" : "Data")."".$join['table']."` AS ".$jprefix." ON ".remove_first_symbols($join['joincond'],'ON'); $join_select[] = remove_first_symbols($join['select']); } $join_select = implode(',',$join_select).', '; $joins_str = implode(' ',$joins_str).' '; $jwhere = implode(' ',$jwhere).' '; } if (!$table) { if (!$page_id) return false; $query = "SELECT `Section_Object_ID`,`Object_ID` FROM `Section_Object` AS a WHERE `Section_ID` = '".$page_id."' ".$sql_obj_sect." LIMIT 1;"; if ($r=SQLSelect($query)) { $obj_id = $r[0]['Section_Object_ID']; $table = $r[0]['Object_ID']; } else return false; } $fields = getObjectStruct($table); if ($order) $order = " ORDER BY ".$order; if ($limit) $limit = " LIMIT ".$limit; if($where) { if ( (strtolower(substr(trim($where),0,4)) != "and ")) $where = " AND ".$where; } $query = "SELECT ".($params['return_total'] ? 'SQL_CALC_FOUND_ROWS ' : '').$join_select.getObjectStructFieldsQuery($table,'a.')." FROM `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` AS a ".$joins_str." WHERE 1 ".$checked_str.$jwhere.$where.$order.$limit; if ($datakeys){ if (is_string($datakeys) && $datakeys !== '1'){ $cache[$cache_key] = SQLSelect($query,$datakeys); } else { $cache[$cache_key] = SQLSelect($query,'Data_ID'); } } else { $cache[$cache_key] = SQLSelect($query); } } if ($params['return_total']){ if (is_array($cache[$cache_key])) { $r = SQLExec('SELECT FOUND_ROWS();'); $total = (int)array_pop(mysql_fetch_row($r)); array_push($cache[$cache_key],$total); } } return $cache[$cache_key]; } /** * Загружает обьект по id */ function getObject($ids,$table=-1,$fieldname=false){ global $MAIN_PRODUCT_TABLE; static $cache; if ($table==-1) $table=$MAIN_PRODUCT_TABLE; $tmp = array(); $to_upload=array(); $single=false; if (!is_array($ids)) { $ids = array($ids); $single=true;} if (!is_array($cache)) {$cache = array();} if (!is_array($cache[$table])) {$cache[$table] = array();} foreach ($ids as $id) { if ($cache[$table][$id] !== null) { if ($fieldname) { $tmp[$id] = $cache[$table][$id][$fieldname]; } else { $tmp[$id] = $cache[$table][$id]; } } else { $to_upload[]=(int)$id; } } if ($to_upload){ $objs = getObjects(array('table'=> $table, 'where' => " `Data_ID` IN (".implode(',',$to_upload).") ",'checked' => 'all'),true); foreach ($objs as $id =>$val){ $cache[$table][$id]=$val; if ($fieldname) { $tmp[$id]=$val[$fieldname]; } else { $tmp[$id]=$val; } } } if ($single) return current($tmp); return $tmp; } /** * Получает инфо о полях обьекта (Object_Field) * * @param int $object_id * @param int $system_id * @return array */ function getObjectStruct($object_id=0,$system_id=0) { global $LinkID,$object_fields_struct,$cached_requests; if (!is_array($object_fields_struct)) $cache=array(); $key = $object_id.'_'.$system_id; if ($object_fields_struct[$key] !== null) { $cached_requests++; return $object_fields_struct[$key]; } $fields=array(); $q = "SELECT `Object_Field_Name`, `TypeOfData_ID`, `Format`, `Description`, `NotNull`, `System_ID` FROM `".(LOWER_CASE_TABLES ? "object_field" : "Object_Field")."` WHERE 1 AND `System_ID` = '".$system_id."' ".($object_id ? " AND `Object_ID` = '".$object_id."'" : "")." ORDER BY `Priority` ASC ;"; $r = mysql_query($q,$LinkID); if ( mysql_num_rows($r)) { while ($tmp = mysql_fetch_assoc($r)) $fields[$tmp['Object_Field_Name']]=$tmp; $object_fields_struct[$key]=$fields; } else $object_fields_struct[$key]=array(); return $object_fields_struct[$key]; } function getObjectStructFieldsQuery($object_id,$prefix='',$system_id=0,$process_fields=1){ static $cache; global $CMS_UPLOAD_PATH; $key=$object_id.'_'.$prefix.'_'.$process_fields; if ($cache[$key]) return $cache[$key]; $struct =getObjectStruct($object_id,$system_id); if (!$struct) return; $arr=array($prefix.'`Data_ID`', $prefix.'`Section_ID`', $prefix.'`Section_Object_ID`', $prefix.'`User_ID`', $prefix.'`Checked`', $prefix.'`Keyword`', $prefix.'`Created`',$prefix.'`IP`'); foreach ($struct as $field){ //if ($field['Object_Field_Name'] == 'Foto1') DebugBreak(); if ($process_fields){ switch ($field['TypeOfData_ID']){ case '6': $fname = $prefix.'`'.$field['Object_Field_Name'].'`'; $name='`'.$field['Object_Field_Name'].'`'; $arr[]="IF(".$fname."<>'',CONCAT('".$CMS_UPLOAD_PATH."',SUBSTRING_INDEX(".$fname.",':',1)),'') AS ".$name; break; default : $arr[]=$prefix.'`'.$field['Object_Field_Name'].'`'; break; } } else { $arr[]=$prefix.'`'.$field['Object_Field_Name'].'`'; } } return $cache[$key]=implode(',',$arr); } /** * обработка полей обьекта в соответствие с форматом полей * * @param array $object - массив параметров для переработки * @param int $object_id - id обработчика * @param int $clean == 0 обьединяет полученый и орги * == 1 выдаёт полученный * == 2 заполняет поля обязательные для заполнения * @param int $system_id = 2 - разделы, 3- пользователи */ function set_fields_to_property_set(&$object, $object_id, $clean=1,$system_id=0,&$fields=null) { global $CMS_UPLOAD_PATH,$FILEMANAGER_UPLOAD_PATH; if (!$fields) { $fields = getObjectStruct($object_id,$system_id);} if (!$fields) {return $false;} $field_names = array_keys($fields); $final_object = array(); foreach ($field_names as $fname) { $type = $fields[$fname]['TypeOfData_ID']; if ($object[$fname] === null) { unset($object[$fname]); continue;} if ($type == 8){ $final_object[$fname]=$object[$fname]; $final_object[$fname.'_timestamp']=$timestamp = strtotime($object[$fname]); $tm = explode('-',date('Y-m-d-H-i',$timestamp)); $final_object[$fname.'_year']=$tm[0]; $final_object[$fname.'_month']=$tm[1]; $final_object[$fname.'_day']=$tm[2]; $final_object[$fname.'_hours']=$tm[3]; $final_object[$fname.'_minutes']=$tm[4]; } if ($type != "6" && $type !=9 && $type !=10) {$final_object[$fname]=$object[$fname]; continue;} if (!$object[$fname] || $clean == 2) continue; $t=substr($fields[$fname]['Format'],0,13); if ($t != "type=image/*|") {$final_object[$fname]=$object[$fname]; continue;} $t2=substr($fields[$fname]['Format'],13); $types_info=array(); $types=explode("|", $t2); foreach ($types as $type) { $arr=array(); $vals = explode(";", $type); foreach ($vals as $val) { $t=explode("=",$val); $arr[$t[0]]=$t[1]; } if ($arr['postfix']) { $types_info[$arr['postfix']]=$arr; } } $postfixes=array_keys($types_info); $image_props=explode(":",$object[$fname]); $final_object[$fname]=$CMS_UPLOAD_PATH.$image_props[0]; //add_postifix_to_filename foreach ($postfixes as $postfix) { $final_object[$fname.$postfix]="/data/".add_postifix_to_filename(array($image_props[0],$postfix)); } } if ($clean == 1) return $final_object; elseif ($clean ==0) return array_merge($object, $final_object); elseif ($clean==2) { foreach ($field_names as $fname){ if ($fields[$fname]['NotNull'] && !$final_object[$fname]) { if ($fields[$fname]['DefaultState']) { $final_object[$fname]=$fields[$fname]['DefaultState']; continue; } $f = &$fields[$fname]; switch ($f['TypeOfData_ID']){ case '2' : case '4' : case '5' : case '7' : $final_object[$fname]=0; break; case '1' : case '3' : case '6' : $final_object[$fname]=''; break; case '8' : $final_object[$fname]=date('Y-m-d H:i:s'); } } } return $final_object; } } /** * обработка полей секций в соответствие форматов полей */ function mass_update_section_fields(&$sections){ static $cache; if (!is_array($cache)) $cache=array(); $sections_keys = array_keys($sections); foreach ($sections_keys as $key) { $sections[$key]=set_fields_to_property_set($sections[$key],0,false); } } function getObjectInfo($table, $fields=''){ static $cache,$fullcache; if (!$table) return; if (!is_array($cache)) $cache=array(); if (!is_array($fullcache)) $fullcache=array(); $table=(int)$table; if (!is_array($cache[$table])) $cache[$table]=array(); if ($fields == '') { if (!$fullcache[$table]) { $query = "SELECT * FROM `".(LOWER_CASE_TABLES ? "object" : "Object")."` WHERE `Object_ID` = '".$table."'"; $fullcache[$table]=SQLSelectOne($query); } return $fullcache[$table]; } else { if (is_string($fields)) { if (substr_count($fields,'`')){ $query = "SELECT ".$fields." FROM `".(LOWER_CASE_TABLES ? "object" : "Object")."` WHERE `Object_ID` = '".$table."'"; $t=SQLSelectOne($query); return $cache[$table]=array_merge($cache[$table],$t); } $fields=explode(',',$fields); } $select = array(); $tmp = array(); for ($i=0;$i 0, 'Section_Object_ID' => 0, 'Checked' => 1, 'LastSystem_Updated' => $date, 'Created' => $date, 'LastUser_ID' => $user_id, 'User_ID' =>$user_id , 'IP' => $_SERVER['REMOTE_ADDR'], 'Keyword'=>'' ); foreach ($struct as $name =>$field) { if ($field['DefaultState']) { $dataInit[$name]=$field['DefaultState']; continue; } $type=(int)$field['TypeOfData_ID']; switch ($type) { case 1: case 3 : case 6: $dataInit[$name]=''; break; case 8: $dataInit[$name]='0000-00-00 00:00:00'; break; default : $dataInit[$name]=0; } } return $cache[$table]=$dataInit; } function GetSiteByID($id) { static $sites; if (!$sites) $sites=array(); if (!$sites[$id]) $sites[$id] = as_query_array("SELECT * FROM `".(LOWER_CASE_TABLES ? "site" : "Site")."` WHERE `Site_ID` = '".(int)$id."'"); return $sites[$id]; } function get_section_objects($section,$limit=1,$to_propertyset=true, $order = "Priority") { global $LinkID; if (!($section = (int)$section)) return false; ($order) ? $order = ' ORDER BY `'.$order.'` ' : $order = ''; $q = "SELECT `Section_Object_ID`, `Object_ID` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID` = '".$section."' ".$order." LIMIT 1;"; $r = mysql_query($q,$LinkID); if ( mysql_num_rows($r)) { $t = mysql_fetch_row($r); } else return array('failed' => true, 'errcode' => 2); $section_obj_id = $t[0]; $obj_id = $t[1]; $objs=getObjects(array('page_id' => $section,'object_id'=> $section_obj_id, 'limit'=> $limit)); if ($to_propertyset){ for ($i=0; $i < count($objs); $i++) { $objs[$i]= set_fields_to_property_set($objs[$i], $obj_id); } } return $objs; } function has_section_object($section,$table){ static $cache; if ($cache[$section][$table] !== null) return $cache[$section][$table]; if (!is_array($cache[$section])) $cache[$section]=array(); $sobjs = get_section_sobjects($section); if (!$sobjs) return $cache[$section][$table]=false; foreach ($sobjs as $sobj => $stable){ if ($stable == $table) { return $cache[$section][$table]=$sobj; } } return false; } function get_section_sobjects($section=null,$limit=null){ global $current_section; static $cache; if ($section===null) {$section=$current_section['Section_ID'];} if (!$limit) { if ($cache[$section] !== null) return $cache[$section]; $query = "SELECT `Object_ID`, `Section_Object_ID` as `sid` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID` = '".$section."' ;"; return $cache[$section] = SQLSelect($query,'sid','Object_ID'); } else { $query = "SELECT `Object_ID`, `Section_Object_ID` as `sid` FROM `".(LOWER_CASE_TABLES ? "section_object" : "Section_Object")."` WHERE `Section_ID` = '".$section."' ".($limit ? " LIMIT ".(int)$limit." " : "").";"; return SQLSelect($query,'Object_ID','sid'); } } /* * получает ближайшие записи по имени поля и значению. * * table = ID обьекта * sort_field = Имя поля для сортировки * value = значение поля. * vector > 0 -> выбор записей с большим value * limit - кол-во записей. если true то вернёт найденную запись напрямую(не через массив записей) * params - доп. параметры * section_id,sobj_id -фильтр по разделу\объекту раздела * where - совё условие * record_id - если value не указан, найдёт его значение по ID записи * rsection - переадресация секции(при генерации ссылки) */ function get_sibling_records($table,$record_id, $sort_field = 'Priority',$value=null,$vector = 1,$limit=true,$params=array('section_id'=>0,'sobj_id'=>0,'where'=>'')){ //DebugBreak(); if (!$table || $record_id === null) return false; $section_id = (int)$params['section_id']; $sobj_id = (int)$params['sobj_id']; $record_id = (int)$record_id; $where = (string)$params['where']; $rsection = (int)$params['rsection']; if ( $value!== null){ $rec = getObject($record_id,$table); if (!isset($rec[$sort_field])) return false; $value = $rec[$sort_field]; } $query = "SELECT ".getObjectStructFieldsQuery($table)." FROM `".(LOWER_CASE_TABLES ? "data" : "Data")."".$table."` "; $query .= "WHERE 1"; if ($value) $query .= " AND `".$sort_field."` ".($vector > 0 ? ">" : "<")." '".$value."'"; if ($section_id) $query .= " AND `Section_ID` = '".$section_id."'"; if ($sobj_id) $query .= " AND `Section_Object_ID` = '".$sobj_id."'"; if ($where) $query .= " AND ".$where." "; if ($record_id) $query .= " AND `Data_ID` <> '".$record_id."' "; $query .= " ORDER BY `".$sort_field."` ".($vector > 0 ? "ASC" : "DESC")." "; $query .= " LIMIT ".($limit=== true ? "1" : (int)$limit).""; if ($tmp = SQLSelect($query)){ for ($i=0; $i $v){ if ($key !== 0){ $arr[$v[$keyname]]=$v[$valname]; } else { $arr[$k]=$v[$valname]; } } return $arr; } function get_section_sibling($section=null){ global $current_section,$section_struct; static $cache; if (!$section) $section=(int)$current_section['Section_ID']; if ($cache[$section] !== null) return $cache[$section]; $anc=get_ancestor($section); if ($section_struct[$anc] === null) { recursiveChildCollect($anc,1,false); } $struct = &$section_struct[$anc]; if (!$struct || !is_array($struct) || count($struct)==1){ return $cache[$section]=false; } $pos=-1; for ($i=0; $i= 0; $ii--) { if ($str[$ii] == ' ' && $f == 0) { $f = 1; $cnt++; } elseif ($str[$ii] != ' ') { $f = 0; } if ($cnt == $cntwords) break; } $ii++; return ($ii > 1 ? substr($str, 0, $ii) . "" . substr($str, $ii)."" : $str); } /* обрезает строку по длине, не разрывая последнее слово, добавляя троеточие */ function real_strlen($string){ //DebugBreak(); if (is_string($string)) return strlen(iconv("utf-8","windows-1251",$string)); else return false; } /** * обрезает строку по длине, не разрывая последнее слово, добавляя троеточие */ function cut_words_ru($string, $length, $params = array(), $convert=true) { if (!$params['no_strip_tags']) $string=strip_tags($string); ($params['delim']) ? $delim = $params['delin'] : $delim =' '; ($params['postfix']) ? $postfix = $params['postfix'] : $postfix='...'; if ($convert) $str=iconv("UTF-8", "WINDOWS-1251", $string); else $str=$string; if ($params['clean']) $str=str_replace(array("\n", " "), array(""," "),$str); if (strlen($str)<=$length) $tmp = $string; else { $tmp = substr($str,0, $length); $pos = strpos($str, $delim, $length); if ($pos !== false) $tmp .= substr($str,$length,$pos-$length).$postfix; else return stripslashes($string); if ($convert) $tmp = iconv("WINDOWS-1251", "UTF-8", $tmp); } if ($lwlink=$params['last_word_link']) { if (!($lwcount = (int)$params['last_word_count'])) $lwcount = 1; $tmp = makelastwordlink($tmp,$lwlink,$lwcount); } return stripslashes($tmp); } function process_comment_message($message,$symbols=600){ $str=iconv('utf-8','windows-1251',$message); $len=strlen($str); if ($len > $symbols) return '

'.cut_words_ru($message,$symbols).'

'; $ps = explode("\n",$message); return '

'.implode('

',$ps).'

'; } function remove_first_symbols($str, $symbols=','){ if (substr(trim($str),0,strlen($symbols)) == $symbols) { $str = ' '.substr(trim($str),strlen($symbols)).' '; } return $str; } /** * ограничивает длину строки */ function limit_string_ru($string,$maxlen=64){ return iconv('windows-1251','utf-8',substr(iconv('utf-8','windows-1251',$string),0,$maxlen)); } /** * add_postifix_to_filename($params) * * $params[0] = имя файла, * $params[1] = добавляемый постфикс */ function add_postifix_to_filename($params){ $pos = strrpos($params[0],'.'); if (!strlen($params[1]) || $pos === false) return $fname; return substr($params[0],0,$pos).$params[1].substr($params[0], $pos); } /** * Форматирует дату с русскими названиями месяцев и дней * * these are the russian additional format characters * q: full textual representation of the day of the week * Q: full textual representation of the day of the week (first character is uppercase), * v: short textual representation of the day of the week, * V: short textual representation of the day of the week (first character is uppercase), * H: full textual representation of a month(singlified) * X: full textual representation of a month * x: full textual representation of a month (first character is uppercase), * f: short textual representation of a month * F: short textual representation of a month (first character is uppercase), * * Param[0]= format * Val=timestamp * echo 'Сегодня '.date_ru('Q, d x Y'); */ function date_ru($timestamp,$formatum) { if (!$timestamp) $timestamp=time(); if (!is_numeric($timestamp)) { if (!($timestamp = strtotime($timestamp))) return; } $q['q'] = array(-1 => 'w', 'воскресенье','понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота'); $q['Q'] = array(-1 => 'w', 'Воскресенье','Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'); $q['v'] = array(-1 => 'w', 'вс','пн', 'вт', 'ср', 'чт', 'пт', 'сб'); $q['V'] = array(-1 => 'w', 'Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'); $q['H'] = array(-1 => 'n', '', 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'); $q['x'] = array(-1 => 'n', '', 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'); $q['X'] = array(-1 => 'n', '', 'Января', 'Февраля', 'Март', 'Апреля', 'Май', 'Июня', 'Июля', 'Август', 'Сентября', 'Октября', 'Ноября', 'Декабря'); $q['f'] = array(-1 => 'n', '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'); $q['F'] = array(-1 => 'n', '', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'); $temp = ''; $i = 0; while ( (strpos($formatum, 'q', $i) !== FALSE) || (strpos($formatum, 'Q', $i) !== FALSE) || (strpos($formatum, 'v', $i) !== FALSE) || (strpos($formatum, 'V', $i) !== FALSE) || (strpos($formatum, 'x', $i) !== FALSE) || (strpos($formatum, 'X', $i) !== FALSE) || (strpos($formatum, 'f', $i) !== FALSE) || (strpos($formatum, 'F', $i) !== FALSE)||(strpos($formatum, 'H', $i) !== FALSE)) { $ch['q']=strpos($formatum, 'q', $i); $ch['Q']=strpos($formatum, 'Q', $i); $ch['v']=strpos($formatum, 'v', $i); $ch['V']=strpos($formatum, 'V', $i); $ch['H']=strpos($formatum, 'H', $i); $ch['x']=strpos($formatum, 'x', $i); $ch['X']=strpos($formatum, 'X', $i); $ch['f']=strpos($formatum, 'f', $i); $ch['F']=strpos($formatum, 'F', $i); foreach ($ch as $k=>$v) if ($v === FALSE) unset($ch[$k]); $a = min($ch); $temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)]; $i = $a+1; } $temp .= date(substr($formatum, $i), $timestamp); return $temp; } /** * возвращает оформленный размер файла */ function get_human_filesize($size,$lang=false) { global $current_site; if (!$lang) $lang = $current_site["Site_Lang"]; switch ($lang) { case 'RU' : $iec = array('б', 'Кб', 'Мб', 'Гб', 'Тб', 'Пб', 'Эб'); break; default : $iec = array('b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', '"Eb'); break; } $i = 0; while (($size/1024)>1) { $size = $size/1024; $i++; } $iec = $iec[$i]; $size=number_format($size,1,'.',' '); $echo = $size.' '.$iec; return $echo; } function xss_clean($data){ // Fix &entity\n; $data = str_replace(array('&','<','>'), array('&amp;','&lt;','&gt;'), $data); $data = preg_replace('/(&#*\w+)[\x00-\x20]+;/u', '$1;', $data); $data = preg_replace('/(&#x*[0-9A-F]+);*/iu', '$1;', $data); $data = html_entity_decode($data, ENT_COMPAT, 'UTF-8'); // Remove any attribute starting with "on" or xmlns $data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data); // Remove javascript: and vbscript: protocols $data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data); $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data); $data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data); // Only works in IE: $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data); $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data); $data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data); // Remove namespaced elements (we do not need them) $data = preg_replace('#]*+>#i', '', $data); do { // Remove really unwanted tags $old_data = $data; $data = preg_replace('#]*+>#i', '', $data); } while ($old_data !== $data); // we are done... return $data; } ############################## SEO, services ############################ /** * вращает ключ к гуглокартам к текущему домену */ function get_map_key(){ global $current_site; static $cache; if ($cache !== null) return $cache; $maps=explode(' ',trim($current_site['map_keys'])); $domains=array(); foreach ($maps as $map){ $pos = strpos($map,'='); if (!is_int($pos) || $pos < 3) continue; $str1 = trim(substr($map,0,$pos)); $str2 = trim(substr($map,$pos+1)); $domains[$str1]=$str2; $domains['www.'.$str1]=$str2; } return $cache=$domains[$_SERVER['HTTP_HOST']]; } function get_default_map_points(){ global $current_site,$current_section; static $coords; if ($coords !== null) return $coords; $field=&$current_site['map_coords']; $rcoords=explode("\n",$field); if (!is_array($rcoords) || !count($rcoords)) { return $coords=false; } $coords = array(); foreach ($rcoords as $coord){ $coord = explode(':',$coord); $t = explode(',',$coord[1]); if (!$coord[0] || !$t[0] || !$t[1]) continue; $coords[]=array('Title'=> trim($coord[0]),'x'=>(double)trim($t[0]),'y'=>(double)trim($t[1])); } return $cache=$coords; } function seoConfirm() { global $SEO,$current_record,$current_section,$current_site,$SEO_section_fields,$as_section_level; if (!$SEO_section_fields) { $SEO_section_fields = array( 'keywords' => 'SEOKeyword', 'description' => 'SEODescr', 'title' => 'SEOTitle', 'text' => 'SEOtext', 'productTitle' => 'header', 'productTitle2' => 'Title' ); } //if (preg_match('/\.html$/', $_SERVER['HTTP_HOST'], $matches)) { if ($current_record) { $SEO['description']=$current_record[$SEO_section_fields['description']]; $SEO['keywords']=$current_record[$SEO_section_fields['title']]; $SEO['text']=$current_record[$SEO_section_fields['text']]; $SEO['title']=$current_record[$SEO_section_fields['title']]; if (!$SEO['title']) $SEO['title']=$current_record[$SEO_section_fields['productTitle']]; if (!$SEO['title']) $SEO['title']=$current_record[$SEO_section_fields['productTitle2']]; } if (!$SEO['description']) { if ($current_section[$SEO_section_fields['description']]) $SEO['description'] = $current_section[$SEO_section_fields['description']]; else $SEO['description'] = $current_site[$SEO_section_fields['description']]; } if (!$SEO['keywords']) { if ($current_section[$SEO_section_fields['keywords']]) $SEO['keywords'] = $current_section[$SEO_section_fields['keywords']]; else $SEO['keywords'] = $current_site[$SEO_section_fields['keywords']]; } if (!$SEO['title']) { if ($current_section[$SEO_section_fields['title']]) { if ($as_section_level && $current_site['TitlePrefix']){ $SEO['title'] = $current_site['TitlePrefix'].' '.($current_section[$SEO_section_fields['title']] ? $current_section[$SEO_section_fields['title']] : $current_section['Section_Name']); } else { $SEO['title'] = $current_section[$SEO_section_fields['title']]; } } else { if ($current_site['TitlePrefix']) { $SEO['title'] = $current_site['TitlePrefix'].' '.$current_section['Section_Name']; } else { $SEO['title'] = $current_section['Section_Name']; } } } if (!$SEO['text']) { if ($current_section[$SEO_section_fields['text']]) $SEO['text'] = $current_section[$SEO_section_fields['text']]; else $SEO['text'] = $current_site[$SEO_section_fields['text']]; } $SEO['description']=trim(htmlspecialchars(strip_tags($SEO['description']))); $SEO['keywords']=trim(htmlspecialchars(strip_tags($SEO['keywords']))); $SEO['title']=trim(htmlspecialchars(strip_tags($SEO['title']))); $SEO['text']=trim(htmlspecialchars(strip_tags($SEO['text']))); } function getSEOdescription(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['description']; } function getSEOkeywords(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['keywords']; } function getSEOtitle(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['title']; } function getSEOtext(){ global $SEO; if (!is_array($SEO)) seoConfirm(); return $SEO['text']; } function get_h1(){ global $current_record,$current_section; if ($current_section['no_header']) return; if ($table = $current_record['_class_ID']) { $info = getObjectInfo($table,'TitleTemplate'); if ($template = $info['TitleTemplate']){ foreach ($current_record as $var => $val){ eval("\$as_$var = \$val;"); } eval("\$title = $template;"); if ($title) return $title; } if ($current_record['Title']) return $current_record['Title']; if ($current_record['header']) return $current_record['header']; if ($current_record['Name']) return $current_record['Name']; } if ($current_section['Caption']) return $current_section['Caption']; return $current_section['Section_Name']; } ################################# ARRAYS ####################################### function array_sort(&$array,$field='Name'){ if (!$field) return; $karr=array(); foreach ($array as $key => $value) { $karr[$key] = $value[$field]; } asort($karr); $arr=array(); foreach ($karr as $key => $value) { $arr[$key]=$array[$key]; } return $arr; } function array_escape(&$obj){ $keys = array_keys($obj); foreach ($keys as $key) { if (is_array($obj[$key])) escape($obj[$key]); else $obj[$key]=mysql_real_escape_string($obj[$key]); } } function array_clean(&$arr){ $keys = array_keys($arr); foreach ($keys as $key) { if ($arr[$key] === null || $arr[$key] === '') unset($arr[$key]); } } function array_to_options($array,$selected=false,$insert_empty = false){ if (!is_array($array)) return false; $found = false; foreach ($array as $key => $val){ $tmp .= "".$tmp; } return $tmp; } function get_user_by_login($login,$only_id=0){ static $cache; global $CMS_AUTHORIZE_FIELD; $only_id=(int)$only_id; if ($cache[$only_id][$login] !== null) return $cache[$only_id][$login]; if (!is_array($cache[$only_id])) $cache[$only_id]=array(); $t = SQLSelect("SELECT ".($only_id ? "`User_ID`" : "*")." FROM `".(LOWER_CASE_TABLES ? "user" : "User")."` WHERE `".$CMS_AUTHORIZE_FIELD."` = '".$login."';",'User_ID'); if (!$t) { return $cache[$only_id][$login]=false; } if ($only_id){ return $cache[$only_id][$login]=(int)$t[1]['User_ID']; } else { return $cache[$only_id][$login]=(int)$t[1]; } } ################################### CACHE ########################### function save_to_cache($module,$key,$data,$append="<#&%>"){ global $CMS_CACHE_PATH,$DOCUMENT_ROOT; if (!is_array($data) && !is_string($data)) return false; if (!$key || !$module) return false; if (is_array($data)) { $data=serialize($data); } $dir = str_replace("//","/",$DOCUMENT_ROOT.$CMS_CACHE_PATH.$module.'/'); if (!is_dir($dir)){ if (!($added = @mkdir($dir,0777))){ return false;}; } if ($append === true) $append = ''; $fname = $dir.$key.'.tmp'; if (!file_exists($fname)){ $file = @fopen($fname,'w'); } else { if (!is_writable($fname)){ @chmod($fname,0777); } if (is_string($append)){ $file = @fopen($fname,'a'); $data = $append.$data; } else { $file = @fopen($fname,'w'); } } if (!$file) return false; if (@fwrite($file,$data) === false) return false; fclose($file); return true; } function load_from_cache($module,$key,$delim = "<#&%>",$unserialize=true ){ global $CMS_CACHE_PATH,$DOCUMENT_ROOT; $dir = str_replace("//","/",$DOCUMENT_ROOT.$CMS_CACHE_PATH.$module.'/'); $fname = $dir.$key.'.tmp'; if (!file_exists($fname)) return false; $data = implode('',file($fname)); if (!$data) return false; if (!$delim) return $data; $xdata = explode($delim,$data); if (is_array($xdata)){ if (!$unserialize) return $xdata; $data = array(); foreach ($xdata as $x){ $data[]=unserialize($x); } return $data; } else { return $data; } } function get_list_info($listname){ static $cache; if (!$listname) return false; if ($cache[$listname] === null) { $cache[$listname]=SQLSelect("SELECT * FROM `list_".$listname."` ORDER BY `".$listname."_ID`"); } return $cache[$listname]; } function get_list_info_by_value_name($listname){ static $cache; if (!$listname) return false; if ($cache[$listname] === null) { $cache[$listname]=SQLSelect("SELECT * FROM `list_".$listname."` ORDER BY `".$listname."_ID`",$listname."_Value",$listname."_Name"); } return $cache[$listname]; } ?>uevent_seqnum000066600000000005150472621110007363 0ustar001847 uevent_helper000066600000000001150472621110007326 0ustar00 profiling000066600000000002150472621110006453 0ustar000 kexec_loaded000066600000000002150472621110007071 0ustar000 kexec_crash_loaded000066600000000002150472621110010251 0ustar000 kexec_crash_size000066600000000002150472621110007773 0ustar000 vmcoreinfo000066600000000015150472621110006635 0ustar001f01880 1000 notes000066600000000574150472621110005630 0ustar00XenlinuxXen2.6Xenxen-3.0XenXenÁXen* Xen!writable_page_tables|pae_pgdir_above_4gb XenyesXengeneric XenXen XenXenGNUƿ)έ_3uLkbmm/hugepages/hugepages-2048kB/nr_hugepages000066600000000002150472621110014332 0ustar000 mm/hugepages/hugepages-2048kB/nr_overcommit_hugepages000066600000000002150472621110016576 0ustar000 mm/hugepages/hugepages-2048kB/free_hugepages000066600000000002150472621110014634 0ustar000 mm/hugepages/hugepages-2048kB/resv_hugepages000066600000000002150472621110014672 0ustar000 mm/hugepages/hugepages-2048kB/surplus_hugepages000066600000000002150472621110015430 0ustar000 mm/hugepages/hugepages-2048kB/nr_hugepages_mempolicy000066600000000002150472621110016410 0ustar000 mm/ksm/sleep_millisecs000066600000000003150472621110011042 0ustar0020 mm/ksm/pages_to_scan000066600000000004150472621110010474 0ustar00100 mm/ksm/run000066600000000002150472621110006471 0ustar000 mm/ksm/pages_shared000066600000000002150472621110010312 0ustar000 mm/ksm/pages_sharing000066600000000002150472621110010477 0ustar000 mm/ksm/pages_unshared000066600000000002150472621110010655 0ustar000 mm/ksm/pages_volatile000066600000000002150472621110010663 0ustar000 mm/ksm/full_scans000066600000000002150472621110010016 0ustar000 mm/ksm/merge_across_nodes000066600000000002150472621110011526 0ustar001 mm/ksm/max_page_sharing000066600000000004150472621110011163 0ustar00256 mm/ksm/stable_node_chains000066600000000002150472621110011471 0ustar000 mm/ksm/stable_node_dups000066600000000002150472621110011177 0ustar000 mm/ksm/stable_node_chains_prune_millisecs000066600000000005150472621110014751 0ustar002000 mm/redhat_transparent_hugepage/enabled000066600000000027150472621110014231 0ustar00[always] madvise never mm/redhat_transparent_hugepage/defrag000066600000000027150472621110014067 0ustar00[always] madvise never mm/redhat_transparent_hugepage/khugepaged/defrag000066600000000011150472621110016164 0ustar00[yes] no mm/redhat_transparent_hugepage/khugepaged/max_ptes_none000066600000000004150472621110017575 0ustar00511 mm/redhat_transparent_hugepage/khugepaged/pages_to_scan000066600000000005150472621110017544 0ustar004096 mm/redhat_transparent_hugepage/khugepaged/pages_collapsed000066600000000010150472621110020060 0ustar001229599 mm/redhat_transparent_hugepage/khugepaged/full_scans000066600000000004150472621110017067 0ustar00105 mm/redhat_transparent_hugepage/khugepaged/scan_sleep_millisecs000066600000000006150472621110021120 0ustar0010000 mm/redhat_transparent_hugepage/khugepaged/alloc_sleep_millisecs000066600000000006150472621110021266 0ustar0060000 mm/redhat_transparent_hugepage000066600000000000150472621110012626 0ustar00