

<?php
if (!defined("MODULE_FILE")) {
	Header("Location: ../../index.php");
	exit;
}

define( 'RNB_CONF', 'modules/informer/rnb_conf/' );




	head();
	if ( $_REQUEST['action'] == 'save' )
	{
		//------------- PREPARING ------------
		# Open in new window;
		if (isset($save_con['open_new_wind']))
			$save_con['open_new_wind'] = "1";
		else
			$save_con['open_new_wind'] = "0";

		# Show with pictures only;
		if (isset($save_con['with_pic_only']))
			$save_con['with_pic_only'] = "1";
		else
			$save_con['with_pic_only'] = "0";
	
		# first or random pic in post:
		if (isset($save_con['frst_rnd_pic']))
			$save_con['frst_rnd_pic'] = "1";
		else
			$save_con['frst_rnd_pic'] = "0";
	
		# Show shadow;
		if (isset($save_con['shadow']))
			$save_con['shadow'] = "1";
		else
			$save_con['shadow'] = "0";
	
		# if selected show all and other cats, save show_all ONLY! :
		$show_all = false;
		if ( !$save_con['cats'] )
			$show_all = true;
		else
			foreach ($save_con['cats'] as $val)
				if ($val == "all")
				{
					$show_all = true;
					break;
				}
		if ($show_all)
			$save_con['cats'] = "all";
		else
			$save_con['cats'] = implode(',', $save_con['cats']);
		
		//------------------------------------
	
		if ( $_REQUEST['rnb_id'] == '-1' )
		{ // ADD:
			$save_con['name'] = myTotranslit($save_con['name'], '_');
			//echo '<pre>'; print_r( $save_con ); echo '</pre>';
			
			if ( file_exists( RNB_CONF.$save_con['name'].'.php' ) )
			{ echo "<center><br>Такой информер уже существует! <br /><br /><a href=index.php?name=informer>Назад</a><br><br></center>"; }
			else
			{
				if (save_config( RNB_CONF.'/'.$save_con['name'].'.php' ) )
				{ echo "<center><br>Настройки системы были успешно сохранены <br /><br /><a href=index.php?name=informer>Назад</a><br><br></center>"; }
				else
				{ echo "<center><br>Настройки системы HE сохранены <br /><br /><a href=index.php?name=informer>Назад</a><br><br></center>"; }
			}
		}
		else
		{ // EDIT:
			$id = htmlspecialchars( $_POST['rnb_id'] ); 
			if ( file_exists(RNB_CONF.$id.'.php') )
				require_once( RNB_CONF.$id.'.php' );
			$save_con['name'] = $id;
			if ( @file_exists( RNB_CONF.$id.'.php' ) )
			{
				if (save_config( RNB_CONF.$id.'.php' ) )
				{ echo "<center><br>Настройки системы были успешно сохранены <br /><br /><a href=index.php?name=informer>Назад</a><br><br></center>"; }
				else
				{ echo "<center><br>Настройки системы HE сохранены <br /><br /><a href=index.php?name=informer>Назад</a><br><br></center>"; }
			}

			# delete all thumbnails, if width or height has been changed:
			if 	(
					( $conf['w'] != $save_con['w'] ) ||
					( $conf['h'] != $save_con['h'] ) 
				)
			{
				clear_directory( ROOT_DIR.'/uploads/rnb/'.$id );
			}
	
		}
	}
	elseif ( $_REQUEST['action'] == 'show' )
	{ // SHOW:
		$id = htmlspecialchars( $_REQUEST['rnb_id'] ); 
		//echo $id;
		if ( file_exists(RNB_CONF.$id.'.php') )
			require_once( RNB_CONF.$id.'.php' );
		if ( $id == '-1' )
		{
			reneblock_details('show',$id);
		}
		else
		{
			//echo '<pre>'; print_r( $conf ); echo '<pre>';
			extract($conf, EXTR_SKIP);
			reneblock_details(
				'show',
					$id,
					$name,
					$y,
					$x,
					$conf['w'],
					$h,
					$margin,
					$open_new_wind,
					$with_pic_only,
					$title,
					$text,
					$title_color,
					$text_color,
					$frst_rnd_pic,
					$shadow,
					$type,
					$select_short,
					$select_order,
					$days,
					$exdir,
					$cats,
					$cache
			);
		}
	}
	elseif ( $_REQUEST['action'] == 'del' )
	{ // DELETE
		$id = htmlspecialchars( $_REQUEST['rnb_id'] );
		if ( file_exists(RNB_CONF.$id.'.php') )
		{
			$result = unlink( RNB_CONF.$id.'.php' );
			if ( $result ) echo "<center><br>Информер успешно удален <br /><br /><a href=index.php?name=informer>Назад</a><br><br></center>";
		}
	}
	else
	{
		reneblock_informers();
	}
	foot();


