<?
/*======================================================================*\
|| #################################################################### ||
|| # vBoard 1.0 Release Candidate 1 Updated Feb 13, 2005              # ||  
|| # ---------------------------------------------------------------- # ||
|| # Copyright @2005 PHPHOST Enterprises Ltd. All Rights Reserved.    # ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # http://www.phphost.cn                                            # ||
|| #################################################################### ||
\*======================================================================*/


error_reporting(E_ALL & ~E_NOTICE);
define('THIS_SCRIPT', 'local_links');
define('ADMIN_SCRIPT', 'local_links_admin');

// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array();

// pre-cache all templates used by this hack
$globaltemplates = array(
	'links_addnewcat',
	'links_addnewlink',
	'links_addnewlink_select',
	'links_catbit',
	'links_catmod',
	'links_footer',
	'links_header',
	'links_linkbit',
	'links_linkseparator',
	'links_main',
	'links_modbit',
	'links_othercatsbit',
	'links_ratebit',
	'links_search',
	'links_subcatbit',
	'navbar',
	'option'
);

// get special data templates from the datastore
$specialtemplates = array(
	'smiliecache',
	'bbcodecache'
);

// pre-cache templates used by specific actions
$actiontemplates = array();

// ######################### REQUIRE BACK-END ############################
require_once('./global.php');
require_once("includes/local_links_include.php");

if (!isset($_REQUEST['action']) or $_REQUEST['action']=="") $_REQUEST['action'] = "links";

// #################### Links Home

if ($_REQUEST['action'] == "links") {

	require_once('includes/functions_bbcodeparse.php');
	$this_navigation_title = "下载中心";

	if (!$perpage) $perpage = $bbuserinfo['maxposts'];
	$checkmax = explode(',', $vboptions['usermaxposts'] . ',' . $vboptions['maxposts']);
	if ($perpage < 1 OR $perpage > max($checkmax)) $perpage = $vboptions['maxposts'];
	$perpage = iif($links_defaults['links_per_page']!=0, $links_defaults['links_per_page'], $perpage);
	build_forum_list();

// fetch the permissions for each forum
	$limitfids = array(0);
	if (!$links_permissions['can_see_protected_links_on_portal']) {
		$forumperms = array();
		foreach ($forumcache AS $forum) {
			if (isset($forum['forumid'])) {
				$forumperms["$forum[forumid]"] = fetch_permissions($forum['forumid']);
				if (!($forumperms["$forum[forumid]"] & CANVIEW) || !($forumperms["$forum[forumid]"] & CANVIEWOTHERS)) {
					$limitfids[] = $forum['forumid'];
				}
			}
		}
	}

	if (!isset($_REQUEST['page']) or $_REQUEST['page']=="") $_REQUEST['page'] = '1';
	$pagenumber = iif( is_numeric($_REQUEST['page']), $_REQUEST['page'], '1');

	if (!isset($_REQUEST['catid']) or !is_numeric($_REQUEST['catid'])) $_REQUEST['catid'] = $BASE_CAT;
	$viewcatid = $_REQUEST['catid'];

	if (isset($linkscat[$viewcatid]) and in_array($linkscat[$viewcatid]["catforum"], $limitfids)) {
		print_no_permission();
		exit;
	} else {
		if (!$links_permissions["can_moderate_links"] and ($viewcatid==$HIDE_CAT or $viewcatid==$AVL_CAT or $viewcatid==$BRKN_CAT or $viewcatid==$INVD_CAT)) {
			print_no_permission();
			exit;
		}
	}

	if (!isset($_REQUEST['sort']) or $_REQUEST['sort']=="") {
		$_REQUEST['sort'] = iif(isset($links_defaults['default_sort_order']), $links_defaults['default_sort_order'], 'N');
	}
	$sort = $_REQUEST['sort'];
	switch ($sort) {
	case 'd': $sorder = "linkdorder ASC, linkdate DESC, linkcatid ASC"; break;
	case 'D': $sorder = "linkdorder ASC, linkdate ASC,  linkcatid ASC"; break;
	case 'h': $sorder = "linkdorder ASC, linkhits DESC, linkcatid ASC"; break;
	case 'H': $sorder = "linkdorder ASC, linkhits ASC,  linkcatid ASC"; break;
	case 'n': $sorder = "linkdorder ASC, linkname DESC, linkcatid ASC"; break;
	case 'N':
	default:  $sorder = "linkdorder ASC, linkname ASC,  linkcatid ASC"; break;
	}
	$searchnav = "1";

	unset ($slimit);

	$catlistbit   = "";
	$linklistbit  = "";

	// nav bar and title
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = $this_navigation_title;
	if ($viewcatid>0 and isset($linkscat["$viewcatid"])) {
		$viewcatname  = parse_bbcode2($linkscat["$viewcatid"]["catname"], $links_defaults['allow_html'], $links_defaults['allow_images'], $links_defaults['allow_smilies'], $links_defaults['allow_bbcode']);
		$viewcatdesc  = parse_bbcode2($linkscat["$viewcatid"]["catdesc"], $links_defaults['allow_html'], $links_defaults['allow_images'], $links_defaults['allow_smilies'], $links_defaults['allow_bbcode']);
		$viewcattext  = parse_bbcode2($linkscat["$viewcatid"]["cattext"], $links_defaults['allow_html'], $links_defaults['allow_images'], $links_defaults['allow_smilies'], $links_defaults['allow_bbcode']);
		$parentlist = $linkscat["$viewcatid"]["parentlist"];
		$parentlist = array_reverse(explode(',', $parentlist));
		foreach ($parentlist AS $linkID) {
			if ($linkID > 0) {
				$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$linkID"] = $linkscat["$linkID"]["catname"];
			}
		}
		$navbits[""] = $linkscat["$viewcatid"]["catname"];
	} else {
		$viewcatdesc  = $viewcattext  = "";
		switch ($viewcatid) {
		case $FAVS_CAT:
			$viewcatname  = $navbits[""] = "My Favourites";
			break;
		case $HIDE_CAT:
			$viewcatname  = $navbits[""] = "Hidden Links";
			break;
		case $AVL_CAT:
			$viewcatname  = $navbits[""] = " Available Links";
			break;
		case $BRKN_CAT:
			$viewcatname  = $navbits[""] = "Broken Links";
			break;
		case $INVD_CAT:
			$viewcatname  = $navbits[""] = "Invalid Links";
			break;
		case $HOT_CAT:
			$viewcatname  = $navbits[""] = "Hottest Links";
			break;
		case $NEW_CAT:
			$viewcatname  = $navbits[""] = "New Links";
			break;
		case $RND_CAT:
			$viewcatname  = $navbits[""] = "Some Random Links...";
			break;
		default:
			$viewcatname  = "";
			break;
		}
	}

	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	// Get links in selected category
	$query = "
		SELECT DISTINCT link.linkid AS linkid, link.linkname AS linkname, link.linkuserid AS linkuserid,
			link.linkusername AS linkusername, link.linkurl AS linkurl, link.linkdesc AS linkdesc,
			link.linkhits AS linkhits, link.linkstatus AS linkstatus, link.linkdate AS linkdate,
			link.linkmoderate AS linkmoderate,
			ltoc.catid AS linkcatid, ltoc.displayorder AS linkdorder, ltoc2.catid AS linkcatid2
		FROM (".THIS_TABLE."linkslink AS link
		LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
		ON link.linkid = ltoc.linkid)
		LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc2
		ON link.linkid = ltoc2.linkid
		";

	switch ($viewcatid) {

	case $FAVS_CAT:
	$query .= "
		LEFT JOIN ".THIS_TABLE."linksfavs AS lfav
		ON link.linkid = lfav.linkid
		WHERE
			lfav.userid = '".$bbuserinfo['userid']."'
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		break;

	case $HIDE_CAT:
		$query .= "WHERE
			link.linkstatus='".$LINK_HIDDEN."'
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		break;

	case $AVL_CAT:
		$query .= "WHERE
			link.linkstatus>0
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		break;

	case $BRKN_CAT:
		$query .= "WHERE
			link.linkstatus='".$LINK_BROKEN."'
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		break;

	case $INVD_CAT:
		$query .= "WHERE
			link.linkstatus='".$LINK_NO_ACCESS."'
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		break;

	case $HOT_CAT:
		$query .= "WHERE
			link.linkstatus>0
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		$sorder = "linkhits DESC, ".$sorder;
		if (isset($_REQUEST['limit'])) {
			$slimit    = "
			LIMIT ".intval($_REQUEST['limit'])."
			";
		} else {
			$slimit    = "
			LIMIT ".intval($links_defaults["links_seen_on_portal"])."
			";
		}
		break;

	case $NEW_CAT:
		if (isset($_REQUEST['limit'])) {
			$when = TIMENOW - intval($_REQUEST['limit'])*24*60*60;
			$viewcatdesc  = $viewcattext  = "New entries within last ".$_REQUEST['limit']." days";
		} else {
			$when = TIMENOW - intval($links_defaults["days_seen_on_portal"])*24*60*60;
			$viewcatdesc  = $viewcattext  = "New entries within last ".$links_defaults["days_seen_on_portal"]." days";
		}
		$query .= "WHERE
			link.linkstatus>0
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
			AND linkdate > $when
		";
		$sorder = "linkname ASC, ".$sorder;
		break;

	case $RND_CAT:
		$query .= "WHERE
			link.linkstatus>0
			AND ltoc.catid <= ltoc2.catid
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		$sorder = "RAND()";
		if (isset($_REQUEST['limit'])) {
			$slimit    = "
			LIMIT ".intval($_REQUEST['limit'])."
			";
		} else {
			$slimit    = "
			LIMIT ".intval($links_defaults["links_seen_on_portal"])."
			";
		}
		break;

	default:
		$query .= "WHERE
			ltoc.catid = '".$viewcatid."' 
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
		";
		break;

	}

	if (!$links_permissions["can_moderate_links"]) {
		$query .= "
			AND (link.linkmoderate = $LINK_ACCEPTED OR (link.linkmoderate = $LINK_TO_MODERATE AND link.linkuserid = ".$bbuserinfo['userid']."))
		";
	}

	$query .= "
		ORDER BY $sorder
		$slimit
		";

	get_linksfav();
	get_linksratings();
	list ($linklistbit, $nhits)  = get_linklistbit($query, "", $pagenumber, $perpage, 0);

	$pcatid   = $linkscat[$viewcatid]["parentid"];
	$catstyle = 1;

	// Get categories at this level
	unset ($thisorder);
	$cattree = cat_walk($viewcatid, $links_defaults['cat_depth_display']);
	foreach ($cattree AS $thisid=>$thischildren) {
		$catlistbit .= get_catlistbit($thisid, $thischildren, 'links_catbit');
	}

	$pagenav = construct_page_nav($nhits, THIS_SCRIPT.".php?action=links&amp;catid=$viewcatid&amp;sort=$sort", "&amp;pp=$perpage");

	$catclosed = $linkscat[$viewcatid]["catclosed"];
	if ($catclosed != 0) {
		$links_permissions["can_add_link"] = 0;
		if (!$links_permissions["can_admin_links"]) $links_permissions["can_edit_link"] = 0;
		$links_permissions["can_add_category"] = 0;
		if (!$links_permissions["can_admin_links"]) $links_permissions["can_edit_category"] = 0;
	}

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_main')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;
}

