<?php
/***************************************************************************
 *                     functions_guestbook.php
 *                            -------------------
 *      Разработка: paul999.
 *      Оптимизация под WAP: Гутник Игорь ( чел ).
 *                   2011 год
 ***************************************************************************/

if (!defined('IN_PHPBB'))
{
	die("Hacking attempt");
}

class guestbook{
	var $userdata;
	var $uid;
	var $url;
	var $url_intern;
	function guestbook(&$uid, $mode = false, $url = false)
	{
		global $phpEx;

		$this->userdata = $uid;
		$this->uid = $this->userdata['group_id'];
		$this->version = '1.0.8';

		if($url !== false)
		{
			$tmp = explode("?", $url);
			if(!count($tmp))
			{
				$url = false;
			}
			else
			{
				if(!file_exists($tmp[0]))
				{
					$url = false;
				}
			}
		}

		if($url === false )
		{
			$this->url_intern = "groupcp." . $phpEx . "?" . POST_GROUPS_URL . "=" . $this->uid;
		}
		else
		{
			$this->url_intern = $url;
		}

		if(!$mode)
		{
			return true;
		}
		else
		{
			return $this->mode($mode);
		}
	}
	function mode($mode)
	{
		global $userdata,$board_config,$lang;
		global $HTTP_GET_VARS, $template, $HTTP_POST_VARS, $phpbb_root_path, $phpEx, $db;

		if(!$userdata['session_logged_in'])
		{
			return false;
		}
		else
		{
			if ( isset($HTTP_POST_VARS['cancel']) )
			{
				$redirect = "groupcp." . $phpEx . "?" . POST_GROUPS_URL . "=" . $this->uid;
				$msg = 'Отменено<br/><br/><a href="' . append_sid($redirect) . '">'.$lang['back_pro'] . '</a>';	
				message_die(GENERAL_MESSAGE,$msg);
			}
			$confirm = ( $HTTP_POST_VARS['confirm'] ) ? TRUE : 0;
			if(($mode == 'delete' || $mode == 'deleteall') && !$confirm)
			{
				$hidden_fields = '<input type="hidden" name="sid" value="' . $userdata['session_id'] . '" /><input type="hidden" name="mode" value="' . $mode . '" /><input type="hidden" name="gb_id" value="' . intval($HTTP_GET_VARS['gb_id']) . '" />';

				$template->set_filenames(array(
					'confirm' => 'confirm_body.tpl')
				);

				$template->assign_vars(array(
					'MESSAGE_TITLE' => $lang['Confirm'],
					'MESSAGE_TEXT' => ( $mode == 'delete' ) ? $lang['Confirm_delete'] : $lang['Confirm_delete_gbpost'],

					'L_YES' => $lang['Yes'],
					'L_NO' => $lang['No'],

					'S_CONFIRM_ACTION' => append_sid($this->url_intern . "&amp;gb=" . $mode),
					'S_HIDDEN_FIELDS' => $hidden_fields)
				);

				$template->pparse('confirm');

				include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
			}
			switch($mode){
				case "view":
					$this->view();
				break;
				case "quote":
				case "post":
				case "edit":
					$sql_per = "SELECT g.*, ug.*
						FROM " . GROUPS_TABLE . " g, " . USER_GROUP_TABLE . " ug 
						WHERE g.group_id = " . $this->uid . "
							AND ug.group_id = g.group_id
							AND ug.user_id = " . $userdata['user_id'] . "
							AND ug.user_pending = 0";
					if ( !($result_per = $db->sql_query($sql_per)) )
					{
						message_die(GENERAL_ERROR, "Couldn't obtain user/group information", "", __LINE__, __FILE__, $sql_per);
					}
					$quick_valid_per = ( ($db->sql_fetchrow($result_per) && $userdata['user_level'] > ANONYMOUS) || $userdata['user_level'] == ADMIN ) ? true : false;
					if( !$quick_valid_per )
					{
						message_die(GENERAL_MESSAGE,sprintf($lang['gb_no_per'],$lang['post_pro']));
					}
					else
					{
						$this->post($mode);
					}
				break;
				case "delete":
					if($userdata['user_level'] == ADMIN || $userdata['user_id'] == $this->userdata['group_moderator'])
					{
						$this->delete();
					}
					else
					{
						message_die(GENERAL_MESSAGE,sprintf($lang['gb_no_per'],$lang['delete_pro']));
					}
				break;
				case "deleteall":
					if($userdata['user_level'] == ADMIN || $userdata['user_id'] == $this->userdata['group_moderator'])
					{
						$this->deleteall();
					}
					else
					{
						message_die(GENERAL_MESSAGE,sprintf($lang['gb_no_per'],$lang['delete_all_pro']));
					}
				break;
				default:
					return false;
			}
		}
		return true;
	}
	
