<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 * Blogs By Aan Gabriel
 */

define('_IN_JOHNCMS', 1);

$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
$act = isset($_GET['act']) ? trim($_GET['act']) : '';
//$do = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : false;


require('../system/bootstrap.php');
/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);
/** @var Johncms\Api\BbcodeInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);


require_once('../system/head.php');
if (!$systemUser->isValid()) {
   echo $tools->displayError('Please Login!');
   require('../system/end.php');
   exit;
}


$flood = $tools->antiflood();
if ($flood) {
    echo sprintf(_t('You cannot add the message so often. Please, wait %d seconds.'), $flood);
     echo '<div class="menu"><a href="index.php">Back</a></div>';
require('../system/end.php');
     exit;
}


if ($systemUser->rights == 5 || $systemUser->rights >= 6) {

function timer($var = '') {
	global $waktu;
	if($var <= 0)
		return;
	if(86400 > $var) {
		if(3600 > $var) {
			if(60 > $var) {
				$time = $var;
				return $time . ' sec.';
			} else if(60 <= $var && (60 * 2) > $var) {
				return 'One Minute';
			}
			$hours = (60 - ceil((3600 - $var) / 60));
			return $hours . ' hour.';
		} else if(3600 <= $var && (3600 * 2) > $var) {
			return $waktu . 'one hour.';
		}
		$days = (24 - ceil((86400 - $var) / 3600));
		return $days . ' days.';
	} else if(86400 <= $var && (86400 * 2) > $var) {
		return $waktu . 'one days.';
	}
	$days = ceil($var / 86400);
	return $days . 'day left.';
}



echo '<div class="phdr"><a href="index.php"><b>Blog</b></a> | Kategori Blogs </div>';
switch ($act) {
    case 'add' :
		if (isset ($_POST['submit'])) {
			
			$name = isset ($_POST['name']) ? trim($_POST['name']) : '';
			
			$error = [];
			
			if(empty($name)) {
				$error[] = 'Name Category empty!';
			
}
			if (mb_strlen($name) < 2 || mb_strlen($name) > 50) {
				$error[] = 'Error! Name category longs';
			}
			if(empty($error)) {
				$q = $db->query("SELECT * FROM `blogs_cat` WHERE `name`='$name' LIMIT 1");
                if ($q->rowCount()) {
					$error[] =  'Category already exists!';
				}
			}
			if(empty($error)) {
				$req = $db->query("SELECT `realid` FROM `blogs_cat` ORDER BY `realid` DESC LIMIT 1");
                if ($req->rowCount()) {
                    $res = $req->fetch();
                    $sort_id = $res['realid'] + 1;
                } else {
                    $sort_id = 1;
                }
				
				$db->prepare("INSERT INTO `blogs_cat` SET
			      `realid` = ?,
                `name` = ?
              ")->execute([
                 $sort_id,
                 $name,
               ]);
				$img_id = $db->lastInsertId();
				$handle = new upload($_FILES['imagefile']);
				if ($handle->uploaded) {
					// Обрабатываем фото
					$handle->file_new_name_body = 'ico_cat_' . $img_id;
					$handle->allowed = array('image/jpeg', 'image/jpg', 'image/gif', 'image/png');
					$handle->file_max_size = 1024 * $config['flsz'];
					$handle->file_overwrite = true;
					$handle->image_resize = true;
					$handle->image_x = 16;
					$handle->image_y = 16;
					$handle->image_convert = 'jpg';
					$handle->process('../blogs/icon/');
					if($handle->processed)
						@chmod('../blogs/icon/ico_cat_' . $img_id . '.jpg', 0666);
					$handle->clean();
				}
				
				header('Location: manage.php');
				
			} else {
				echo $tools->displayError($error, '<a href="manage.php?act=add">Repeat</a>');
			}
			
		} else {
			echo '<form action="manage.php?act=add" method="post" enctype="multipart/form-data">
			<div class="gmenu"><p>
			<b>Category:</b><br />
			<input type="text" name="name" /><br /><small>Max 50 Character</small><br />
			<b>Icon Category:</b><br />
			<input type="file" name="imagefile"/><br />
			<small>Format Allowed: GIF, JPEG, JPG, PNG, max 300kb auto resize to 16X16px</small><br />
			<input type="hidden" name="MAX_FILE_SIZE" value="' . (1024 * $config['flsz']) . '" />
			</p><p><input type="submit" value="Add" name="submit" />
			</p></div></form>';
		}
		echo '<div class="phdr"><a href="manage.php">Manage Blogs</a></div>';
		break;

	case 'up' :
		////////////////////////////////////////////////////////////
        // Displacement on one position upwards                      //
        ////////////////////////////////////////////////////////////
		if ($id) {
			$req = $db->query("SELECT * FROM `blogs_cat` WHERE `id` = '$id' LIMIT 1");
            if ($req->rowCount()) {
				$res1 = $req->fetch();
				$sort = $res1['realid'];
				$req = $db->query("SELECT * FROM `blogs_cat` WHERE `realid` < '$sort' ORDER BY `realid` DESC LIMIT 1");
				if ($req->rowCount()) {
					$res = $req->fetch();
					$id2 = $res['id'];
					$sort2 = $res['realid'];
					$db->exec("UPDATE `blogs_cat` SET `realid` = '$sort2' WHERE `id` = '$id'");
					$db->exec("UPDATE `blogs_cat` SET `realid` = '$sort' WHERE `id` = '$id2'");
				}
			}
		}
        header('Location: manage.php');
		break;
	case 'down' :
		////////////////////////////////////////////////////////////
        // Displacement on one position downwards                 //
        ////////////////////////////////////////////////////////////
        if ($id) {
            $req = $db->query("SELECT `realid` FROM `blogs_cat` WHERE `id` = '$id' LIMIT 1");
            if ($req->rowCount()) {
                $res1 = $req->fetch();
                $sort = $res1['realid'];
                $req = $db->query("SELECT `id`, `realid` FROM `blogs_cat` WHERE `realid` > '$sort' ORDER BY `realid` ASC LIMIT 1");
                if ($req->rowCount()) {
                    $res = $req->fetch();
                    $id2 = $res['id'];
                    $sort2 = $res['realid'];
                    $db->exec("UPDATE `blogs_cat` SET `realid` = '$sort2' WHERE `id` = '$id'");
                    $db->exec("UPDATE `blogs_cat` SET `realid` = '$sort' WHERE `id` = '$id2'");
                }
            }
        }
		header('Location: manage.php');
		break;

	case 'edit' :
		if($id) {
			$q = $db->query("SELECT * FROM `blogs_cat` WHERE `id`='$id' LIMIT 1");
			if ($q->rowCount()) {
				
				$row = $q->fetch();
				
				if (isset ($_POST['submit'])) {
					
					$name = isset ($_POST['name']) ? trim($_POST['name']) : '';
					
					$error = [];
					
					if(empty($name)) {
						$error[] = 'Name category empty!';
                }
					if (mb_strlen($name) < 2 || mb_strlen($name) > 50) {
						$error[] = 'Error!<br/>Min. 2 Max. 50';
					
}
					if(empty($error)) {
						if($name != $row['name']) {
							$q = $db->query("SELECT * FROM `blogs_cat` WHERE `name`='$name' LIMIT 1");
							if ($q->rowCount()) {
								$error[] =  'Category already exists!';
							}
						}
					}

					if(empty($error)) {
						$db->exec("UPDATE `blogs_cat` SET
						`name` = '$name' WHERE `id`='$id' LIMIT 1");
						$handle = new upload($_FILES['imagefile']);
						if ($handle->uploaded) {
							// Обрабатываем фото
							$handle->file_new_name_body = 'ico_cat_' . $id;
							$handle->allowed = array('image/jpeg', 'image/jpg', 'image/gif', 'image/png');
							$handle->file_max_size = 1024 * $config['flsz'];
							$handle->file_overwrite = true;
							$handle->image_resize = true;
							$handle->image_x = 16;
							$handle->image_y = 16;
							$handle->image_convert = 'jpg';
							$handle->process('../blogs/icon/');
							if($handle->processed)
								@chmod('../blogs/icon/ico_cat_' . $id . '.jpg', 0666);
							$handle->clean();
						}
						
						header('Location: manage.php');
						
					} else {
						echo $tools->displayError($error, '<a href="manage.php?act=edit&amp;id='.$id.'">Repeat</a>');
					}
					
				} else {
					echo '<form action="manage.php?act=edit&amp;id=' . $id . '" method="post" enctype="multipart/form-data">
					<div class="gmenu"><p>
					<b>Category:</b><br />
					<input type="text" name="name" value="' . htmlentities($row['name'], ENT_QUOTES, 'UTF-8') . '"/><br /><small>Min. 2, Max. 50 Character</small><br />
					<b>Icon category:</b><br />
					<input type="file" name="imagefile"/><br />
					<small>Format Allowed: GIF, JPEG, JPG, PNG, max. 300kb auto resize to 16X16px</small><br />
					<input type="hidden" name="MAX_FILE_SIZE" value="' . (1024 * $config['flsz']) . '" />
					</p><p><input type="submit" value="Edit" name="submit" />
					</p></div></form>';
				}
			} else {
				echo $tools->displayError('Category not found');
			}
		} else {
			echo $tools->displayError('Category not selected');
		}
		echo '<div class="phdr"><a href="manage.php">Manage Blogs</a></div>';
		break;

	case 'delete' :
		if($id) {
			$q = $db->query("SELECT * FROM `blogs_cat` WHERE `id`='$id' LIMIT 1");
			if ($q->rowCount()) {
				if (isset ($_POST['submit'])) {
					$cn = $db->query("SELECT COUNT(*) FROM `blogs` WHERE `refid` = '$id'")->fetchColumn();
					if($cn) {
						$reqs = $db->query("SELECT * FROM `blogs` WHERE `refid`='$id'");
						$massdel = [];
						while (($row = $reqs->fetch()) !== false) {
							$massdel[] = $row['id'];
							if(file_exists(ROOT_PATH . 'blogs/icon/news_' . $row['id'] . '.jpg') !== false) {
								unlink('../blogs/icon/news_' . $row['id'] . '.jpg');
								unlink('../blogs/icon/small_news_' . $row['id'] . '.jpg');
							}
						}
						if($massdel) {
							$result = implode(',', $massdel);
							$db->exec("DELETE FROM `blogs` WHERE `id` IN (" . $result . ")");
							$db->exec("DELETE FROM `blogs_comments` WHERE `refid` IN (" . $result . ")");
						}
					}
					$db->exec("DELETE FROM `blogs_cat` WHERE `id` = '$id'");
					if(file_exists(ROOT_PATH . 'blogs/icon/ico_cat_' . $id . '.jpg') !== false)
						unlink('../blogs/icon/ico_cat_' . $id . '.jpg');
					header('Location: manage.php');
				} else {
					echo '<form action="manage.php?act=delete&amp;id=' . $id . '" method="post">
					<div class="gmenu"><p>
					Are you sure you want to delete this category?
					</p><p><input type="submit" value="Delete" name="submit" />
					</p></div></form>';
				}
			} else {
				echo $tools->displayError('Category not found');
			}
		} else {
			echo $tools->displayError('Category not selected!');
		}
		echo '<div class="phdr"><a href="manage.php">Manage Blogs</a></div>';
		break;


	case 'delnews' :
		if($id) {
			if ($db->query("SELECT COUNT(*) FROM `blogs` WHERE `id`='$id'")->fetchColumn() != 0) {
				if (isset ($_POST['submit'])) {
					if(file_exists(ROOT_PATH . 'blogs/icon/news_' . $id . '.jpg')) {
						unlink('../blogs/icon/news_' . $id . '.jpg');
						unlink('../blogs/icon/small_news_' . $id . '.jpg');
					}
					$db->exec("DELETE FROM `blogs` WHERE `id`='$id'");
					$db->exec("DELETE FROM `blogs_comments` WHERE `refid`='$id'");
					
					echo '<div class="rmenu">Blog Removed</div>';
				} else {
					echo '<form action="manage.php?act=delnews&amp;id=' . $id . '" method="post">
					<div class="gmenu"><p>
					Are you sure you want to remove this blog?
					</p><p><input type="submit" value="Remove" name="submit" />
					</p></div></form>';
				}
			} else {
				echo $tools->displayError('Blogs not found!');
			}
		} else {
			echo $tools->displayError('Blogs Not selected!');
		}
	break;
	case 'clear' :
		echo '<div class="phdr">Remove Blog</div>';
            if (isset ($_POST['submit'])) {
                $cl = isset ($_POST['cl']) ? intval($_POST['cl']) : '';
                switch ($cl) {
                    case '1' :
                        $reqs = $db->query("SELECT * FROM `blogs` WHERE `time`<='" . ($realtime - 604800) . "'");
						$massdel = [];
						while (($row = $reqs->fetch()) !== false) {
							$massdel[] = $row['id'];
							if(file_exists(ROOT_PATH . 'blogs/icon/news_' . $row['id'] . '.jpg')) {
								unlink('../blogs/icon/news_' . $row['id'] . '.jpg');
								unlink('../blogs/icon/small_news_' . $row['id'] . '.jpg');
							}
						}
						if($massdel) {
							$result = implode(',', $massdel);
							$db->exec("DELETE FROM `blogs` WHERE `id` IN (" . $result . ")");
							$db->exec("DELETE FROM `blogs_comments` WHERE `refid` IN (" . $result . ")");
							$db->exec("OPTIMIZE TABLE `blogs`, `blogs_comments`;");
						}


                        echo '<p class="rmenu">Are you sure you want to delete a blogs on 1 week</p>';
                        break;

                    case '2' :
                        // Проводим полную очистку
						$reqs = $db->query("SELECT * FROM `blogs` WHERE `time`<='" . ($realtime - 604800) . "'");
						while (($row = $reqs->fetch()) !== false) {
							if(file_exists(ROOT_PATH . 'blogs/icon/news_' . $row['id'] . '.jpg')) {
								unlink('../blogs/icon/news_' . $row['id'] . '.jpg');
								unlink('../blogs/icon/small_news_' . $row['id'] . '.jpg');
							}
						}
						$db->exec("TRUNCATE TABLE `blogs`");
						$db->exec("TRUNCATE TABLE `blogs_comments`");
                        
                        echo '<p class="rmenu">Are you sure you want to remove all blog</p>';
                        break;

                    default :
                        // Чистим сообщения, старше 1 месяца
						$reqs = $db->query("SELECT * FROM `blogs` WHERE `time`<='" . ($realtime - 2592000) . "'");
						$massdel = array();
						while (($row = $reqs->fetch()) !== false) {
							$massdel[] = $row['id'];
							if(file_exists(ROOT_PATH . 'blogs/icon/news_' . $row['id'] . '.jpg')) {
								unlink('../blogs/icon/news_' . $row['id'] . '.jpg');
								unlink('../blogs/icon/small_news_' . $row['id'] . '.jpg');
							}
						}
						if($massdel) {
							$result = implode(',', $massdel);
							$db->exec("DELETE FROM `blogs` WHERE `id` IN (" . $result . ")");
							$db->exec("DELETE FROM `blogs_comments` WHERE `refid` IN (" . $result . ")");
							$db->exec("OPTIMIZE TABLE `blogs`, `blogs_comments`;");
						}
                        echo '<p class="rmenu">Blogs has been deleted within 1 month.</p>';
                }
            } else {
                echo '<div class="gmenu"><p><u>Removing Metode:</u>';
                echo '<form id="clean" method="post" action="manage.php?act=clear"><div>';
                echo '<input type="radio" name="cl" value="0" checked="checked" />1 Mount<br />';
                echo '<input type="radio" name="cl" value="1" />1 Week<br />';
                echo '<input type="radio" name="cl" value="2" />All<br />';
                echo '<input type="submit" name="submit" value="Remove" /></div>';
                echo '</form></p></div>';
            }
		echo '<div class="phdr"><a href="manage.php">Manage Blogs</a></div>';
		break;
		
	case 'ico' :
		if($id) {
			$q = $db->query("SELECT * FROM `blogs_cat` WHERE `id`='$id' LIMIT 1");
			if ($q->rowCount()) {
				if (isset ($_POST['submit'])) {
					if(file_exists(ROOT_PATH . 'blogs/icon/ico_cat_' . $id . '.jpg'))
						unlink('../blogs/icon/ico_cat_' . $id . '.jpg');
					Header('Location: manage.php');
				} else {
					echo '<form action="manage.php?act=ico&amp;id=' . $id . '" method="post" enctype="multipart/form-data">
					<div class="gmenu"><p>

					Are you sure you want to delete this icon?
					</p><p><input type="submit" value="Remove" name="submit" />
					</p></div></form>';
				}
			} else {
				echo $tools->displayError('Category Not Found!');
			}
		} else {
			echo $tools->displayError('Please select the category');
		}
		echo '<div class="phdr"><a href="manage.php?act=news">Manage Blogs</a></div>';
		break;

	case 'list' :
		$total = $db->query("SELECT COUNT(*) FROM `blogs`")->fetchColumn();
		if($total) {
			$req = $db->query("SELECT `id`, `name`, `text`, `time` FROM `blogs` ORDER BY `time` DESC LIMIT "
						  . $start . "," . $kmess);
			$i = 1;
			while (($row = $req->fetch()) !== false) {
				echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
				if(file_exists(ROOT_PATH . 'blogs/icon/small_news_' . $row['id'] . '.jpg')) {
					echo '<table cellpadding="0" cellspacing="0" width="100%"><tr><td width="32">';
					echo '<img style="margin: 0 0 -3px 0;border: 0px;" src="../blogs/icon/small_news_' . $row['id'] . '.jpg" alt="" width="32" height="32"/>&#160;';
					echo '</td><td>';
					echo '<a href="'.$config['homeurl'].'/blogs/' . $tools->Rewrite($row['name']) . '_' . $row['id'] . '.html">' . htmlentities($row['name'], ENT_QUOTES, 'UTF-8') . '</a> <br />(' . date('d.m.o / H:i', $row['time'] + $sdvigclock * 3600) . ')<br />';
					echo '</td></tr></table>';
				} else {
					 echo '<a href="'.$config['homeurl'].'/blogs/' . $tools->Rewrite($row['name']) . '_' . $row['id'] . '.html">' . htmlentities($row['name'], ENT_QUOTES, 'UTF-8') . '</a> (' . date('d.m.o / H:i', $row['time'] + $sdvigclock * 3600) . ')<br />';
				}
				echo '<div class="sub"></div>';
				$text = $row['text'];
				if(mb_strlen($text) > 100) {
					$str = mb_substr($text, 0, 100);
					$text = mb_substr($str, 0, mb_strrpos($str, ' ')) . '...';
				}
				echo $tools->checkout($text, 2, 1);
				if($row['time'] > time())
					echo '<div class="sub func">Time left to hide: ' . timer($row['time'] - time()) . '</div>';
				echo '</div>
				<div class="bmenu"><a href="manage.php?act=newsedit&amp;id=' . $row['id'] . '">Edit Blogs</a> | <a href="manage.php?act=delnews&amp;id=' . $row['id'] . '">Delete</a></div>';
				++$i;
			}
			echo '<div class="phdr">Total Blogs: ' . $total . '</div>';
			if ($total > $kmess) {
				echo '<p>' . $tools->displayPagination('index.php?act=blogs&amp;mod=list&amp;', $start, $total, $kmess) . '</p>';
				echo '<p><form action="index.php" method="get">
				<input type="hidden" name="act" value="mod_news"/>
				<input type="hidden" name="mod" value="list"/>
				<input type="text" name="page" size="2"/>
				<input type="submit" value="To page &gt;&gt;"/></form></p>';
			}
		} else {
			echo '<div class="rmenu">Blogs Empty</div>';
		}
		
		echo '<div class="phdr"><a href="manage.php">Manage Blogs</a></div>';
		break;

	
	
	
	case 'newsedit' :
		if($id) {
			$q = $db->query("SELECT * FROM `blogs` WHERE `id`='$id' LIMIT 1");
			if ($q->rowCount()) {
				$row = $q->fetch();
				
				$day = date('d', $row['time']);
				$year= date('o', $row['time']);
				$month = date('m', $row['time']);
				$minutes = date('i', $row['time']);
				$hour = date('H', $row['time']);
				
				if (isset ($_POST['submit'])) {
					$time = time();
					$timer = time();
					
					$date['day'] = date('d', $time);
					$date['year'] = date('o', $time);
					$date['month'] = date('m', $time);
					$date['i'] = date('i', $time);
					$date['h'] = date('H', $time);
					
					$name = isset ($_POST['name']) ? trim($_POST['name']) : '';
					$text = isset ($_POST['text']) ? trim($_POST['text']) : '';
					$cat = isset($_POST['cat']) ? abs(intval($_POST['cat'])) : 0;
					$day = isset($_POST['day']) && $_POST['day'] >= 1 && $_POST['day'] <= 31 ? abs(intval($_POST['day'])) : $date['day'];
					$month = isset($_POST['month']) && $_POST['month'] >= 1 && $_POST['month'] <= 12 ? abs(intval($_POST['month'])) : $date['month'];
					$year = isset($_POST['year']) && $_POST['year'] >= $date['year'] && $_POST['year'] <= ($date['year'] + 1) ? abs(intval($_POST['year'])) : $date['year'];
					
					$hour = isset($_POST['hour']) && $_POST['hour'] >= 0 && $_POST['hour'] <= 24 ? abs(intval($_POST['hour'])) : $date['h'];
					$minutes = isset($_POST['minutes']) && $_POST['minutes'] >= 0 && $_POST['minutes'] <= 60 ? abs(intval($_POST['minutes'])) : $date['i'];
					
					//$error = array();
			
					$error = [];
					
					if(empty($name))
						$error[] =  'Title of blogs is empty!';
					else if (mb_strlen($name) < 2 || mb_strlen($name) > 150)
						$error[] =  'Error on title blogs!<br/>Min. 2 Max.150';
					if(empty($text))
						$error[] = 'Blogs empty!';
					else if (mb_strlen($text) < 2 || mb_strlen($text) > 5000)
						$error[] = 'Error!<br/>Min. 2 Max. 5000!';
					if(!$cat)
						$error[] = 'Error on selected category!';
						
					if(empty($day) || empty($month) || empty($year))
						$timer = 0;
					else 
						$time = strtotime("$day.$month.$year.$hour.$minutes");
						
					/*if(!empty($timer) && $time < time() && $time != $row['time']) {
						$error[] = 'Не верная дата!';
					}*/
					if(!$error) {
						$data = $db->query("SELECT * FROM `blogs_cat` WHERE `id`='$cat';");
						if(!$data->rowCount())
							$error[] = 'Category not found!';
					}
					
					if(empty($error)) {
						if($name != $row['name']) {
							$q = $db->query("SELECT * FROM `blogs` WHERE `name`='$name' LIMIT 1");
							if ($q->rowCount()) {
								$error[] =  'Blogs already exists!';
							}
						}
					}
					
					if(empty($error)) {
						
						$db->exec("UPDATE `blogs` SET
						`refid` = '$cat',
						`name` = '$name',
						`text` = '$text',
						`user_id` = '" . $systemUser->id . "',
						`time` = '" . $time . "' WHERE `id`='$id'");
						
						//$img_id = mysql_insert_id();
						
						//require_once ($server . '/incfiles/lib/class.upload.php');
						$handle = new upload($_FILES['imagefile']);
						if ($handle->uploaded) {
							
							// Обрабатываем фото
							$handle->file_new_name_body = 'news_' . $id;
							$handle->allowed = array('image/jpeg', 'image/jpg', 'image/gif', 'image/png');
							$handle->file_max_size = 1024 * $config['flsz'];
							$handle->file_overwrite = true;
							$handle->image_resize = true;
							$handle->image_x = 100;
							$handle->image_ratio_y = true;
							$handle->image_convert = 'jpg';
							$handle->process('../blogs/icon/');
							if($handle->processed) {
								@ chmod('../blogs/icon/news_' . $id . '.jpg', 0666);
							}
							
							$handle->file_new_name_body = 'small_news_' . $id;
							$handle->allowed = array('image/jpeg', 'image/jpg', 'image/gif', 'image/png');
							$handle->file_max_size = 1024 * $config['flsz'];
							$handle->file_overwrite = true;
							$handle->image_resize = true;
							$handle->image_x = 32;
							$handle->image_y = 32;
							$handle->image_convert = 'jpg';
							$handle->process('../blogs/icon/');
							if($handle->processed) {
								@chmod('../blogs/icon/small_news_' . $id . '.jpg', 0666);
							}
						}
						$handle->clean();
						
						//header('Location: index.php?act=view&id='.$id);
						header('Location: manage.php?act=list');
					} else {
						echo $tools->displayError($error, '<a href="manage.php?act=news">Repeat</a>');
					}
					
				} else {
					
					echo '<form action="manage.php?act=newsedit&amp;id=' . $id . '" method="post" enctype="multipart/form-data">
					<div class="gmenu"><p>
					<b>Title Blogs:</b><br />
					<input type="text" name="name" value="' . htmlentities($row['name'], ENT_QUOTES, 'UTF-8') . '" /><br />
					<small>Min. 2, max. 150 character</small><br />
					<b>Blogs text:</b><br />
					<textarea name="text" cols="24" rows="4">' . htmlentities($row['text'], ENT_QUOTES, 'UTF-8') . '</textarea><br />
					<small>Min. 2, max. 5000 character</small><br />
					<b>Select category:</b><br />
					<select name="cat">';
					$req = $db->query("SELECT * FROM `blogs_cat` ORDER BY `realid` ASC");
					while (($rows = $req->fetch()) !== false) {
						echo '<option value="' . $rows['id'] . '"' . ($rows['id'] == $row['refid'] ? ' selected="selected"':'') . '>' . htmlentities($rows['name'], ENT_QUOTES, 'UTF-8') . '</option>';
					}
					echo '</select><br /><b>Date:</b><br />
					<table><tr>
					<td><span style="text-decoration: underline;">Date:</span><br />
					<input type="text" value="' . $day . '" size="2" maxlength="2" name="day" />.</td>
					<td><span style="text-decoration: underline;">Mounth</span><br />
					<input type="text" value="' . $month . '" size="2" maxlength="2" name="month" />.</td>
					<td><span style="text-decoration: underline;">Year</span><br />
					<input type="text" value="' . $year . '" size="4" maxlength="4" name="year" />-</td>
					<td><span style="text-decoration: underline;">Hour</span><br />
					<input type="text" value="' . $hour . '" size="2" maxlength="2" name="hour" />:</td>
					<td><span style="text-decoration: underline;">Minute</span><br />
					<input type="text" value="' . $minutes . '" size="2" maxlength="2" name="minutes" /></td>
					</tr></table>
					<small>Date on system: ' . date('d.m.o / H:i', time() + $sdvigclock * 3600) . '<br />
					 Date content to display blog for a specified time</small><br />
					<b>Image blogs:</b><br />
					<input type="file" name="imagefile"/><br />
					<small>Format allowed: GIF, JPEG, JPG, PNG max.data 1000 kb<br />
					</small><br />
					<input type="hidden" name="MAX_FILE_SIZE" value="' . (1024 * $config['flsz']) . '" />
					</p><p><input type="submit" value="Edit" name="submit" />
					</p></div></form>';
				}
			} else {
				echo '<div class="rmenu">Blogs not found</div>';
			}
		} else {
			echo '<div class="rmenu">Blogs not selected</div>';
		}
		echo '<div class="phdr"><a href="manage.php">Manage Blogs</a></div>';
		break;
	
	
	
	default:
	$total = $db->query("SELECT COUNT(*) FROM `blogs_cat`")->fetchColumn();
	if($total) {
		$req = $db->query("SELECT `id`, `name` FROM `blogs_cat`
		ORDER BY `realid` ASC LIMIT "
					  . $start . "," . $kmess);
		$i = 1;
		while (($row = $req->fetch()) !== false) {
			echo $i % 2 ? '<div class="list1">' : '<div class="list2">';
			if(file_exists(ROOT_PATH . 'blogs/icon/ico_cat_' . $row['id'] . '.jpg'))
				echo '<a href="index.php?act=blogs&amp;mod=ico&amp;id=' . $row['id'] . '"><img style="margin: 0 0 -3px 0;border: 0px;" src="../blogs/icon/ico_cat_' . $row['id'] . '.jpg" alt="" width="16" height="16"/></a>&#160;';
			echo htmlentities($row['name'], ENT_QUOTES, 'UTF-8') . ' <a href="index.php?id=' . $row['id'] . '">&raquo;</a>';
			echo '<div class="sub">
			<a href="manage.php?act=up&amp;id=' . $row['id'] . '">Up</a> | <a href="manage.php?act=down&amp;id=' . $row['id'] . '">Down</a> | <a href="manage.php?act=edit&amp;id=' . $row['id'] . '">Edit</a> | <a href="manage.php?act=delete&amp;id=' . $row['id'] . '">Remove</a>
			</div>';
			echo '</div>';
			++$i;
		}
		echo '<div class="phdr">Total Category: ' . $total . '</div>';
		if ($total > $kmess) {
			echo '<p>' . $tools->displayPagination('manage.php?', $start, $total, $kmess) . '</p>';
			echo '<p><form action="index.php" method="get">
			<input type="hidden" name="act" value="mod_news"/>
			<input type="text" name="page" size="2"/>
			<input type="submit" value="To page &gt;&gt;"/></form></p>';
		}
	} else {
		echo '<div class="rmenu">Category empty</div>';
	}
	echo '<div class="gmenu"><form action="manage.php?act=add" method="post"><input type="submit" value="Add Category" /></form></div>';
	if($total) {
		echo '<div class="gmenu"><form action="write.php" method="post"><input type="submit" value="Add Blogs" /></form></div>';
		echo '<div class="bmenu"><a href="manage.php?act=list">Blogs List</a></div>';
		echo '<div class="bmenu"><a href="manage.php?act=clear">Remove Blog</a></div>';
	}
	
}
}
else { echo '<div class="rmenu"><center><b>Sorry access only for admin!</b></center></div>';
}
echo '<p class="menu"><a href="index.php">Back</a></p>';
require_once('../system/end.php');
?>