<?php 
if (!defined('MODULE_FILE')) {
	Header("Location: ../../index.php");
	exit;
}
$module_name = basename(dirname(__FILE__));
get_lang($module_name);
require_once("config/config_pages.php");
require_once("function/comments.php");
$pagetitle = "$defis "._CONTENT_NAME."";

function categories($id="") {
	global $prefix, $db, $module_name, $multilingual, $currentlang, $tablenumhome, $homesubcat, $catdescrhome, $shownumeric;
	static $massiv, $massiv2;
	$id = (intval($id)) ? $id : 0;
	if ($id) {
		$where = "WHERE parentid = '$id'";
	} elseif ($id && $multilingual) {
		$where = "WHERE parentid = '$id' AND (planguage='$currentlang' OR planguage='')";
	} elseif ($multilingual) {
		$where = "WHERE planguage='$currentlang' OR planguage=''";
	} else {
		$where = "";
	}
	$tdwidth = intval(100/$tablenumhome);
	if (!is_array($massiv)) {
		$result = $db->sql_query("SELECT cid, title, description, parentid FROM ".$prefix."_pages_categories ".$where."");
		while (list($cid, $title, $description, $parentid) = $db->sql_fetchrow($result)) $massiv[] = array($cid, $title, $description, $parentid);
	}
	if (!is_array($massiv2)) {
		$result = $db->sql_query("SELECT cid, title, description, parentid FROM ".$prefix."_pages_categories");
		while (list($cid, $title, $description, $parentid) = $db->sql_fetchrow($result)) $massiv2[] = array($cid, $title, $description, $parentid);
	}
	// начало вставки 1
    if (!is_array($massiv3)) {
        $result = $db->sql_query("SELECT cid, Count(pid) FROM ".$prefix."_pages WHERE active != '0' GROUP BY cid");
        while (list($cid, $summ) = $db->sql_fetchrow($result)) $massiv3[$cid] = $summ;
    }
    // конец вставки 1
	if ($massiv) {
		foreach ($massiv as $key => $val) {
			if ($val[3] == $id) {
			// добавлено условие, что бы выводился ноль, в случае отсутствия файлов в категории
                if (!isset($massiv3[$val[0]])) {$massiv3[$val[0]] = 0;}
            // добавлено $massiv3[$val[0]]
                $description = ($catdescrhome) ? "<tr><td colspan=\"2\"><i>".$val[2]."</i></td></tr>" : "";
                $ccontent .= "<td valign=\"top\" width=\"".$tdwidth."%\"><table border=\"0\"><tr><td><img border=\"0\" src=\"images/blocks/Pages.gif\" title=\"$title\"></td><td width=\"100%\"><a href=\"index.php?name=$module_name&op=cat&id=$val[0]\" title=\"$val[1]\"><b>$val[1]</b></a> (".$massiv3[$val[0]].")</td></tr>".$description."";
				if ($homesubcat == 1 && $massiv2) {
					foreach ($massiv2 as $key => $val2) {
						if ($val[0] == $val2[3]) {
						 // добавлено условие, что бы выводился ноль, в случае отсутствия файлов в категории
                            if (!isset($massiv3[$val2[0]])) {$massiv3[$val2[0]] = 0;}

                            // добавлено $massiv3[$val2[0]]
                            $ccontent .= "<tr><td colspan=\"2\"><img border=\"0\" src=\"images/navi.gif\" title=\"$val2[1]\"> <a href=\"index.php?name=$module_name&op=cat&id=$val2[0]\" title=\"$val2[1]\">$val2[1]</a> (".$massiv3[$val2[0]].")</td></tr>";
						}
					}
				}
				$ccontent .= "</table></td>";
				if ($cont == ($tablenumhome - 1)) {
					$ccontent .= "</tr><tr>";
					$cont = 0;
				} else {
					$cont++;
				}
			}
		}
	}
	if ($ccontent) {
		OpenTable();
		echo "<table border=\"0\" cellspacing=\"0\" cellpadding=\"10\" align=\"center\"><tr>".$ccontent."</td></tr></table>";
		if ($shownumeric == 1) {
			list($pages_num) = $db->sql_fetchrow($db->sql_query("SELECT Count(pid) FROM ".$prefix."_pages WHERE active='1'"));
			list($cat_num) = $db->sql_fetchrow($db->sql_query("SELECT Count(cid) FROM ".$prefix."_pages_categories"));
			echo "<hr><center>"._ALLP.": <b>$pages_num</b> "._ALLP2." <b>$cat_num</b> "._ALLP3."</center>";
		}
		CloseTable();
	}
}

