<?php

/*
 *  W-AGORA 4.2
 *  -----------
 *  $Id: view.php,v 1.80 2005/04/14 13:59:50 mdruilhe Exp $
 *  Usage:	display a note
 *  Author:	Marc Druilhe <mdruilhe@w-agora.net>
 */

function exit_error ($title="", $msg="") {
	global $site, $ext, $header_footer, $before_access;
	if (!empty($before_access)) include $before_access;
	display_header ($title, $header_footer);
	msgForm ($msg, "list.$ext", "");
	display_footer ($header_footer);
	exit;
}

# Initialization stuff
# --------------------
	$bn_action="view";
	$bn_action_mode="R";
	require ("init.inc");

	$where = "";	// must be defined in before_access

# Either thread or key ID must be set
# -----------------------------------
	$key = (int) getFormVar('key');
	$thread = (int) getFormVar('thread');
	if ( empty($key) && empty($thread) ) {
		exit_error ("error", ERROR_SPECIFY_KEY);
	}

# Handle view mode :
#	v=t => threaded mode
#	v=tr => threaded mode in reverse order (descending date)
#	v=f => flat mode in ascending date
#	v=fr => flat mode in reverse order (descending date)
# ------------------------------------------------------
	$set_url_view = false;
	$v = getFormVar('v');
	if (!is_null($v)) {
		$v = ( ($v=='f') || ($v=='fr') || ($v=='tr') ) ? $v : 't';	// default to thread mode
		if (!@setcookie ("${bn}_view", $v, time()+ 8640000, '/')) {
			$set_url_view = true;
		}
	} elseif (!empty($HTTP_COOKIE_VARS["${bn}_view"]) ) {
		$v = $HTTP_COOKIE_VARS["${bn}_view"];
	} else {
		$v = 't';
	}

# Adjust $key if $a is set (show next/previous message in thread)
# ---------------------------------------------------------------
	$a = getFormVar('a');
	if (!empty($a) ) {
		if (empty($key) ) {
			exit_error ("error", ERROR_SPECIFY_KEY);
		}
		if(empty($thread)) {
			$result = $db->query ("SELECT thread FROM $bn_db WHERE cle=$key");
			if (!$db->next_record() ) {
				exit_error ("error", ERROR_SPECIFY_KEY);
			}
			$thread = $db->f("thread");
		}
		if ($a == "next") {
			$db->query("select min(cle) as next from $bn_db where thread=$t and cle>$key order by unixdate");
			if ($db->next_record() ) {
				$navkey = $db->f("next");
			}
		} elseif ($a == "prev") {
			$db->query("select max(cle) as prev from $bn_db where thread=$t and cle<$key order by unixdate");
			if ($db->next_record() ) {
				$navkey = $db->f("prev");
			}
		}
		if (!empty($navkey)) {
			$key = $navkey;
		}
	}

# handle thread sorting in order to properly set links to next/previous thread in the current list
# ------------------------------------------------------------------------------------------------
	$set_url_sort = false;
	$sort = getFormVar('sort');
	if (!is_null($sort)) {
		list ($s, $o) = split(',', htmlspecialchars($sort), 2);
		$s = preg_replace('/\W/', '', $s);
		if ($o[0]=="d") {
			$sort = "$s,d";
			$threads_order = "$s DESC";
		} else {
			$sort = "$s";
			$threads_order = "$s";
		}
		if (!@setcookie ("${bn}_sort", $sort, 0, '/')) {
			$set_url_sort = true;
		}
	} elseif (!empty($HTTP_COOKIE_VARS["${bn}_sort"]) ) {
		$sort = $HTTP_COOKIE_VARS["${bn}_sort"];
		list ($s, $o) = split(',', $sort, 2);
		$o = ($o[0]=="d") ? "DESC" : "ASC";
		$threads_order = "$s $o";
	} else {
		$threads_order = (empty($default_threads_order)) ? "newest DESC" : $default_threads_order;
		list ($sort, $o) = split(' ', $threads_order, 2);
		if ($o=="DESC") {
			$sort .= ',d';
		}
	}

# read note from database, exit if error
# --------------------------------------
	if(empty($key)) {
		$key = $thread;
	}

	$note = $db->getNote ($bn_db, $key, $where, $threads_order);
	if ($note < 0) {
		exit_error ("error", sprintf(ERROR_NOTE_NOT_FOUND, $msg[0]));
	}

# set all fields as global variables
# ----------------------------------
	extract ($note);

# (4.0) Exit with error if this note is hidden
# --------------------------------------------
	if (!$is_moderator && ($note['hidden'] == '1') ) {
		exit_error ('forbidden', ERROR_FORBIDDEN_ACCESS);
	}

