<?php
/*
=====================================================
 Модуль создал: REZER (http://rezer.net)
=====================================================
 Файл: functions.php
=====================================================
 Данный код защищен авторскими правами
=====================================================
 Назначение: Необходимые функции
=====================================================
*/

if( !defined( "DATALIFEENGINE" ) ) die( "Hacking attempt!" );

require_once( ENGINE_DIR."/inc/board/init.php" );

//----------------------------------------------------
//  Открытие ячейки
//----------------------------------------------------

$OpenTableStyle = false;
function opentable( $style = false ) {
	global $OpenTableStyle;
  
	if( $style === true || $OpenTableStyle === false )
		{
			$OpenTableStyle = true;
			echo "<link rel=\"stylesheet\" href=\"engine/inc/board/style/board.css\" />";
		}
   
echo <<<HTML

<table width="100%" border="0">
    <tr>
        <td width="4"><img src="engine/skins/images/tl_lo.gif" width="4" height="4" border="0"></td>
        <td background="engine/skins/images/tl_oo.gif"><img src="engine/skins/images/tl_oo.gif" width="1" height="4" border="0"></td>
        <td width="6"><img src="engine/skins/images/tl_ro.gif" width="6" height="4" border="0"></td>
    </tr>
    <tr>
        <td background="engine/skins/images/tl_lb.gif"><img src="engine/skins/images/tl_lb.gif" width="4" height="1" border="0"></td>
        <td style="padding:5px;" bgcolor="#FFFFFF">
HTML;

}

//----------------------------------------------------
//  Закрытие ячейки
//----------------------------------------------------

function closetable() {
	
echo <<<HTML
    </td>
        <td background="engine/skins/images/tl_rb.gif"><img src="engine/skins/images/tl_rb.gif" width="6" height="1" border="0"></td>
    </tr>
    <tr>
        <td><img src="engine/skins/images/tl_lu.gif" width="4" height="6" border="0"></td>
        <td background="engine/skins/images/tl_ub.gif"><img src="engine/skins/images/tl_ub.gif" width="1" height="6" border="0"></td>
        <td><img src="engine/skins/images/tl_ru.gif" width="6" height="6" border="0"></td>
    </tr>
</table>

HTML;
}

//----------------------------------------------------
//  Название ячейки
//----------------------------------------------------

function tableheader($value, $right = "", $unterline="unterline") {

if( $right )
	{
		$right = "<td style=\"padding: 5px;\" class=\"navigation\" align=\"right\" bgcolor=\"#efefef\" height=\"29\">{$right}</td>";	
	}
	
echo <<<HTML
<table width="100%">
    <tr>
        <td bgcolor="#EFEFEF" height="29" style="padding-left:10px;" align="left"><div class="navigation">{$value}</div></td>
		$right
    </tr>
</table>
<div class="$unterline"></div>

HTML;
}

//----------------------------------------------------
//  Название ячейки
//----------------------------------------------------

function tableheaderList($value,$right="") {
	
if( $right )
	{
		$right = "<td style=\"padding: 5px;\" class=\"navigation\" align=\"right\" height=\"29\">{$right}</td>";	
	}
	
echo <<<HTML
<table width="100%">
    <tr onmouseover="this.bgColor = '#D5FECD'" onmouseout="this.bgColor = '#EFEFEF'" bgcolor="#EFEFEF" height="29">
        <td style="padding-left:10px;">{$value}</td>
		$right
    </tr>
</table>

HTML;
}

//----------------------------------------------------
// Полоса разделения
//----------------------------------------------------

function unterline() {
echo <<<HTML
<div class="unterline"></div>
HTML;
}

//----------------------------------------------------
//	Маленькая полоска
//----------------------------------------------------

function showStart(){

return <<<HTML

<table width="100%" border="0">
	<tr>
		<td background="engine/skins/images/mline.gif" height="1" colspan="2"></td>
	</tr>
</table>

HTML;
   
}

//----------------------------------------------------
//  Отображение заголовка и описание настройки
//----------------------------------------------------

function showRow($title="", $description="", $field=""){

echo <<<HTML

<table width="100%" border="0">
	<tr onmouseover ="this.bgColor = '#FAF4C7'" onmouseout  ="this.bgColor = '#FFFFFF'" $id>
		<td style="padding:4px" class="option"><b>$title</b><br /><span class="small">$description</span></td>
		<td width="250" align="left">$field</td>
	</tr>
	<tr>
		<td background="engine/skins/images/mline.gif" height="1" colspan="2"></td>
	</tr>
</table>

HTML;
   
}