function main() {
	global $db, $prefix, $module_name, $multilingual, $currentlang, $tablenumhome, $newhome, $newhomenum, $datetime,$pagesadd,$addquest;
    head();
	title(""._PAGESNOTE."");
	categories();
	OpenTable();
	if ((is_user($user) && $pagesadd == 1) || (!is_user($user) && $addquest == 1)) echo"<a href=\"index.php?name=$module_name&op=add_pages\">Добавить статью</a>";
	CloseTable();
	$newhomenum = intval($newhomenum);
	if ($newhome == 1) {
		$result = $db->sql_query("SELECT pid, title, hometext, date, postname,totalcomments, counter FROM ".$prefix."_pages WHERE cid != '0' AND date <= now() AND active = '1' ORDER BY pid DESC LIMIT $newhomenum");
		if ($db->sql_numrows($result) > 0) {
			OpenTable();
			echo "<font class=\"option\">"._NEWPAGES."</font><hr>";
			while (list($p_pid, $p_title, $p_hometext, $date,$postname, $totalcomments, $counter) = $db->sql_fetchrow($result)) {
				formatTimestamp($date);
				echo "<hr><a href=\"index.php?name=$module_name&op=page&pid=$p_pid\" title=\"$p_title\"><b>$p_title</b></a><br>Добавил: <a href=\"/index.php?name=Account&op=info&uname=$postname\">$postname</a> $datetime<br>".bb_decode($p_hometext)."<br /><b>"._COUNTPAGE."</b>: $counter "._COUNT."<br /><b>Комментариев</b>:  $totalcomments<br>";
			}
			CloseTable();
		}
	}
	$result2 = $db->sql_query("SELECT pid, title, hometext, date, postname FROM ".$prefix."_pages WHERE cid = '0' AND date <= now() AND active = '1' ORDER BY pid DESC");
	if ($db->sql_numrows($result2) > 0) {
		OpenTable();
		echo "<font class=\"option\">"._PAGESHOMECATS."</font><hr>";
		while (list($p_pid, $p_title, $p_hometext, $date, $postname) = $db->sql_fetchrow($result2)) {
			formatTimestamp($date);
			echo "<a href=\"index.php?name=$module_name&op=page&pid=$p_pid\" title=\"$p_title\"><b>$p_title</b></a><br>Добавил: <a href=\"/index.php?name=Account&op=info&uname=$postname\">$postname</a> $datetime<br>".bb_decode($p_hometext)."<br />";
		}
		CloseTable();
	}
	get_page($module_name);
	foot();
}