# save reply body (before formatting it)
# --------------------------------------
	if ($bn_view_reply) {
		$reply_body = strip_url(strip_smileys(stripSlashes($body)));
		$reply_subject = kill_quotes(stripSlashes($subject));
		if (!eregi ("^re:", $reply_subject)) {
			$reply_subject = "Re: $reply_subject";
		}

	}

# set URLs to be displayed in the toolbar
# ---------------------------------------

	// DOWNLOAD THREAD
	$download_thread_url = "download_thread.$ext?site=$site&bn=$bn&thread=$thread";
	$download_thread_text = LABEL_EXPAND_THREAD;
	if ( ($childs>0) || ($parent>0) ) {
		$download_thread_link = anchor ($download_thread_url, "", $download_thread_text, ALT_DOWNLOAD_THREAD);
	}

	// SUBSCRIBE TO THREAD
	$subscribe_thread_url = "subscribe_thread.$ext?site=$site&bn=$bn&thread=$thread";
	$subscribe_thread_text = LABEL_SUBSCRIBE_THREAD;
	if ($bn_user_mail && $bn_thread) {
		$subscribe_thread_link = anchorWindow ($subscribe_thread_url, $subscribe_thread_text, ALT_RECEIVE_UPDATES, 620, 460);
	}

	$bn_view_reply = ($bn_thread && ($forum['state'] == '1') && ( ($forum["type"]=="pub") || $auth->havePermission($bn, "W") ) ) ? $bn_view_reply :  false;

	// CLOSE
	$close_url = "close.$ext?bn=$bn&key=$key";
	$close_text = LABEL_CLOSE_OPEN_THREAD;
	if ($is_moderator && $bn_thread) {
		$close_link = anchor ($close_url, "", $close_text, $close_text );
	}

	// LIST
	$e = '';
	// $e = (empty($expnd) ) ? "&expnd=$thread" : "&expnd=$expnd";
	$list_url = "list.$ext?bn=$bn&here=$key".$nav.$e;
	if ($set_url_sort) {
		$list_url .= "&sort=".urlencode($sort);
	}
	$list_text = LABEL_LIST;
	$list_link = anchor ($list_url, "", $list_text, ALT_BACK_TO_LIST );

	// PREVIOUS / NEXT THREAD
	$view_prev_text = LABEL_PREV_THREAD;
	if (!empty($note["tprev"])) {
		$tprev = $note["tprev"];
		$view_prev_url = "$WA_SELF?bn=$bn&key=$tprev".$nav;
		if ($set_url_sort) {
			$view_prev_url .= "&sort=".urlencode($sort);
		}
		$view_prev_link = anchor ($view_prev_url, "", $view_prev_text, ALT_PREV_THREAD);
	} else {
		$view_prev_url = "";
		$view_prev_link = "";
	}

	$view_next_text = LABEL_NEXT_THREAD;
	if (!empty($note["tnext"])) {
		$tnext = $note["tnext"];
		$view_next_url = "$WA_SELF?bn=$bn&key=$tnext".$nav;
		if ($set_url_sort) {
			$view_next_url .= "&sort=".urlencode($sort);
		}
		$view_next_link = anchor ($view_next_url, "", $view_next_text, ALT_NEXT_THREAD);
	} else {
		$view_next_url = "";
		$view_next_link = "";
	}


	// PREVIOUS / NEXT NOTE

	$prev_note_text = LABEL_PREV_NOTE_IN_THREAD;
	if ($cle != $thread) {
		$prev_note_url = "$WA_SELF?bn=$bn&t=$thread&key=$key&a=prev".$nav;
		$prev_note_link = anchor ($prev_note_url, "", LABEL_PREV_NOTE_IN_THREAD, ALT_PREV_NOTE_IN_THREAD);
	} else {
		$prev_note_url = "";
		$prev_note_link = "";
	}

	$next_note_text = LABEL_NEXT_NOTE_IN_THREAD;
	if ($unixdate != $newest) {
		$next_note_url = "$WA_SELF?bn=$bn&t=$thread&key=$key&a=next".$nav;
		$next_note_link = anchor ($next_note_url, "", LABEL_NEXT_NOTE_IN_THREAD, ALT_NEXT_NOTE_IN_THREAD);
	} else {
		$next_note_url = "";
		$next_note_link = "";
	}

# set the thread navigation bar (next/prev thread in forum)
# --------------------------------------------------------
	$label_current_thread = LABEL_CURRENT_THREAD;
	$nav_bar = '<div class="navbar"><span class="nav_link">'.$view_prev_link.'</span>';
	$nav_bar .= '<span class="nav_link">'.$view_next_link.'</span></div>';

# set the note navigation bar (next/prev. note in thread)
# -------------------------------------------------------
	$note_nav_bar = '<div class="navbar"><span class="nav_link">'.$prev_note_link.'</span>';
	$note_nav_bar .= '<span class="nav_link">'.$next_note_link.'</span></div>';

