<?php
/********************************************************
	sNews 1.5.26 RC
	Copyright (C) 2006 Solucija.com - All Rights Reserved
	sNews is licensed under a Creative Commons License
	http://creativecommons.org/licenses/by/2.5/
*********************************************************/

/*** CONFIGURATION VARIABLES ***/

error_reporting(E_ALL ^ E_NOTICE);

// DATABASE VARIABLES
function db($variable) {
	$db = array();
	$db['website'] = 'http://localhost/sNews/';
	$db['dbhost'] = 'localhost'; //MySQL Host
	$db['dbname'] = 'snews'; //Database Name
	$db['dbuname'] = 'root'; //Database Username
	$db['dbpass'] = ''; //Database password
	$db['prefix'] = ''; //Database prefix
	$db['dberror'] = '<strong>There was an error while connecting to the database.</strong> <br /> Check your database settings.'; //Database error message
	return $db[$variable];
}

// LANGUAGE VARIABLES
function l($variable) {
	if (s('language') != 'EN' && file_exists('snews_'.s('language').'.php')) {include('snews_'.s('language').'.php');} else {
	$l = array();
	
	#SITE LANGUAGE VARIABLES
	$l['home'] = 'Home';
	$l['home_sef'] = 'home'; //home SEF
	$l['archives'] = 'Archive';
	$l['rss_feed'] = 'RSS Feed';
	$l['contact'] = 'Contact';
	$l['sitemap'] = 'Site Map';
	$l['divider'] = '&middot;'; //divider character
	$l['image_folder'] = 'img';
	#categories
	$l['cat_listSEF'] = 'home,archives,contact,sitemap,rss,gallery,login,administration,add_category,add_article,article_new,side_new,page_new,categories,articles,extra_contents,pages,settings,files,logout'; //SEF links of the hardcoded categories
	$l['month_names'] = 'January, February, March, April, May, June, July, August, September, October, November, December';
	#search
	$l['search_keywords'] = 'Search Keywords';
	$l['search_button'] = 'Search';
	$l['search_results'] = 'Search results';
	$l['charerror'] = 'At least 4 characters are needed to perform the search.';
	$l['noresults'] = 'There are no results for query ';
	$l['resultsfound'] = 'results were found for query';
	#comments
	$l['addcomment'] = 'Write a comment';
	$l['comments'] = 'Comments';
	$l['comment'] = 'Comment';
	$l['page'] = 'Page';
	#paginator
	$l['first_page'] = 'First';
	$l['last_page'] = 'Last';
	$l['previous_page'] = 'Previous';
	$l['next_page'] = 'Next';
	$l['name'] = 'Name';
	#comments
	$l['comment_sent'] = 'Your comment has been sent';
	$l['comment_sent_approve'] = 'Your comment is waiting moderation.';
	$l['comment_error'] = 'Your comment was not sent';
	$l['comment_back'] = 'Back to your comment';
	$l['no_comment'] = 'This article hasn\'t been commented yet.';
	$l['ce_reasons'] = '<strong>Possible reasons:</strong> You left blank column or the comment is too short.';
	$l['url'] = 'Website URL';
	#contact
	$l['email'] = 'Email';
	$l['message'] = 'Message';
	$l['contact_sent'] = 'Thank you, your message has been sent.';
	$l['contact_not_sent'] = 'Your message was not sent';
	$l['message_error'] = '<strong>Possible reasons:</strong> You left name or message field blank, or email address does not exist.';
	#generic links
	$l['backhome'] = 'Back home';
	$l['backarticle'] = 'Back to article';
	$l['read_more'] = 'Read more';
	#contents error
	$l['article_not_exist'] = 'Requested contents does not exist';
	$l['category_not_exist'] = 'Requested category does not exist';
	
	#ADMINISTRATION LANGUAGE VARIABLES
	#administration
	$l['administration'] = 'Administration';
	$l['manage'] = 'Manage';
	$l['articles'] = 'Articles';
	$l['extra_contents'] = 'Extra contents';
	$l['pages'] = 'Pages';
	#basic buttons
	$l['view'] = 'View';
	$l['add_new'] = 'Add new';
	$l['article_new'] = 'New Article';
	$l['side_new'] = 'New Extra Contents';
	$l['page_new'] = 'New Page';
	$l['edit'] = 'Edit';
	$l['delete'] = 'Delete';
	$l['save'] = 'Save';
	$l['submit'] = 'Submit';
	#settings
	$l['settings'] = 'Settings';
	$l['site_settings'] = 'Site';
	#login
	$l['login_status'] = 'Login status';
	$l['login'] = 'Login';
	$l['username'] = 'Username';
	$l['password'] = 'Password';
	$l['logged_in'] = 'You are Logged In';
	$l['log_out'] = 'Logging out';
	$l['logout'] = 'Logout';
	#categories
	$l['categories'] = 'Categories';
	$l['category'] = 'Category';
	$l['appear_category'] = 'Appear only on Category';
	$l['appear_page'] = 'Appear only on Page';
	$l['add_category'] = 'New category';
	$l['category_order'] = 'Category order';
	$l['order_category'] = 'Reorder';
	$l['description'] = 'Description';
	$l['publish_category'] = 'Publish category';
	$l['status'] = 'Status:';
	$l['published'] = 'Published';
	$l['unpublished'] = '<span style="color: #FF0000">Unpublished</span>';
	#articles
	$l['articles'] = 'Articles';
	$l['article'] = 'Article';
	$l['newarticle'] = 'New Article';
	$l['article_date'] = 'Article date (enter a higher date for future posting)';
	$l['preview'] = 'Preview';
	$l['view'] = 'View';
	$l['paginator'] = 'p';
	#customize article
	$l['customize'] = 'Customize';
	$l['display_title'] = 'Display title';
	$l['display_info'] = 'Display info line (read more/ comments/ date)';
	$l['server_time'] = 'Time on Server';
	$l['future_posting'] = '<span style="color: #FF9900;">Future posting</span>';
	$l['publish_date'] = 'Publish Date';
	$l['day'] = 'Day';
	$l['month'] = 'Month';
	$l['year'] = 'Year';
	$l['hour'] = 'Hour';
	$l['minute'] = 'Minute';
	$l['publish_article'] = 'Publish article';
	$l['operation_completed'] = 'Operation completed succesfully!';
	$l['deleted_success'] = 'Succesfuly deleted';
	#files
	$l['files'] = 'Files';
	$l['attach_image'] = 'Attach image';
	$l['upload_image'] = 'Upload Image';
	$l['upload'] = 'Upload';
	$l['no_image'] = 'No image';
	$l['image_error'] = 'Image could not be copied';
	$l['deleted'] = 'File deleted!';
	#comments
	$l['comments'] = 'Comments';
	$l['enable_commenting'] = 'Enable comments';
	$l['edit_comment'] = 'Edit comment';
	$l['freeze_comments'] = 'Freeze comments';
	$l['unfreeze_comments'] = 'Unfreeze comments';
	$l['enable'] = 'Enable';
	$l['approved'] = 'Approved';
	$l['enabled'] = 'Enabled';
	$l['disabled'] = 'Disabled';
	#article structure
	$l['title'] = 'Title';
	$l['sef_title'] = 'Search engine friendly title (will be used as link to the article)';
	$l['sef_title_cat'] = 'Search engine friendly title (will be used as link to the category)';
	$l['text'] = 'Text';
	$l['position'] = 'Position';
	$l['display_page'] = 'Page';
	$l['center'] = 'Center';
	$l['contents'] = 'Contents';
	$l['side'] = 'Extra contents';
	#errors
	$l['error_not_logged_in'] = 'You are not currently logged in and so are not allowed to do that.';
	$l['admin_error'] = 'Error';
	$l['back'] = 'Back';
	$l['err_TitleEmpty'] = 'The Title cannot be empty.';
	$l['err_TitleExists'] = 'The Title already exists.';
	$l['err_SEFEmpty'] = 'The SEF Title cannot be empty.';
	$l['err_SEFExists'] = 'The SEF Title already exists.';
	$l['err_SEFIllegal'] = 'The SEF title you entered contains illegal characters.<br />You can only use <strong>a-z 0-9_-</strong><br />A new SEF url has been selected from the title. Please check it.';
	$l['errNote'] = '<strong>Be carefull:</strong> Due to the fact that when something goes wrong most posting options are lost, please check them before posting again.';
	$l['warning_delete'] = 'Are you sure you want to delete this?';
	$l['image_url'] = 'Enter Image URL';
	$l['image_alt'] = 'Enter Image Alt';
	$l['file_url'] = 'Enter File URL';
	#settings form
	$l['a_true'] = 'True';
	$l['a_false'] = 'False';
	$l['none'] = "None";
	$l['change_up'] = 'Change Username and Password';
	$l['newer_top'] = 'Newer on top';
	$l['newer_bottom'] = 'Newer on bottom';
	$l['pass_mismatch'] = 'Passwords do not match';
	$l['a_username'] = 'Username';
	$l['a_password'] = 'Password';
	$l['a_password2'] = 'Repeat password';
	$l['a_prefix'] = 'Database prefix';
	$l['a_home'] = 'Home title';
	$l['a_display_page'] = "Use Page as Home Page";
	$l['a_display_new_on_home'] = 'Display new Articles on home';
	$l['a_display_pagination'] = 'Display Pagination on articles';
	$l['a_website_title'] = 'Website Title';
	$l['a_home_sef'] = 'Home SEF (used as link to <em>Home</em>)';
	$l['a_website_email'] = 'Email';
	$l['a_description'] = 'Default description META Tag (for search engines)';
	$l['a_keywords'] = 'Default keywords META Tag (keywords separated by comma)';
	$l['a_contact_info'] = 'Contact info';
	$l['a_contact_subject'] = 'Contact Form Subject';
	#file inclusion
	$l['a_word_filter_file'] = 'Badwords filter file';
	$l['a_word_filter_change'] = 'Badwords replacement word';
	$l['a_word_filter_enable'] = 'Enable Badwords filter';
	$l['file_include_extensions'] = 'php,txt,inc';
	$l['error_file_name'] = '<br /><span style="color: #FF0000; font-weight: bold;">Include Error: Forbidden file name</span><br />';
	$l['error_file_exists'] = '<br /><span style="color: #FF0000; font-weight: bold;">Include Error: File doesn\'t exists</span><br />';
	$l['a_num_categories'] = 'Display number of articles next to a category';
	$l['charset'] = 'Default charset';
	$l['a_time_settings'] = 'Time and Locale settings';
	$l['a_date_format'] = 'Date Format';
	$l['a_comments_order'] = 'Comments Order';
	$l['a_comment_limit'] = 'Comment results per page';
	$l['a_rss_limit'] = 'RSS Articles Limit';
	$l['a_approve_comments'] = 'Approve comments before publishing';
	$l['a_approve'] = 'Approve';
	$l['a_article_limit'] = 'Articles per page limit';
	$l['a_language'] = 'sNews Language';
	$l['description_meta'] = 'Description META Tag (for search engines)';
	$l['keywords_meta'] = 'Keywords META Tag (keywords separated by comma)';
	$l['all'] = 'All';
	} return $l[$variable];
}

// INFO LINE TAGS (readmore, comments, date)
function tags($tag) {
	$tags = array(); $tags['infoline'] = '<p class="date">,readmore,comments,date,edit,</p>';
	$tags['comments'] = '<div class="comment">,<p class="date">,name, on ,date,edit,</p>,<p>,comment,</p>,</div>';
	return $tags[$tag];
}

/*** END OF SETTINGS & VARIABLES, EDIT BELOW THIS LINE ONLY IF YOU KNOW WHAT YOU'RE DOING ***/

// SITE SETTINGS - grab settings from database
function s($variable) {
	$query = "SELECT value FROM ".db('prefix')."settings WHERE name = '$variable'";
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {$value = $r['value'];}
	return $value;
}

// STARTUP
function snews_startup() {
	connect_to_db();
	if (get_id('category') == "rss") { rss(); die; }
	update_articles();
	if (isset($_POST['Loginform']) == 'True') {
		if (clean($_POST['uname']) == s('username') && md5(clean($_POST['pass'])) == s('password')) {
			$_SESSION[db('website').'Logged_In'] = 'True'; $_SESSION['uname'] = s('username'); $_SESSION['Website'] = db('website');
}}}
snews_startup();

// TITLE
function title() {
	echo '<base href="'.db('website').'" />';
	$categorySEF = get_id('category'); $articleSEF = get_id('article');
	$categoryName = retrieve('name', 'categories', 'seftitle', $categorySEF);
	$articleTitle = retrieve('title', 'articles', 'seftitle', $articleSEF);
	$title = s('website_title');
	if (!empty($categoryName)) {$title .= ' '.l('divider').' '.$categoryName;}
	if (!empty($articleTitle)) {$title .= ' '.l('divider').' '.$articleTitle;}
	echo '<title>'.$title.'</title>';
	echo '<meta http-equiv="Content-Type" content="text/html; charset='.s('charset').'" />';
	if (!empty($articleSEF)) {
		$query = "SELECT * FROM ".db(prefix)."articles WHERE seftitle = '$articleSEF'";
		$result = mysql_query($query);
		while ($r = mysql_fetch_array($result)) {$dmeta = $r['description_meta']; $kmeta = $r['keywords_meta'];}
	}
	echo '<meta name="description" content="'.(!empty($dmeta) ? $dmeta : s('website_description')).'" />';
	echo '<meta name="keywords" content="'.(!empty($kmeta) ? $kmeta : s('website_keywords')).'" />';
	if (isset($_SESSION[db('website').'Logged_In'])) {js();}
}