function cat() {
    global $db, $prefix, $module_name, $numpage, $pagenum, $datetime, $pagetitle, $defis, $hometext;
	$cid = intval($_GET['id']);
	list($c_title, $c_description) = $db->sql_fetchrow($db->sql_query("SELECT title, description FROM ".$prefix."_pages_categories WHERE cid='$cid'"));
	$pagetitle = "$defis "._CONTENT_NAME." $defis $c_title";
	$hometext = $c_description;
	head();
	title(""._PAGESNOTE."");
	OpenTable();
	echo "<center><font class=\"option\">$c_title</font><br />$c_description</center>";
	CloseTable();
	categories($cid);
    if ($pagenum == "") $pagenum = 1;
	$offset = ($pagenum - 1) * $numpage;
	$offset = intval($offset);
	$numpage = intval($numpage);
	$result = $db->sql_query("SELECT pid, title, hometext, date, counter,postname,totalcomments FROM ".$prefix."_pages WHERE cid ='$cid' AND date <= now() AND active = '1' ORDER BY pid DESC LIMIT $offset, $numpage");
    if ($db->sql_numrows($result) > 0) {
		OpenTable();
		$i = 0;
		while (list($p_pid, $p_title, $p_hometext, $date, $p_counter,$postname,$totalcomments) = $db->sql_fetchrow($result)) {
			formatTimestamp($date);
			$hr = ($i) ? "<hr>" : "";
			echo "$hr<a href=\"index.php?name=$module_name&op=page&pid=$p_pid\" title=\"$p_title\"><b>$p_title</b></a><br>Добавил: <a href=\"/index.php?name=Account&op=info&uname=$postname\">$postname</a> $datetime<br><hr>".bb_decode($p_hometext)."<br /><b>"._COUNTPAGE."</b>: $p_counter "._COUNT."<br><b>Комментариев</b>: $totalcomments<br>";



			$i++;
		}
		CloseTable();
    }
	list($numstories) = $db->sql_fetchrow($db->sql_query("SELECT Count(pid) FROM ".$prefix."_pages WHERE cid ='$cid' AND date <= now() AND active = '1'"));
    $numpages = ceil($numstories / $numpage);
	num_page($module_name, $numstories, $numpages, $numpage, "op=cat&id=".$cid."&");
	get_page($module_name);
    foot();
}

function page($pid, $pagenum=0) {
    global $pagetitle, $hometext, $bodytext, $db, $prefix, $module_name, $admin, $pagecatlink, $pagecatnumlinc, $admin_file, $defis, $datetime, $addfiles, $addquest;
    $pid = intval($pid);
	$result = $db->sql_query("SELECT cid, title, hometext, bodytext, date, counter,postname  FROM ".$prefix."_pages WHERE pid='$pid' AND date <= now() AND active = '1'");
	if ($db->sql_numrows($result) > 0) {
		if ($pagenum == 0) $db->sql_query("UPDATE ".$prefix."_pages SET counter=counter+1 WHERE pid='$pid'");
		list($cid, $title, $hometext, $bodytext, $date, $counter,$postname) = $db->sql_fetchrow($result);
		$cid = intval($cid);
		$pagetitle = "$defis "._CONTENT_NAME." $defis $title";	
		formatTimestamp($date);
		$contentpages = explode("[pagebreak]", $bodytext);
		$pageno = count($contentpages);
		if ($pagenum=="" || $pagenum < 1) $pagenum = 1;
		if ($pagenum > $pageno) $pagenum = $pageno;
		$arrayelement = (int)$pagenum;
		$arrayelement --;
		list($c_title, $c_description) = $db->sql_fetchrow($db->sql_query("SELECT title, description FROM ".$prefix."_pages_categories WHERE cid='$cid'"));
		$c_title = ($c_title) ? $c_title : ""._PAGESHOMECATS."";
		$pagetitle = "$defis "._CONTENT_NAME." $defis $c_title $defis $title";	
		head();
		title(""._PAGESNOTE."");
		OpenTable();
		echo "<center><font class=\"option\">$c_title</font><br />$c_description</center>";
		CloseTable();
		OpenTable();
		echo "<font class=\"option\">$title</font><br />Добавил: <a href=\"/index.php?name=Account&op=info&uname=$postname\">$postname</a> $datetime<br />"._COUNTPAGE.": $counter "._COUNT."<hr>".bb_decode($hometext)."<hr>".bb_decode($contentpages[$arrayelement])."";
		
		if (is_admin($admin)) {
			echo "<hr><center>[ <a href=".$admin_file.".php?op=delete_page&id=$pid>"._DELETE."</a> | <a href=".$admin_file.".php?op=add_pages&id=$pid>"._EDIT."</a> | <a href=".$admin_file.".php?op=active_pages&id=$pid&act=0>"._OFFPAGE."</a> ]</center>";
		}
		CloseTable();
		num_page($module_name, 1, $pageno, 1, "op=page&pid=".$pid."&");
		if ($pagecatlink == 1) {
			$pagecatnumlinc = intval($pagecatnumlinc);
			$result2 = $db->sql_query("SELECT pid, title FROM ".$prefix."_pages WHERE cid='$cid' AND pid !='$pid' AND date <= now() AND active = '1' LIMIT $pagecatnumlinc");
			if ($db->sql_numrows($result2) > 0) {
				OpenTable();
				echo "<font class=\"option\">"._LINKPAGES."</font><hr>";
				while (list($l_pid, $l_title) = $db->sql_fetchrow($result2)) {
					echo "<table border=\"0\"><tr><td><a href=\"index.php?name=$module_name&op=page&pid=$l_pid\" title=\"$l_title\"><img border=\"0\" src=\"images/blocks/News.gif\" alt=\"$l_title\"></a></td><td><a href=\"index.php?name=$module_name&op=page&pid=$l_pid\" title=\"$l_title\"><b>$l_title</b></a></td></tr></table>";
				}
				CloseTable();
			}
		}
		get_page($module_name);
		
		echo "<a name=\"$pid\"></a>"; //комментарии
        ShowComments($pid);
		
		
		
		
		foot();
	} else {
		Header("Location: index.php?name=".$module_name."");
	}
}
function pagegetparent($parentid, $title) {
    global $prefix, $db, $admin_file;
    list($cid, $ptitle, $pparentid) = $db->sql_fetchrow($db->sql_query("SELECT cid, title, parentid FROM ".$prefix."_pages_categories WHERE cid='$parentid'"));
    if ($ptitle != "") $title = $ptitle."/".$title;
    if ($pparentid != 0) $title = pagegetparent($pparentid, $title);
    return $title;
}