function showRowWatermark( $title = "", $description = "", $name = "save_con[water_mark_position]", $value = 9 ){
	
	$max = 9;
	$OnLine = 3;
	$List = "";
	$value = ( $value < 1 || $value > $max ) ? $max : intval( $value );
	
	for( $i = 1; $i <= $max; $i++ )
		{			
			$checked = $i == $value ? "checked=\"checked\"" : "";
			$List .= "<td align=\"center\"><input type=\"radio\" name=\"{$name}\" value=\"{$i}\" {$checked} /></td>";
			if( $i % $OnLine == 0 && $i != $max ) $List .= "</tr><tr height=\"26px\">";	
		}

echo <<<HTML

<table width="100%" border="0">
	<tr onmouseover ="this.bgColor = '#FAF4C7'" onmouseout  ="this.bgColor = '#FFFFFF'" $id>
		<td style="padding:4px" class="option"><b>$title</b><br /><span class="small">$description</span></td>
		<td width="250" align="left" style="padding: 7px 0px 7px 0px;">
			<div style="border: 1px solid #ccc; width: 95px; padding: 2px 1px 4px 3px;">
				<table width="90px" border="0" cellpadding="0" cellspacing="0">
					<tr height="26px">
						{$List}
					</tr>
				</table>
			</div>
		</td>
	</tr>
	<tr>
		<td background="engine/skins/images/mline.gif" height="1" colspan="2"></td>
	</tr>
</table>

HTML;
   
}

//----------------------------------------------------
//  Функция выбора опций (Включить/Выключить)
//----------------------------------------------------

function SelectList( $list, $select = "" ){
	
	if( is_array( $list ) )
		{
			foreach( $list as $name => $value )
				{
					if( is_array( $select ) )
						{
							if( in_array( $name, $select ) ) $selected = "selected"; else $selected = "";
						}
							else
						{
							if( $name == $select ) $selected = "selected"; else $selected = "";	
						}
					$return .= "<option value=\"{$name}\" {$selected}>{$value}</option>\n";	
				}
				
			return $return;
		}
			else
		{
			return false;	
		}
		
	return false;
}