//BREADCRUMBS
function breadcrumbs() {
	$link = '<a href="'.db('website').'';
	if ($_SESSION[db('website').'Logged_In'] == 'True') {echo $link.'administration/" title="'.l('administration').'">'.l('administration').'</a> '.l('divider').' ';}
	$categorySEF = get_id('category'); $articleSEF = get_id('article'); $home = s('home_sef');
	echo (!empty($categorySEF) || $categorySEF == $home || !empty($articleSEF)) ? $link.'" title="'.l('home').'">'.l('home').'</a>' : l('home');
	$categoryName = retrieve('name', 'categories', 'seftitle', $categorySEF);
	if (!empty($categoryName)) {
		echo ' '.l('divider').' '.(!empty($articleSEF) ? $link.$categorySEF.'/" title="'.$categoryName.'">'.$categoryName.'</a>' : $categoryName);
	}
	$articleTitle = retrieve('title', 'articles', 'seftitle', $articleSEF);
	if (!empty($articleTitle)) {echo ' '.l('divider').' '.$articleTitle;}
	if (check_category($categorySEF) == true && $categorySEF != $home && $categorySEF != 'administration') {echo ' '.l('divider').' '.l($categorySEF);}
}

// LOGIN LOGOUT LINK
function login_link() {
	$login = '<a href="'.db('website').'';
	$login .= isset($_SESSION[db('website').'Logged_In']) ? 'administration/" title="'.l('administration').'">'.l('administration').'' : 'login/" title="'.l('login').'">'.l('login').'';
	$login .= '</a>';
	echo $login;
}

// DISPLAY CATEGORIES
function categories() {
	$categorySEF = get_id('category');
	echo '<li><a'.$class.' href="'.db('website').'" title="'.s('website_title').'">'.l('home').'</a></li>';
	$query = "SELECT * FROM ".db('prefix')."categories WHERE published = 'YES' ORDER BY catorder ASC"; 
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {
		$calc_num_query = "SELECT * FROM ".db('prefix')."articles WHERE position = 1 AND category = $r[id]"; 
		$cm_result = mysql_query($calc_num_query);
		$num_rows = mysql_num_rows($cm_result);
		if ($num_rows > 0) {
			$category_title = $r['seftitle'];
			$class = $category_title == $categorySEF  ? ' class="current"' : '';
			echo '<li><a'.$class.' href="'.db('website').$category_title.'/" title="'.$r['description'].'">'.$r['name'];
			echo s('num_categories') == 'on' ? ' ('.$num_rows.')' : '';
			echo '</a></li>';
		}
	}
}

// DISPLAY PAGES
function pages() {
	$categorySEF = get_id('category');
	$pageSEF = get_id('article');
	$home = s('home_sef');
	$class = (empty($categorySEF) || $categorySEF == $home && empty($pageSEF)) ? ' class="current"' : '';
	echo '<li><a'.$class.' href="'.db('website').'" title="'.(!empty($class) ? 'You\'re currently browsing '.l('home') : l('home')).'">'.l('home').'</a></li>';
	$class = ($categorySEF == 'archives') ? ' class="current"' : '';
	echo '<li><a'.$class.' href="'.db('website').'archives/" title="'.l('archives').'">'.l('archives').'</a></li>';
	$query = "SELECT * FROM ".db('prefix')."articles WHERE position = 3 ORDER BY id"; 
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {
		$class = ($pageSEF == $r['seftitle'])? ' class="current"' : '';
		if ($r['id'] != s('display_page')) {echo '<li><a'.$class.' href="'.db('website').s('home_sef').'/'.$r['seftitle'].'/" title="'.$r['title'].'">'.$r['title'].'</a></li>';}
	}
	$class = ($categorySEF == 'contact') ? ' class="current"': '';
	echo '<li><a'.$class.' href="'.db('website').'contact/" title="'.l('contact').'">'.l('contact').'</a></li>';
	$class = ($categorySEF == 'sitemap') ? ' class="current"': '';
	echo '<li><a'.$class.' href="'.db('website').'sitemap/" title="'.l('sitemap').'">'.l('sitemap').'</a></li>';
}

//EXTRA CONTENT
function extra() {
	$categorySEF = get_id('category');
	$categoryId = (check_category($categorySEF) == true || empty($categorySEF) || $categorySEF == s('home_sef')) ? 0 : retrieve('id', 'categories', 'seftitle', $categorySEF);
	$pageSEF = get_id('article');
	$pageId = (empty($categorySEF)) ? 0 : retrieve('id', 'articles', 'seftitle', $pageSEF);
	$query = "SELECT * FROM ".db('prefix')."articles WHERE SUBSTRING(position, 1, 1) = '2' AND published = 1 ORDER BY id DESC";
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {
		$pos = $r['position']; $pos_depend = substr($pos, 1, 1); $pos_artID = substr($pos, 2);
		switch (true) {
			case ($pos_depend == 0 && $categoryId == 0): $print = true; break;
			case ($pos_depend == 1 && $categoryId == $pos_artID): $print = true; break;
			case ($pos_depend == 2 && $pageId == $pos_artID): $print = true; $category = -1; break;
			case ($pos_depend != 2 && $r['category'] == -1): $print = true; break; default: $print = false;
		}
		if ($print == true) {
			echo $r['displaytitle'] == 'YES' ? '<h3>'.$r['title'].'</h3>' : '';
			file_include($r['text'], 99990000);
			echo $_SESSION[db('website').'Logged_In'] == 'True' ? '<p><a href="'.db('website').'index.php?action=edit_article&amp;id='.$r['id'].'" title="'.l('edit').' '.$r['seftitle'].'">'.l('edit').'</a></p>' : '';
}}}

// PAGINATOR
function paginator($category, $pageNum, $maxPage, $article, $pagePrefix) {
	$link = ' <a href="'.db('website').$category.'/';
	if (!empty($article)) {$link .= $article.'/';}
	$prefix = !empty($pagePrefix) ? $pagePrefix : '';
	if ($pageNum > 1) {
		$goTo = !empty($article) ? $link : '<a href="'.db('website');
		if (($pageNum - 1) == 1) {$prev = $goTo.'" title="'.l('page').' '.($pageNum - 1).'">&lt; '.l('previous_page').'</a> ';}
		else {$prev = $link.$prefix.($pageNum - 1).'/" title="'.l('page').' '.($pageNum - 1).'">&lt; '.l('previous_page').'</a> ';}
		$first = $goTo.'" title="'.l('first_page').' '.l('page').'">&lt;&lt; '.l('first_page').'</a>';
    }
	else {$prev = '&lt; '.l('previous_page'); $first = '&lt;&lt; '.l('first_page');}
	if ($pageNum < $maxPage) {
		$next = $link.$prefix.($pageNum + 1).'/" title="'.l('page').' '.($pageNum + 1).'">'.l('next_page').' &gt;</a> ';
		$last = $link.$prefix.$maxPage.'/" title="'.l('last_page').' '.l('page').'">'.l('last_page').' &gt;&gt;</a> ';
	}
	else {$next = l('next_page').' &gt; '; $last = l('last_page').' &gt;&gt;';}
	echo '<div class="paginator">'.$first.' '.$prev.' <strong>  ['.$pageNum.'</strong> / <strong>'.$maxPage.']  </strong> '.$next.' '.$last.'</div>';
}

// CENTER			
function center() {
	if (isset($_GET['category'])) {$id = $action = $_GET['category'];}
	if (isset($_GET['articleid'])) {$articleid = $_GET['articleid'];}
	if (isset($_POST['submit_text'])) {processing(); $processed = true;}
	if (isset($_POST['contactform'])) {contact(); $processed = true;}
	if (isset($_POST['search_query'])) {search(); $processed = true;} 
	if (isset($_POST['comment'])) {comment('comment_posted'); $processed = true;}
	if (isset($_POST['Loginform']) == 'True') {administration(); $processed = true;}
	else if (isset($_GET['action'])) {$action = $_GET['action'];}
	if (isset($processed) and $processed == true) {unset($action);}

	switch ($action) {
	case 'archives': archives(); break;
	case 'sitemap': sitemap(); break;
	case 'contact': contact(); break;
	case 'login': login(); break;
	case 'administration': if (isset($_SESSION[db('website').'Logged_In'])) {administration();}	break;
	case 'settings': if (isset($_SESSION[db('website').'Logged_In'])) {settings();} break;
	case 'categories': if (isset($_SESSION[db('website').'Logged_In'])) {admin_categories();} break;
	case 'add_category': if (isset($_SESSION[db('website').'Logged_In'])) {form_categories();} break;
	case 'edit_category': if (isset($_SESSION[db('website').'Logged_In'])) {form_categories();} break;
	case 'articles': if (isset($_SESSION[db('website').'Logged_In'])) {admin_articles('article_view');} break;
	case 'extra_contents': if (isset($_SESSION[db('website').'Logged_In'])) {admin_articles('side_view');} break;
	case 'pages': if (isset($_SESSION[db('website').'Logged_In'])) {admin_articles('page_view');} break;
	case 'article_new': if (isset($_SESSION[db('website').'Logged_In'])) {form_articles('article_new');} break;
	case 'side_new': if (isset($_SESSION[db('website').'Logged_In'])) {form_articles('side_new');} break;
	case 'page_new': if (isset($_SESSION[db('website').'Logged_In'])) {form_articles('page_new');} break;
	case 'edit_article': if (isset($_SESSION[db('website').'Logged_In'])) {form_articles('');} break;
	case 'editcomment': if (isset($_SESSION[db('website').'Logged_In'])) {edit_comment();} break;
	case 'files': if (isset($_SESSION[db('website').'Logged_In'])) {files();} break;
	case 'process': if (isset($_SESSION[db('website').'Logged_In']) && $display_further <> 'NO') {processing();} break;	
	case 'logout': session_destroy();
		echo '<meta http-equiv="refresh" content="1; url='.db('website').'">';
		echo '<h2>'.l('log_out').'</h2>';
	break;
	default:
		if ($processed == false) {
			$article = get_id('article');
			$currentPage = strpos($article, l('paginator')) === 0 ? str_replace(l('paginator'), '', $article) : '';
			$home = s('home_sef'); $categorySEF = get_id('category');
			$categorySEF = empty($categorySEF) ? $home : $categorySEF;
			$use_cat_id = $categorySEF == $home ? 0 : retrieve('id', 'categories', 'seftitle', $categorySEF);
			$query_articles = "SELECT * FROM ".db('prefix')."articles WHERE published = 1 AND SUBSTRING(position, 1, 1) != '2'";
  			if (!empty($article) && empty($currentPage)) {$query_articles .= " AND seftitle = '$article'";}
			else if ($categorySEF == $home && s('display_page') <> 0) {$id_page = s('display_page'); $query_articles .= " AND id = '$id_page'";}
  			else {
				if (s('display_new_on_home') == 'on') {$query_articles .= $use_cat_id != 0 ? " AND category = $use_cat_id" : '';}
				else {$query_articles .= " AND category = $use_cat_id";}
				$query_articles .= " AND position <> 3 ORDER BY date DESC";
				$result_articles = mysql_query($query_articles);
				$numrows_articles = mysql_num_rows($result_articles);
				if ($result_articles && $numrows_articles) {
					$articleCount = s('article_limit');
					$article_limit = (empty($articleCount) || $articleCount < 1) ? 100 : $articleCount;
					$totalPages = ceil($numrows_articles/$article_limit);
					if (!isset($currentPage) || !is_numeric($currentPage) || $currentPage < 1) {$currentPage = 1;}
					else if ($currentPage > $totalPages) {$currentPage = $totalPages;}
					$query_articles .= " LIMIT ".($currentPage - 1) * $article_limit.", ".$article_limit;
				}
			}
			$result = mysql_query($query_articles);
			$numrows = mysql_num_rows($result);
			if (!$result || !$numrows) {echo '<h2>'.l('article_not_exist').'</h2>';}
			else {
				while ($r = mysql_fetch_array($result)) {
					$infoline = $r['displayinfo'] == 'YES' ? true : false;
					if (!empty($currentPage)) {$short_display = strpos($r['text'], '[break]'); $shorten = $short_display == 0 ? 9999000 : $short_display;}
					else {$shorten = 9999000;}
					$comments_query = "SELECT * FROM ".db('prefix')."comments WHERE articleid = $r[id] AND approved = 'True'";
					$comments_result = mysql_query($comments_query);
					$comments_num = mysql_num_rows($comments_result);
					$a_date_format = date(s('date_format'), strtotime($r['date']));
      				$position = $r['position'];
					$category = $r['category'] == 0 ? $home : retrieve('seftitle', 'categories', 'id', $r['category']);
					if ($r['displaytitle'] == 'YES') {
							echo '<h2>';
							if (strlen($r['text']) > $shorten) {
								echo '<a href="'.db('website').$category.'/'.$r['seftitle'].'/" title="'.$r['title'].'">'.$r['title'].'</a>';
							} else {echo $r['title'];}
							echo '</h2>';
						}
					file_include(str_replace('[break]', '', $r['text']), $shorten);
					$commentable = $r['commentable']; 
					if (!empty($currentPage)) {
						$tag = explode(',', tags('infoline'));
						$link = '<a href="'.db('website');
						$edit_link = $link.'index.php?action=edit_article&amp;id='.$r['id'].'" title="'.l('edit').' '.$r['title'].'">'.l('edit').'</a>';
						if ($infoline == true) {
							foreach ($tag as $tag) {
								switch (true) {
									case ($tag == 'date'): echo $a_date_format; break;
									case ($tag == 'readmore' && strlen($r['text']) > $shorten):
										echo $link.$category.'/'.$r['seftitle'].'/" title="'.l('read_more').'">'.l('read_more').'</a> '; break;
									case ($tag == 'comments' && ($commentable == 'YES' || $commentable == 'FREEZ')):
										echo $link.$category.'/'.$r['seftitle'].'/#'.l('comment').'1" title="'.l('comments').'">'.l('comments').' ('.$comments_num.')</a> '; break;
									case ($tag == 'edit' && $_SESSION[db('website').'Logged_In'] == 'True'): echo ' '.$edit_link; break;
									case ($tag != 'readmore' && $tag != 'comments' && $tag != 'edit'): echo $tag; break;
								}
							}
						}
						else if ($_SESSION[db('website').'Logged_In'] == 'True') {echo '<p>'.$edit_link.'</p>';}
					}
					else if (substr($position, 0, 1) != 2 && empty($currentPage)) {
						$edit_link = '<a href="'.db('website').'index.php?action=edit_article&amp;id='.$r['id'].'" title="'.l('edit').' '.$r['title'].'">'.l('edit').'</a>';
						if ($infoline == true) {
							$tag = explode(',', tags('infoline'));
								foreach ($tag as $tag ) {
									switch ($tag) {
										case 'date': echo $a_date_format; break;
										case 'readmore':
										case 'comments': ; break;
										case 'edit': if ($_SESSION[db('website').'Logged_In'] == 'True') {echo '&nbsp; '.$edit_link;} break;
										default: echo $tag;
									}
								}
						}
						else if ($_SESSION[db('website').'Logged_In'] == 'True') {echo '<p>'.$edit_link.'</p>';}
					}
				}
				if (!empty($currentPage) && ($numrows_articles > $article_limit) && s('display_pagination') == 'True') {
					paginator($categorySEF, $currentPage, $totalPages, '', l('paginator'));
				}
				if (!empty($article) && empty($currentPage) && $infoline == true) {
					if ($commentable == 'YES') {comment('unfreezed');}
					else if ($commentable == 'FREEZ') {comment('freezed');}
}}}}}