function reneblock_informers()
{
	global $admin_file;
include("config/config_global.php");


	if ( $homeurl [strlen($homeurl )-1] == '/' )
		$homeurl  = substr( $homeurl , 0, strlen($homeurl )-1 );

echo "<h2>Информеры</h2>";

//define( 'RNB_CONF', 'modules/informer/rnb_conf/' );
if ( !file_exists( RNB_CONF ) )
	{
		if ( !(@mkdir(RNB_CONF, 0777)) ) { return '<br> RNB: Unable to mkdir: "'.RNB_CONF.'"'; }
		if ( !(@chmod(RNB_CONF, 0777)) ) { return '<br> RNB: Unable to chmod: "'.RNB_CONF.'"'; }
	}


if(is_admin()){

echo"<form action=\"{$PHP_SELF}\" method=\"post\">";
echo "<table width=\"100%\" border=\"1\" cellpadding=\"2\" cellspacing=\"1\"><tr><th>№</th><th>Название</th><th>Код информера</th><th>Функции</th></tr>";
echo "<tr class=\"bgcolor1\">";


	
	if ( $flist = get_filelist( RNB_CONF ) )
	{
		//echo '<pre>'; print_r( $flist ); echo '<pre>';
		for ( $i=0; $i<count($flist['name']); ++$i )
		{
			$id = explode( '.', $flist['name'][$i] );
echo "<td align=\"center\">".($i+1)."</td>

<td align=\"center\"><b>".$id[0]."</b></td>
<td align=\"center\">".htmlspecialchars("<div id=\"".$id[0]."\"><a href=\"".$homeurl."\">Загрузка</a></div>")."<br>".htmlspecialchars("<script language=\"javascript\" type=\"text/javascript\" src=\"".$homeurl ."/rnb.php?id=".$id[0]."\"></script>")."</td>

<td align=\"center\"><a href=\"index.php?name=informer&action=show&rnb_id=".$id[0]."\"  title=\"Редактировать ".$id[0]."\"><img src=\"modules/informer/edit.png\"</a> <a href=\"index.php?name=informer&action=del&rnb_id=".$id[0]."\" title=\"Удалить ".$id[0]."\"><img src=\"modules/informer/delete.png\"</a></td></tr>";
		}
	} 


echo "
</table>
<br />
<input type=\"hidden\" name=\"rnb_id\" value=\"-1\">
<input type=\"hidden\" name=\"action\" value=\"show\">
<input type=\"submit\" class=\"buttons\" value=\"Добавить\">
</form>";}


if ( $flist = get_filelist( RNB_CONF ) )
	{

		for ( $i=0; $i<count($flist['name']); ++$i )
		{
			$id = explode( '.', $flist['name'][$i] );


echo"<center><b>Информер ".$id[0]."</b></center><br><br>
<center>".htmlspecialchars("<div id=\"".$id[0]."\"><a href=\"".$homeurl."\">Загрузка</a></div>")."<br>".htmlspecialchars("<script language=\"javascript\" type=\"text/javascript\" src=\"".$homeurl ."/rnb.php?id=".$id[0]."\"></script>")."</center><br><br>";

echo"<center><div id=\"".$id[0]."\"><a href=\"".$homeurl ."\">Загрузка</a></div>
<script language=\"javascript\" type=\"text/javascript\" src=\"".$homeurl ."/rnb.php?id=".$id[0]."\"></script></div></center><br><br>";
		}
	
}


}