function add_pages() {
    global $prefix, $db, $admin_file, $multilingual, $stop, $module_name, $user, $userinfo,$pagesadd,$addquest;
    head();
	 if ($pagesadd == "1") {
	if ($stop) warning($stop, "", "", 1);
	if (isset($_REQUEST['id'])) {
		$pid = intval($_REQUEST['id']);
		$result = $db->sql_query("SELECT pid, cid, title, hometext, bodytext, date, active, FROM ".$prefix."_pages WHERE pid='$pid'");
        list($pid, $cat, $title, $hometext, $bodytext, $time, $status) = $db->sql_fetchrow($result);
		$associated = explode("-", $associated);
		$functitle = ""._PAGEEDIT."";
	} else {
		$pid = $_POST['pid'];
		$cat = $_POST['cid'];
		$title = $_POST['title'];
		$hometext = save_text($_POST['hometext']);
		$bodytext = save_text($_POST['bodytext']);
		$status = $_POST['status'];
		if (isset($_POST['year'])) {
			$time = "".$_POST['year']."-".$_POST['mon']."-".$_POST['day']." ".$_POST['hour'].":".$_POST['min'].":00";
		} else {
			$today = getdate();
			$time = "".$today[year]."-".$today[mon]."-".$today[mday]." ".$today[hours].":".$today[minutes].":00";
		}
		$functitle = ""._ADDPAGE."";
	}
	if ($hometext) preview("<b>".$title."</b><br /><br />".bb_decode($hometext)."<br /><br />".bb_decode($bodytext)."");
	OpenTable();
	echo "<center><font class=\"option\">".$functitle."</font><br /><br />"
    .""._ADDPAGENOTE."</center>";
    CloseTable();
	OpenTable();
	echo "<table border=\"0\" cellpadding=\"3\" cellspacing=\"0\" align=\"center\"><form name=\"post\" action=\"index.php?name=$module_name&op=add_pages\" method=\"post\">";
if (is_user($user)) {
		getusrinfo($user);
		echo "<tr><td>"._YOURNAME.":</td><td>".$userinfo['user_name']."</td></tr>";
	} else {
		echo "<tr><td>"._YOURNAME.":</td><td><input type=\"text\" name=\"postname\" value=\"".$_POST['postname']."\" size=\"65\" style=\"width:400px\"></td></tr>";
	}

           echo"<tr><td>"._TITLE.":</td><td><input type=\"text\" name=\"title\" value=\"".$title."\" maxlength=\"80\" size=\"65\" style=\"width:400px\"></td></tr>"
	."<tr><td>"._CATEGORY.":</td><td><select name=\"cid\" style=\"width:400px\"><option value=\"0\">"._HOMECAT."</option>";
	$result = $db->sql_query("SELECT cid, title, parentid FROM ".$prefix."_pages_categories ORDER BY parentid,title");

	while (list($cid, $title, $parentid) = $db->sql_fetchrow($result)) {
		if ($parentid != 0) $title = pagegetparent($parentid, $title);
		$sel = ($cat == $cid) ? "selected" : "";
		echo "<option value=\"$cid\" $sel>$title</option>";
	}
    echo "</select></td></tr>";
	echo "<tr><td>"._HOMETEXTPAGE.":</td><td><textarea id=\"area\" name=\"hometext\" cols=\"65\" rows=\"10\" style=\"width:400px\" OnKeyPress=\"TransliteFeld(this, event)\" OnSelect=\"FieldName(this, this.name)\" OnClick=\"FieldName(this, this.name)\" OnKeyUp=\"FieldName(this, this.name)\">".replace_break($hometext)."</textarea>".get_code("area")."</td></tr>"
	."<tr><td>"._BODYTEXTPAGE.":</td><td><textarea id=\"area1\" name=\"bodytext\" cols=\"65\" rows=\"25\" style=\"width:400px\" OnKeyPress=\"TransliteFeld(this, event)\" OnSelect=\"FieldName(this, this.name)\" OnClick=\"FieldName(this, this.name)\" OnKeyUp=\"FieldName(this, this.name)\">".replace_break($bodytext)."</textarea>".get_code("area1")."</td></tr>";
	echo"<tr><td  colspan=\"2\" align=\"center\"><select name=\"posttype\">"
	."<option value=\"preview\">"._PREVIEW."</option>"
	."<option value=\"save\">"._SEND."</option></select>"
	." <input type=\"hidden\" name=\"pid\" value=\"$pid\">"
	." <input type=\"hidden\" name=\"op\" value=\"save_pages\">"
	."<input type=\"submit\" value=\""._OK."\"></td></tr></form></table>";
	CloseTable();
	get_page($module_name);
    foot();
}
}
function save_pages() {
    global $prefix, $db, $multilingual, $stop, $module_name, $user, $userinfo;
    if (is_user($user)) {
		getusrinfo($user);
		$postname = text_filter(substr($userinfo['user_name'], 0, 25));
	} else {
		$postname = text_filter(substr($_POST['postname'], 0, 25));
	}

	$pid = intval($_POST['pid']);
	$title = $_POST['title'];
	$cat = $_POST['cid'];
	$hometext = save_text($_POST['hometext']);
	$bodytext = save_text($_POST['bodytext']);
	$status = $_POST['status'];
	if (isset($_POST['year'])) {
		$time = "".$_POST['year']."-".$_POST['mon']."-".$_POST['day']." ".$_POST['hour'].":".$_POST['min'].":00";
	} else {
		$today = getdate();
		$time = "".$today[year]."-".$today[mon]."-".$today[mday]." ".$today[hours].":".$today[minutes].":00";
	}
	if (!$hometext) $stop = ""._CERROR1."";
	if (!$stop && $_POST['posttype'] == "save") {
		if ($pid) {
			$db->sql_query("UPDATE ".$prefix."_pages SET  cid='$cat', title='$title'  , hometext='$hometext', bodytext='$bodytext', date='$time', active='$status' ,postname='$postname' WHERE pid='$pid'");
		} else {
			$db->sql_query("INSERT INTO ".$prefix."_pages VALUES (NULL,  ' $cat',' $title'  , '$hometext', '$bodytext', '$time', '0', '$status' ,'$postname','0')");
		}
		head();
		title(""._ADDNEWS."");
		warning(""._SUBTEXT."", "", 5, 2);
		foot();

		
	} else {
		add_pages();
	}
}





switch($op) {
	case "cat":
    cat();
    break;
    
    case "add_pages":
    add_pages();
    break;

case "save_pages":
    save_pages();
    break;

    case "page":
    page($pid, $pagenum);
    break;

    default:
    main();
    break;
}
?>