// COMMENTS
function comment($freeze_status) {
	$categorySEF = get_id('category'); $articleSEF = get_id('article');
	if (strpos($articleSEF, l('paginator')) === 0) {$articleSEF = str_replace(l('paginator'), '', $articleSEF);}
	$query = "SELECT id FROM ".db('prefix')."articles WHERE seftitle = '$articleSEF'";
	$result = mysql_query($query);
  	while ($r = mysql_fetch_array($result)) {$articleId = $r['id'];}
	$commentsPage = get_id('commentspage');
	if (!isset($commentsPage) || !is_numeric($commentsPage) || $commentsPage < 1) {$commentsPage = 1;}
	$comments_order = s('comments_order');
	if (isset($_POST['comment'])) {
		$comment = cleanXSS($_POST['text']);
		$name = clean(cleanXSS($_POST['name']));
		$url = strtolower(clean(cleanXSS($_POST['url'])));
		if ($_POST['ip'] == $_SERVER['REMOTE_ADDR'] && (time() - $_POST['time']) > 4 && strlen($comment) >= 5 && strlen($name) >= 2 && is_numeric($_POST['id'])) {
			$url = (preg_match('/((http)+(s)?:(\/\/)|(www\.))([a-z0-9_\-]+)/', $url) && strpos($url, ' ') === false && strpos($url, '?') === false) ? $url : '';
			$url = substr($url, 0, 3) == 'www' ? 'http://'.$url : $url;
			$time = date("Y-m-d H:i:s");
			$post_article_id = cleanXSS($_POST['id']);
			if(s('approve_comments') != 'on') {$approved = 'True';}
			$query = "INSERT INTO ".db('prefix')."comments(articleid, name, url, comment, time, approved) VALUES('$post_article_id', '$name', '$url', '$comment', '$time', '$approved')";
			mysql_query($query);
			$commentStatus = s('approve_comments') == 'on' ? l('comment_sent_approve') : l('comment_sent');
		}
		else {$commentStatus = l('comment_error'); $commentReason = l('ce_reasons');}
		echo '<h2>'.$commentStatus.'</h2>';
		if (!empty($commentReason)) {echo '<p>'.$commentReason.'</p>';}
		$back_link = db('website').$_POST['category'].'/'.$_POST['article'].'/';
		echo '<p><a href="'.$back_link;
		if (isset($_POST['commentspage']) && is_numeric($_POST['commentspage'])) {$go_to_page = $_POST['commentspage'];}
		if ($comments_order != 'DESC') {echo $go_to_page > 1 ? $go_to_page.'/' : ''; echo '" title="'.l('comment_back').'">';}
		else {echo '" title="'.l('comment_back').'">';}
		echo l('backarticle').'</a></p>';
		echo '<meta http-equiv="refresh" content="2; url='.$back_link.($go_to_page > 1 ? $go_to_page.'/' : '').'">';
	}
	else {
		$commentCount = s('comment_limit');
		$comment_limit = (empty($commentCount) || $commentCount < 1) ? 100 : $commentCount;
		if(isset($commentsPage)) {$pageNum = $commentsPage;}
		$offset = ($pageNum - 1) * $comment_limit;
		$totalrows = "SELECT id FROM ".db('prefix')."comments WHERE articleid = $articleId AND approved = 'True'";
		$rowsresult = mysql_query($totalrows);
		$numrows = mysql_num_rows($rowsresult);
		if (!$numrows || !$rowsresult) {
			if ($freeze_status != 'freezed') {echo '<p>'.l('no_comment').'</p>';}
		}
		else {
			$query = "SELECT * FROM ".db('prefix')."comments WHERE articleid = $articleId AND approved = 'True' ORDER BY id $comments_order LIMIT $offset, $comment_limit";
			$result = mysql_query($query) or die(db('dberror'));
			$ordinal = 1;
			$date_format = s('date_format');
			while ($r = mysql_fetch_array($result)) {
				$date = date($date_format, strtotime($r['time']));
				$commentNum = $offset + $ordinal;
				$tag = explode(',', tags('comments'));
				$edit_link = '&nbsp; <a href="'.db('website').'index.php?action=';
				foreach ($tag as $tag) {
					switch (true) {
						case ($tag == 'date'):
							echo '<a id="'.l('comment').$commentNum.'" name="'.l('comment').$commentNum.'" title="'.l('comment').' '.$commentNum.'"></a>'.$date;
							break;
						case ($tag == 'name'): echo !empty($r['url']) ? '<a href="'.$r['url'].'" title="'.$r['url'].'" rel="nofollow">'.$r['name'].'</a> ' : $r['name']; break;
						case ($tag == 'comment'): echo $r['comment']; break;
						case ($tag == 'edit' && $_SESSION[db('website').'Logged_In'] == 'True'):
							echo $edit_link.'editcomment&amp;commentid='.$r['id'].'" title="'.l('edit').' '.l('comment').'">'.l('edit').'</a> ';
							echo $edit_link.'process&amp;task=deletecomment&amp;articleid='.$r['articleid'].'&amp;commentid='.$r['id'].'" title="'.l('delete').' '.l('comment').'" onclick="return pop()">'.l('delete').'</a>';
						break; case ($tag == 'edit'): ; break; default: echo $tag;
					}
				}
				$ordinal++;
			}
			$maxPage = ceil($numrows / $comment_limit); $back_to_page = ceil(($numrows + 1) / $comment_limit);
			if ($maxPage > 1) {paginator($categorySEF, $pageNum, $maxPage, $articleSEF, '');}
		}
		if ($freeze_status != 'freezed') { ?>
			<div class="commentsbox"><h2><?php echo l('addcomment') ?></h2>
			<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
			<p><label for="name">* <?php echo l('name'); ?>:</label><br />
			<input class="text" name="name" type="text" id="name" /></p>
			<p><label for="url"><?php echo l('url'); ?>:</label><br />
			<input class="text" name="url" type="text" id="url" /></p>
  			<p><label for="text">* <?php echo l('comment'); ?>:</label><br />
  			<textarea name="text" id="text" rows="5" cols="5"></textarea></p>
			<p><input name="category" id="category" type="hidden" value="<?php echo $categorySEF; ?>" />
			<input name="id" id="id" type="hidden" value="<?php echo $articleId; ?>" />
			<input name="article" id="article" type="hidden" value="<?php echo $articleSEF; ?>" />
			<input name="commentspage" id="commentspage" type="hidden" value="<?php echo $back_to_page; ?>" />
			<input type="hidden" name="ip" value="<?php echo $_SERVER['REMOTE_ADDR'] ?>">
			<input type="hidden" name="time" value="<?php echo time(); ?>">
  			<input name="comment" type="submit" value="<?php echo l('submit'); ?>" /></p>
  	    	</form></div>
<?php }}}

// ARCHIVES
function archives() {
	echo '<h2>'.l('archives').'</h2><br />';
	$query = "SELECT * FROM ".db('prefix')."articles WHERE position = 1 AND published = 1 ORDER BY date DESC"; 
	$result = mysql_query($query);
	echo '<p>';
	$home = s('home_sef');
	$home_name = l('home');
	$month_names = explode(', ', l('month_names'));
	while ($r = mysql_fetch_array($result)) {
		$year = substr($r['date'], 0, 4);
		$month = substr($r['date'], 5, 2) -1;
		$month_name = (substr($month, 0, 1) == 0) ? $month_names[substr($month, 1, 1)] : $month_names[$month];
		$categorySEF = $r['category'] != 0 ? find_cat_sef($r['category']) : $home;
		$articleSEF = retrieve('seftitle', 'articles', 'id', $r['id']);
		$cat_name = $r['category'] != 0 ? retrieve('name', 'categories', 'seftitle', $categorySEF) : $home_name;
		if ($last <> $year.$month) {echo '<strong>'.$month_name.', '.$year.'</strong><br />';}
		echo l('divider').' <a href="'.db('website').$categorySEF.'/'.$articleSEF.'/" title="'.$r['title'].'">'.$r['title'].'</a> ('.$cat_name.')<br />';
		$last = $year.$month;
	}
	echo '</p>';
}

//SITEMAP
function sitemap() {
	echo '<h2>'.l('sitemap').'</h2>';
	echo '<p><strong>'.l('pages').'</strong></p>';
	$link = l('divider').' <a href="'.db('website');
	echo '<p>'.$link.'" title="'.l('home').'">'.l('home').'</a><br />';
	echo l('divider').' <a href="'.db('website').'archives/">'.l('archives').'</a><br />';
	$query = "SELECT * FROM ".db('prefix')."articles WHERE position = 3 AND published = '1' ORDER BY id"; 
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {
		if ($r['id'] != s('display_page')) { echo l('divider').' <a href="'.db('website').s('home_sef').'/'.$r['seftitle'].'/">'.$r['title'].'</a><br />'; }
	}
	echo $link.'contact/">'.l('contact').'</a><br />';
	echo $link.'sitemap/">'.l('sitemap').'</a><br />';	
	echo $link.'rss/">'.l('rss_feed').'</a></p>';
	echo '<p><strong>'.l('articles').'</strong></p>';
	$art_query = "SELECT * FROM ".db('prefix')."articles WHERE position = 1 AND published = '1'";
	$query = $art_query." AND category = 0 ORDER BY date DESC"; 
	$result = mysql_query($query);
	echo '<p><strong><a href="'.db('website').'" title="'.l('home').'">'.l('home').'</a></strong><br />';
	while ($r = mysql_fetch_array($result)) {
		echo $link.find_cat_sef($r['category']).'/'.$r['seftitle'].'/" title="'.$r['title'].'">'.$r['title'].'</a><br />';
	}
	echo '</p>';
	$cat_query = "SELECT * FROM ".db('prefix')."categories WHERE published = 'YES'"; 
	$cat_result = mysql_query($cat_query);
	while ($c = mysql_fetch_array($cat_result)) {
		echo '<p><strong><a href="'.db('website').$c['seftitle'].'/" title="'.$c['description'].'">'.$c['name'].'</a></strong><br />';
		$catid = $c['id'];
		$query = $art_query." AND category = $catid ORDER BY id DESC";
		$result = mysql_query($query);
		while ($r = mysql_fetch_array($result)) {
			$date = date(s('date_format'), strtotime($r['date']));
			echo $link.$c['seftitle'].'/'.$r['seftitle'].'/" title="'.$r['title'].'">'.$r['title'].'</a><br />';
		}
		echo '</p>';
}}

//NOTIFICATION
function notification($error, $errNote, $link) {
	$errNote = !empty($errNote) ? '<br />'.$errNote : '';
	echo '<h2'.(!empty($error) ? ' class="error">'.l('admin_error').'</h2><p>'.$error.$errNote.'</p>' : '>'.l('operation_completed').'</h2>');
	echo (!empty($link)) ? '<p><a href="'.db('website').$link.'" title="'.l('back').'">'.l('back').'</a></p>' : '';
}

// CONTACT FORM
function contact() {
	if ($_POST['contactform'] == '') {?>
		<div class="commentsbox"><h2><?php echo l('contact'); ?></h2>
		<form method="post" action="">
		<p>* <label for="name"><?php echo l('name'); ?>:</label><br />
		<input name="name" type="text" id="name" class="text" /></p>
		<p>* <label for="email"><?php echo l('email'); ?>:</label><br />
		<input name="email" type="text" id="email" class="text" /><br />
		<p><label for="weblink"><?php echo l('url'); ?>:</label></p>
		<p><input name="weblink" type="text" id="weblink" class="text" /></p>
		<p>* <label for="message"><?php echo l('message'); ?>:</label><br />
  		<textarea name="message" id="message" rows="5" cols="5"></textarea></p>
    	<p><input name="contactform" type="submit" value="<?php echo l('submit'); ?>" /></p>
		</form></div>
  	<?php }
	if (isset($_POST['contactform'])) {
		$to = s('website_email');
		$subject = s('contact_subject');
		$name = clean(cleanXSS($_POST['name']));
		$mail = clean(cleanXSS($_POST['email']));
		$url = clean(cleanXSS($_POST['weblink']));
		$message = clean(cleanXSS($_POST['message']));
		$body = $name.', '.$url.'\n\n'.$message.'\n';
		$from_header = 'From: '.strtolower($mail);
		if (strlen($name) > 2 && strlen($message) > 9 && strlen($mail) > 6) {
			mail($to, $subject, $body, $from_header);
			notification('','','');
			echo '<p><a href="'.db('website').'">'.l('backhome').'</a></p>';
			echo '<meta http-equiv="refresh" content="1; url='.db('website').'">';
		}
		else {
			notification(l('contact_not_sent'),l('message_error'),'contact/');
			echo '<meta http-equiv="refresh" content="1; url='.db('website').'contact/">';
		}
	}
}