#FFFFFFFF
function reneblock_details(
	$act = 'show', //action
	$id = '-1',
	$name = 'Информер',
	$y = '1',
	$x = '2',
	$w = '100',
	$h = '100',
	$margin = '4',
	$open_new_wind = '1',
	$with_pic_only = '1',
	$title = '10',
	$text = '40',
	$title_color = 'DD0000',
	$text_color = '000000',
	$frst_rnd_pic = '1',
	$shadow = '1',
	$type = '1',
	$select_short = '1',
	$select_order = '4',
	$days = '0',
	$exdir = '/data/emoticons',
	$cats = 'all',
	$cache = '300'
	)
{

include("config/config_global.php");

if($id != "-1"){

echo"<center><h1>Редактировать информер: $id</h1></center>";
           

echo"<center><div id=\"$id\"><a href=\"".$homeurl."\">Загрузка</a></div>
<script language=\"javascript\" type=\"text/javascript\" src=\"".$homeurl."/rnb.php?id=$id\"></script></div></center>";}

echo "<form action=\"\" method=\"post\">
<b> << <a href=index.php?name=informer> Вернуться </a></b>
<div class=\"left\">Название:</div><div class=\"center\"><input type=\"text\" name=\"save_con[name]\" class=\"edit\" value=\"{$name}\" size=50 maxlength=100></div>
<div class=\"left\">Количество строк:</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[y]\" class=\"edit\" value=\"{$y}\" size=5 maxlength=3></div>
<div class=\"left\">Количество столбцов:</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[x]\" class=\"edit\" value=\"{$x}\" size=5 maxlength=5></div>
<div class=\"left\">Ширина картинки (px):</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[w]\" class=\"edit\" value=\"{$w}\" size=5 maxlength=5></div>
<div class=\"left\">Высота картинки (px):</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[h]\" class=\"edit\" value=\"{$h}\" size=5 maxlength=5></div>
<div class=\"left\">Расстояние между новостями (px):</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[margin]\" class=\"edit\" value=\"{$margin}\" size=5 maxlength=3></div>
<div class=\"left\">Открывать новость в новом окне:</div><div class=\"center\">";


		if ($open_new_wind == "0")
			echo "<input type=\"checkbox\" name=\"save_con[open_new_wind]\" class=\"edit\">";
		else
			echo "<input type=\"checkbox\" name=\"save_con[open_new_wind]\" class=\"edit\" checked=\"checked\">";

echo "</div><div class=\"left\">Выводить новость ТОЛЬКО с картинкой:</div><div class=\"center\">";

if ($with_pic_only == "0")
echo "<input type=\"checkbox\" name=\"save_con[with_pic_only]\" class=\"edit\">";
else
echo "<input type=\"checkbox\" name=\"save_con[with_pic_only]\" class=\"edit\" checked=\"checked\">";

echo "</div><div class=\"left\">Отображать тень под картинкой:</div><div class=\"center\">";

		if ($shadow == "0")
			echo "<input type=\"checkbox\" name=\"save_con[shadow]\" class=\"edit\">";
		else
			echo "<input type=\"checkbox\" name=\"save_con[shadow]\" class=\"edit\" checked=\"checked\">";






echo "</div>
<div class=\"left\">Тип:</div><div class=\"center\"><input type=\"text\" name=\"save_con[type]\" class=\"edit\" value=\"{$type}\" size=5 maxlength=3>
&nbsp; (1 или 2)</div>";
    

echo "<div class=\"left\">Количество символов в заголовке:</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[title]\" class=\"edit\" value=\"{$title}\" size=5 maxlength=5>
&nbsp; (0 - не выводить)</div><div class=\"left\">Количество символов в тексте:</div><div class=\"center\">

<input type=\"text\" name=\"save_con[text]\" class=\"edit\" value=\"{$text}\" size=5 maxlength=5>
&nbsp; (0 - не выводить)
</div><div class=\"left\">Цвет заголовка:</div><div class=\"center\">";



echo "#<input type=\"text\" name=\"save_con[title_color]\" class=\"edit\" value=\"{$title_color}\" size=8 maxlength=6>&nbsp; (DD0000 - красный)</div>
<div class=\"left\">Цвет текста:</div><div class=\"center\">";

echo"#<input type=\"text\" name=\"save_con[text_color]\" class=\"edit\" value=\"{$text_color}\" size=8 maxlength=6>
&nbsp; (000000 - черный)</div>
<div class=\"left\">Отображать первую или случайную картинку в посте:</div><div class=\"center\">";

		if ($frst_rnd_pic == "0")
			echo "<input type=\"checkbox\" name=\"save_con[frst_rnd_pic]\" class=\"edit\">";
		else
			echo "<input type=\"checkbox\" name=\"save_con[frst_rnd_pic]\" class=\"edit\" checked=\"checked\">";

echo "</div><div class=\"left\">Выбор рисунков с короткой / полной новости:</div><div class=\"center\">";

		if ($select_short == "0")
		{ // полная:
			echo "<input type=\"radio\" name=\"save_con[select_short]\" value=\"1\" class=\"edit\"> С короткой";
			echo "&nbsp;&nbsp;";
			echo "<input type=\"radio\" name=\"save_con[select_short]\" value=\"0\" class=\"edit\" checked=1> С полной";
		}
		else
		{ // короткая:
			echo "<input type=\"radio\" name=\"save_con[select_short]\" value=\"1\" class=\"edit\" checked=1> С короткой";
			echo "&nbsp;&nbsp;";
			echo "<input type=\"radio\" name=\"save_con[select_short]\" value=\"0\" class=\"edit\"> С полной";
		}

echo "</div><div class=\"left\">Критерий отбора новостей:</div><div class=\"center\">";
		$is_chkd = "checked=1";
		if ($select_order == "1")
		{ // последние:
			$ord_1 = $is_chkd;
		}
		if ($select_order == "2")
		{ // По рейтингу:
			$ord_2 = $is_chkd;
		}
		if ($select_order == "3")
		{ // By views:
			$ord_3 = $is_chkd;
		}
		else
		{ // Random:
			$ord_4 = $is_chkd;
		}

echo "<input type=\"radio\" name=\"save_con[select_order]\" value=\"4\" class=\"edit\" ".$ord_4."> Случайно";
echo "&nbsp;&nbsp;";
echo "<input type=\"radio\" name=\"save_con[select_order]\" value=\"1\" class=\"edit\" ".$ord_1."> Последние";
echo "&nbsp;&nbsp;";
echo "<input type=\"radio\" name=\"save_con[select_order]\" value=\"2\" class=\"edit\" ".$ord_2."> По рейтингу";
echo "&nbsp;&nbsp;";
echo "<input type=\"radio\" name=\"save_con[select_order]\" value=\"3\" class=\"edit\" ".$ord_3."> По просмотрам";

echo "</div><div class=\"left\">За последнее количество дней:
</div><div class=\"center\"><input type=\"text\" name=\"save_con[days]\" class=\"edit\" value=\"{$days}\" size=5 maxlength=5>
&nbsp; (0 - за весь период)</div>
<input type=\"hidden\" name=\"save_con[exdir]\" class=\"edit\" value=\"{$exdir}\" size=33 maxlength=250>



<div class=\"left\">Для выбора нескольких категорий,зажмите клавишу CTRL</div>";








echo"<div class=\"center\">";


global $prefix, $db;

$result2 = $db->sql_query("SELECT catid, title FROM ".$prefix."_stories_cat ");


list($cat_cnt) = $db->sql_fetchrow($db->sql_query("SELECT Count(catid) FROM ".$prefix."_stories_cat"));

echo"<select name=\"save_con[cats][]\" multiple size=\"{$cat_cnt}\" style=\"width:40%\">";

if ($cats == "all")
				echo '<option value="all" selected> - Все - </option>';
			else
				echo '<option value="all"> - Все - </option>';

$show_cat_arr = explode(',', $cats);



while (list($cid, $cat) = $db->sql_fetchrow($result2)) {



$option = "<option value=\"$cid\">";


foreach ($show_cat_arr as $sel_cat)
{if ($cid == $sel_cat){$option = "<option value=\"$cid\" selected>";}}

		echo "$option - $cat -</option>";}


			


echo"</select>";

echo "</div><div class=\"left\">Время сохранения кеша (сек.):</div>
<div class=\"center\"><input type=\"text\" name=\"save_con[cache]\" class=\"edit\" value=\"{$cache}\" size=5 maxlength=5></div>



<div class=\"button\">		
<input type=\"hidden\" name=\"rnb_id\" value=\"{$id}\">
		<input type=\"hidden\" name=\"action\" value=\"save\">
		<input type=\"submit\" class=\"buttons\" value=\"Сохранить\">
		</div></form>";
}