function makeDropDown( $options, $name, $selected, $disabled = false, $multiple = false ){ 

	if( $disabled ) $disabled = "disabled";
	if( $multiple ) $multiple = "multiple=\"multiple\"";
	$output = "<select name=\"$name\" {$disabled} {$multiple}>\r\n";
	foreach( $options as $value => $description )
		{
			$output .= "<option value=\"$value\"";
			if( is_array( $selected ) )
				{
					if( in_array( $value, $selected ) ) $output .= " selected=\"selected\" ";
				}
					else
				{
					if( trim( $selected ) == trim( $value ) ) $output .= " selected=\"selected\" ";
				} 
					  
			$output .= ">$description</option>\n";
		}
		
	$output .= "</select>";
	return $output;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Выбор групп пользователей
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function BoardGroups( $selected, $visitor = "yes", $all = false ) {
	global $user_group;
	
	foreach( $user_group as $groups ) 
		{    
			$group_id = $groups['id'];    
			if( $group_id == 5 && $visitor != "yes" )
				$visitor_ok = false;
			else
				$visitor_ok = true;
				
			if( $visitor_ok )
				{
					$result .= "<option value=\"{$groups['id']}\"";
					if( in_array( $groups['id'], $selected ) ) 
						{
							$result .= " selected";
						} 
					
					$result .= ">".$groups['group_name']."</option>";
				}
		}
	
	if( $all )
		{
			$select = in_array( "all", $selected ) || count( $selected ) < 1 || !$selected[0] ? "selected=\"selected\"" : "";
			$result = "<option value=\"all\" {$select}> - Все - </option>{$result}";
		}
	
	return $result;
}


//----------------------------------------------------
// Спсиок групп
//----------------------------------------------------

function SelectGroup( $select = array(), $not = array() ){
	global $user_group;
	
	if( !is_array( $select ) ) $select = array();
	if( !is_array( $not ) ) $not = array();
	foreach( $user_group as $row )
		{
			$id = $row['id'];
			$title = stripslashes( $row['group_name'] );
					
			if( !in_array( $id, $not ) )
				{
					if( in_array( $id ,$select ) )
						$selected = "selected=\"selected\"";
					else
						$selected = "";
							
					$return .= "<option value=\"{$id}\" {$selected}>{$title}</option>";
				}
		}
			
	return $return;
}

//----------------------------------------------------
// Конец страницы и копирайты
//----------------------------------------------------

function footer(){

echo  <<<HTML
<div style="padding-top:5px; padding-bottom:10px;">
<table width="100%">
    <tr>
        <td bgcolor="#EFEFEF" height="40" align="center" style="padding-right:10px;"><div class="navigation">Powered By <a href="http://rezer.net/" target="_blank">REZER</a> for <a href="http://dle-news.ru/" target="_blank" />DataLife Engine</a></div></td>
    </tr>
</table></div>		
		</td>
		<td width="4" background="engine/skins/images/tb_rt.gif"><img src="engine/skins/images/tb_rt.gif" width="4" height="1" border="0" /></td>
    </tr>
	<tr>
        <td height="16" background="engine/skins/images/tb_lb.gif"></td>
		<td background="engine/skins/images/tb_tb.gif"></td>
		<td background="engine/skins/images/tb_rb.gif"></td>
    </tr>
</table>
</body>
</html>
HTML;

}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  Функция для сортировки
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function board_sort( $url, $n, $ajax="" ){

   // Делаем переменные
	$img_url = "engine/inc/board/style/images/arrow";	
	$on_up = "onmouseover=\"this.src='{$img_url}_up-v.gif'\" onmouseout=\"this.src='{$img_url}_up.gif'\"";
	$on_down = "onmouseover=\"this.src='{$img_url}_down-v.gif'\" onmouseout=\"this.src='{$img_url}_down.gif'\"";
	$link = $url."&sort={$n}";
	
	if( $ajax )
		{
			$ajax_k = "onclick=\"UpdateList( 'main', '{$ajax}&sort={$n}_k' ); return false;\"";
			$ajax_d = "onclick=\"UpdateList( 'main', '{$ajax}&sort={$n}_d' ); return false;\"";
		}
	
   // Сортировка по порядку	
	if($_REQUEST['sort'] == $n."_k")
	    $sort_k = "<img src=\"{$img_url}_up-v.gif\" border=\"0\">";
	   else
	    $sort_k = "<a href=\"{$link}_k\" title=\"{$title_k}\"><img src=\"{$img_url}_up.gif\" border=\"0\" {$ajax_k} {$on_up}></a>";
	
   // Сортировка в обратном порядке  
	if($_REQUEST['sort'] == $n."_d")
	    $sort_d = "<img src=\"{$img_url}_down-v.gif\" border=\"0\">";
	   else
	    $sort_d = "<a href=\"{$link}_d\" title=\"{$title_d}\"><img src=\"{$img_url}_down.gif\" border=\"0\" {$ajax_d} {$on_down}></a>";
	  	  
  return $sort_k.$sort_d;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//  3 функции для навигации
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

function navigation_page($url_off,$url_on, $page, $ajax=""){
  global $config;
    if( $ajax ) 
		{
			$ajax = str_replace( "{page}", $page, $ajax );
			$onclick = "onclick=\"{$ajax} return false;\"";
		}
	$page_url = "<a href=\"".$url_off.$page."\" {$onclick}>".$page."</a> ";
 return $page_url;
}

function navigation_while($i,$page_get,$usl,$url_off,$url_on, $ajax=""){
 
while($i < $usl)
    { 
	  if($i == $page_get)
	    {
		  $navigation .= "<span>".$i."</span> ";
		  $i++;
	  }else{
	  	  $navigation .= navigation_page($url_off,$url_on,$i, $ajax);
	      $i++;
		}
	} 

 return $navigation;
}

function Board_Navigation($url_off,$url_on, $count_page, $page_get, $ajax=""){
  global $config;

// Чтобы не было недоразумений
if($page_get < 0){$page_get = 1;}
if($page_get > $count_page){$page_get = $count_page;}

  $first_pagination = $page_get - 4; // Сколько страниц выводится слева от активной
  $last_pagination = $page_get + 5; // Сколько страниц выводится справа от активной
  $prev_page = $page_get - 1; // Предыдущая страница
  $next_page = $page_get + 1; // Следующая страница
  $page_min = 8; // Минимально значение для начала пагинации
  $page_max = $count_page - 8; // Максимально значение для начала пагинации
  $divider = "... ";  // На что заменяем пробелы
  
  // Работа с ЧПУ 
  $gl = ""; $ss = $url_off; 
  
  if( $ajax )
	{
		$link_prev = str_replace( "{page}", ($page_get - 1), $ajax );
		$link_next = str_replace( "{page}", ($page_get + 1), $ajax );
		$prev_onclick = "onclick=\"{$link_prev} return false;\"";
		$next_onclick = "onclick=\"{$link_next} return false;\"";
	}
  
  // Предыдущая страница
  if($page_get > 1)
	  $prev_page = "<a href=\"".$ss.($page_get - 1)."".$gl."\" {$prev_onclick}>Назад</a> ";
	else
	  $prev_page = "<span>Назад</span> ";
	  
  // Слудеющая страница
  if($page_get < $count_page)
	  $next_page = "<a href=\"".$ss.($page_get + 1)."".$gl."\" {$next_onclick}>Далее</a> ";
	else
	  $next_page = "<span>Далее</span> ";
	  
  // Если страниц меньше чем 10
  if($count_page < 10)
    {
      $i=1;
      $navigation = navigation_while($i,$page_get,$count_page + 1,$url_off,$url_on, $ajax);
	  $navigation = $prev_page.$navigation.$next_page;

  }else{	  
	  
  // По середине  
  if(($page_get >= $page_min - 2) and ($page_get <= $page_max + 2))
    {
      $navigation = navigation_while($first_pagination,$page_get,$last_pagination,$url_off,$url_on, $ajax);
      $navigation = $prev_page.navigation_page($url_off,$url_on,"1", $ajax).$divider.$navigation.$divider.navigation_page($url_off,$url_on,$count_page, $ajax).$next_page;
	
  // Если страница не больше 8 - ой
  }elseif($page_get < $page_min)
    {  
      $i=1;
      $navigation = navigation_while($i,$page_get,$page_min + 1,$url_off,$url_on, $ajax);
      $navigation = $prev_page.$navigation.$divider.navigation_page($url_off,$url_on,$count_page, $ajax).$next_page;

  // Если страница больше пред 8 - ми последней
  }elseif($page_get > $page_max)
    {
	  $i=$page_max;
      $navigation = navigation_while($i,$page_get, $count_page + 1,$url_off,$url_on, $ajax);
      $navigation = $prev_page.navigation_page($url_off,$url_on,"1", $ajax).$divider.$navigation.$next_page;
    } 
  }	
 return $navigation;
}

function SetReferer( $url ){
	@session_register( "AdminboardReferer" );
	$_SESSION['AdminboardReferer'] = $url;
}

//----------------------------------------------------
//  Вид для мини окошка
//----------------------------------------------------

function miniloader( $title = "DataLife Engine - Панель управлениия" ){

echo <<<HTML

<html>
	<head>
		<meta content="text/html; charset={$config['charset']}" http-equiv="content-type" />
		<title>{$title}</title>
		<script type="text/javascript" src="engine/skins/default.js"></script>
		<link rel="stylesheet" href="engine/inc/board/style/mini.css" />
	</head>
<body>

HTML;
}

function minifooter(){
	echo "</body>\n</html>";
}

//----------------------------------------------------
//  Вывод ошибки для мини окошка
//----------------------------------------------------

function minimsg( $title, $text, $back = "", $close = true ){
	
	if( $close )
		{
			$close = "<a href=\"#\" onclick=\"window.close();\">Закрыть окно</a>";	
		}
			else
		{
			$close = "";	
		}
		
	if( $back )
		{
			$back = "<a href=\"{$back}\">Вернуться назад</a>";
			if( $close ) $close = " | {$close}";
		}
			else
		{
			$back = "";	
		}
	
	miniloader( $title );
	opentable();
	tableheader( $title );
										
	echo "<br /><div style=\"padding: 5px;\" align=\"center\">{$text}<br /><br />{$back} {$close}</div><br />";
										
	closetable();
	minifooter();
	die();
}

//----------------------------------------------------
//  Функция вывода js для открытия вкладок
//----------------------------------------------------

function ChangeOption( $options ){

	$options = explode(",", $options);
    foreach($options as $opt)
    	{
        	$Slist .= "document.getElementById('{$opt}').style.display = \"none\";";
        	$list .= "if(selectedOption == '{$opt}') {document.getElementById('$opt').style.display = \"\"; if( \"{$opt}\" != \"options\" && \"{$opt}\" != \"about\" ) UpdateUrl = \"{$opt}\"; }";
        }

return <<<HTML

<script language="JavaScript" type="text/javascript">

function ChangeOption(selectedOption) {
		
    {$Slist}
	{$list}	
}
    
</script>

HTML;

}

if( !function_exists( "CharsetConvert" ) )
	{
		function CharsetConvert( $text, $to = "auto" ){
			global $config;
			
			$text = stripslashes( $text );
			$charset = mb_detect_encoding( $text, "utf-8,windows-1251" );
			if( $to == "auto" ) $to = $config['charset'];
			if( $charset != $to && $to != "" ) $text = iconv( $charset, $to."//IGNORE", $text );
			return urldecode( $text );
		}
	}

?>