// MENU ARTICLES
function menu_articles($start, $size) {
	$query = "SELECT * FROM ".db('prefix')."articles WHERE position = 1 AND published = 1 ORDER BY id DESC LIMIT $start, $size";
	$result = mysql_query($query);
	$home = s('home_sef');
	while ($r = mysql_fetch_array($result)) {
		$date = date(s('date_format'), strtotime($r['date']));
		$categorySEF = find_cat_sef($r['category']);
		$title = $r['category'] == 0 ? $home : retrieve('name', 'categories', 'seftitle', $categorySEF);
		echo '<li><a href="'.db('website').$categorySEF.'/'.$r['seftitle'].'/" title="'.$title.' ('.$date.')">'.$r['title'].'</a></li>';
}}

// NEW COMMENTS
function new_comments($number, $stringlen) {
	$query = "SELECT * FROM ".db('prefix')."comments WHERE approved = 'True' ORDER BY id DESC LIMIT $number";
	$result = mysql_query($query);
	$comment_limit = s('comment_limit') < 1 ? 1 : s('comment_limit');
	$comments_order = s('comments_order');
	while ($r = mysql_fetch_array($result)) {
		$art_query = "SELECT * FROM ".db('prefix')."comments WHERE articleid = '$r[articleid]' ORDER BY id $comments_order";
		$art_result = mysql_query($art_query);
		$num = 1;
		while ($r_art = mysql_fetch_array($art_result)) {
			if ($r_art['id'] == $r['id']) {$ordinal = $num;}
			$num++;
		}
		$name = strip_tags($r['name']);
		$comment = strip_tags($r['comment']);
		$page = ceil($ordinal / $comment_limit);
		$ncom = $name.' ('.$comment;
		$ncom = strlen($ncom) > $stringlen ? substr($ncom, 0, $stringlen - 3).'...' : $ncom;
		$ncom.= strlen($name) < $stringlen ? ')' : '';
		$ncom = str_replace(' ...', '...', $ncom);
		$articleSEF = retrieve('seftitle', 'articles', 'id', $r['articleid']);
        $articleCat = retrieve('category', 'articles', 'seftitle', $articleSEF);
        $categorySEF = find_cat_sef($articleCat);
		if (!empty($articleSEF)) {
			$paging = $page > 1 ? '/'.$page : '';
			echo '<li><a href="'.db('website').$categorySEF.'/'.$articleSEF.$paging.'/#'.l('comment').$ordinal.'" title="Comment posted in '.retrieve('title', 'articles', 'id', $r['articleid']).'">'.$ncom.'</a></li>';
		}
		$num++;
}}

// SEARCH FORM
function searchform() { ?>
	<form class="search" id="search_engine" method="post" action="">
	<p><input class="text" name="search_query" type="text" id="keywords" value="<?php echo l('search_keywords'); ?>" onfocus="document.forms['search_engine'].keywords.value='';" onblur="if (document.forms['search_engine'].keywords.value == '') document.forms['search_engine'].keywords.value='<?php echo l('search_keywords'); ?>';" />
	<input class="searchbutton" name="submit" type="submit" value="<?php echo l('search_button')?>" /></p>
	</form>
<?php }

//SEARCH ENGINE
function search() {
	$search_query = clean(cleanXSS($_POST['search_query']));
	echo '<h2>'.l(search_results).'</h2><br />';
	if (strlen($search_query) < 4 || $search_query == l('search_keywords')) {echo '<p>'.l(charerror).'</p>';}
	else {
		$keywords = explode(' ', $search_query);
		$keyCount = count($keywords);
		$query = "SELECT * FROM ".db('prefix')."articles WHERE SUBSTRING(position, 1, 1) != '2' AND published = 1 AND";
		if ($keyCount > 1) {
			for ($i = 0; $i < $keyCount - 1; $i++) {$query = $query." (title LIKE '%$keywords[$i]%' || text LIKE '%$keywords[$i]%') &&";}
			$j = $keyCount - 1;
			$query = $query." (title LIKE '%$keywords[$j]%' || text LIKE '%$keywords[$j]%')";
		}
		else {$query = $query." (title LIKE '%$keywords[0]%' || text LIKE '%$keywords[0]%')";}
		$query = $query." ORDER BY id DESC";
		$result = mysql_query($query);
		$numrows = mysql_num_rows($result);
		if (!$numrows) {echo '<p>'.l('noresults').' <strong>'.$search_query.'</strong>.</p>';}
		else {
			echo '<strong>'.$numrows.'</strong> '.l('resultsfound').' <strong>'.$search_query.'</strong>.</p>';
			while ($r = mysql_fetch_array($result)) {
				$date = date(s('date_format'), strtotime($r['date']));
				echo '<p><a href="'.db('website').find_cat_sef($r['category']).'/'.$r['seftitle'].'/">'.$r['title'].'</a> - '.$date.'</p>';
        	}
		}
	}
	echo '<p><a href="'.db('website').'">'.l('backhome').'</a></p>';
}

// RSS FEED
function rss() {
	$limit = s('rss_limit');
	$result = mysql_query("SELECT * FROM ".db('prefix')."articles WHERE position = 1 AND published = 1 ORDER BY date DESC LIMIT 0, $limit");
	header('Content-type: text/xml; charset='.s('charset'));
	$header = '<?xml version="1.0" ?>';
	$header .= '<rss version="2.0">';
    $header .= '<channel>';
    $header .= '<title>'.s('website_title').'</title>';
    $header .= '<description>'.s('website_title').'</description>';
    $header .= '<link>'.db('website').'</link>';
    $header .= '<copyright>Copyright '.s('website_title').'</copyright>';
    $header .= '<generator>sNews</generator>';
    $footer = '</channel>';
    $footer .= '</rss>';
	echo $header;    
	while ($r = mysql_fetch_assoc($result)) {
		$link = db('website').find_cat_sef($r['category']).'/'.$r['seftitle'].'/';
		$date = date('D, d M Y H:i:s +0000', strtotime($r['date']));
		$description = preg_replace("[\[(.*?)\]]", "", stripslashes(strip_tags($r['text'])));
		$item  = '<item>';
		$item .= '<title>'.$r['title'].'</title>';
		$item .= '<description>'.$description.'</description>';
		$item .= '<pubDate>'.$date.'</pubDate>';
		$item .= '<link>'.$link.'</link>';
		$item .= '<guid>'.$link.'</guid>';
		$item .= '</item>';
		echo $item;
	}
	echo $footer;
}

/*** ADMINISTRATIVE FUNCTIONS ***/

// LOGIN
function login() {
	if ($_SESSION[db('website').'Logged_In'] != 'True') { ?>
		<h2>Login</h2><br />
		<form method="post" action="<?php echo db('website'); ?>">
    	<p><label for="uname"><?php echo l('username'); ?>:</label><br />
    	<input type="text" class="text" name="uname" id="uname" /></p>
		<p><label for="pass"><?php echo l('password'); ?>:</label><br />
		<input type="password" class="text" name="pass" id="pass" /></p>
    	<p><input type="hidden" name="Loginform" value="True" />
    	<input type="submit" name="submit" value="<?php echo l('login'); ?>" /></p>
    	</form>
    <?php }
	else { ?>
		<h2><?php echo l('logged_in'); ?></h2>
		<p><a href="<?php echo db('website'); ?>logout/"><?php echo l('logout'); ?></a></p>
	<?php }
}

//CONTENTS COUNTER
function stats($field, $position) {
	if (!empty($position)) {$pos = $position == 2 ? " WHERE SUBSTRING(position, 1, 1)= '$position'" :" WHERE position = '$position'";}
	$query = 'SELECT id FROM '.db('prefix').$field.$pos;
	$result = mysql_query($query);
	$numrows = mysql_num_rows($result);
	return $numrows;
}

// FORM GENERATOR
function html_input($type, $name, $id, $value, $label, $css, $script1, $script2, $script3, $checked, $rows, $cols, $method, $action, $legend) {
	$lbl = !empty($label) ? '<label for="'.$id.'">'.$label.'</label>' : '';
	$ID = !empty($id) ? ' id="'.$id.'"' : '';
	$style = !empty($css) ? ' class="'.$css.'"' : '';
	$js1 = !empty($script1) ? ' '.$script1 : '';
	$js2 = !empty($script2) ? ' '.$script2 : '';
	$js3 = !empty($script3) ? ' '.$script3 : '';
	$attribs = $ID.$style.$js1.$js2.$js3;
	$val = ' value="'.$value.'"';
	$input = '<input type="'.$type.'" name="'.$name.'"'.$attribs;
	switch($type) {
		case 'form': $output = (!empty($method) && $method != 'end') ? '<form method="'.$method.'" action="'.$action.'"'.$attribs.'>' : '</form>'; break;
		case 'fieldset': $output = (!empty($legend) && $legend != 'end') ? '<fieldset><legend'.$attribs.'>'.$legend.'</legend>' : '</fieldset>'; break;
		case 'text':
		case 'password': $output = '<p>'.$lbl.':<br />'.$input.$val.' /></p>'; break;
		case 'checkbox':
		case 'radio': $check = $checked == 'ok' ? ' checked="checked"' : ''; $output = '<p>'.$input.$check.' /> '.$lbl.'</p>'; break;
		case 'hidden':
		case 'submit':
		case 'reset':
		case 'button': $output = $input.$val.' />'; break;
		case 'textarea': $output = $lbl.':<br /><textarea name="'.$name.'" rows="'.$rows.'" cols="'.$cols.'"'.$attribs.'>'.$value.'</textarea>'; break;
	}	
	echo $output;
}

// ADMINISTRATION FORM
function administration() {
	if ($_SESSION[db('website').'Logged_In'] != 'True') {notification(l('error_not_logged_in'),'','login/');}
	else {
		foreach ($_POST as $key => $value) {unset($_POST[$key]);}
		echo $_POST['Loginform'];
		echo $_POST['uname'];
		html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '','<a href="http://snews.solucija.com/" title="sNews CMS">sNews</a> '.l('administration'));
		echo '<p>'.l('categories').': <a href="add_category/" title="'.l('add_new').'">'.l('add_new').'</a>';
		$link = ' '.l('divider').' <a href="';
		if (stats('categories','') > 0) {echo $link.'categories/" title="'.l('view').'">'.l('view').'</a></p>';}
		echo '<p>'.l('articles').': <a href="article_new/" title="'.l('add_new').'">'.l('add_new').'</a>';		
		if (stats('articles',1) > 0) {echo $link.'articles/" title="'.l('view').'">'.l('view').'</a></p>';}
		echo '<p>'.l('extra_contents').': <a href="side_new/" title="'.l('add_new').'">'.l('add_new').'</a>';
		if (stats('articles',2) > 0) {echo $link.'extra_contents/" title="'.l('view').'">'.l('view').'</a></p>';}
		echo '<p>'.l('pages').': <a href="page_new/" title="'.l('add_new').'">'.l('add_new').'</a>';
		if (stats('articles',3) > 0) {echo $link.'pages/" title="'.l('view').'">'.l('view').'</a></p>';}
		echo '</fieldset>';
		$query_comm = "SELECT * FROM ".db('prefix')."comments WHERE approved <> 'True'";
		$result_comm = mysql_query($query_comm);
		$unapproved = mysql_num_rows($result_comm);
		if ($unapproved > 0) {
			html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('comments'));
			echo '<p><a onclick="toggle(\'sub1\')" style="cursor: pointer;" title="Unapproved comments">'.$unapproved.' comments waiting approval</a></p>';
			echo '<div id="sub1" style="display: none;">';
			while ($r = mysql_fetch_array($result_comm)) {
				$categorySEF = find_cat_sef($r['articleid']);
				$cat = $categorySEF != '' ? $categorySEF : s('home_sef');
				echo '<p>'.$r['name'].' '.l('divider').' <a href="'.db('website').'index.php?action=editcomment&amp;commentid='.$r['id'].'">'.l('edit').'</a></p>';
			}
			echo '</div>';
		}
		if ($unapproved > 0) {echo '</fieldset>';}
		html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('site_settings'));
		echo '<p><a href="settings/" title="'.l('settings').'">'.l('settings').'</a></p>';
		echo '<p><a href="files/" title="'.l('files').'">'.l('files').'</a></p></fieldset>';
		html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('login_status'));
		echo '<p><a href="logout/" title="'.l('logout').'">'.l('logout').'</a></p></fieldset>';
}}