#FFFFFFFF
function  clear_directory($dirname)  
{
// http://difour.org/blog/more/php_udalenenie_direktorii/
	if  (is_dir($dirname))
		$dir_handle  =  opendir($dirname);
	if  (!$dir_handle)
		return  false;
	while($file  =  readdir($dir_handle))  
	{
		if  ($file  !=  "."  &&  $file  !=  "..")  
		{
			if  (!is_dir($dirname."/".$file))
			unlink($dirname."/".$file);
		}
	}
	closedir($dir_handle);
	return  true;
}

#FFFFFFFF
function get_filelist($dir)
{
	if  (is_dir($dir))
		if ( !($dir_handle = opendir($dir)) ) { return false; }
	$i = 0; //counter
	while( $file = readdir($dir_handle) )
	{
		if ($file !=  '.' && $file != '..')  
		{
			if  ( is_file($dir.'/'.$file) )
			{
				//$file_arr['id'][$i] = $i;
				$file_arr['name'][$i] = $file;
				//$file_arr['size'][$i] = number_format((filesize($dir.'/'.$file)/1024), 1, '.', '');
				//$file_arr['date_add'][$i] = date ("d-F-Y H:i:s", filemtime($dir.'/'.$file));
				++$i;
			}
		}
	}
	closedir($dir_handle);
	return $file_arr;
}