	function view()
	{
		global $db, $HTTP_GET_VARS, $HTTP_POST_VARS, $board_config, $start_gb;

		$sql = "SELECT * FROM ".GROUPS_GUESTBOOK_TABLE." g, ".USERS_TABLE." u
				WHERE g.group_id = ".$this->uid." AND g.poster_id = u.user_id
				ORDER BY g.gb_time DESC
				LIMIT $start_gb, " . $board_config['posts_per_page'];
		if( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR,"Could not query guestbook","",__LINE__,__FILE__,$sql);
		}
		if( !$db->sql_numrows($result) )
		{
			if($start_gb == 0)
			{
				$this->maak_view($result,'nores',1);
			}
			else
			{
				$this->maak_view($result,'nopag',1);
			}
		}
		else
		{
			$this->maak_view($result,'',0);
		}
	}
	function maak_view($result, $fout = '', $tot)
	{
		global $phpbb_root_path, $phpEx, $template, $lang, $group_info, $userdata, $images, $board_config, $start_gb;
		global $db,$theme,$HTTP_GET_VARS;

		include_once($phpbb_root_path."includes/bbcode.".$phpEx);
		$template->set_filenames(array(
			'gb_body' => 'gb_view.tpl')
		);
		if($userdata['user_id'] == $this->userdata['group_moderator'] || $userdata['user_level'] == ADMIN)
		{
			$u_deleteall = sprintf($lang['gb_text2'],append_sid($this->url_intern . "&amp;gb=deleteall"));
		}
		$template->assign_vars(array(
			"L_GUESTBOOK" => $lang['gb_txt'],
			"U_DELETEALL" => $u_deleteall,
			"L_BACK_TO_TOP" => $lang['Back_to_top'],
			"MINI_POST_IMG" => $images['icon_minipost'],
			"UID" => $this->uid,
			"U" => POST_USERS_URL,
			"URL" => $board_config['server_name'],
			"PAD" => $board_config['script_path'],
			"SECURE" => ($board_config['cookie_secure']) ? "s" : '',
			"PHPEX" => $phpEx)
		);
		if($fout != '')
		{
			$reply_topic_url = append_sid($this->url_intern . 'gb=post');
			$template->assign_vars(array(
				'U_POST_REPLY_TOPIC' => $reply_topic_url)
			);
			switch($fout)
			{
				case "nores":
					$template->assign_block_vars("error",array(
						"ERROR" => $lang['gb_nores']
					));
				break;
				case "nopag":
					$template->assign_block_vars("error",array(
						"ERROR" => $lang['gb_error']
					));
				break;
			}
		}
		else
		{
			$postrow = array();
			$row = $db->sql_fetchrow($result);
			do
			{
				$postrow[] = $row;
			}
			while ($row = $db->sql_fetchrow($result));
			$db->sql_freeresult($result);

			$total_posts = count($postrow);

			$orig_word = array();
			$replacement_word = array();
			obtain_word_list($orig_word, $replacement_word);

			$sql2 = "SELECT COUNT(gb_id) AS total FROM " . GROUPS_GUESTBOOK_TABLE . " WHERE group_id = " . $this->uid;
			if( !($result2 = $db->sql_query($sql2)) )
			{
				message_die(GENERAL_ERROR,"Could not get total of guestbook posts!","",__LINE__,__FILE__,$sql2);
			}
			$total_replies = $db->sql_fetchrow($result2);
			$total_replies = $total_replies['total'];

			$pagination = ( $total_replies > $board_config['posts_per_page'] ) ? generate_pagination('groupcp.' . $phpEx . '?gb=view&' . POST_GROUPS_URL . '='.$this->uid, $total_replies, $board_config['posts_per_page'], $start_gb) : '';

			$template->assign_vars(array(
				'PAGINATION_GB' => $pagination)
			);

			for($i = 0; $i < $total_posts; $i++)
			{
				$post_nr = $i + $start_gb + 1;

				$poster_id = $postrow[$i]['poster_id'];
				$poster = $postrow[$i]['username'];
				$post_date = create_date($board_config['default_dateformat'], $postrow[$i]['gb_time'], $board_config['board_timezone']);
				$poster_posts = '[' . $postrow[$i]['user_posts'].']';

				$temp_url = append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=$poster_id");
				$poster = '<a href="' . $temp_url . '">'.$poster.'</a>';

				$temp_url = append_sid($this->url_intern . "&amp;gb=quote&amp;gb_id=" . $postrow[$i]['gb_id']);
				$quote = '<a href="' . $temp_url . '">Цит</a>';

				if ($userdata['user_id'] == $poster_id || $userdata['user_level'] == ADMIN || $userdata['user_id'] == $this->userdata['group_moderator'])
				{
					$temp_url = append_sid($this->url_intern . "&amp;gb=edit&amp;gb_id=".$postrow[$i]['gb_id']);
					$edit = '|<a href="' . $temp_url . '">Изм</a>';
				}
				else
				{
					$edit = '';
				}

				if ($userdata['user_level'] == ADMIN || $userdata['user_id'] == $this->userdata['group_moderator'])
				{
					$temp_url = append_sid($this->url_intern . "&amp;gb=delete&amp;gb_id=" . $postrow[$i]['gb_id']);
					$delpost = '|<a href="' . $temp_url . '">Уд</a>';
				}
				else
				{
					$delpost = '';
				}

				$message = stripslashes($postrow[$i]['message']);
				$bbcode_uid = $postrow[$i]['bbcode'];

				if ( $bbcode_uid != '' )
				{
					$message = ( $board_config['allow_bbcode'] ) ? bbencode_second_pass($message, $bbcode_uid) : preg_replace('/\:[0-9a-z\:]+\]/si', ']', $message);
				}

				$message = make_clickable($message);
				$message = smilies_pass($message);

				$message = str_replace("\n", "\n<br />\n", $message);
				$row_class = ( !($i % 2) ) ? 'row_easy' : 'row_hard';
				
				$template->assign_block_vars('postrow', array(
					'U_POST_ID' => $postrow[$i]['gb_id'],
					'ROW_CLASS' => $row_class,
					'POSTER_NAME' => $poster,
					'POSTER_POSTS' => $poster_posts,
					'POST_DATE' => $post_date,
					'MESSAGE' => $message,

					'EDIT' => $edit,
					'QUOTE' => $quote,
					'DELETE' => $delpost,
					'NUMBER' => $post_nr
				));
			}
		}
		include_once($phpbb_root_path."includes/functions_post.".$phpEx);

		$quick_valid = true;

		$sql = "SELECT g.*, ug.*
			FROM " . GROUPS_TABLE . " g, " . USER_GROUP_TABLE . " ug 
			WHERE g.group_id = " . $this->uid . "
				AND ug.group_id = g.group_id
				AND ug.user_id = " . $userdata['user_id'] . "
				AND ug.user_pending = 0";
		if ( !($result = $db->sql_query($sql)) )
		{
			message_die(GENERAL_ERROR, "Couldn't obtain user/group information", "", __LINE__, __FILE__, $sql);
		}
		$quick_valid = ( ($db->sql_fetchrow($result) && $userdata['user_level'] > ANONYMOUS) || $userdata['user_level'] == ADMIN ) ? true : false;

		if($quick_valid)
		{
			$template->assign_block_vars('quick',array());
		}
		
		$action = append_sid($this->url_intern . "&amp;gb=post");
		
		$template->assign_vars(array(
			'L_POST_QUICK' => $lang['gb_quick_reply'],
			'L_GB_POST' => $lang['gb_post2'],
			'L_MESSAGE_BODY' => $lang['Message_body'],
			'L_SUBMIT' => $lang['Submit'],
			'L_USERNAME' => $lang['Username'],
			'U_PROFILE' => append_sid('groupcp.'.$phpEx.'?'.POST_GROUPS_URL.'='.$this->uid),

			'S_POST_ACTION' => $action)
		);
		$template->assign_var_from_handle('GUESTBOOK', 'gb_body');
	}
	
	function post($mode)
	{
		global $board_config,$userdata,$lang,$HTTP_POST_VARS,$phpbb_root_path,$phpEx,$db,$HTTP_GET_VARS,$unhtml_specialchars_replace,$unhtml_specialchars_match,$html_entities_match,$html_entities_replace;

		if(isset($HTTP_POST_VARS['message']))
		{
			$me = $HTTP_POST_VARS['message'];
			include_once($phpbb_root_path."includes/bbcode.".$phpEx);
			include_once($phpbb_root_path."includes/functions_post.".$phpEx);

			$bbcode = make_bbcode_uid();
			$me = prepare_message($me,$board_config['allow_html'],true,true,$bbcode);
			$err = false;
			$errmsg = array();
			if(empty($me))
			{
				$errmsg[] = $lang['gb_no_me'];
				$err = true;
			}
			else
			{
				$message_validate = bbencode_second_pass($me, $bbcode);
				$message_validate = strip_tags($message_validate);
				$message_validate = trim($message_validate);
				if (empty($message_validate))
				{
					$errmsg[] = $lang['gb_no_me'];
					$err = true;
				}
			}

			$id = abs(intval($HTTP_GET_VARS['gb_id']));

			if($err)
			{
				$action = append_sid($this->url_intern . "&amp;gb=$mode&amp;gb_id=$id");
				$this->post_table($me,$action,$bbcode,$errmsg);
				return;
			}

			$pid = $userdata['user_id'];
			if($mode != 'edit')
			{
				$sql = "SELECT MAX(gb_time) AS last_post_time
					FROM " . GROUPS_GUESTBOOK_TABLE . "
					WHERE poster_id = " . $userdata['user_id'];
				if ($result = $db->sql_query($sql))
				{
					if ($row = $db->sql_fetchrow($result))
					{
						if (intval($row['last_post_time']) > 0 && (time() - intval($row['last_post_time'])) < intval($board_config['flood_interval']))
						{
							message_die(GENERAL_MESSAGE, $lang['Flood_Error']);
						}
					}
				}

				$sql = "INSERT INTO ".GROUPS_GUESTBOOK_TABLE." (group_id, poster_id, bbcode, message, gb_time) VALUES
				(".$this->uid.",$pid,'$bbcode','" . str_replace("\'", "''", $me) . "','".time()."')";
			}
			else
			{
				if(empty($id))
				{
					message_die(GENERAL_ERROR,$lang['gb_no_id'],"",__LINE__,__FILE__);
				}
				$sql = "UPDATE ".GROUPS_GUESTBOOK_TABLE."
					SET bbcode = '$bbcode', message = '" . str_replace("\'", "''", $me) . "'
					WHERE gb_id = $id";
			}
			$result = $db->sql_query($sql);
			if(!$result)
			{
				message_die(GENERAL_ERROR,"Could not insert or update user guestbook!","",__LINE__,__FILE__,$sql);
			}

			$id = $db->sql_nextid();
			$msg = '<br/><br/><a href="' . append_sid($this->url_intern . "&amp;gb=view") . '#' . $id . '">'.$lang['back_pro'] . '</a>';	
			if($mode == 'edit')
			{
				message_die(GENERAL_MESSAGE,$lang['gb_edit'].$msg);
			}
			else
			{
				message_die(GENERAL_MESSAGE,$lang['gb_post'].$msg);
			}

		}
		else
		{
			if($mode == 'edit')
			{
				$id = abs(intval($HTTP_GET_VARS['gb_id']));
				if(empty($id))
				{
					message_die(GENERAL_ERROR,$lang['gb_no_id'],"",__LINE__,__FILE__);
				}
				$action = append_sid($this->url_intern . "&amp;gb=edit&amp;gb_id=" . $id);
				$sql = "SELECT * FROM ".GROUPS_GUESTBOOK_TABLE." WHERE gb_id = $id";;
				$r = $db->sql_query($sql);
				if(!$r)
				{
					message_die(GENERAL_ERROR,"Could not select edit information!",__LINE__,__FILE__,$sql);
				}
				$row = $db->sql_fetchrow($r);
				if($userdata['user_level'] != ADMIN && $userdata['user_id'] != $this->userdata['group_moderator'] && $row['poster_id'] != $userdata['user_id'])
				{
					message_die(GENERAL_MESSAGE,sprintf($lang['gb_no_per'],$lang['edit_pro']));
				}
				$me = $row['message'];
				if ( $row['bbcode'] != '' )
				{
					$me = preg_replace('/\:(([a-z0-9]:)?)' . $row['bbcode'] . '/s', '', $me);
				}
			}
			elseif($mode == 'quote')
			{
				$action = append_sid($this->url_intern . "&amp;gb=post");
				$id = abs(intval($HTTP_GET_VARS['gb_id']));
				if(empty($id))
				{
					message_die(GENERAL_ERROR,$lang['gb_no_id'],"",__LINE__,__FILE__);
				}
				$sql = "SELECT * FROM ".GROUPS_GUESTBOOK_TABLE." g, ".USERS_TABLE." u WHERE g.gb_id = $id AND u.user_id = g.poster_id";
				$result = $db->sql_query($sql);
				if(!$result)
				{
					message_die(GENERAL_ERROR,"Could not select edit information!",__LINE__,__FILE__,$sql);
				}
				$row = $db->sql_fetchrow($result);
				$me = $row['message'];
				if ( $row['bbcode'] != '' )
				{
					$me = preg_replace('/\:(([a-z0-9]:)?)' . $row['bbcode'] . '/s', '', $me);
				}
				$me = '[quote="' . $row['username'] . '"]' . $me . '[/quote]';
			}
			else
			{
				$action = append_sid($this->url_intern . "&amp;gb=post");
				$me = '';
			}
			$this->post_table($me,$action);
			return;
		}
	}

	function post_table($me,$action,$bbcode = '',$errmsg = array())
	{
		global $phpbb_root_path,$phpEx,$template,$mode,$userdata,$lang,$db,$unhtml_specialchars_replace,$unhtml_specialchars_match,$html_entities_match,$html_entities_replace;

		include_once($phpbb_root_path."includes/bbcode.".$phpEx);
		include_once($phpbb_root_path."includes/functions_post.".$phpEx);
		$template->set_filenames(array(
			'body' => 'gb_post.tpl')
		);
		if(count($errmsg) > 0)
		{
			$template->set_filenames(array(
				'reg_header' => 'error_body.tpl')
			);
			$error_msg = $lang['gb_error'];
			for($i = 0;$i<count($errmsg);$i++)
			{
				$error_msg .= ': '.$errmsg[$i];
			}
			$template->assign_vars(array(
				'ERROR_MESSAGE' => $error_msg)
			);
			$template->assign_var_from_handle('ERROR_BOX', 'reg_header');
		}
		if ( $bbcode != '' )
		{
			$me = preg_replace('/\:(([a-z0-9]:)?)' . $bbcode . '/s', '', $me);
		}
		$me = unprepare_message($me);
		$template->assign_vars(array(
			'MESSAGE' => stripslashes($me),

			'L_GB_POST' => $lang['gb_txt'],
			'L_MESSAGE_BODY' => $lang['Message_body'],
			'L_SUBMIT' => $lang['Submit'],
			'L_EMPTY_MESSAGE' => $lang['Empty_message'],
			'U_PROFILE' => append_sid('groupcp.'.$phpEx.'?'.POST_GROUPS_URL.'='.$this->uid),

			'S_POST_ACTION' => $action)
		);
		$template->pparse('body');
		include_once($phpbb_root_path."includes/page_tail.".$phpEx);
	}
	function deleteall()
	{
		global $db,$lang,$phpEx;
		$sql = "DELETE FROM ".GROUPS_GUESTBOOK_TABLE." WHERE group_id = ".$this->uid."";
		if(!$db->sql_query($sql))
		{
			message_die(GENERAL_ERROR,"Could not delete guestbook posts!","",__LINE__,__FILE__,$sql);
		}
		$msg = '<br/><br/><a href="' . append_sid($this->url_intern . "&amp;gb=view") . '">'.$lang['back_pro'].'</a>';
		message_die(GENERAL_MESSAGE,$lang['gb_all_del'] . $msg);
	}
	function delete()
	{
		global $lang,$HTTP_POST_VARS,$db,$phpEx;
		$id = intval($HTTP_POST_VARS['gb_id']);
		if(empty($id))
		{
			message_die(GENERAL_ERROR,$lang['gb_no_id'],"",__LINE__,__FILE__);
		}
		$sql = "DELETE FROM ".GROUPS_GUESTBOOK_TABLE." WHERE group_id = ".$this->uid." AND gb_id = $id";
		if(!$db->sql_query($sql))
		{
			message_die(GENERAL_ERROR,"Could not delete guestbook posts!","",__LINE__,__FILE__,$sql);
		}
		$msg = '<br/><br/><a href="' . append_sid($this->url_intern . "&amp;gb=view") . '">'.$lang['back_pro'].'</a>';
		message_die(GENERAL_MESSAGE,$lang['gb_del'] . $msg);
	}
}

?>