// #################### Set up a Search
if ($_REQUEST['action'] == "search") {

	$this_navigation_title = "文件搜索";
	build_forum_list();

	// Make Links Nav Bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = $this_navigation_title;
	$navbits = construct_navbits($navbits);

	eval('$navbar = "' . fetch_template('navbar') . '";');

	// this code controls which menu items are visible in the header template
	$viewcatid = -2;
	$links_permissions["can_add_link"] = 0;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_search')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;
}

// #################### Show Links, i.e. Execute a Search
if ($_REQUEST['action'] == "show") {

	require_once('includes/functions_bbcodeparse.php');

	$this_navigation_title = "文件搜索";

	$sstring = $_REQUEST['search'];
	$sforum  = intval($_REQUEST['forum']);
	$suser   = $_REQUEST['user'];

	build_forum_list();

// fetch the permissions for each forum
	$limitfids = array(-999999);

	$forumperms = array();
	foreach ($forumcache AS $forum) {
		if (isset($forum['forumid'])) {
			$forumperms["$forum[forumid]"] = fetch_permissions($forum['forumid']);
			if (!($forumperms["$forum[forumid]"] & CANVIEW) || !($forumperms["$forum[forumid]"] & CANVIEWOTHERS)) {
				$limitfids[] = $forum['forumid'];
			}
		}
	}
	unset($forum);

	$subtitle = "entries";

	unset ($slimit);
	$squery = "
		WHERE
			link.linkforum NOT IN (".implode(',', $limitfids).")
			AND (link.linkmoderate = $LINK_ACCEPTED 
			 OR (link.linkmoderate = $LINK_TO_MODERATE AND link.linkuserid = ".$bbuserinfo['userid']."))
		";

	$sorder = "
		ORDER BY linkdorder ASC, linkname ASC, linkcatid ASC
		";

	if ($sstring <> "") {
		$squery .= "
			AND MATCH (link.linkname, link.linkdesc) AGAINST ('".addslashes($sstring)."'
			";
		if (defined('CANDO_BOOLEAN')) $squery .= " IN BOOLEAN MODE";
		$squery .= ")";
	}

	if ($suser <> "") {
		$squery .= "
			AND link.linkuserid = '".addslashes($suser)."'
			";
	}

	if ($sforum <> "") {
		if (preg_match ( "/^\s*\d+\s*$/", $sforum)) {
			$squery .= "
			AND link.linkforum IN ($sforum)
			";
		} else {
			eval(print_standard_error('Invalid search forumid - not a number. <a href=javascript:history.back(1)><b>Return</b></a>',0));
			exit;
		}
	}

	$query = "
		SELECT link.linkid AS linkid, link.linkname AS linkname, link.linkuserid AS linkuserid,
			link.linkusername AS linkusername, link.linkurl AS linkurl, link.linkdesc AS linkdesc,
			link.linkhits AS linkhits, link.linkstatus AS linkstatus, link.linkdate AS linkdate,
			link.linkmoderate AS linkmoderate,
			ltoc.catid AS linkcatid, ltoc.displayorder AS linkdorder
		FROM ".THIS_TABLE."linkslink AS link
		LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
		ON link.linkid = ltoc.linkid

		$squery
		$sorder
		$slimit
		";

	$viewcatid = $BASE_CAT;
	$catlistbit   = "";

	// draw nav bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = $this_navigation_title;
	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	get_linksfav();
	get_linksratings();

	// Get links that match the search query
	list ($linklistbit, $nhits)  = get_linklistbit($query, $sstring);

	$pcatid   = $linkscat[$viewcatid]["parentid"];
	$viewcatname  = "Search Results";
	$message = iif ($nhits,$nhits,'No').' '.$subtitle;
	if ($sstring <> "") $message .= " matching $sstring";
	if ($sforum <> "")  $message .= " associated with forum \"".$forumcache[$sforum][title]."\"";
	if ($suser <> "") {
		$userinfo = fetch_userinfo($suser);
		$message .= " submitted by ".$userinfo['username'];
	}
	$viewcatdesc = $message;
	$viewcattext = $message;

	// this code controls which menu items are visible in the header template
	$viewcatid = -2;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;

	$action = "";
	if ($sstring <> "") $action = "&amp;search=$sstring";
	if ($sforum <> "") $action .= "&amp;forum=$sforum";

	$pagenav = "";
	$searchnav = "";

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_main')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;
}


// #################### Moderate

if ($_REQUEST['action'] == "mod") {

	require_once('includes/functions_bbcodeparse.php');

	if (!isset($links_permissions["can_moderate_links"]) or !$links_permissions["can_moderate_links"]) {
		print_no_permission();
		exit;
	}

	$this_navigation_title = "版主选项";
	build_forum_list();

	// Make Links Nav Bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	$navbits[""] = "Links Moderation";
	$navbits = construct_navbits($navbits);

	eval('$navbar = "' . fetch_template('navbar') . '";');

// fetch the permissions for each forum
	$limitfids = array(0);
	$forumperms = array();
	foreach ($forumcache AS $forum) {
		if (isset($forum['forumid'])) {
			$forumperms["$forum[forumid]"] = fetch_permissions($forum['forumid']);
			if (!($forumperms["$forum[forumid]"] & CANVIEW) || !($forumperms["$forum[forumid]"] & CANVIEWOTHERS)) {
				$limitfids[] = $forum['forumid'];
			}
		}
	}
	unset($forum);

	$query = $DB_site->query("
		SELECT forumid, title
		FROM ". TABLE_PREFIX . "forum
	");
	while ($row=$DB_site->fetch_array($query)) {
		$forum[$row['forumid']] = $row['title'];
	}

	$query = $DB_site->query("
		SELECT link.linkid AS linkid, ltoc.catid AS linkcatid, link.linkmoderate AS linkmoderate
		FROM ". THIS_TABLE . "linkslink AS link
		LEFT JOIN ". THIS_TABLE . "linksltoc AS ltoc
		ON link.linkid = ltoc.linkid
		WHERE
			link.linkforum NOT IN (".implode(',', $limitfids).")
			AND (
			link.linkmoderate = $LINK_TO_MODERATE
				OR
			(link.linkreviewfreq>0 AND (link.linkmoddate+link.linkreviewfreq*24*60*60)<".TIMENOW.")
			)
	");

	foreach ($linkscat AS $thiscat) {
		$tomod[$thiscat['catid']] = 0;
	}
	while ($row=$DB_site->fetch_array($query)) {
		$tomod[$row['linkcatid']] += 1;
	}

	$catlistbit = '';
	$linklistbit = '';

	$links_permissions["can_edit_category"] = 0;

	foreach ($linkscat AS $thiscat) {
		if (!in_array($thiscat["catforum"], $limitfids) and
			($tomod[$thiscat['catid']] > 0 or $thiscat['catmoderate'] == $LINK_TO_MODERATE)) {
			$catlistbit = get_catlistbit ($thiscat['catid'], array(), 'links_catmod');
		}
	}

	if ($catlistbit == '') $catlistbit = "<tr valign=\"top\"><td colspan=\"2\" class=\"alt1\"><span class=\"smallfont\">There are no links requiring moderation</span></td></tr>";

	$pagenav = "";
	$searchnav = "";

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_main')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;
}


if ($_REQUEST['action'] == "domod") {

	require_once('includes/functions_bbcodeparse.php');

	if (!isset($links_permissions["can_moderate_links"]) or !$links_permissions["can_moderate_links"]) {
		print_no_permission();
		exit;
	}

	$this_navigation_title = "版主选项";

	build_forum_list();

	unset($linkid);
	unset($viewcatid);
	if (isset($_REQUEST['id'])) {
		$linkid = $_REQUEST['id'];
	} elseif (isset($_REQUEST['catid'])) {
		$viewcatid = intval($_REQUEST['catid']);
	} else {
		eval(print_standard_error('Cannot moderate: no link/category selected. <a href='.THIS_SCRIPT.'.php?action=links><b>Return</b></a>',0));
		exit;
	}

// fetch the permissions for each forum
	$limitfids = array(0);
	$forumperms = array();
	foreach ($forumcache AS $forum) {
		if (isset($forum['forumid'])) {
			$forumperms["$forum[forumid]"] = fetch_permissions($forum['forumid']);
			if (!($forumperms["$forum[forumid]"] & CANVIEW) || !($forumperms["$forum[forumid]"] & CANVIEWOTHERS)) {
				$limitfids[] = $forum['forumid'];
			}
		}
	}
	unset($forum);

// find unmoderated links
	$query = "
		SELECT link.linkid AS linkid, link.linkname AS linkname, link.linkuserid AS linkuserid,
			link.linkusername AS linkusername, link.linkurl AS linkurl, link.linkdesc AS linkdesc,
			link.linkhits AS linkhits, link.linkstatus AS linkstatus, link.linkdate AS linkdate,
			link.linkmoderate AS linkmoderate,
			ltoc.catid AS linkcatid, ltoc.displayorder AS linkdorder
		FROM ".THIS_TABLE."linkslink AS link
		LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
		ON link.linkid = ltoc.linkid

		WHERE
			".iif(isset($linkid),"link.linkid = '$linkid'",
			"ltoc.catid = '$viewcatid'
			AND link.linkforum NOT IN (".implode(',', $limitfids).")
			AND (
			link.linkmoderate = $LINK_TO_MODERATE
				OR
			(link.linkreviewfreq>0 AND (link.linkmoddate+link.linkreviewfreq*24*60*60)<".TIMENOW.")
			)
			")."
		ORDER BY linkcatid, linkname
		";

	$catlistbit   = "";
	list ($linklistbit, $nhits)  = get_linklistbit($query, "", 1, 999999, 1);

// build nav bar
	$navbits = array();
	if ($viewcatid>0 and isset($linkscat["$viewcatid"])) {
		$parentlist = $linkscat["$viewcatid"]["parentlist"];
		$parentlist = array_reverse(explode(',', $parentlist));
		foreach ($parentlist AS $pid) {
			if ($pid > 0) {
				$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$pid"] = $linkscat["$pid"]["catname"];
			}
		}
		$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$viewcatid"] = $linkscat["$viewcatid"]["catname"];
	}
	$navbits[""] = $this_navigation_title;

	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	$pcatid   = $linkscat[$viewcatid]["parentid"];
	$viewcatname  = $linkscat[$viewcatid]["catname"];
	$message = iif($nhits, $nhits.' entries to be moderated',"No entries to moderate");
	$viewcatdesc = $message;
	$viewcattext = $message;

	// this code controls which menu items are visible in the header template
	$viewcatid = -2;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;

	$pagenav = "";
	$searchnav = "";

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_main')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;
}

// #################### Add Entry
if ($_REQUEST['action'] == "addlink") {

	require_once('includes/functions_bbcodeparse.php');

	if (!isset($links_permissions["can_add_link"]) or !$links_permissions["can_add_link"]) {
		print_no_permission();
		exit;
	}

	if (!isset($_REQUEST['catid']) or $_REQUEST['catid']=="") {
		$_REQUEST['catid'] = $BASE_CAT;
	}
	$viewcatid = intval($_REQUEST['catid']);
	$viewcatname = "";
	if (isset($linkscat[$viewcatid]["catname"])) $viewcatname = $linkscat[$viewcatid]["catname"];
	$viewlinkid  = -1;
	$linkmod  = 0; // not moderating

	if ($linkscat[$viewcatid]["catclosed"] != 0) {
		eval(print_standard_error('Category closed for new entries. <a href='.THIS_SCRIPT.'.php?action=links&catid=$viewcatid><b>Return</b></a>',0));
		exit;
	}

	if (!isset($links_defaults["default_forumid"]) or
		!forumid_is_valid($links_defaults["default_forumid"])
		) {
		eval(print_standard_error('Unable to proceed - ask administrator to set default forum. <a href='.THIS_SCRIPT.'.php?action=links&catid=$viewcatid><b>Return</b></a>',0));
		exit;
	}
	$curforumid = $links_defaults["default_forumid"];
	$this_navigation_title = "添加文件";
	build_forum_list();
	$curforumtitle = $forumcache[$curforumid][title];

	// draw nav bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	if ($viewcatid>0 and isset($linkscat["$viewcatid"])) {
		$parentlist = $linkscat["$viewcatid"]["parentlist"];
		$parentlist = array_reverse(explode(',', $parentlist));
		foreach ($parentlist AS $linkID) {
			if ($linkID > 0) {
				$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$linkID"] = $linkscat["$linkID"]["catname"];
			}
		}
		$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$viewcatid"] = $linkscat["$viewcatid"]["catname"];
	}
	$navbits[""] = $this_navigation_title;

	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	// Build the category list
	$pcatid = array($viewcatid);
	$optbit = construct_category_list ($pcatid, 0);
	$link_pcatbit = construct_parent_list ($pcatid);

	$linkurl = "http://";
	$action = "doaddlink";

	$display_order = $links_defaults["default_link_dseq"];
	$instructions = parse_bbcode2($linkscat[$viewcatid]["catinstructions"], $links_defaults['allow_html'], $links_defaults['allow_images'], $links_defaults['allow_smilies'], $links_defaults['allow_bbcode']);

	// this code controls which menu items are visible in the header template
	$links_permissions["can_add_link"] = 0;
	$links_permissions["can_delete_link"] = 0;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;
	$pcatid = $viewcatid;
	$linkreviewfreq = 0;
	unset($linkstatus);
	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_addnewlink')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;

}

// #################### Edit Entry
if ($_REQUEST['action'] == "editlink") {

	require_once('includes/functions_bbcodeparse.php');

	$viewlinkid = intval($_REQUEST['linkid']);
	$viewcatid  = intval($_REQUEST['catid']);
	$viewcatname = "";
	if (isset($linkscat[$viewcatid]["catname"])) $viewcatname = $linkscat[$viewcatid]["catname"];

	if (!isset($_REQUEST['page']) or $_REQUEST['page']=="") $_REQUEST['page'] = '1';
	$pagenumber = iif( is_numeric($_REQUEST['page']), $_REQUEST['page'], '1');

	$linkmod  = intval($_REQUEST['mod']); // may be moderating
	if ($linkmod != 1) $linkmod = 0;

	$asb = $DB_site->query("
		SELECT *
		FROM ".THIS_TABLE."linkslink
		WHERE linkid=$viewlinkid
		LIMIT 1
	");
	if ($DB_site->num_rows($asb)) {
		while ($myrow=$DB_site->fetch_array($asb)) {
			$linkname = $myrow["linkname"];
			$linkurl = $myrow["linkurl"];
			$linkdesc = $myrow["linkdesc"];
			$linkforum = $myrow["linkforum"];
			$linkuserid	= $myrow["linkuserid"];
			$linkusername  = $myrow["linkusername"];
			$linkreviewfreq = $myrow["linkreviewfreq"];
			$linkstatus = $myrow["linkstatus"];
		}
	} else {
		eval(print_standard_error('Invalid entry - specified linkid $viewlinkid does not exist. <a href='.THIS_SCRIPT.'.php?action=links><b>Return</b></a>',0));
		exit;
	}

	// always allow the link creator to edit, otherwise check usergroup permissions
	if ($bbuserinfo[userid]<>$linkuserid and (!isset($links_permissions["can_edit_link"]) or !$links_permissions["can_edit_link"])) {
		print_no_permission();
		exit;
	}

	$this_navigation_title = "编辑文件";

	// draw nav bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	if ($viewcatid>0 and isset($linkscat["$viewcatid"])) {
		$parentlist = $linkscat["$viewcatid"]["parentlist"];
		$parentlist = array_reverse(explode(',', $parentlist));
		foreach ($parentlist AS $linkID) {
			if ($linkID > 0) {
				$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$linkID"] = $linkscat["$linkID"]["catname"];
			}
		}
		$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$viewcatid"] = $linkscat["$viewcatid"]["catname"];
	}
	$navbits[""] = $this_navigation_title;

	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	$curforumid = $linkforum;
	build_forum_list();
	$curforumtitle = $forumcache[$curforumid][title];

	// Build the category list
	$pcatid = array();
	$asb = $DB_site->query("
		SELECT catid FROM ".THIS_TABLE."linksltoc
		WHERE linkid=$viewlinkid
	");
	while ($myrow=$DB_site->fetch_array($asb)) {
		$pcatid[] = $myrow["catid"];
	}

	$optbit = construct_category_list ($pcatid, 0);
	$link_pcatbit = construct_parent_list ($pcatid);

	$action = "doeditlink";

	$asb = $DB_site->query("
		SELECT *
		FROM ".THIS_TABLE."linksltoc
		WHERE linkid=$viewlinkid AND catid=$viewcatid
		LIMIT 1
	");
	if ($DB_site->num_rows($asb)) {
		while ($myrow=$DB_site->fetch_array($asb)) {
			$display_order = $myrow["displayorder"];
		}
	} else {
		$display_order = $links_defaults["default_link_dseq"];
	}

	$instructions = parse_bbcode2($linkscat[$viewcatid]["catinstructions"], $links_defaults['allow_html'], $links_defaults['allow_images'], $links_defaults['allow_smilies'], $links_defaults['allow_bbcode']);

	// this code controls which menu items are visible in the header template
	$links_permissions["can_add_link"] = 0;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;
	$pcatid = $viewcatid;

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_addnewlink')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;

}

// #################### Do (Add) Entry
if ($_REQUEST['action'] == "doaddlink") {

	$pcatid	= $_REQUEST['pcatid'];  // an array ...
	$viewcatid = intval($_REQUEST['viewcatid']);
	$pforum	= intval($_REQUEST['pforum']);
	$linkname = $_REQUEST['linkname'];
	$linkurl = $_REQUEST['linkurl'];
	$linkdesc = $_REQUEST['linkdesc'];
	$submit = $_REQUEST['submit'];
	$display_order = intval($_REQUEST['display_order']);
	$change_display_order = intval($_REQUEST['change_display_order']);
	$linkreviewfreq = intval($_REQUEST['linkreviewfreq']);
	$linkuser = $_REQUEST['linkuser'];

	$url = THIS_SCRIPT.".php?action=links&catid=$viewcatid";

	if ($submit <> $vbphrase['submit']) {
		eval(print_standard_redirect('Action abandoned',0));
		exit;
	}

	if ($pforum<=0) { $pforum = $links_defaults["default_forumid"]; };

	if ($bbuserinfo['usergroupid'] <= 1) {
		if (!is_valid_email($linkuser)) {
			$err = 'Invalid email address'.$linkuser.'. <a href=$url><b>Return</b></a>';
			eval(print_standard_error($err,0));
			exit;
		}
	} else {
		$linkuser = $bbuserinfo['username'];
	}

	if (!forumid_is_valid($pforum)) {
		$err = 'Specified associated forum $pforum does not exist. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if (!is_array($pcatid)) {
		$err = 'No category specified. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if ($linkname == '') {
		$err = 'No link name specified. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if ($linkurl == '' and !$links_defaults["allow_null_links"]) {
		$err = 'No link specified. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	} elseif ($linkurl == '') {
		$statuscheck = $LINK_OK;
	} else {
		$statuscheck = check_url($linkurl);
	}

	if ($statuscheck == $LINK_NO_ACCESS) {
		$err = 'Cannot handle $linkurl file protocol. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	$statustime  = TIMENOW;
	if (isset($links_permissions["can_moderate_links"]) and $links_permissions["can_moderate_links"]) {
		$moderate = $LINK_ACCEPTED;
	} else {
		$moderate = iif($links_defaults["moderate_links"] != '0', $LINK_TO_MODERATE, $LINK_ACCEPTED);
	}

	$linkid = insert_link ($linkuser, $bbuserinfo['userid'], $linkname, $linkurl, $linkdesc, $pcatid, $pforum, $statuscheck, $moderate, $linkreviewfreq);
	if ($linkid > 0) {
		switch ($change_display_order) {
		case 1:
			$DB_site->query("
				UPDATE ".THIS_TABLE."linksltoc SET
				displayorder='".$display_order."'
				WHERE linkid='$linkid' AND catid='$viewcatid'
			");
			break;
		case 2:
			$DB_site->query("
				UPDATE ".THIS_TABLE."linksltoc SET
				displayorder='".$display_order."'
				WHERE linkid='$linkid'
			");
			break;
		default:
			break;
		}
	}

	if ($moderate != $LINK_TO_MODERATE) {
		if ($statuscheck) {
			$message = "Entry added, link checked ok";
			eval(print_standard_redirect($message,0));
		} else {
			$eurl = THIS_SCRIPT.".php?action=editlink&amp;linkid=$linkid&amp;catid=$viewcatid";
			$message = "Link check <a href='$linkurl' target='_blank'>$linkurl</a> <b>failed</b><br />".
			"<a href='$url'><b>Accept</b></a>&nbsp;&nbsp;<a href=$eurl><b>Modify</b></a>"
			;
			eval(print_standard_error($message,0));
		}
	} else {
		if ($statuscheck) {
			$message = "Entry submitted for moderation, link checked ok";
			eval(print_standard_redirect($message,0));
		} else {
			$eurl = THIS_SCRIPT.".php?action=editlink&linkid=$linkid&catid=$viewcatid";
			$message = "Submitted for moderation, link check <a href='$linkurl' target='_blank'>$linkurl</a> <b>failed</b><br />".
			"<a href='$url'><b>Accept</b></a>&nbsp;&nbsp;<a href=$eurl><b>Modify</b></a>"
			;
			eval(print_standard_error($message,0));
		}
	}
	exit;

}

// #################### Do (Edit) Entry
if ($_REQUEST['action'] == "doeditlink") {
	$pcatid = $_REQUEST['pcatid'];  // an array ...
	$viewcatid = intval($_REQUEST['viewcatid']);
	$viewlinkid = intval($_REQUEST['viewlinkid']);
	$pforum = intval($_REQUEST['pforum']);
	$linkname = $_REQUEST['linkname'];
	$linkurl = $_REQUEST['linkurl'];
	$linkdesc = $_REQUEST['linkdesc'];
	$linkmod = intval($_REQUEST['mod']);
	$submit = $_REQUEST['submit'];

	if (!isset($_REQUEST['page']) or $_REQUEST['page']=="") $_REQUEST['page'] = '1';
	$pagenumber = iif( is_numeric($_REQUEST['page']), $_REQUEST['page'], '1');

	$display_order = intval($_REQUEST['display_order']);
	$change_display_order = intval($_REQUEST['change_display_order']);
	$linkreviewfreq = intval($_REQUEST['linkreviewfreq']);
	$linkuser = $_REQUEST['linkuser'];

	if ($linkmod == 1) {
		$url = THIS_SCRIPT.".php?action=mod";
	} else {
		$url = THIS_SCRIPT.".php?action=links&catid=$viewcatid&page=$pagenumber";
	}

	if ($submit <> $vbphrase['submit'] and $submit <> "Accept" and $submit <> $vbphrase['delete'] and $submit <> "Hide" and $submit <> "Unhide") {
		eval(print_standard_redirect('Action abandoned',0));
		exit;
	}

	if ($viewlinkid == '') {
		$err = 'Specified link $linkid does not exist. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if ($bbuserinfo['usergroupid'] <= 1) {
		if (!is_valid_email($linkuser)) {
			$err = 'Invalid email address'.$linkuser.'. <a href=$url><b>Return</b></a>';
			eval(print_standard_error($err,0));
			exit;
		}
	} else {
		$linkuser = $bbuserinfo['username'];
	}

	if ($pforum<=0) { $pforum = $links_defaults["default_forumid"]; };

	if (!forumid_is_valid($pforum)) {
		$err = 'Specified associated forum $pforum does not exist. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if ($submit == $vbphrase['submit'] and !is_array($pcatid)) {
		$err = 'No category specified. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if ($submit == $vbphrase['submit'] and $linkname == '') {
		$err = 'No link name specified. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	if ($submit == $vbphrase['submit']) {
		if ($linkurl == '' and !$links_defaults["allow_null_links"]) {
			$err = 'No link specified. <a href=$url><b>Return</b></a>';
			eval(print_standard_error($err,0));
			exit;
		} elseif ($linkurl == '') {
			$statuscheck = $LINK_OK;
		} else {
			$statuscheck = check_url($linkurl);
		}
	}

	$asb = $DB_site->query("
		SELECT * FROM ".THIS_TABLE."linkslink
		WHERE linkid=$viewlinkid LIMIT 1
		");

	if ($DB_site->num_rows($asb)<=0) {
		$err = 'Unknown link $viewlinkid. <a href=$url><b>Return</b></a>';
		eval(print_standard_error($err,0));
		exit;
	}

	$statustime  = TIMENOW;

	if ($submit == $vbphrase['submit']) {

		if ($statuscheck == $LINK_NO_ACCESS) {
			$err = 'Cannot handle $linkurl file protocol. <a href=$url><b>Return</b></a>';
			eval(print_standard_error($err,0));
			exit;
		}

		$query = "
			UPDATE ".THIS_TABLE."linkslink SET
			linkname='".addslashes($linkname)."',
			linkurl='".addslashes(str_replace('"', '&quot;', $linkurl))."',
			linkdesc='".addslashes($linkdesc)."',
			linkforum='$pforum',
			linkcheck='$statustime',
			linkstatus='$statuscheck',
			linkreviewfreq='$linkreviewfreq'
			WHERE linkid='$viewlinkid'
			";
		write_debug($query);
		$DB_site->query($query);
		$DB_site->query("
			DELETE FROM ".THIS_TABLE."linksltoc
			WHERE linkid='$viewlinkid'
			");
		foreach ($pcatid as $p) {
			$DB_site->query("
			INSERT INTO ".THIS_TABLE."linksltoc (linkid, catid)
			VALUES ('$viewlinkid', '$p')
			");
		}

		switch ($change_display_order) {
		case 1:
			$DB_site->query("
				UPDATE ".THIS_TABLE."linksltoc SET
				displayorder='".$display_order."'
				WHERE linkid='$viewlinkid' AND catid='$viewcatid'
			");
			break;
		case 2:
			$DB_site->query("
				UPDATE ".THIS_TABLE."linksltoc SET
				displayorder='".$display_order."'
				WHERE linkid='$viewlinkid'
			");
			break;
		default:
			break;
		}

		fix_cat_count();

		if ($statuscheck) {
			$message = "Entry edited, link checked ok";
			eval(print_standard_redirect($message,0));
		} else {
			$eurl = THIS_SCRIPT.".php?action=editlink&amp;linkid=$viewlinkid&amp;catid=$viewcatid&amp;page=$pagenumber";
			$message = 'Link check <a href=$linkurl target=_blank>$linkurl</a> <b>failed</b><br />'.
			'<a href=$url><b>Accept</b></a>&nbsp;&nbsp;<a href=$eurl><b>Modify</b></a>'
			;
			eval(print_standard_error($message,0));
		}
	}

	if ($submit == "Accept") {
		$DB_site->query("
			UPDATE ".THIS_TABLE."linkslink SET
			linkmoderate=$LINK_ACCEPTED,
			linkmoddate='$statustime'
			WHERE linkid='$viewlinkid'
			");
		eval(print_standard_redirect('Entry accepted.',0));
	}

	if ($submit == "Hide") {
		$DB_site->query("
			UPDATE ".THIS_TABLE."linkslink SET
			linkmoderate=$LINK_TO_MODERATE, 
			linkstatus=$LINK_HIDDEN,
			linkmoddate='$statustime'
			WHERE linkid='$viewlinkid'
			");
		eval(print_standard_redirect('Entry hidden.',0));
	}

	if ($submit == "Unhide") {
		$DB_site->query("
			UPDATE ".THIS_TABLE."linkslink SET
			linkmoderate=$LINK_ACCEPTED, 
			linkstatus=$LINK_OK,
			linkmoddate='$statustime'
			WHERE linkid='$viewlinkid'
			");
		eval(print_standard_redirect('Entry unhidden.',0));
	}

	if ($submit == $vbphrase['delete']) {
		$DB_site->query("
			DELETE FROM ".THIS_TABLE."linkslink
			WHERE linkid='$viewlinkid'
			");
		$DB_site->query("
			DELETE FROM ".THIS_TABLE."linksltoc
			WHERE linkid='$viewlinkid'
			");
		$DB_site->query("
			DELETE FROM ".THIS_TABLE."linksfavs
			WHERE linkid='$viewlinkid'
			");
		fix_cat_count();
		eval(print_standard_redirect('Entry deleted.',0));
	}

	exit;
}

// #################### Do (Rate) Entry
if ($_REQUEST['action'] == "doratelink") {

	$viewcatid = intval($_REQUEST['catid']);
	$linkid	   = intval($_REQUEST['id']);
	$linkvote  = intval($_REQUEST['vote']);

	if (!isset($_REQUEST['page']) or $_REQUEST['page']=="") $_REQUEST['page'] = '1';
	$pagenumber = iif( is_numeric($_REQUEST['page']), $_REQUEST['page'], '1');

	$url = THIS_SCRIPT.".php?action=links&catid=$viewcatid&page=$pagenumber";

	if ($linkvote < 0) {
		if (isset($links_permissions["can_admin_links"])) {
			$DB_site->query("
			DELETE FROM ".THIS_TABLE."linksrate
			WHERE linkid='$linkid'
			");
			eval(print_standard_redirect('Ratings cleared for linkid '.$linkid.'.',0));
		} else {
			print_no_permission();
		}
		exit;
	}

	if (!isset($links_permissions["can_rate_link"]) or !$links_permissions["can_rate_link"]) {
		print_no_permission();
		exit;
	}

	if ($linkvote<$MIN_VOTE or $linkvote>$MAX_VOTE) {
		eval(print_standard_redirect('Invalid rating - not recorded.',0));
		exit;
	}

	$DB_site->query("
		DELETE FROM ".THIS_TABLE."linksrate
		WHERE linkid='$linkid' AND linkuserid='$bbuserinfo[userid]'
		");

	$DB_site->query("
		INSERT INTO ".THIS_TABLE."linksrate (linkid, linkuserid, linkvote)
		VALUES (
		'$linkid',
		$bbuserinfo[userid],
		'$linkvote'
		)
	");

	eval(print_standard_redirect('Rating recorded.',0));

	exit;
}

// #################### Do Add/Remove Favourite
if ($_REQUEST['action'] == "dofavlink") {

	$viewcatid = intval($_REQUEST['catid']);
	$linkid	   = intval($_REQUEST['id']);
	$linkset   = intval($_REQUEST['set']);

	if (!isset($_REQUEST['page']) or $_REQUEST['page']=="") $_REQUEST['page'] = '1';
	$pagenumber = iif( is_numeric($_REQUEST['page']), $_REQUEST['page'], '1');

	$url = THIS_SCRIPT.".php?action=links&catid=$viewcatid&page=$pagenumber";

	if ($linkset < 0) {
		$DB_site->query("
			DELETE FROM ".THIS_TABLE."linksfavs
			WHERE linkid='".$linkid."' AND userid='".$bbuserinfo['userid']."'
			");
		eval(print_standard_redirect('Link removed from My Favourites.',0));
		exit;
	}

	if (!isset($links_permissions["can_mark_link"]) or !$links_permissions["can_mark_link"]) {
		print_no_permission();
		exit;
	}

	$DB_site->query("
		DELETE FROM ".THIS_TABLE."linksfavs
		WHERE linkid='".$linkid."' AND userid='".$bbuserinfo[userid]."'
		");

	$DB_site->query("
		INSERT INTO ".THIS_TABLE."linksfavs (linkid, userid)
		VALUES (
		'".$linkid."',
		'".$bbuserinfo[userid]."'
		)
	");

	eval(print_standard_redirect('Link added to My Favourites.',0));

	exit;
}

// #################### Add Category
if ($_REQUEST['action'] == "addcat") {

	$catmod  = 0;

	if (!isset($links_permissions["can_add_category"]) or !$links_permissions["can_add_category"]) {
		print_no_permission();
		exit;
	}

	if (!isset($_REQUEST['catid']) or $_REQUEST['catid']=="") {
		$_REQUEST['catid'] = $BASE_CAT;
	}

	if (!isset($links_defaults["default_forumid"]) or
		!forumid_is_valid($links_defaults["default_forumid"])
		) {
		eval(print_standard_error('Unable to proceed - ask administrator to set default forum. <a href='.THIS_SCRIPT.'.php?action=links&catid=$viewcatid><b>Return</b></a>',0));
		exit;
	}

	$curforumid = $links_defaults["default_forumid"];
	$this_navigation_title = "添加分类";
	build_forum_list();
	$curforumtitle = $forumcache[$curforumid][title];

	$pcatid = array();
	$pcatid[0] = intval($_REQUEST['catid']);
	$optbit = construct_category_list($pcatid, 1);

	$display_order = $links_defaults["default_cat_dseq"];

	// draw nav bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	if ($pcatid[0]>0 and isset($linkscat[$pcatid[0]])) {
		$parentlist = $linkscat[$pcatid[0]]["parentlist"];
		$parentlist = array_reverse(explode(',', $parentlist));
		foreach ($parentlist AS $linkID) {
			if ($linkID > 0) {
				$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$linkID"] = $linkscat["$linkID"]["catname"];
			}
		}
		$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=".$pcatid[0]] = $linkscat[$pcatid[0]]["catname"];
	}
	$navbits[""] = $this_navigation_title;

	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	$action	   = "doaddcat";
	$viewcatid = $BASE_CAT;
	$catname   = "";
	$catdesc   = "";
	$cattext   = "";
	$catinstructions = "";

	// this code controls which menu items are visible in the header template
	$links_permissions["can_add_link"] = 0;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;
	$links_permissions["can_delete_category"] = 0;
	$pcatid = $pcatid[0];

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_addnewcat')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;

}

// #################### Edit Category
if ($_REQUEST['action'] == "editcat") {

	$catmod  = $_REQUEST['mod']; // may be moderating
	if ($catmod != 1) $catmod = 0;

	$viewcatid = intval($_REQUEST['catid']);
	$pcatid = array();

	if (isset($linkscat[$viewcatid])) {
		$catname	 = $linkscat[$viewcatid]["catname"];
		$catdesc	 = $linkscat[$viewcatid]["catdesc"];
		$cattext	 = $linkscat[$viewcatid]["cattext"];
		$pcatid[0]   = $linkscat[$viewcatid]["parentid"];
		$forum		 = $linkscat[$viewcatid]["catforum"];
		$catuserid   = $linkscat[$viewcatid]["userid"];
		$catusername = $linkscat[$viewcatid]["username"];
		$catinstructions = $linkscat[$viewcatid]["catinstructions"];
	} else {
		eval(print_standard_error('Invalid entry - specified category $viewcatid does not exist. <a href='.THIS_SCRIPT.'.php?action=links><b>Return</b></a>',0));
		exit;
	}

	// always allow the category creator to edit, otherwise check usergroup permissions
	if ($bbuserinfo[userid]<>$catuserid and (!isset($links_permissions["can_edit_category"]) or !$links_permissions["can_edit_category"])) {
		print_no_permission();
		exit;
	}

	$this_navigation_title = "编辑分类";

	$display_order = $linkscat[$viewcatid]["displayorder"];

	// draw nav bar
	$navbits = array();
	$navbits[THIS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	if ($viewcatid>0 and isset($linkscat["$viewcatid"])) {
		$parentlist = $linkscat["$viewcatid"]["parentlist"];
		$parentlist = array_reverse(explode(',', $parentlist));
		foreach ($parentlist AS $linkID) {
			if ($linkID > 0) {
				$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$linkID"] = $linkscat["$linkID"]["catname"];
			}
		}
		$navbits[THIS_SCRIPT.".php?$session[sessionurl]catid=$viewcatid"] = $linkscat["$viewcatid"]["catname"];
	}
	$navbits[""] = $this_navigation_title;

	$navbits = construct_navbits($navbits);
	eval('$navbar = "' . fetch_template('navbar') . '";');

	$curforumid = $forum;
	build_forum_list();
	$curforumtitle = $forumcache[$curforumid][title];

	$optbit = construct_category_list($pcatid, 1);

	$action = "doeditcat";

	// this code controls which menu items are visible in the header template
	$links_permissions["can_add_link"] = 0;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;
	$pcatid = $pcatid[0];

	eval("\$output  = \"".fetch_template('links_header')."\";");
	eval("\$output .= \"".fetch_template('links_addnewcat')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");

	print_output($output);
	exit;

}

// #################### Do (Add) Category
if ($_REQUEST['action'] == "doaddcat") {
	$pcatid	 = intval($_REQUEST['pcatid']); // NB - single value
	$catname = $_REQUEST['catname'];
	$catdesc = $_REQUEST['catdesc'];
	$cattext = $_REQUEST['cattext'];
	$catinstructions = $_REQUEST['catinstructions'];
	$display_order = intval($_REQUEST['display_order']);
	$pforum	 = intval($_REQUEST['pforum']);
	$submit	 = $_REQUEST['submit'];

	$url = THIS_SCRIPT.".php?action=links&catid=$pcatid";

	if ($submit <> $vbphrase['submit']) {
		eval(print_standard_redirect('Action abandoned',0));
		exit;
	}

	if ($catname == ''){
		eval(print_standard_error('No category name specified. <a href=$url><b>Return</b></a>',0));
		exit;
	}

	if ($pforum<=0) { $pforum = $links_defaults["default_forumid"]; };

	if (!forumid_is_valid($pforum)) {
		eval(print_standard_error('Specified forum $pforum does not exist. <a href=$url><b>Return</b></a>',0));
		exit;
	}

	if ($cattext == ''){
		$cattext = $catdesc;
	}

	if ($pcatid > 0) {
		if (isset($linkscat[$pcatid])) {
			$pcatlist = "$pcatid,".$linkscat[$pcatid]["parentlist"];
		} else {
			eval(print_standard_error('Invalid entry - unknown parent category $pcatid. <a href=$url><b>Return</b></a>',0));
		}
	} else {
		$pcatlist = $pcatid;
	}

	if (isset($links_permissions["can_moderate_links"]) and $links_permissions["can_moderate_links"]) {
		$moderate = $LINK_ACCEPTED;
	} else {
		$moderate = iif($links_defaults["moderate_links"] != '0', $LINK_TO_MODERATE, $LINK_ACCEPTED);
	}

	$DB_site->query("
		INSERT INTO ".THIS_TABLE."linkscat (catname, catdesc, cattext, parentid, parentlist, catforum, catusername, catuserid, catentry, catdate, catmoderate, catinstructions, displayorder)
		VALUES (
		'".addslashes($catname)."',
		'".addslashes($catdesc)."',
		'".addslashes($cattext)."',
		'$pcatid',
		'$pcatlist',
		'$pforum',
		'".addslashes(htmlspecialchars($bbuserinfo[username]))."',
		$bbuserinfo[userid],
		0,
		0,
		$moderate,
		'".addslashes($catinstructions)."',
		$display_order
		)
		");
	$catid = $DB_site->insert_id();
	fix_cat_count();
	$url = THIS_SCRIPT.".php?action=links&catid=$catid";
	eval(print_standard_redirect('Entry added successfully.',0));
	exit;

}

// #################### Do (Edit) Category
if ($_REQUEST['action'] == "doeditcat") {
	$pcatid	 = intval($_REQUEST['pcatid']);
	$catid	 = intval($_REQUEST['catid']);
	$catname = $_REQUEST['catname'];
	$catdesc = $_REQUEST['catdesc'];
	$cattext = $_REQUEST['cattext'];
	$catinstructions = $_REQUEST['catinstructions'];
	$display_order = intval($_REQUEST['display_order']);
	$pforum	 = intval($_REQUEST['pforum']);
	$submit	 = $_REQUEST['submit'];
	$catmod = intval($_REQUEST['mod']);

	if ($catmod == 1) {
		$url = THIS_SCRIPT.".php?action=mod";
	} else {
		$url = THIS_SCRIPT.".php?action=links&catid=$pcatid";
	}

	if ($submit <> $vbphrase['submit'] and $submit <> "Accept" and $submit <> $vbphrase['delete'] and $submit <> "Open" and $submit <> "Close") {
		eval(print_standard_redirect('Action abandoned',0));
		exit;
	}

	if ($catid == '' or !isset($linkscat[$catid])) {
		eval(print_standard_error('Category $catid does not exist. <a href='.$url.'><b>Return</b></a>',0));
		exit;
	}

	if ($submit == $vbphrase['submit']) {

		if ($pforum<=0) $pforum = $links_defaults["default_forumid"];

		if (!forumid_is_valid($pforum)) {
			$err = 'Associated forum $pforum does not exist. <a href=$url><b>Return</b></a>';
			eval(print_standard_error($err,0));
			exit;
		}

		if ($catname == ''){
			eval(print_standard_error('No category name specified. <a href=$url><b>Return</b></a>',0));
			exit;
		}

		if ($cattext == '') $cattext = $catdesc;

		if ($pcatid > 0) {
			if (isset($linkscat[$pcatid])) {
				if ($catid == $pcatid or in_array($catid, explode(",", $linkscat[$pcatid]["parentlist"]))) {
					eval(print_standard_error('You are trying to make category a child of itself. <a href=$url><b>Return</b></a>',0));
					exit;
				}
				$pcatlist = "$pcatid,".$linkscat[$pcatid]["parentlist"];
			} else {
				eval(print_standard_error('Unknown parent category $pcatid. <a href=$url><b>Return</b></a>',0));
			}
		} else {
			$pcatlist = $pcatid;
		}

		$DB_site->query("
			UPDATE ".THIS_TABLE."linkscat SET
			catid='$catid',
			catname='".addslashes($catname)."',
			catdesc='".addslashes($catdesc)."',
			cattext='".addslashes($cattext)."',
			parentid='$pcatid',
			parentlist='$pcatlist',
			catforum='$pforum',
			catinstructions='".addslashes($catinstructions)."',
			displayorder='$display_order'
			WHERE catid='$catid'
		");

		fix_cat_parentlist();
		fix_cat_count();

		if ($catmod != 1) $url = THIS_SCRIPT.".php?action=links&catid=$catid";
		eval(print_standard_redirect('Entry edited successfully.',0));

	}

	if ($submit == "Accept") {
		$DB_site->query("
			UPDATE ".THIS_TABLE."linkscat SET
			catmoderate=$LINK_ACCEPTED
			WHERE catid='$catid'
			");
		eval(print_standard_redirect('Entry accepted.',0));

	}

	if ($submit == "Open") {

		if (!isset($links_permissions["can_admin_links"]) or !$links_permissions["can_admin_links"]) {
			print_no_permission();
			exit;
		}

		$DB_site->query("
			UPDATE ".THIS_TABLE."linkscat SET
			catclosed=0
			WHERE catid='$catid'
			");
		$url = THIS_SCRIPT.".php?action=admin";
		eval(print_standard_redirect('Category opened.',0));

	}

	if ($submit == "Close") {

		if (!isset($links_permissions["can_admin_links"]) or !$links_permissions["can_admin_links"]) {
			print_no_permission();
			exit;
		}

		$DB_site->query("
			UPDATE ".THIS_TABLE."linkscat SET
			catclosed=1
			WHERE catid='$catid'
			");
		$url = THIS_SCRIPT.".php?action=admin";
		eval(print_standard_redirect('Category closed.',0));

	}

	if ($submit == $vbphrase['delete']) {
		$asb = $DB_site->query("
			SELECT * FROM ".THIS_TABLE."linksltoc
			WHERE catid='$catid'
			");
		$hasentries = $DB_site->num_rows($asb);
		foreach ($linkscat as $thiscat) {
			if ($thiscat["parentid"] == $catid) {
				$hasentries = 1;
				break;
			}
		}
		if ($hasentries) {
			eval(print_standard_error('Invalid delete - category '.$catid.' still contains links/subcategories. <a href=$url><b>Return</b></a> to continue',0));
		} else {
			$DB_site->query("
				DELETE FROM ".THIS_TABLE."linkscat
				WHERE catid='$catid'
				");
			eval(print_standard_redirect('Entry deleted.',0));
		}

	}

	exit;
}

// #################### Jump

function record_hit($id, $url, $status) {
	global $DB_site, $bbuserinfo, $links_permissions;

	if ($links_permissions["can_bypass_hit_recording"]) return;

	$userip = iif (isset($_SERVER[REMOTE_ADDR]), $_SERVER[REMOTE_ADDR], 'unknown IP address');
	$userbrowser = iif (isset($_SERVER[HTTP_USER_AGENT]), $_SERVER[HTTP_USER_AGENT], 'unknown browser');
	$username = $bbuserinfo[username];
	$userid = $bbuserinfo[userid];

	$time = TIMENOW;
	$time60 = $time - 60;
	$jumplink = $DB_site->query("
		SELECT * FROM ".THIS_TABLE."linksdownloads
		WHERE linkid='$id' AND userid='$userid' AND usertime>'$time60'
		LIMIT 1
		");

// Avoid double hits
	if ($DB_site->num_rows($jumplink)>0) return(-1);

	$DB_site->query("
		UPDATE ".THIS_TABLE."linkslink
		SET linkhits=linkhits+1, linkstatus=$status
		WHERE linkid='$id'
		LIMIT 1
	");

	$DB_site->query("
		INSERT INTO ".THIS_TABLE."linksdownloads (linkid, linkurl, username, userid, userip, userbrowser, usertime)
		VALUES (
		'".intval($id)."',
		'".addslashes($url)."',
		'".addslashes(htmlspecialchars($username))."',
		'".$userid."',
		'".$userip."',
		'".addslashes(htmlspecialchars($userbrowser))."',
		$time
		)
	");

	return(0);
}

if ($_REQUEST['action'] == "jump") {

	$time = TIMENOW;
	unset($url);

	if (isset($_REQUEST['link'])) {
		$link = preg_replace("/(\"*)(.*)\\1/", "\\2", $_REQUEST['link']);
		if (preg_match("/(.*)\/(.*)/", $link, $match)) {
			$lname = addslashes($match[2]);
			$cname = addslashes($match[1]);
		} else {
			$lname = addslashes($link);
			$cname = "%";
		}
		$jumplink = $DB_site->query("
			SELECT link.linkid AS linkid, link.linkname AS linkname,
				link.linkurl AS linkurl, link.linkforum AS linkforum, link.linkstatus AS linkstatus,
				cat.catname AS catname
			FROM ".THIS_TABLE."linkslink AS link
			LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
			ON link.linkid = ltoc.linkid
			LEFT JOIN ".THIS_TABLE."linkscat AS cat
			ON ltoc.catid = cat.catid
			WHERE link.linkname LIKE '$lname' AND cat.catname LIKE '$cname'
			LIMIT 1
			");
		while ($jump=$DB_site->fetch_array($jumplink)) {
			$url	   = $jump['linkurl'];
			$linkid    = $jump['linkid'];
			$linkforum = $jump['linkforum'];
			$linkstatus = $jump['linkstatus'];
		}
		if (!isset($url)) {
			eval(print_standard_error('Error - Link '.$lname.'/'.$cname.' not found.',0));
			exit;
		}

	} elseif (isset($_REQUEST['id'])) {
		$id = intval($_REQUEST['id']);
		$jumplink = $DB_site->query("
			SELECT linkurl, linkforum, linkstatus FROM ".THIS_TABLE."linkslink
			WHERE linkid='$id'
			LIMIT 1
			");
		while ($jump=$DB_site->fetch_array($jumplink)) {
			$url	   = $jump['linkurl'];
			$linkforum = $jump['linkforum'];
			$linkstatus = $jump['linkstatus'];
		}
		if (!isset($url)) {
			eval(print_standard_error('Error - Link #'.$id.' not set.',0));
			exit;
		}

	} else {
		eval(print_standard_error('Error - no link/id specified.',0));
		exit;
	}


	if (!forumid_is_valid($linkforum)) {
		$DB_site->query("
			UPDATE ".THIS_TABLE."linkslink
			SET linkstatus=$LINK_NO_ACCESS, linkcheck=$time
			WHERE linkid='$id'
			LIMIT 1
		");
		eval(print_standard_error('Error - Cannot determine if you can access link #'.$id.' - must assume not',0));
		exit;

	} elseif ($linkforum > 0) {

// fetch the permissions for this forum
		$forumperms = fetch_permissions($linkforum);

		if (!($forumperms & CANVIEW) || !($forumperms & CANVIEWOTHERS)) {
			print_no_permission();
			exit;
		}

	}

	$urlInfo = parse_url($url);
	if ($urlInfo['scheme'] != "" and !in_array($urlInfo['scheme'], $schemes)) {
		$hit = record_hit($id, $url, $LINK_BROKEN);
		eval(print_standard_error('Sorry - unable to handle '.$urlInfo['scheme'].' protocol.',0));
		exit;
	}

	$dfname  = basename($urlInfo['path']);
	$type	 = substr(strrchr($dfname, "."), 1);

	$mimetype = get_mimetype($type);
	if ($links_defaults["force_redirect"]==1 or !is_array($mimetype) or $urlInfo['query'] != "") {

// force redirect mode or not a known mimetype or a qualified mimetype (a la Sourceforge)
// so this as a regular link
		write_debug("jump($url) begin redirect");
		$hit = record_hit($id, $url, $LINK_OK);
		eval(print_standard_redirect('Redirecting.',0));

	} else {

// mimetype found so assume this is a file to be downloaded

// guard against allow_url_fopen being turned off
		if (!ini_get('allow_url_fopen')) {
			eval(print_standard_error('Sorry - the site has disabled downloads (allow_url_fopen is off).',0));
			exit;
		}

		$file = cleanto_fopen($url);
		$conn = @fopen($file, "rb");

		if (!$conn) {

			write_debug("jump($url) open $file fails");
			$hit = record_hit($id, $url, $LINK_BROKEN);
			eval(print_standard_error('Sorry - link is not currently available.',0));
			exit;

		} else {

			write_debug("jump($url) begin transfer");

			ini_set('zlib.output_compression', 'Off');
			exec_nocache_headers();

			if (HEADER_BEHAVIOUR == "inline") {
				header("Content-disposition: inline; filename=\"$dfname\"");
			} else {
				header("Content-type: application/x-download");
				header("Content-disposition: attachment; filename=\"$dfname\"");
			}

			if ($type != 'txt') {
				header('Content-transfer-encoding: binary');
			}

			if ($linkstatus > 1) {
				header("Accept-Ranges: bytes");
				header("Content-Length: $linkstatus");
			}

			foreach ($mimetype AS $index => $header) {
				header($header);
			}

			$bytes = 0;
			while ($contents = fread ($conn, $READ_BUFFER_SIZE)) {
				echo $contents;
				$bytes += strlen($contents);
			}
			flush();
			fclose($conn);
			if ($bytes==0) $bytes=$LINK_OK;
			$hit = record_hit($id, $url, $bytes);

			write_debug("jump($url) open $file ok, $bytes read");

		}

	}
	exit;
}

// Default fall through
$url = THIS_SCRIPT.".php?action=links";
eval(print_standard_redirect('Unknown action requested',0));
exit;

?>