// SETTINGS FORM
function settings() {
	html_input('form', '', '', '', '', '', '', '', '', '', '', '', 'post', 'index.php?action=process&amp;task=save_settings', '');
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '','<a title="'.l('settings').'" onclick="toggle(\'sub1\')" style="cursor: pointer;">'.l('settings').'</a>');
	echo '<div id="sub1" style="display: none;">';
	html_input('text', 'website_title', 'webtitle', s('website_title'), l('a_website_title'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'home', 'homeid', l('home') == '' ? l('home') : l('home'), l('a_home'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'home_sef', 'webSEF', s('home_sef') == '' ? l('home_sef') : s('home_sef'), l('a_home_sef'), '', 'onKeyPress="return SEFrestrict(event);"', '', '', '', '', '', '', '', '');
	html_input('text', 'website_description', 'wdesc', s('website_description'), l('a_description'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'website_keywords', 'wkey', s('website_keywords'), l('a_keywords'), '', '', '', '', '', '', '', '', '', '');
	echo '</div></fieldset>';
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', '<a title="'.l('a_contact_info').'" onclick="toggle(\'sub2\')" style="cursor: pointer;">'.l('a_contact_info').'</a>');
	echo '<div id="sub2" style="display: none;">';
	html_input('text', 'website_email', 'we', s('website_email'), l('a_website_email'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'contact_subject', 'cs', s('contact_subject'), l('a_contact_subject'), '', '', '', '', '', '', '', '', '', '');
	echo '</div></fieldset>';
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', '<a title="'.l('a_time_settings').'" onclick="toggle(\'sub3\')" style="cursor: pointer;">'.l('a_time_settings').'</a>');
	echo '<div id="sub3" style="display: none;">';
	html_input('text', 'language', 'char', s('language') == '' ? 'EN' : s('language'), l('a_language'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'charset', 'char', s('charset') == '' ? 'UTF-8' : s('charset'), l('charset'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'date_format', 'dt', s('date_format'), l('a_date_format'), '', '', '', '', '', '', '', '', '', '');
	echo '</div></fieldset>';
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '','<a title="'.l('contents').'" onclick="toggle(\'sub4\')" style="cursor: pointer;">'.l('contents').'</a>');
	echo '<div id="sub4" style="display: none;">';
	html_input('text', 'article_limit', 'artl', s('article_limit'), l('a_article_limit'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'rss_limit', 'rssl', s('rss_limit'), l('a_rss_limit'), '', '', '', '', '', '', '', '', '', '');
	echo '<p><label for="dp">'.l('a_display_page').':</label> <select name="display_page" id="dp">';
	echo '<option value="0"'.(s('display_page') == 0 ? ' selected="selected"' : '').'>'.l('none').'</option>';
	$query = "SELECT * FROM ".db('prefix')."articles WHERE position = 3 ORDER BY id ASC"; 
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) { 
		echo '<option value="'.$r['id'].'"';
		if (s('display_page') == $r['id']) {echo ' selected="selected"';}					
		echo '>'.$r['title'].'</option>';
	}
	echo '</select></p>';
	html_input('checkbox', 'display_new_on_home', 'dnoh', '', l('a_display_new_on_home'), '', '', '', '', (s('display_new_on_home') == true ? 'ok' : ''), '', '', '', '', '');
	html_input('checkbox', 'display_pagination', 'dpag', '', l('a_display_pagination'), '', '', '', '', (s('display_pagination') == 'True' ? 'ok' : ''), '', '', '', '', '');
	html_input('checkbox', 'num_categories', 'nc', '', l('a_num_categories'), '', '', '', '', s('num_categories') == true ? 'ok' : '', '', '', '', '', '');
	echo '</div></fieldset>';
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', '<a title="'.l('comments').'" onclick="toggle(\'sub5\')" style="cursor: pointer;">'.l('comments').'</a>');
	echo '<div id="sub5" style="display: none;">';
	html_input('checkbox', 'approve_comments', 'ac', '', l('a_approve_comments'), '', '', '', '', s('approve_comments') == true ? 'ok' : '', '', '', '', '', '');
	echo '<p><label for="co">'.l('a_comments_order').':</label><br /><select id="co" name="comments_order">';
	echo '<option value="DESC"'.(s('comments_order') == 'DESC' ? ' selected="selected"' : '').'>'.l('newer_top').'</option>';
	echo '<option value="ASC"'.(s('comments_order') == 'ASC' ? ' selected="selected"' : '').'>'.l('newer_bottom').'</option></select></p>';
	html_input('text', 'comment_limit', 'cl', s('comment_limit'), l('a_comment_limit'), '', '', '', '', '', '', '', '', '', '');
	html_input('checkbox', 'word_filter_enable', 'wfe', '', l('a_word_filter_enable'), '', '', '', '', s('word_filter_enable') == 'on' ? 'ok' : '', '', '', '', '', '');
	html_input('text', 'word_filter_file', 'wff', s('word_filter_file'), l('a_word_filter_file'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'word_filter_change', 'wfc', s('word_filter_change'), l('a_word_filter_change'), '', '', '', '', '', '', '', '', '', '');
	echo '</div></fieldset><p>';
	html_input('hidden', 'task', 'task', 'save_settings', '', '', '', '', '', '', '', '', '', '', '');
	html_input('submit', 'save', 'save', l('save'), '', '', '', '', '', '', '', '', '', '', '');
	echo '</p></form>';
	html_input('form', '', '', '', '', '', '', '', '', '', '', '', 'post', 'index.php?action=process&amp;task=changeup', '');
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', '<a title="'.l('change_up').'" onclick="toggle(\'sub6\')" style="cursor: pointer;">'.l('change_up').'</a>');
	echo '<div id="sub6" style="display: none;">';
	html_input('text', 'uname', 'uname', s('username'), l('a_username'), '', '', '', '', '', '', '', '', '', '');
	html_input('password', 'pass1', 'pass1', '', l('a_password'), '', '', '', '', '', '', '', '', '', '');
	html_input('password', 'pass2', 'pass2', '', l('a_password2'), '', '', '', '', '', '', '', '', '', '');
	echo '<p>';
	html_input('hidden', 'task', 'task', 'changeup', '', '', '', '', '', '', '', '', '', '', '');
	html_input('submit', 'submit_pass', 'submit_pass', l('save'), '', '', '', '', '', '', '', '', '', '', '');
	echo '</p></div></fieldset></form>';
}

// CATEGORIES FORM
function form_categories() {
	if (isset($_GET['id']) && is_numeric($_GET['id']) && !is_null($_GET['id'])) {
		$categoryid = $_GET['id'];
		$query = mysql_query("SELECT * FROM ".db('prefix')."categories WHERE id='$categoryid'");
		$r = mysql_fetch_array($query);
		$frm_action = db('website').'index.php?action=process&amp;task=edit_category&amp;id='.$categoryid;
		$frm_add_edit = l('edit');
		$frm_name = $r['name'];
		$frm_sef_title = $r['seftitle'];
		$frm_description = $r['description'];
		$frm_publish = $r['published'] == 'YES' ? 'ok' : '';
		$frm_task = 'edit_category';
		$frm_submit = l('edit');
	}
	else {
		$frm_action = db('website').'index.php?action=process&amp;task=add_category';
		$frm_add_edit = l('add_category');
		$frm_name = $_POST['name'];
		$frm_sef_title = $_POST['name'] == '' ? cleanSEF($_POST['name']) : cleanSEF($_POST['seftitle']);
		$frm_description = '';
		$frm_publish = 'ok';
		$frm_task = 'add_category';
		$frm_submit = l('add_category');
	}
	html_input('form', '', 'post', '', '', '', '', '', '', '', '', '', 'post', $frm_action, '');
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', $frm_add_edit);
	html_input('text', 'name', 't', $frm_name, l('name'), '', 'onchange="genSEF(this,document.forms[\'post\'].seftitle)"', 'onkeyup="genSEF(this,document.forms[\'post\'].seftitle)"', '', '', '', '', '', '', '');
	html_input('text', 'seftitle', 's', $frm_sef_title, l('sef_title_cat'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'description', 'desc', $frm_description, l('description'), '', '', '', '', '', '', '', '', '', '');
	html_input('checkbox', 'publish', 'pub', 'YES', l('publish_category'), '', '', '', '', $frm_publish, '', '', '', '', '');
	echo '</fieldset><p>';
	html_input('hidden', 'task', 'task', $frm_task, '', '', '', '', '', '', '', '', '', '', '');
	html_input('submit', 'submit_category', 'submit_category', $frm_submit, '', '', '', '', '', '', '', '', '', '', '');
	if (!empty($categoryid)) {
		echo '&nbsp;&nbsp;';
		html_input('hidden', 'id', 'id', $categoryid, '', '', '', '', '', '', '', '', '', '', '');
		html_input('submit', 'delete_category', 'delete_category', l('delete'), '', '', 'onclick="javascript: return pop()"', '', '', '', '', '', '', '', '');
	}
	echo '</p></form>';

	$query = "SELECT * FROM ".db('prefix')."categories WHERE published = 'YES' ORDER BY catorder ASC"; 
	$result = mysql_query($query);
	$numrows = mysql_num_rows($result);
	if ($numrows > 1) {
		html_input('form', '', 'post', '', '', '', '', '', '', '', '', '', 'post', 'index.php?action=process&amp;task=order_category', '');
		html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('category_order'));
		$counter = 0;
		while ($r = mysql_fetch_array($result)) {
			echo '<p><input name="catorder['.$counter.']" type="text" id="'.$r['id'].'" value="'.$r['catorder'].'" size="1" /> <label for="'.$r['id'].'">'.$r['name'].'</label><input type="hidden" name="counter_id['.$counter.']" value="'.$r['id'].'" /></p>';
			$counter++;
		}
		echo '</fieldset><p>';
		html_input('hidden', 'counter', 'counter', $counter, '', '', '', '', '', '', '', '', '', '', '');
		html_input('hidden', 'task', 'task', 'order_category', '', '', '', '', '', '', '', '', '', '', '');
		html_input('submit', 'order_category', 'order_category', l('order_category'), '', '', '', '', '', '', '', '', '', '', '');
		echo '</p></form>';
}}

// ARTICLES - POSTING TIME
function posting_time($time='') {
	echo '<p>'.l('day').':<select name="fposting_day">';
	$thisDay = !empty($time) ? substr($time, 8, 2) : intval(date('d'));
	for($i = 1; $i < 32; $i++) {
		echo '<option value="'.$i.'"';
		if($i == $thisDay) {echo ' selected="selected"';}
		echo '>'.$i.'</option>';
	}
	echo '</select>'.l('month').':<select name="fposting_month">';
	$thisMonth = !empty($time) ? substr($time, 5, 2) : intval(date('m'));
	for($i = 1; $i < 13; $i++) {
		echo '<option value="'.$i.'"';
		if($i == $thisMonth) {echo ' selected="selected"';}
		echo '>'. $i .'</option>';
	}
	echo '</select>'.l('year').':<select name="fposting_year">';
	$thisYear = !empty($time) ? substr($time, 0, 4) : intval(date('Y'));
	for($i = $thisYear; $i < $thisYear + 3; $i++) {
		echo '<option value="'.$i.'"';
		if($i == $thisYear) {echo ' selected="selected"';}
		echo '>'.$i.'</option>';
	}
	echo '</select>'.l('hour').':<select name="fposting_hour">';
	$thisHour = !empty($time) ? substr($time, 11, 2) : intval(date('H'));
	for($i = 0; $i < 24; $i++) {
		echo '<option value="'.$i.'"';
		if($i == $thisHour) {echo ' selected="selected"';}
		echo '>'.$i.'</option>';
	}
	echo '</select>'.l('minute').':<select name="fposting_minute">';
	$thisMinute = !empty($time) ? substr($time, 14, 2) : intval(date('i'));
	for($i = 0; $i < 60; $i++) {
		echo '<option value="'.$i.'"';
		if($i == $thisMinute) {echo ' selected="selected"';}
		echo '>'.$i.'</option>';
	}
	echo '</select></p>';
}

// ARTICLES FORM
function form_articles($contents) {
	if (isset($_GET['id']) && is_numeric($_GET['id']) && !is_null($_GET['id'])) {
		$id = $_GET['id'];
		$query = mysql_query("SELECT * FROM ".db('prefix')."articles WHERE id='$id'");
		$r = mysql_fetch_array($query);
		$article_category = $r['category'];
		$edit_option = substr($r['position'], 0, 1);
		$edit_page = substr($r['position'], 2);
		switch ($edit_option) {
			case 1: $frm_fieldset = l('edit').' '.l('article'); $frm_position1 = 'selected="selected"'; break;
			case 2: $frm_fieldset = l('edit').' '.l('extra_contents'); $frm_position2 = 'selected="selected"'; break;
			case 3: $frm_fieldset = l('edit').' '.l('page'); $frm_position3 = 'selected="selected"'; break;
		}
		$frm_action = db('website').'index.php?action=process&amp;task=edit_article&amp;id='.$id;
		$frm_title = $_SESSION['temp']['title'] ? $_SESSION['temp']['title'] : $r['title'];
		$frm_sef_title = $_SESSION['temp']['seftitle'] ? cleanSEF($_SESSION['temp']['seftitle']) : $r['seftitle'];
		$frm_text = str_replace('&', '&amp;', $_SESSION['temp']['text'] ? $_SESSION['temp']['text'] : $r['text']);
		$frm_meta_desc = $_SESSION['temp']['description_meta'] ? cleanSEF($_SESSION['temp']['description_meta']) : $r['description_meta'];
		$frm_meta_key = $_SESSION['temp']['keywords_meta'] ? cleanSEF($_SESSION['temp']['keywords_meta']) : $r['keywords_meta'];
		$frm_display_title = $r['displaytitle'] == 'YES' ? 'ok' : '';
		$frm_display_info = $r['displayinfo'] == 'YES' ? 'ok' : '';
		$frm_publish = $r['published'] == 1 ? 'ok' : '';
		$frm_commentable = ($r['commentable'] == 'YES' || $r['commentable'] == 'FREEZ') ? 'ok' : '';
		$frm_task = 'edit_article';
		$frm_submit = l('edit');
	}
	else {
		switch ($contents) {
			case 'article_new': $frm_fieldset = l('article_new'); $pos = 1; $frm_position1 = 'selected="selected"'; break;
			case 'side_new': $frm_fieldset = l('side_new'); $pos = 2; $frm_position2 = 'selected="selected"'; break;
			case 'page_new': $frm_fieldset = l('page_new'); $pos = 3; $frm_position3 = 'selected="selected"'; break;
		}
		$frm_action = db('website').'index.php?action=process&amp;task=add_article';
		$frm_title = $_SESSION['temp']['title'];
		$frm_sef_title = cleanSEF($_SESSION['temp']['seftitle']);
		$frm_text = $_SESSION['temp']['text'];
		$frm_meta_desc = cleanSEF($_SESSION['temp']['description_meta']);
		$frm_meta_key = cleanSEF($_SESSION['temp']['keywords_meta']);
		$frm_display_title = 'ok';
		$frm_display_info = ($contents == 'side_new') ? '' : 'ok';
		$frm_publish = 'ok';
		$frm_commentable = ($contents == 'side_new' || $contents == 'page_new') ? '' : 'ok';
		$frm_task = 'add_article';
		$frm_submit = l('submit');
	}
	html_input('form', '', 'post', '', '', '', '', '', '', '', '', '', 'post', $frm_action, '');
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', $frm_fieldset);
	html_input('text', 'title', 'at', $frm_title, 'Title', '', 'onchange="genSEF(this,document.forms[\'post\'].seftitle)"', 'onkeyup="genSEF(this,document.forms[\'post\'].seftitle)"', '', '', '', '', '', '', '');
	if ($contents == 'side_new' || $edit_option == 2) {
		echo '<div style="display: none;">';
		html_input('text', 'seftitle', 'as', $frm_sef_title, l('sef_title'), '', '', '', '', '', '', '', '', '', '');
		echo '</div>';
	}
	else {html_input('text', 'seftitle', 'as', $frm_sef_title, l('sef_title'), '', '', '', '', '', '', '', '', '', '');}
	html_input('textarea', 'text', 'txt', str_replace('<br />', '', $frm_text), l('text'), '', '', '', '', '', '2', '100', '', '', '');
	echo '<p>';
	html_input('button', '', '', 'B', '', 'button', 'onclick="tags(\'strong\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'I', '', 'button', 'onclick="tags(\'em\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'Strike', '', 'button', 'onclick="tags(\'strike\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'P', '', 'button', 'onclick="tags(\'p\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'Break', '', 'button', 'onclick="tags(\'break\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'Image', '', 'button', 'onclick="tags(\'img\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'Link', '', 'button', 'onclick="tags(\'link\')"', '', '', '', '', '', '', '', '');
	html_input('button', '', '', 'Include', '', 'button', 'onclick="tags(\'include\')"', '', '', '', '', '', '', '', '');
	echo '</p>';
	if ($contents == 'article_new' || $edit_option == 1) {
		html_input('checkbox', 'publish_article', 'pu', 'YES', l('publish_article'), '', '', '', '', $frm_publish, '', '', '', '', '');
	}
	echo '</fieldset>';
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('preview'));
	echo '<div id="preview"></div></fieldset>';
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', '<a title="'.l('customize').'" onclick="toggle(\'sub1\')" style="cursor: pointer;">'.l('customize').'</a>');
	echo '<div id="sub1" style="display: none;">';
	if ($contents != 'page_new' && $edit_option != 3) {
		echo '<p><label for="cat">';
		echo ($contents == 'side_new' || $edit_option == 2) ?  l('appear_category') : l('category');
		echo ':</label><br /><select name="define_category" id="cat" onchange="dependancy();">';
		if ($contents == 'side_new' || $edit_option == 2) {echo '<option value="-1"'.($article_category == -1 ? ' selected="selected"' : '').'>'.l('all').'</option>';}
		echo '<option value="0"'.($article_category == 0 && $contents != 'side_new' ? ' selected="selected"' : '').'>'.l('home').'</option>';
		$category_query = "SELECT * FROM ".db('prefix')."categories WHERE published = 'YES' ORDER BY catorder ASC"; 
		$category_result = mysql_query($category_query);
		while ($cat = mysql_fetch_array($category_result)) { 
			echo '<option value="'.$cat['id'].'"';
			if ($article_category == $cat['id']) {echo ' selected="selected"';}					
			echo '>'.$cat['name'].'</option>';
		}
		echo '</select></p>';
		if ($contents == 'side_new' || $edit_option == 2) {
			echo '<p id="def_page"><label for="dp">'.l('appear_page').':</label><br /><select name="define_page" id="dp">';
			echo '<option value="0"'.($edit_option != 2 ? ' selected="selected"' : '').'>'.l('all').'</option>';
			$query = "SELECT * FROM ".db('prefix')."articles WHERE position = 3 ORDER BY id ASC"; 
			$result = mysql_query($query);
			while ($r = mysql_fetch_array($result)) { 
				echo '<option value="'.$r['id'].'"';
				if ($edit_page == $r['id']) {echo ' selected="selected"';}					
				echo '>'.$r['title'].'</option>';
			}
			echo '</select></p>';
		}	
	}
	if (isset($_GET['action']) == 'edit_article') {
		echo '<p><label for="pos">'.l('position').':</label><br /><select name="position" id="pos">';
		echo '<option value="1"'.$frm_position1.'>'.l('center').'</option>';
		echo '<option value="2"'.$frm_position2.'>'.l('side').'</option>';
		echo '<option value="3"'.$frm_position3.'>'.l('display_page').'</option>';
		echo '</select></p>';
	}
	else {html_input('hidden', 'position', 'position', $pos, '', '', '', '', '', '', '', '', '', '', '');}
	if ($contents != 'side_new' && $edit_option != 2) {
		html_input('text', 'description_meta', 'dm', $frm_meta_desc, l('description_meta'), 'smalltxtarea', '', '', '', '', '2', '100', '', '', '');
		html_input('text', 'keywords_meta', 'km', $frm_meta_key, l('keywords_meta'), 'smalltxtarea', '', '', '', '', '2', '100', '', '', '');
	}
	html_input('checkbox', 'display_title', 'dt', 'YES', l('display_title'), '', '', '', '', $frm_display_title, '', '', '', '', '');
	if ($contents != 'side_new' && $edit_option != 2) {
		html_input('checkbox', 'display_info', 'di', 'YES', l('display_info'), '', '', '', '', $frm_display_info, '', '', '', '', '');
		html_input('checkbox', 'commentable', 'ca', 'YES', l('enable_commenting'), '', '', '', '', $frm_commentable, '', '', '', '', '');
		if (!empty($id)) {
			echo '<p><input name="freeze" type="checkbox" id="fc"';
			if ($r['commentable'] == 'FREEZ') {echo ' value="YES" checked="checked">';}
			else if ($r['commentable'] == 'YES') {echo ' value="">';}
			echo ' <label for="fc"> '.l('freeze_comments').'</label></p>';
		}
	}
	echo '</fieldset>';
	if ($contents == 'article_new' || $edit_option == 1) {
		html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', '<a title="'.l('publish_date').'" onclick="toggle(\'sub2\')" style="cursor: pointer;">'.l('publish_date').'</a>');
		echo '<div id="sub2" style="display: none;">';
		html_input('checkbox', 'fposting', 'fp', 'YES', l('enable'), '', '', '', '', '', '', '', '', '', '');
		echo '<p>'.l('server_time').': '.date(s('date_format')).':'.date('s').'</p>';
		!empty($id) ? posting_time($r['date']) : posting_time();
		echo '</div></fieldset>';
	}
	echo '<p>';
	html_input('hidden', 'task', 'task', $frm_task, '', '', '', '', '', '', '', '', '', '', '');
	html_input('submit', 'submit_article', 'submit_article', $frm_submit, '', '', '', '', '', '', '', '', '', '', '');
	if (!empty($id)) {
		html_input('hidden', 'id', 'id', $id, '', '', '', '', '', '', '', '', '', '', '');
		html_input('submit', 'delete_article', 'delete_article', l('delete'), '', '', 'onclick="javascript: return pop()"', '', '', '', '', '', '', '', '');
	}
	echo '</p></form>';
}

// ARTICLES - ADMIN LIST
function admin_articles($contents) {
	switch ($contents) {
		case 'article_view': $title = l('articles'); $subquery = "WHERE position = 1"; break;
		case 'side_view': $title = l('extra_contents'); $subquery = "WHERE SUBSTRING(position,1,1) = '2'"; break;
		case 'page_view': $title = l('pages'); $subquery = "WHERE position = 3"; break;
	}
	echo '<fieldset><legend>'.$title.'</legend>';
	$query = "SELECT * FROM ".db('prefix')."articles $subquery ORDER BY date DESC";
	$result = mysql_query($query);
	if (!$result || !mysql_num_rows($result)) {echo '<p>'.l('article_not_exist').'</p>';}
	else {
		$i = 0;
  		while ($r = mysql_fetch_array($result)) {
			$categorySEF = find_cat_sef($r['category']).'/';
			$articleSEF = $contents != 'side_view' ? $r['seftitle'].'/' : '';
			echo '<p>'.date(s('date_format'), strtotime($r['date'])).' <strong>'.$r['title'].'</strong> '.l('divider').' <a href="'.db('website').$categorySEF.$articleSEF.'">'.l('view').'</a> ';
			echo  l('divider').' <a href="'.db('website').'index.php?action=edit_article&amp;id='.$r['id'].'">'.l('edit').'</a> ';
    		if ($r['published'] == 2) {echo  l('divider').' ['.l('status').' '.l('future_posting').']';}
			if ($r['published'] == 0) {echo  l('divider').' ['.l('status').' '.l('unpublished').']';}
			echo '</p>';
			$i++;
		}
		echo '</fieldset>';
}}

//CATEGORIES - ADMIN LIST
function admin_categories() {
	echo '<fieldset><legend>'.l('categories').'</legend>';
	$query = "SELECT * FROM ".db('prefix')."categories ORDER BY catorder ASC";
	$result = mysql_query($query);
	if (!$result || !mysql_num_rows($result)) {echo '<p>'.l('category_not_exist').'</p>';}
	else {
		while ($r = mysql_fetch_array($result)) {
			echo '<p><strong>'.$r['name'].'</strong> '.l('divider').' <a href="'.db('website').'index.php?action=edit_category&amp;id='.$r['id'].'" title="'.$r['description'].'">'.l('edit').'</a> ';
    		echo $r['published'] != 'YES' ? ' '.l('divider').' ['.l('status').' '.l('unpublished').']' : '';
			echo '</p>';
		}
	}
}

// COMMENTS - EDIT
function edit_comment() {
	echo '<h2>'.l('edit_comment').'</h2>';
	$commentid = $_GET['commentid'];
	$query = mysql_query("SELECT * FROM ".db('prefix')."comments WHERE id='$commentid'");
	$r = mysql_fetch_array($query);
	html_input('form', '', '', '', '', '', '', '', '', '', '', '', 'post', '', '');
	html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('edit_comment'));
	html_input('textarea', 'editedcomment', 'ec', stripslashes($r['comment']), l('comment'), '', '', '', '', '', '2', '100', '', '', '');
	html_input('text', 'name', 'n', $r['name'], l('name'), '', '', '', '', '', '', '', '', '', '');
	html_input('text', 'url', 'url', $r['url'], l('url'), '', '', '', '', '', '', '', '', '', '');
	html_input('checkbox', 'approved', 'a', '', l('approved'), '', '', '', '', $r['approved'] == 'True' ? 'ok' : '', '', '', '', '', '');
	echo '<p>';
	html_input('hidden', 'id', 'id', $r['articleid'], '', '', '', '', '', '', '', '', '', '', '');
	html_input('hidden', 'commentid', 'commentid', $r['id'], '', '', '', '', '', '', '', '', '', '', '');
	html_input('hidden', 'task', 'commentid', 'editcomment', '', '', '', '', '', '', '', '', '', '', '');
	html_input('submit', 'submit_text', 'submit_text', l('edit'), '', '', '', '', '', '', '', '', '', '', '');
	echo '</p></fieldset></form>';
}

/*** PROCESSING (CATEGORIES, CONTENTS, COMMENTS) ***/
function processing() {
	if ($_SESSION[db('website').'Logged_In'] != 'True') {notification(l('error_not_logged_in'),'','login/');}
	$action = $_REQUEST['action'];
  	$id = $_REQUEST['id'];
  	$commentid = $_POST['commentid'];
  	$approved = $_POST['approved'] == 'on' ? 'True' : '';
  	$name = str_replace("\'", "&#39;", $_POST['name']);
  	$category = $_POST['define_category'];
  	$description = $_POST['description'];
  	$title = str_replace("\'", "&#39;", $_POST['title']);
  	$seftitle = $_POST['seftitle'];
	$url = cleanXSS($_POST['url']);
   	$comment = str_replace("\'", "&#39;", $_POST['editedcomment']);
   	$text = str_replace("\'", "&#39;", $_POST['text']);
   	$text = str_replace("\n", "<br />", $text);
   	$text_limit = $_POST['text_limit'];
  	$date = date('Y-m-d H:i:s');
  	$description_meta = str_replace("\'", "'", $_POST['description_meta']);
	$keywords_meta = str_replace("\'", "'", $_POST['keywords_meta']);
  	$display_title = $_POST['display_title'] == 'on' ? 'YES' : 'NO';
	$display_info = $_POST['display_info'] == 'on' ? 'YES' : 'NO';
  	$commentable = $_POST['commentable'] == 'on' ? 'YES' : 'NO';
  	if ($_POST['freeze'] == 'on' && $commentable == 'YES') {$commentable = 'FREEZ';}
	$position = $_POST['position'];
	if ($position == 2) {$position = $_POST['cat_dependant'] == 'on' ? 21 : 2;}
  	$publish_article = ($_POST['publish_article'] == 'on' || $position > 1) ? 1 : 0;
  	$publish_category = $_POST['publish'] == 'on' ? 'YES' : 'NO';
  	$fpost_enabled = false;
    if($_POST['fposting'] == 'on') {
		$fpost_enabled = true;
		$publish_article = 2;
		$date = $_POST['fposting_year'].'-'.$_POST['fposting_month'].'-'.$_POST['fposting_day'].' '.$_POST['fposting_hour'].':'.$_POST['fposting_minute'].':00'; 
    }
  		
	switch ($_REQUEST['task']) {
		case 'save_settings':
			if (isset($_POST['save'])) {
				$website_title = $_POST['website_title'];
	    		$home_sef = $_POST['home_sef'];
				$website_description = $_POST['website_description'];
				$website_keywords = $_POST['website_keywords'];
				$website_email = $_POST['website_email'];
	    		$contact_subject = $_POST['contact_subject'];
				$language = $_POST['language'];
				$charset = $_POST['charset'];
				$date_format = $_POST['date_format'];
				$article_limit = $_POST['article_limit'];
				$rss_limit = $_POST['rss_limit'];
				$display_page = $_POST['display_page'];
				$display_new_on_home = $_POST['display_new_on_home'];
				$display_pagination = $_POST['display_pagination'] == 'on' ? 'True' : '';
				$num_categories = $_POST['num_categories'];
				$approve_comments = $_POST['approve_comments'];
				$comments_order = $_POST['comments_order'];
				$comment_limit = $_POST['comment_limit'];
				$word_filter_enable = $_POST['word_filter_enable'];
				$word_filter_file = $_POST['word_filter_file'];
				$word_filter_change = $_POST['word_filter_change'];
				$query = "UPDATE ".db('prefix')."settings SET VALUE=";
	    		mysql_query($query."'$home' WHERE name='home' LIMIT 1");
	    		mysql_query($query."'$display_new_on_home' WHERE name='display_new_on_home' LIMIT 1");
	    		mysql_query($query."'$approved' WHERE name='approved' LIMIT 1");
	    		mysql_query($query."'$language' WHERE name='language' LIMIT 1");
	    		mysql_query($query."'$website_title' WHERE name='website_title' LIMIT 1");
				mysql_query($query."'$home_sef' WHERE name='home_sef' LIMIT 1");
				mysql_query($query."'$website_description' WHERE name='website_description' LIMIT 1");
				mysql_query($query."'$website_keywords' WHERE name='website_keywords' LIMIT 1");
	    		mysql_query($query."'$website_email' WHERE name='website_email' LIMIT 1");
	    		mysql_query($query."'$contact_subject' WHERE name='contact_subject' LIMIT 1");
				mysql_query($query."'$word_filter_enable' WHERE name='word_filter_enable' LIMIT 1");
				mysql_query($query."'$word_filter_file' WHERE name='word_filter_file' LIMIT 1");
				mysql_query($query."'$word_filter_change' WHERE name='word_filter_change' LIMIT 1");
	    		mysql_query($query."'$num_categories' WHERE name='num_categories' LIMIT 1");
				mysql_query($query."'$charset' WHERE name='charset' LIMIT 1");
	    		mysql_query($query."'$date_format' WHERE name='date_format' LIMIT 1");
	    		mysql_query($query."'$comments_order' WHERE name='comments_order' LIMIT 1");
	    		mysql_query($query."'$approve_comments' WHERE name='approve_comments' LIMIT 1");
	    		mysql_query($query."'$comment_limit' WHERE name='comment_limit' LIMIT 1");
	    		mysql_query($query."'$rss_limit' WHERE name='rss_limit' LIMIT 1");
				mysql_query($query."'$article_limit' WHERE name='article_limit' LIMIT 1");
				mysql_query($query."'$display_page' WHERE name='display_page' LIMIT 1");
				mysql_query($query."'$display_pagination' WHERE name='display_pagination' LIMIT 1");
				notification('','','');
				echo '<meta http-equiv="refresh" content="1; url='.db('website').'administration/">';
			}
		break;
		case 'changeup':
			if (isset($_POST['submit_pass'])) {
	    		if ($_POST['pass1'] == $_POST['pass2'] && strlen($_POST['pass1']) > 3 && !empty($_POST['uname'])) {
		    		$uname = $_POST['uname'];
	    			$pass = md5($_POST['pass1']);
	    			$query = "UPDATE ".db('prefix')."settings SET VALUE=";
	            	mysql_query($query."'$uname' WHERE name='username' LIMIT 1");
	    	 		mysql_query($query."'$pass' WHERE name='password' LIMIT 1");
					notification('','','');
					echo '<meta http-equiv="refresh" content="1; url='.db('website').'administration/">';
        		}
				else {notification(l('pass_mismatch'),'','settings/');}
			}
		break;
		case 'add_category':
			if (isset($_POST['submit_category'])) {
				switch(true) {
      			case(empty($name)): notification(l('err_TitleEmpty'),l('errNote'),''); form_categories(); break;
				case(empty($seftitle)): notification(l('err_SEFEmpty'),l('errNote'),''); form_categories(); break;
				case(check_if_unique('category_name', $name, $id)): notification(l('err_TitleExists'),l('errNote'),''); form_categories(); break;
				case(check_if_unique('category_seftitle', $seftitle, $id)): notification(l('err_SEFExists'),l('errNote'),''); form_categories(); break;
				case(cleancheckSEF($seftitle) == 'notok'): notification(l('err_SEFIllegal'),l('errNote'), ''); form_categories(); break;
				default:
        			mysql_query("INSERT INTO ".db('prefix')."categories(name, seftitle, description, published) VALUES('$name', '$seftitle', '$description', '$publish_category')");
					notification('','','');
					echo '<meta http-equiv="refresh" content="1; url='.db('website').'categories/">';
				}
			}
		break;
		case 'edit_category':
			if (isset($_POST['submit_category'])) {
				switch(true) {
				case(empty($name)): notification(l('err_TitleEmpty'),l('errNote'),''); form_categories(); break;
				case(empty($seftitle)): notification(l('err_SEFEmpty'),l('errNote'),''); form_categories(); break;
				case(check_if_unique('category_name', $name, $id)): notification(l('err_TitleExists'),l('errNote'),''); form_categories(); break;
				case(check_if_unique('category_seftitle', $seftitle, $id)): notification(l('err_SEFExists'),l('errNote'),''); form_categories(); break;
				case(cleancheckSEF($seftitle) == 'notok'): notification(l('err_SEFIllegal'),l('errNote'), ''); form_categories(); break;
				default:
					$query = "UPDATE ".db('prefix')."categories SET";
					$query_end = "WHERE id='$id' LIMIT 1";
	    			mysql_query($query." name='$name' ".$query_end);
	      			mysql_query($query." seftitle='$seftitle' ".$query_end);
	      			mysql_query($query." description='$description' ".$query_end);
	      			mysql_query($query." published='$publish_category' ".$query_end);
					notification('','','');
					echo '<meta http-equiv="refresh" content="1; url='.db('website').'categories/">';
				}
			}
			if (isset($_POST['delete_category'])) {
				mysql_query("DELETE FROM ".db('prefix')."categories WHERE id=$id LIMIT 1");
				notification('','','');
				echo '<meta http-equiv="refresh" content="1; url='.db('website').'categories/">';
			}
		break;
		case 'order_category':
			if (isset($_POST['order_category'])) {
				$counter = $_POST['counter'];
				for($i = 0; $i < $counter; $i++) {
					$category_order = $_POST['catorder'][$i];
					$counter_id = $_POST['counter_id'][$i];
					if ($category_order == '' || !is_numeric($category_order)) {$category_order = 0;}
					$query = "UPDATE ".db('prefix')."categories SET catorder = '$category_order' WHERE id = '$counter_id' LIMIT 1";
					mysql_query($query);
				}
				notification('','','');
				echo '<meta http-equiv="refresh" content="1; url='.db('website').'categories/">';
			}
		break;
		case 'add_article':
			if (isset($_POST['submit_article'])) {
				if (substr($position, 0, 1) == 2) {
					$category = $_POST['define_category'];
					$page = $_POST['define_page'];
					if ($category != -1) {$position = '21'.$category;}
					else if ($page != 0) {$position = '22'.$page; $category = -1;}
				}	
				$_SESSION['temp']['title'] = $title; $_SESSION['temp']['seftitle'] = $seftitle; $_SESSION['temp']['text'] = $text;
				switch(true) {
				case(empty($title)): notification(l('err_TitleEmpty'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(empty($seftitle)):
					notification(l('err_SEFEmpty'),l('errNote'),'');
					$_SESSION['temp']['seftitle'] = $_SESSION['temp']['title']; form_articles(''); unset($_SESSION['temp']); break;
				case(cleancheckSEF($seftitle) == 'notok'): notification(l('err_SEFIllegal'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(check_if_unique('article_title', $title)): notification(l('err_TitleExists'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(check_if_unique('article_seftitle', $seftitle)): notification(l('err_SEFExists'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				default:
        			$query = "INSERT INTO ".db('prefix')."articles(title, seftitle, text, date, category, position, displaytitle, displayinfo, commentable, published, description_meta, keywords_meta) VALUES('$title', '$seftitle', '$text', '$date', '$category', '$position', '$display_title', '$display_info', '$commentable', '$publish_article', '$description_meta', '$keywords_meta')";
					mysql_query($query); $pos = substr($position, 0, 1);
					switch ($pos) {
						case 1: $link = 'articles/'; break;
						case 2: $link = 'extra_contents/'; break;
						case 3: $link = 'pages/'; break;
					}
					notification('','','');
					echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">'; unset($_SESSION['temp']);
				}
			}
		break;
		case 'edit_article':
			if (isset($_POST['submit_article'])) {
				if (substr($position, 0, 1) == 2) {
					$category = $_POST['define_category'];
					$page = $_POST['define_page'];
					if ($category != -1) {$position = '21'.$category;}
					else if ($page != 0) {$position = '22'.$page; $category = -1;}
				}
				$_SESSION['temp']['title'] = $title; $_SESSION['temp']['seftitle'] = $seftitle; $_SESSION['temp']['text'] = $text;
				switch(true) {
				case(empty($title)): notification(l('err_TitleEmpty'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(empty($seftitle)): notification(l('err_SEFEmpty'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(cleancheckSEF($seftitle) == 'notok'): notification(l('err_SEFIllegal'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(check_if_unique('article_title', $title, $id)): notification(l('err_TitleExists'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				case(check_if_unique('article_seftitle', $seftitle, $id)): notification(l('err_SEFExists'),l('errNote'),''); form_articles(''); unset($_SESSION['temp']); break;
				default:
					$query = "UPDATE ".db('prefix')."articles SET";
					$query_end = "WHERE id='$id' LIMIT 1";
		      		mysql_query($query." title='$title' ".$query_end);
		      		mysql_query($query." seftitle='$seftitle' ".$query_end);
		      		mysql_query($query." text='$text' ".$query_end);
		      		mysql_query($query." textlimit='$text_limit' ".$query_end);
		      		mysql_query($query." date='$date' ".$query_end);
		      		mysql_query($query." category='$category' ".$query_end);
		      		mysql_query($query." position='$position' ".$query_end);
		      		mysql_query($query." displaytitle='$display_title' ".$query_end);
					mysql_query($query." displayinfo='$display_info' ".$query_end);
		      		mysql_query($query." commentable='$commentable' ".$query_end);
					mysql_query($query." published='$publish_article' ".$query_end);
		      		mysql_query($query." description_meta='$description_meta' ".$query_end);
					mysql_query($query." keywords_meta='$keywords_meta' ".$query_end);
					$link = (substr($position, 0, 1) != 2) ? find_cat_sef($category).'/'.retrieve('seftitle', 'articles', 'id', $id).'/' : find_cat_sef($category).'/';
					notification('','','');
					echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">'; unset($_SESSION['temp']);
				}
			}
			if (isset($_POST['delete_article'])) {
				mysql_query("DELETE FROM ".db('prefix')."articles WHERE id='$id' LIMIT 1");
				mysql_query("DELETE FROM ".db('prefix')."comments WHERE articleid='$id'");
				$pos = substr($position, 0, 1);
				switch ($pos) {
					case 1: $link = 'articles/'; break;
					case 2: $link = 'extra_contents/'; break;
					case 3: $link = 'pages/'; break;
				}
				notification('','','');
				echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">';
			}
		break;
		case 'approvecomment':
			mysql_query("UPDATE ".db('prefix')."comments SET approved='True' WHERE id='$id' LIMIT 1");
			notification('','','');
			echo '<meta http-equiv="refresh" content="1; url='.db('website').'administration/">';
		break;
		case 'editcomment':
			$query = "UPDATE ".db('prefix')."comments SET";
			$query_end = "WHERE id='$commentid' LIMIT 1";
	   		mysql_query($query." name='$name' ".$query_end);
	  		mysql_query($query." url='$url' ".$query_end);
    		mysql_query($query." comment='$comment' ".$query_end);
    		mysql_query($query." approved='$approved' ".$query_end);
			$link = find_cat_sef($categoryid).'/'.retrieve('seftitle', 'articles', 'id', $id).'/';
			notification('','','');
			echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">';
		break;
		case 'freezecomments':
			$categoryId = retrieve('category', 'articles', 'id', $id);
      		mysql_query("UPDATE ".db('prefix')."articles SET commentable='FREEZ' WHERE id='$id' LIMIT 1");
			$link = find_cat_sef($categoryid).'/'.retrieve('seftitle', 'articles', 'id', $id).'/';
			notification('','','');
			echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">';
		break;
		case 'unfreezecomments':
			$categoryId = retrieve('category', 'articles', 'id', $id);
    		mysql_query("UPDATE ".db('prefix')."articles SET commentable='YES' WHERE id='$id' LIMIT 1");
			$link = find_cat_sef($categoryid).'/'.retrieve('seftitle', 'articles', 'id', $id).'/';
			notification('','','');
			echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">';
		break;
		case 'deletecomment':
      		$commentid = $_GET['commentid'];
    		$articleid = $_GET['articleid'];
       		mysql_query("DELETE FROM ".db('prefix')."comments WHERE id='$commentid' LIMIT 1");
			$link = find_cat_sef($categoryid).'/'.retrieve('seftitle', 'articles', 'id', $articleid).'/';
			notification('','','');
			echo '<meta http-equiv="refresh" content="1; url='.db('website').$link.'">';
		break;
	}
}

/*** FILES ***/
function files() {
	if (isset($_POST['upload']) && isset($_SESSION[db('website').'Logged_In']) && $_POST['ip'] == $_SERVER['REMOTE_ADDR'] && (time() - $_POST['time']) > 4) {
		if ($_FILES['imagefile']['type']) { 
			$upload_dir = $_POST['upload_dir'].'/';	 
			copy ($_FILES['imagefile']['tmp_name'], $upload_dir.$_FILES['imagefile']['name']) or die ('Could not copy'); notification('','','files/');
			$kb_size = round(($_FILES['imagefile']['size'] / 1024), 1);
        	echo '<p><a href="'.$upload_dir.$_FILES['imagefile']['name'].'" title="'.$_FILES['imagefile']['name'].'">'.$_FILES['imagefile']['name'].'</a> ['.$kb_size.' KB] ['.$_FILES['imagefile']['type'].']';
    		} else {echo '<h2>'.l('admin_error').'</h2><p>'.l('image_error').'</p>';}
		} else {
		if (isset($_GET['task']) == 'delete') {
			$file_to_delete = $_GET['folder'].'/'.$_GET['file'];
			@unlink($file_to_delete);
			notification('','','files/');
		} else {
			html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('upload'));
			echo '<form method="post" action="" enctype="multipart/form-data">';
			echo '<p><select name="upload_dir" id="ud" onChange="goto(this.form);">';
			echo '<option value=".">..</option>';
			filelist('option',".", 0);
			echo '</select><input type="file" name="imagefile" />';
			html_input('hidden', 'ip', 'ip', $_SERVER['REMOTE_ADDR'], '', '', '', '', '', '', '', '', '', '', '');
			html_input('hidden', 'time', 'time', time(), '', '', '', '', '', '', '', '', '', '', '');
			html_input('submit', 'upload', 'upload', l('upload'), '', '', '', '', '', '', '', '', '', '', '');
			echo '</p></form></fieldset>';
			html_input('fieldset', '', '', '', '', '', '', '', '', '', '', '', '', '', l('view').' '.l('files'));
			echo '<form method="post" action="" enctype="multipart/form-data">';
			echo $_POST['upload_dir'];
			echo '<p><select name="upload_dir" id="ud"><option value=".">..</option>';
			filelist('option',".");
			echo '</select>';
			html_input('hidden', 'file', 'file', $file, '', '', '', '', '', '', '', '', '', '', '');
			html_input('hidden', 'ip', 'ip', $_SERVER['REMOTE_ADDR'], '', '', '', '', '', '', '', '', '', '', '');
			html_input('hidden', 'time', 'time', time(), '', '', '', '', '', '', '', '', '', '', '');
			html_input('submit', 'show', 'show', l('view'), '', '', '', '', '', '', '', '', '', '', '');
			$handle = (isset($_POST['upload_dir']) && strlen($_POST['upload_dir']) > 2) ? substr($_POST['upload_dir'],2) : ".";
			echo '<p>';
			filelist('list',$handle);
			echo '</p></form></fieldset>';
}}}

// FILELIST FUNCTION
function filelist($mode, $path, $depth = 0) {
	$ignore = array('cgi-bin', '.htaccess', '.', '..', 'Thumbs.db');
	$extension = array('php', 'html');
	$dh = @opendir($path);
	while (false !== ($file = readdir($dh))) {
		if(!in_array($file, $ignore) && !in_array(substr($file, -3), $extension)) {
			$spaces = str_repeat(l('divider').' ',($depth));
			if($mode != "list" && is_dir("$path/$file")) {
				if ($_POST['upload_dir'] == $file) {$selected = ' selected="selected"';} else {$selected == '';}
				echo '<option value="'.$path.'/'.$file.'"'.$selected.'>'.$spaces.$file.'</option>';
			  	filelist("option", "$path/$file",($depth + 1));
			} else if (is_file("$path/$file")) {
				echo '<a href="'.db('website').$path.'/'.$file.'" title="'.l('view').' '.$file.'">'.$file.'</a> '.l('divider').' <a href="'.db('website').'index.php?action=files&amp;task=delete&amp;folder='.$path.'&amp;file='.$file.'" title="'.l('delete').' '.$file.'" onclick="return pop()">'.l('delete').'</a><br />';
			}
		}
	}
	closedir($dh);
}

// CONNECT TO DATABASE
function connect_to_db() {
	$db = mysql_connect(db('dbhost'), db('dbuname'), db('dbpass'));
	mysql_select_db(db('dbname')) or die(db('dberror'));
}

// SMART RETRIEVE FUNCTION
function retrieve($column, $table, $field, $value) {
	$query = "SELECT $column FROM ".db('prefix')."$table WHERE $field = '$value'";
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {$retrieve = $r[$column];}
	return $retrieve;
}

// FIND CATEGORY'S SEF TITLE THROUGH ARTICLE'S CATEGORY ID
function find_cat_sef($categoryid) {
	$query = "SELECT seftitle FROM ".db('prefix')."categories WHERE id = '$categoryid'";
	$result = mysql_query($query);
	while ($r = mysql_fetch_array($result)) {$cat_sef = $r['seftitle'];}
	$cat_sef_title = isset($cat_sef) ? $cat_sef : s('home_sef');
	return $cat_sef_title;
}

// CLEAN - cleaning query
function clean($query) {
	$query = mysql_real_escape_string(addslashes($query));
	return $query;
}

// CLEAN - XSS stuff clean.
function cleanXSS($text) {
	$allowedtags = "<strong><em><a><ul><li><pre><hr><blockquote><img><span>";
	$notallowedattribs = array("@javascript:|onclick|ondblclick|onmousedown|onmouseup"
	."|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup@si");
	$changexssto = '';
	$text = preg_replace($notallowedattribs, $changexssto, $text);
	$text = strip_tags($text, $allowedtags);
	$text = nl2br($text);
	$text = cleanWords($text);
	return $text;
}

// CLEAN - WORD FILTER
function cleanWords($text) {
	if ((strtolower(s('word_filter_enable')) == 'on') && (file_exists(s('addon_folder').'/'.s('word_filter_file')))) {
		$bad_words_from_what = preg_replace('/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/', '', file(s('addon_folder').'/'.s('word_filter_file')));
		$bad_words_from_what = preg_replace('/^(.*)$/', '/\\1/i', $bad_words_from_what);
		echo $test[0];
		$bad_words_to_what = s('word_filter_change');
		$text = preg_replace($bad_words_from_what, $bad_words_to_what, $text);
		return $text;
	} else {return $text;}
}

// CHECK IF UNIQUE
function check_if_unique($what, $text, $not_id = 'x') {
	switch ($what) {
		case 'article_seftitle': $sql = "articles WHERE seftitle = '".clean($text)."' AND id != '".$not_id."'"; break;
		case 'article_title': $sql = "articles WHERE title = '".clean($text)."' AND id != '".$not_id."'"; break;
		case 'category_seftitle': $sql = "categories WHERE seftitle = '".clean($text)."' AND id != '".$not_id."'"; break;
		case 'category_name': $sql = "categories WHERE name = '".clean($text)."' AND id != '".$not_id."'"; break;
	}
	$rows = mysql_num_rows(mysql_query("SELECT id FROM ".db('prefix').$sql));
	if ($rows == 0) {return false;}
	else {return true;}
}

// GET ID
function get_id($parameter) {
	$url = array();
	$url = explode('/', clean($_GET['category']));
  	$get_id = array();
	$get_id['category'] = $url['0'];
	if (isset($url['1'])) {$get_id['article'] = $url['1'];}
	if (isset($url['2'])) {$get_id['commentspage'] = $url['2'];}
	if (isset($get_id[$parameter])) {return $get_id[$parameter];}
}

//CATEGORY CHECK
function check_category($category) {
	$main_menu = explode(',', l('cat_listSEF'));
	if (in_array($category, $main_menu)) {return true;}
	else {return false;}
}

//FILE INCLUSION
function file_include($text, $shorten) {
	$fulltext = substr(stripslashes($text), 0, $shorten);
	$inc = strpos($fulltext, '[/include]');
	if ($inc > 0) {
		$text = str_replace('[include]', '|&|', $fulltext);
		$text = str_replace('[/include]', '|&|', $text);
		$text = explode('|&|', $text); 
		$num = count($text);
		$extension = explode(',', l('file_include_extensions'));
		for ($i = 0; ; $i++) {
			if ($i == $num) {break;}
			if (!in_array(substr($text[$i], -3), $extension)) {echo substr(stripslashes($text[$i]), 0);}
			else {
				if (preg_match("#^[a-z0-9_\-.\/]+$#i", $text[$i])) {
					$filename = $text[$i];
					file_exists($filename) ? include($filename) : print l('error_file_exists');
				} else {echo l('error_file_name');}
			}
		}
	} else {echo $fulltext;}
}
				
// ARTICLES - FUTURE POSTING
function update_articles() {
	mysql_query("UPDATE ".db('prefix')."articles SET published=1 WHERE published=2 AND date <= '".date("Y-m-d H:i:s")."'");
}

// MAKE A CLEAN SEF URL
function cleanSEF($string) {
	$string = str_replace(' ', '-', $string);
	$string = preg_replace('/[^0-9a-zA-Z-_]/', '', $string); 
	$string = str_replace('-', ' ', $string);
	$string = preg_replace('/^\s+|\s+$/', '', $string);
	$string = preg_replace('/\s+/', ' ', $string);
	$string = str_replace(' ', '-', $string);
	return strtolower($string);
}

function cleancheckSEF($string) {
	$ret = !ereg('^[_a-zA-Z0-9-]+$', $string) ? 'notok' : 'ok';
	return $ret;
}

// JAVASCRIPT FUNCTIONS
function js() { ?>
	<script type="text/javascript">
	//<![CDATA[
	var allowsef = /new|add|_ar|_ca/.test("<?php echo get_id('category').$_GET['action']; ?>");
	var allowpreview = /new|_add|_ar|/.test("<?php echo get_id('category').$_GET['action']; ?>");
	
	// copy title in the sef url field
	if (allowpreview == true) { window.onLoad = startPreview(); }
	function startPreview() { window.self.setInterval("updatePreview()", 5); }
		
	// generate SEF urls 	
	function genSEF(from,to) { 
		if (allowsef == true) {
			var str = from.value.toLowerCase();
			str = str.replace(/[^a-zA-Z 0-9]+/g,'');
			str = str.replace(/\s+/g, "-");		
			to.value = str;
		}
	}
	 
	// generate preview
	function updatePreview() {
		if (document.getElementById("txt")) {					
			var body = document.getElementById("txt").value;
			body = body.replace(/\n/g, '<br />');
			document.getElementById("preview").innerHTML = body;
		}
	}
	
	// settings home SEF restrict to alphanumeric
	function SEFrestrict(x) {
		if (window.event)
   			var key = window.event.keyCode;
		else if (x)
   			key = x.which;
		else
   			return true;
		var keychar = String.fromCharCode(key);
		keychar.toLowerCase();
		if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) )
   			return true;
		else if ((("abcdefghijklmnopqrstuvwxyz0123456789-_").indexOf(keychar) > -1))
   			return true;
		else
   			return false;
	}
	// delete warnings		
	function pop() {
		var agree=confirm("<?php echo l('warning_delete'); ?>");
		if (agree)
			return true;
		else
			return false;
	}
	
	// basic html textarea editor
	function tags(tag) {
    	var src = document.getElementById("txt");
    	if(tag == 'break'){ start = "[break]"; end = "";}	
    	else if(tag == 'img'){ 
	    	var url = prompt("<?php echo l('image_url'); ?>", "");
			var alt = prompt("<?php echo l('image_alt'); ?>", "");
			if(url != null) { start = "<img src=\""+url+"\" alt=\""+alt+"\" />"; end = ""; } else { start = ""; end = ""; }
		} else if(tag == 'link'){ var url = prompt("Enter URL:", "");
			if(url != null) { start = "<a href=\"" + url + "\">"; end = "</a>"; } else { start = ""; end = ""; }
		} else if(tag == 'include'){
	    	var url = prompt("<?php echo l('file_url'); ?>", "");
			if(url != null) { start = "[include]" + url + "[/include]"; end = ""; } else { start = ""; end = ""; }
		} else { var start = "<" + tag + ">"; var end = "</" + tag + ">"; }
		if(!src.setSelectionRange) { 
			var selected = document.selection.createRange().text; 
			if(selected.length <= 0) { src.value += start + end;
        	} else {
            	var codetext = start + selected + end; 
            	document.selection.createRange().text = codetext; 
        	}
		} else {
        	var pretext = src.value.substring(0, src.selectionStart);
        	var codetext = start + src.value.substring(src.selectionStart, src.selectionEnd) + end;
        	var posttext = src.value.substring(src.selectionEnd, src.value.length)
        	if(codetext == start + end)
            	codetext = start + end;
            	src.value = pretext + codetext + posttext;
    		}
		src.focus();
	}
	// toggle dynamic divs
	function toggle(div) {
		if (document.getElementById(div).style.display=='') {
			document.getElementById(div).style.display = 'none';
			return
		} document.getElementById(div).style.display = ''; 
	}	
	// dependancy limiter
	function dependancy() {
		var category = document.forms['post']['define_category'];
		var page = document.getElementById("def_page");
		if (category.options[category.selectedIndex].value == "-1") { page.style.display = 'inline'; } 
		else { page.style.display = 'none'; }
	}
	//]]>
	</script>
<?php } ?>