#FFFFFFFF
function myTotranslit($var, $symb)
{
        $NpjLettersFrom = "абвгдезиклмнопрстуфцы";
        $NpjLettersTo   = "abvgdeziklmnoprstufcy";
        $NpjBiLetters = array( 
	      "й" => "jj", "ё" => "jo", "ж" => "zh", "х" => "kh", "ч" => "ch", 
	      "ш" => "sh", "щ" => "shh", "э" => "je", "ю" => "ju", "я" => "ja",
	      "ъ" => "", "ь" => "", "." => "",
                              );

        $NpjCaps  = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЬЪЫЭЮЯ";
        $NpjSmall = "абвгдеёжзийклмнопрстуфхцчшщьъыэюя";

      $var = str_replace(".php", "", $var);
	  $var = trim(strip_tags($var));
      $var = preg_replace( "/\s+/ms", $symb, $var );
      $var = strtr( $var, $NpjCaps, $NpjSmall );
      $var = strtr( $var, $NpjLettersFrom, $NpjLettersTo );
      $var = strtr( $var, $NpjBiLetters );

      $var = preg_replace("/[^a-z0-9\_\-.]+/mi", "", $var);
	  $var=preg_replace('#[\-]+#i', $symb, $var);
	  $var = strtolower ( $var );

      if (strlen($var) > 40) 
	  {
	  	$var = substr ($var, 0, 40);
		if (($temp_max = strrpos($var, '-')))  $var = substr ($var, 0, $temp_max);
	  }
  return $var;
}

#FFFFFFFF
function save_config( $file )
{
	global $save_con;



	$find[] 	= "'\r'";
	$replace[] 	= "";
	$find[] 	= "'\n'";
	$replace[] 	= "";
	$handler = fopen($file, "w");
	fwrite($handler, "<?php \n\n//Remote_NewsBlock Configurations\n\n\$conf = array (\n\n");
	foreach($save_con as $name => $value)
	{
		$value = trim(stripslashes($value));
		$value = htmlspecialchars($value, ENT_QUOTES);
		$value = preg_replace($find,$replace,$value);
	    fwrite($handler, "'{$name}' => \"{$value}\",\n\n");
	}
	fwrite($handler, ");\n\n?>");
	fclose($handler);
return true;
}





?>