# read complete thread
# --------------------
	$expnd="all";
	$list_var["body"]=1;    // forces body to be listed
	$order = ($v[1] == 'r') ? 'd' : 'a';
	$display = ($v[0] == 't') ? 't' : 'f';

	$msgcount = $db->getThread ($bn_db, $key, $thread, $order, $display, $is_moderator);
	if ($msgcount < 1) {
		exit_error ("error", sprintf(ERROR_NOTE_NOT_FOUND, $msg[0]));
	}

# Set the navigation bar
# ----------------------
	$view_url = "view.$ext?bn=$bn&thread=$thread";
	if($set_url_view) {
		$view_url .= "&v=$v";
	}
	if ($set_url_sort) {
		$view_url .= "&sort=".urlencode($sort);
	}
	$st = (int) getFormVar('st', 0);	// start key
	$page_nav_bar = getNavBar($view_url, $msgcount, $st, $bn_maxthreads, 5, true, 'st');

# Execute before_access program
# -----------------------------
	if (!empty($before_access)) include $before_access;

# Increments hits count
# ---------------------
	if (!$bn_no_stats) {
		$hoe = $db->setHaltOnError('report'); // skip possible DB errors
		$increment_hits = true;
		if ($note['userid'] == "guest") {
			if ($note['unixdate'] > time()-5*60 ) {
				$increment_hits = ($note['ip'] == get_remote_ip() ) ? false : true;
			}
		} elseif ($note['userid'] == $auth->userid) {
			$increment_hits = false;
		}
		if ($increment_hits) {
			$hits++;
			$db->query("UPDATE $bn_db SET hits=hits+1 WHERE cle=$key");
		}
		if ($is_authenticated) {
			$_u = $db->preserveQuotes($auth->userid);
			$db->query("UPDATE ${site}_userforum SET totalread=totalread+1 WHERE bn_name='$bn' AND userid='$_u'");
		}
		$db->addLogEntry ($bn, 'view', $auth->userid, $thread, $key);
		$db->setHaltOnError($hoe);
	}

# set the tool bar (download - subscribe - reply ...)
# ---------------------------------------------------
	$tool_bar = '<div class="toolbar">';
	if (!empty($download_thread_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$download_thread_link.'</span>';
	}
	if (!empty($subscribe_thread_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$subscribe_thread_link.'</span>';
	}
	if (!empty($reply_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$reply_link.'</span>';
	}
	if (!empty($edit_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$edit_link.'</span>';
	}
	if (!empty($delete_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$delete_link.'</span>';
	}
	if (!empty($mail_moder_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$mail_moder_link.'</span>';
	}
	if (!empty($close_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$close_link.'</span>';
	}
	if (!empty($list_link)) {
		$tool_bar .= '<span class="toolbar_link">'.$list_link.'</span>';
	}
	$tool_bar .= '</div>';

# Display HTML headers and  header include file if any
# ----------------------------------------------------
	display_header (stripSlashes($subject), $header_footer);

# display navigation bar
# ----------------------
	if (!$bn_no_nav_bar) {
		print $nav_bar;
	}

# Display note and attachments (using template)
# ---------------------------------------------
	$viewkey = $key;
	include "$inc_dir/viewnote.$ext";

# Display toolbar (optional)
# --------------------------
	if (!$bn_no_toolbar) {
		print $tool_bar;
	}

# display current thread
# ----------------------
	if ($bn_thread && !$bn_no_thread_list) {
		$here=$key;
		$expnd="all";

		require_once "$inc_dir/listrenderer.$ext";
		$list =& new ListRenderer($db, $st, $bn_maxthreads);
		$list->displayList(0, 'view');
		print $page_nav_bar;
	}

# Display form reply if option set
# --------------------------------
	if ($bn_view_reply) {
		$bn_action="reply";
		$bn_action_mode="W";
		comment ("REPLY FORM");

		// set user's name and e-mail
		$reply_name = stripSlashes($username);
		$reply_address = stripSlashes($useraddress);
		$username = "";
		$useraddress = "";

		$subject = $reply_subject;
		if ($reply_body) {
			if ($reply_name != "") {
				$quoted_text = sprintf (LABEL_WROTE, $reply_name) . "\n";
			}
			$quoted_text .= quote_text($reply_body);
			$body = "";
		}

#	Displays the FORM
# -----------------
		$setUserField = true;       // Set username and password in form fields
		$mail_reply = $default_mail_reply; //	reset to default value
		$form_action = "insert.$ext";
		$back_form="view";
		$bn_popup=0;

		include "$inc_dir/form.$ext";
	}

# Display footer
# --------------
	display_footer ($header_footer);
?>
