<?

// ###################### Start functions #######################
error_reporting(E_ALL & ~E_NOTICE);

define('LINKS_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_admin',
	'links_admin_downloads',
	'links_admin_downloads_choose',
	'links_admin_oneperm',
	'links_admin_onesetting',
	'links_admin_onesetting_start',
	'links_admin_onesetting_end',
	'links_admin_scan_start',
	'links_admin_scan_end',
	'links_admin_scan_line',
	'links_admin_scan_one',
	'links_footer',
	'links_header',
	'navbar',
	'option'
);

// get special data templates from the datastore
$specialtemplates = array();

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

// chdir('./../');

require_once('./global.php');
require_once("includes/local_links_include.php");

if (!isset($_REQUEST['action']) or $_REQUEST['action']=="") $_REQUEST['action'] = "admin";
if (!isset($_REQUEST['set']) or $_REQUEST['set']=="") $_REQUEST['set'] = "all";
switch ($_REQUEST['set']) {
case "statistics":
case "settings":
case "permissions":
case "importexport":
case "all":
	$adminset = $_REQUEST['set'];
	break;

default:
	$adminset = "all";
	break;
}

// Administrators only

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

// #################### Administer Links/Files Database

// Utility routines

function build_cat_tree($level) {
	global $linkscat, $forum;
	$tree = '';
	$keys = array_keys($linkscat);
	foreach ($keys as $thiskey) {
		$thiscat = $linkscat[$thiskey];
		if ($thiscat['parentid'] == $level) {
			$depth = preg_replace("/[^,]/", "", $thiscat['parentlist']);
			$depth = preg_replace("/,/", "-", $depth);
			$tree .= $depth.'
				<a href="'.LINKS_SCRIPT.'.php?action=links&amp;catid='.$thiscat['catid'].'">'.
				$thiscat['catname'].'</a> [Catid:'.$thiscat['catid'].' Links:'.$thiscat['catentry'].
				', Forum: '.$forum[$thiscat['catforum']].']';
			if ($thiscat['catclosed'] == 0) {
				$tree .= ' [Category open:
				<a href="'.LINKS_SCRIPT.'.php?action=doeditcat&amp;submit=Close&amp;catid='.
				$thiscat['catid'].'">close</a>]';
			} else {
			$tree .= ' [Category closed:
				<a href="'.LINKS_SCRIPT.'.php?action=doeditcat&amp;submit=Open&amp;catid='.
				$thiscat['catid'].'">re-open</a>]';
			}
			$tree .= '<br />';
			$tree .= build_cat_tree($thiscat['catid']);
		}
	}
	return $tree;
}

function export_cat_tree($level) {
	global $linkscat;
	$keys = array_keys($linkscat);
	foreach ($keys as $thiskey) {
		$thiscat = $linkscat[$thiskey];
		if ($thiscat['parentid'] == $level) {
			$search = array ("'\r'", "'\n'", "'&amp;'");
			$replace = array ("\\\\r", "\\\\n", "&");
			$rec = "category," . $thiscat["catid"] . ",\"" . $thiscat["catname"] . "\",\"" .
				preg_replace ($search, $replace, $thiscat["catdesc"]) . "\",\"" . $thiscat["parentlist"] . "\"\r\n";
			echo $rec;
			export_cat_tree($thiscat['catid']);
		}
	}
	return;
}

function dohead() {
	echo '<html><head><title>下载管理</title><style type="text/css">
		<!--
		body {
			background: #CCCCCC; color: #00476C; font: 10pt tahoma, arial, helvetica, sans-serif;
			margin: 5px 5px 10px 5px;
		}
		body a:link { color: #22229C; }
		body a:visited { color: #22229C; }
		body a:hover, body a:active { color: #FF4400; }
		-->
		</style>
		</head><body>';
	flush();
}

function dofoot() {
	echo '</body></html>';
	flush();
}

// #################### Display main Administration Page

if ($_REQUEST['action'] == "admin") {  // admin only

	$this_navigation_title = "下载管理";
	build_forum_list();

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

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

	fix_cat_count();  // just in case

	if ($adminset == "statistics" or $adminset == "all") {

		// Information about the database contents
		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
		");
		$linkstats['links'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
			WHERE linkstatus>0
		");
		$linkstats['linksok'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
			WHERE linkstatus=$LINK_BROKEN
		");
		$linkstats['linksbroken'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
			WHERE linkstatus=$LINK_NO_ACCESS
		");
		$linkstats['linksinvalid'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
			WHERE linkmoderate=$LINK_TO_MODERATE
		");
		$linkstats['linksmod'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
			WHERE linkstatus=$LINK_HIDDEN
		");
		$linkstats['linkshidden'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS links
			FROM ".THIS_TABLE."linkslink
			WHERE linkreviewfreq>0 AND (linkmoddate+linkreviewfreq*24*60*60)<".TIMENOW."
		");
		$linkstats['linksreview'] = $count['links'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS cats
			FROM ".THIS_TABLE."linkscat
		");
		$linkstats['categories'] = $count['cats'];

		$count = $DB_site->query_first("
			SELECT COUNT(*) AS cats
			FROM ".THIS_TABLE."linkscat
			WHERE catmoderate=$LINK_TO_MODERATE
		");
		$linkstats['catsmod'] = $count['cats'];

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

		$linkstats['catlist'] = build_cat_tree(-1);

		$time = TIMENOW - 60*60*24*7;
		$count = $DB_site->query_first("
			SELECT COUNT(*) AS downloads
			FROM ".THIS_TABLE."linksdownloads
			WHERE usertime>$time
		");
		$linkstats['downloads'] = $count['downloads'];

		$linkstats['users'] = '';
		$count = $DB_site->query("
			SELECT linkusername, linkuserid, COUNT(linkuserid) AS usercount
			FROM ".THIS_TABLE."linkslink GROUP BY linkuserid
		");
		while ($row = $DB_site->fetch_array($count)) {
			$linkstats['users'] .= '
				<a href="member.php?userid='.$row['linkuserid'].'">'.$row['linkusername'].'</a>
				('.$row['usercount'].' <a href="'.LINKS_SCRIPT.'.php?action=show&amp;user='.
				$row['linkuserid'].'">entries</a>)<br />
			';
		}

		$count = $DB_site->query("
			SELECT linkurl, count( linkurl ) AS cnt
			FROM ".THIS_TABLE."linkslink
			GROUP BY linkurl
			ORDER BY cnt DESC
		");
		$dups = array();
		while ($row = $DB_site->fetch_array($count)) {
			if ($row[cnt]<=1) break;
			$dups[] .= $row['linkurl'];
		}
		$linkstats['dups'] = '';
		foreach ($dups AS $dup) {
			$count = $DB_site->query("
				SELECT link.linkname AS linkname, link.linkid AS linkid, link.linkurl AS linkurl,
				cat.catid AS catid, 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.linkurl = '".$dup."'
				ORDER BY catname ASC
			");
			$n = 0;
			while ($row = $DB_site->fetch_array($count)) {
				if (!$n) {
					$linkstats['dups'] .= 'Link '. $row['linkurl'] . '<br />';
					$n++;
				}
				$linkstats['dups'] .= ' -&gt;&gt; category <a href="local_links.php?catid=' . $row['catid']
					. '" target="_blank">' . $row['catname'] . '</a> ' . ' entry ' . $row['linkname'] . '<br />';
			}
		}
	}

// Mime types, i.e. types under downloadable control
	$junk = get_mimetype("");
	foreach ($mimetype_cache as $mimetype => $mime) {
		$linkstats['mimetypes'] .= $mimetype.' ';
	}

// Permissions
	$linksperms = '';
	$linkssettings = '';
	$asb = $DB_site->query("
		SELECT usergroupid, title
		FROM " . TABLE_PREFIX . "usergroup AS usergroup
	");
	while ($row = $DB_site->fetch_array($asb)) {
		$usergroup[$row['usergroupid']] = $row['title'];
	}

	$asb = $DB_site->query("
		SELECT *
		FROM ".THIS_TABLE."linksadmin
		ORDER BY sequence
	");
	while ($admin_settings = $DB_site->fetch_array($asb)) {
		if (substr($admin_settings["settingname"],0,3) == "can") {
			eval("\$linksperms .= \"".fetch_template('links_admin_onesetting_start')."\";");
			$array = preg_split("/[\s,]+/", $admin_settings['setting']);
			foreach ($usergroup as $usergroupid => $title) {
				if (in_array($usergroupid, $array)) {
					$checked = 'checked="checked"';
				} else {
					$checked = '';
				}
				eval("\$linksperms .= \"".fetch_template('links_admin_oneperm')."\";");
			}
			eval("\$linksperms .= \"".fetch_template('links_admin_onesetting_end')."\";");
		} else {
			eval("\$linkssettings .= \"".fetch_template('links_admin_onesetting_start')."\";");
			$setting = '<input type="text" name="' . $admin_settings[settingname] .
					'[]" value="'.$admin_settings[setting].'" size="25" />';
			if ($admin_settings["settingname"] == "default_forumid") {
				// Try to set up a modified forum jump for use here
				if (preg_match("/(<option value=\"\d.*?<.option>.*)<\/optgroup/is", $forumjump, $local_forumjump) == 1) {
					$local_forumjump[1] = preg_replace("/option (value=\"".$links_defaults["default_forumid"]."\")/", "option selected $1", $local_forumjump[1]);
					$setting = '<select name="default_forumid[]"><option value="-999" >' .
						'Turn off (-999)</option>' . $local_forumjump[1] . '</select>';
				}
			}
			eval("\$linkssettings .= \"".fetch_template('links_admin_onesetting')."\";");
			eval("\$linkssettings .= \"".fetch_template('links_admin_onesetting_end')."\";");
		}
	}

	// 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;

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

	print_output($output);
	exit;

}

// #################### File import

if ($_REQUEST['action'] == "doadmin" and $_REQUEST['submit'] == "Import") {

	$file = $_FILES["import"]["tmp_name"];
	if ($file) {
		$messages = "<strong>Importing ".$_FILES["import"]["name"]."</strong><br />";
		$tcat = 0;
		$keys = array_keys($linkscat);
		foreach ($keys as $thiskey) { $tcat++; }
		$ncat = 0;
		$nlnk = 0;
		$fp = @fopen ($file,"r");
		if (!$fp) {
			$messages .= "Unable to open $file";
		} else {
			unset ($data);

			while ($data = fgetcsv ($fp, 1000, ",")) {
				$num = count ($data);
				for ($c=0; $c < $num; $c++) {
					$data[$c] = preg_replace ("/^ *(\")(.*)\\1/", "\\2", $data[$c]);
					$data[$c] = preg_replace ("/\\x5Cr/", "\r", $data[$c]);
					$data[$c] = preg_replace ("/\\x5Cn/", "\n", $data[$c]);
				}

				if (preg_match("/category/i", $data[0])) {
					if ($tcat>0) {
						$messages .= "&gt; create cat $data[2] failed: categories already exist<br />";
						continue;
					}
					if (!isset($data[4]) or !preg_match ( "/^[\s\d-,]+$/", $data[4])) {
						$messages .= "&gt; create cat $data[2] failed: invalid parentlist $data[4]<br />";
						continue;
					}
					if (!isset($data[5])) {
						$data[5] = $links_defaults["default_forumid"];
					} else {
						if (!preg_match ( "/^[\s\d]+$/", $data[5])) {
							$messages .= "&gt; create cat $data[2] failed: invalid forumid $data[5]<br />";
							continue;
						}
					}

					$parentid = explode(',', $data[4]);
					$DB_site->query("
					INSERT INTO ".THIS_TABLE."linkscat (catid, catname, catdesc, cattext, parentid, parentlist, catforum, catusername, catuserid, catentry, catdate, catmoderate, catinstructions)
					VALUES (
					'$data[1]',
					'".addslashes($data[2])."',
					'".addslashes($data[3])."',
					'".addslashes($data[3])."',
					'".$parentid[0]."',
					'".$data[4]."',
					'".$data[5]."',
					'".addslashes(htmlspecialchars($bbuserinfo[username]))."',
					$bbuserinfo[userid],
					0,
					0,
					$LINK_ACCEPTED,
					''
					)
					");

					$messages .= "&gt; Inserted cat $data[2] as #$data[1]<br />";
					$ncat++;
					$linkscat[$data[1]] = 1; // force it to be set
				}

				if (preg_match("/link/i", $data[0])) {
					if (!isset($data[5])) {
						$data[5] = $links_defaults["default_forumid"];
					} else {
						if (!preg_match ( "/^[\s\d]+$/", $data[5])) {
							$messages .= "&gt; $data[2] failed: invalid forumid $data[5]<br />";
							continue;
						}
					}
					if (!preg_match ( "/^[,\s\d]+$/", $data[4])) {
						$messages .= "&gt; $data[2] failed: invalid category id list $data[4]<br />";
						continue;
					}
					$pcatid = explode(',', $data[4]);
					foreach ($pcatid as $p) {
						if (!isset($linkscat[$p])) {
							$messages .= "&gt; $data[2] failed: non-existent category id $p<br />";
							continue 2;
						}
					}
					$linkid = insert_link ($bbuserinfo['username'], $bbuserinfo['userid'], $data[1], $data[2], $data[3], explode(',', $data[4]), $data[5], $LINK_BROKEN, 0, 0, 0);
					$messages .= "&gt; Inserted $data[2] as link #$linkid into category id $data[4]<br />";
					$nlnk++;
				}

			}
		}
		fclose ($fp);
		$messages .= '<strong>Import completed:</strong> '.$ncat.' categories, '.$nlnk.' links inserted<br />
		Remember to <a href="'.ADMIN_SCRIPT.'.php?action=doadmin&amp;submit=Validate&amp;set='.$adminset.'">re-validate</a><br />';
	}

	$this_navigation_title = "Import";
	build_forum_list();

	// Make Links Nav Bar
	$navbits = array();
	$navbits[LINKS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	$navbits[ADMIN_SCRIPT.".php?$session[sessionurl]action=admin&amp;set=".$adminset] = "下载管理";
	$navbits[""] = $this_navigation_title;
	$navbits = construct_navbits($navbits);

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

// control menu items visible in the header template
	unset($pcatid);
	$links_permissions["can_add_link"] = 0;
	$links_permissions["can_add_category"] = 0;
	$links_permissions["can_edit_category"] = 0;

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

	print_output($output);
	exit;

}

// #################### File Export

if ($_REQUEST['action'] == "doadmin" and $_REQUEST['submit'] == "Export") {

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

	header("Content-Type: application/octet-stream");
	header("Content-Disposition: attachment; filename=\"export.csv\"");

	export_cat_tree(-1);

	$query = "
		SELECT link.linkid AS linkid, link.linkname AS linkname, link.linkurl AS linkurl,
			link.linkdesc AS linkdesc, ltoc.catid AS linkcatid
		FROM ".THIS_TABLE."linkslink AS link
		LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
		ON link.linkid = ltoc.linkid
		";

	$asb = $DB_site->query($query);

	while ($myrow = $DB_site->fetch_array($asb)) {
		$search = array ("'\r'", "'\n'", "'&amp;'");
		$replace = array ("\\\\r", "\\\\n", "&");
		$myrow["linkdesc"] = preg_replace ($search, $replace, $myrow["linkdesc"]);
		$rec = "link,\"" . $myrow["linkname"] . "\",\"" . $myrow["linkurl"] . "\",\""
			. $myrow["linkdesc"] . "\"," . $myrow["linkcatid"] . "\r\n";
		echo $rec;
	}

	flush();
	exit;

}

// #################### Admin Dump

if ($_REQUEST['action'] == "doadmin" and $_REQUEST['submit'] == "Dump") {

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

	header("Content-Type: application/octet-stream");
	header("Content-Disposition: attachment; filename=\"dump.csv\"");

	$query = "
		SELECT link.linkid AS linkid, link.linkname AS linkname, link.linkurl AS linkurl,
			link.linkdesc AS linkdesc, ltoc.catid AS linkcatid
		FROM ".THIS_TABLE."linkslink AS link
		LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
		ON link.linkid = ltoc.linkid
		ORDER BY link.linkname
		";

	$asb = $DB_site->query($query);

	$rec = "\"". "VBCode" . "\",\"" . "LinkID" . "\",\"" . "LinkName" . "\",\"" 
			. "URL" . "\",\"" . "Description" . "\",\"" . "CategoryID" . "\",\"" 
			. "Category" . "\"\r\n";
		echo $rec;
	while ($myrow = $DB_site->fetch_array($asb)) {
		$search = array ("'\r'", "'\n'", "'&amp;'", "'\"'");
		$replace = array ("\\\\r", "\\\\n", "&", "");
		$myrow["linkdesc"] = preg_replace ($search, $replace, $myrow["linkdesc"]);
		$myrow["vbcode"] = "[LINK=".$myrow["linkid"]."]".$myrow["linkname"]."[/LINK]";
		$rec = "\"" . $myrow["vbcode"] . "\",\"" 
			. $myrow["linkid"] . "\",\"" 
			. $myrow["linkname"] . "\",\"" 
			. $myrow["linkurl"] . "\",\"" 
			. $myrow["linkdesc"] . "\",\"" 
			. $myrow["linkcatid"] . "\",\"" 
			. $linkscat[$myrow["linkcatid"]]["catname"] . "\"," . "\r\n";
		echo $rec;
	}

	flush();
	exit;

}

// #################### Permissions

if ($_REQUEST['action'] == "doadmin" and $_REQUEST["submit"] == "Go") {

	$asb = $DB_site->query("
		SELECT *
		FROM ".THIS_TABLE."linksadmin
	");

	$errors = array();
// check that key settings are valid
    while ($admin_settings = $DB_site->fetch_array($asb)) {
		if (!isset($_REQUEST[$admin_settings[settingname]])) continue;

//echo $admin_settings[settingname].'<br />';
//var_dump($_REQUEST[$admin_settings[settingname]]); echo '<br />';
		$newsetting = trim(implode(',', $_REQUEST[$admin_settings[settingname]]));
		$error = 0;

		switch ($admin_settings[settingname]) {
		case "default_forumid":
			if (!forumid_is_valid($newsetting)) { $error = 1; } break;

		case "allow_bbcode":
		case "allow_html":
		case "allow_images":
		case "allow_smiles":
		case "allow_null_links":
		case "count_depth":
		case "local_file_root":
		case "moderate_links":
			if ($newsetting != "0" and $newsetting != "1") { $error = 1; } break;

		case "force_redirect":
			if ($newsetting != "0" and $newsetting != "1" and $newsetting != "2") { $error = 1; } break;

		case "default_link_dseq":
		case "default_cat_dseq":
		case "links_per_page":
		case "links_seen_on_portal":
		case "cat_depth_display":
		case "cat_sub_display":
			if (!is_numeric($newsetting) or $newsetting < 0) { $error = 1; } break;

		case "default_sort_order":
			if (!preg_match("/^[NnHhDd]$/", $newsetting)) { $error = 1; } break;

		case "categories_seen_on_portal":
			if (!preg_match("/^[\d,]*$/", $newsetting)) { $error = 1; } break;

		case "monitor_catid":
			if ($newsetting != '') {
				if (!preg_match("/^[\d]*$/", $newsetting)) { $error = 1; }
				if (!isset($linkscat[$newsetting])) { $error = 1; }
			}
			break;

		case "file_icons_dir":
			if ($newsetting != '') {
				if (substr($newsetting,-1) != '/') {
					$newsetting .= '/';
					$_REQUEST[$admin_settings[settingname]] = array($newsetting);
				}
				if ($handle = @opendir($newsetting)) {
				    closedir($handle);
				} else {
					if (!$open_basedir) $error = 1;
				}
			}
			break;

		case "monitor_dir":
			$dir = wild_explode($newsetting);
			$ndir = array();
			foreach ($dir as $this) {
				$this = trim($this);
				if ($this != '' and substr($this,-1) != '/') {
					$this .= '/';
				}
				$url = cleanto_fopen($this);
				if ($handle = @opendir($url)) {
				    closedir($handle);
				} else {
					$error = 1;
				}
				$ndir[] = $this;
			}
//			$_REQUEST[$admin_settings[settingname]] = array(implode(',', $ndir));
			break;

		case "robots_meta_tag":
			break;
		}
		if ($error) $errors[$admin_settings[settingname]] = $newsetting;
	}
//exit;

	$isok = 1;
	foreach ($errors as $k => $v) {
		if ($isok == 1) { dohead(); echo "The following setting(s) are invalid<br />"; }
		echo $k.' : '.$v.'<br />';
		$isok = 0;
	}

	if ($isok == 1) {

		$DB_site->data_seek(0, $asb);
//		$asb = $DB_site->query("
//			SELECT *
//			FROM ".THIS_TABLE."linksadmin
//		");

	    while ($admin_settings = $DB_site->fetch_array($asb)) {
			if (!isset($_REQUEST[$admin_settings[settingname]]) and substr($admin_settings["settingname"],0,3) == "can") {
				$_REQUEST[$admin_settings[settingname]] = array(-1);
			}
			if (!isset($_REQUEST[$admin_settings[settingname]])) continue;
			$newsetting = trim(implode(',', $_REQUEST[$admin_settings[settingname]]));

			if ($newsetting != $admin_settings[setting]) {

				$DB_site->query("
					UPDATE ".THIS_TABLE."linksadmin
					SET setting='$newsetting'
					WHERE settingname='$admin_settings[settingname]'
					LIMIT 1
				");
				write_debug("admin_setting(".$admin_settings[settingname].")=".$newsetting);
			}
		}
		$url = ADMIN_SCRIPT.".php?action=admin&amp;set=".$adminset;
		eval(print_standard_redirect('Settings updated',0));

	} else {
		echo "<a href=javascript:history.back(1)><b>Go back</b></a><br />";
		dofoot();
	}

	exit;
}

// #################### Validate database

if ($_REQUEST['action'] == "doadmin" and preg_match("/validate/i", $_REQUEST["submit"])) {

	$startat = intval($_REQUEST['at']);
	$where = "";
	$limit = 10;

	if ($startat <> "") {
		$where .= "AND linkid >= $startat ";
	}

	if (preg_match("/broken/i", $_REQUEST["submit"])) {
		$where .= "AND linkstatus = 0 ";
	}

	if (preg_match("/invalid/i", $_REQUEST["submit"])) {
		$where .= "AND linkstatus = -1 ";
	}

	$asb = $DB_site->query("
		SELECT linkid, linkurl, linkforum, linkstatus
		FROM ".THIS_TABLE."linkslink
		WHERE (1)
		$where
		ORDER BY linkid
		LIMIT $limit
	");

	$num = 0;
	dohead();
	while ($myrow=$DB_site->fetch_array($asb)) {
		$linkid	= $myrow["linkid"];
		$linkforum = $myrow["linkforum"];
		$nextid	= $linkid + 1;
		$linkurl   = $myrow["linkurl"];
		echo "checking $linkid $linkurl";
		echo " (<a href=".ADMIN_SCRIPT.".php?action=doadmin&amp;submit=".$_REQUEST["submit"]."&amp;at=$nextid&amp;set=".$adminset.">force next</a>, ";
		echo " <a href=".ADMIN_SCRIPT.".php?action=doadmin&amp;submit=".$_REQUEST["submit"]."&amp;at=999999&amp;set=".$adminset.">quit checking</a>)";
		flush();
		if (!forumid_is_valid($linkforum)) {
			$status = $LINK_NO_ACCESS;
			echo ": <b>invalid forum</b><br />";
		} else {
			$status = check_url ($linkurl);
			switch ($status) {
			case $LINK_NO_ACCESS:
				echo ": <b>invalid</b> (forum/protocol)<br />";
				break;
			case $LINK_BROKEN:
				echo ": <b>failed</b><br />";
				break;
			default:
				echo ": ok<br />";
			}
		}
		$time = TIMENOW;
		$DB_site->query("
			UPDATE ".THIS_TABLE."linkslink
			SET linkstatus=$status, linkcheck=$time
			WHERE linkid='$linkid'
			LIMIT 1
		");
		$num++;
	}
	dofoot();
	if ($num >= $limit) {
		$url = ADMIN_SCRIPT.".php?action=doadmin&submit=".$_REQUEST["submit"]."&at=$nextid&set=".$adminset;
		redirect($url);
	} else {
		$url = ADMIN_SCRIPT.".php?action=admin&set=".$adminset;
		redirect($url);
	}

}

// #################### Log downloads/jumps

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

	$this_navigation_title = "Downloads";
	build_forum_list();

	// Make Links Nav Bar
	$navbits = array();
	$navbits[LINKS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	$navbits[ADMIN_SCRIPT.".php?$session[sessionurl]action=admin&amp;set=".$adminset] = "下载管理";
	$navbits[""] = $this_navigation_title;
	$navbits = construct_navbits($navbits);

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

	if (!isset($_REQUEST['sortby'])) {
		$startat = TIMENOW - 60*60*24*7; // one week
		$startat = date ("Y-m-d", $startat);
		$endat = TIMENOW;
		$endat = date ("Y-m-d", $endat); //today
		eval("\$output  = \"".fetch_template('links_header')."\";");
		eval("\$output .= \"".fetch_template('links_admin_downloads_choose')."\";");
		eval("\$output .= \"".fetch_template('links_footer')."\";");
		print_output($output);
		exit;
	}

	if (isset($_REQUEST['start'])) {
		$chars = preg_split('/-/', $_REQUEST['start'], 3, PREG_SPLIT_NO_EMPTY);
		$startat = mktime ( 0, 0, 0, $chars[1], $chars[2], $chars[0]);
	} else {
		$startat = TIMENOW - 60*60*24*365; // one year
		$_REQUEST['start'] = date ("Y-m-d", $startat);
	}

	if (isset($_REQUEST['end'])) {
		$chars = preg_split('/-/', $_REQUEST['end'], 3, PREG_SPLIT_NO_EMPTY);
		$endat = mktime ( 0, 0, 0, $chars[1], $chars[2], $chars[0]);
	} else {
		$endat = TIMENOW;
		$_REQUEST['end'] = date ("Y-m-d", $endat); //today
	}

	$query = "
		SELECT *
		FROM ".THIS_TABLE."linksdownloads
		WHERE usertime>=$startat AND usertime<=$endat
		ORDER BY ";
	switch ($_REQUEST['sortby']) {
	case "byuser": $query .= " username"; break;
	case "byip":   $query .= " userip"; break;
	case "bydate":
	default:       $query .= " usertime"; break;
	}

	$asb = $DB_site->query($query);
	$counts = array();
	$linkdownloadsbit = '<tr><td class="tcat" align="center" colspan="4">'.
		'<b>Downloads/hits from '.$_REQUEST['start'].' to '.$_REQUEST['end'].
		'</b></td></tr>';
	while ($myrow=$DB_site->fetch_array($asb)) {
		$whenh = date ("H:i", $myrow['usertime']);
		$whend = date ("Y-m-d", $myrow['usertime']);
		$linkdownloadsbit .= '<tr>'.
		'<td class="alt1"><span class="smallfont">'.iif(strlen($myrow['linkurl'])<=48,$myrow['linkurl'],substr($myrow['linkurl'],0,45).'...').'</span></td>'.
		'<td class="alt1"><span class="smallfont">'.$myrow['username'].'</span></td>'.
		'<td class="alt1"><span class="smallfont">'.$myrow['userip'].'</span></td>'.
		'<td class="alt1"><span class="smallfont">'.$whenh.', '.$whend.'</span></td>'.
		'</tr>';
		switch ($_REQUEST['sortby']) {
		case "byuser": $counts[$myrow['username']]++; break;
		case "byip":   $counts[$myrow['userip']]++; break;
		case "bydate":
		default:       $counts[$whend]++; break;
		}
	}

	$linkdownloadsbit .= '<tr><td class="alt2">&nbsp;</td><td colspan="3" class="alt2"><span class="smallfont"><b>Download/hit count</b></span></td></tr>';
	ksort($counts);
	foreach ($counts as $key=>$this) {
		$linkdownloadsbit .= '<tr><td class="alt1"><span class="smallfont">'.$key.'</span></td>'.
			'<td colspan="3" class="alt1"><span class="smallfont">'.$this.'</span></td></tr>';
	}

	$linkdownloadsbit .= '<tr><td colspan="4" class="alt2">&nbsp</td></tr>'.
		'<tr><td class="alt1"><span class="smallfont">'.
		'<a href='.ADMIN_SCRIPT.'.php?action=cleanjumps&amp;start='.$_REQUEST['start'].
		'&amp;end='.$_REQUEST['end'].'&amp;set='.$adminset.'><b>Delete</b></a> these log entries'.
		'</span></td>'.
		'<td colspan="3" class="alt1">'.
		'<a href=javascript:history.back(1)><span class="smallfont"><b>Return</span></b></a>'.
		'</td></tr>'
		;

// 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;

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

	print_output($output);
	exit;

}

// #################### Clean up downloads/jumps log

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

	if (isset($_REQUEST['start'])) {
		$chars = preg_split('/-/', $_REQUEST['start'], 3, PREG_SPLIT_NO_EMPTY);
		$startat = mktime ( 0, 0, 0, $chars[1], $chars[2], $chars[0]);
	} else {
		$startat = 0;
		$_REQUEST['start'] = date ("Y-m-d", $startat);
	}

	if (isset($_REQUEST['end'])) {
		$chars = preg_split('/-/', $_REQUEST['end'], 3, PREG_SPLIT_NO_EMPTY);
		$endat = mktime ( 0, 0, 0, $chars[1], $chars[2], $chars[0]);
	} else {
		$endat = TIMENOW - 60*60*24*30; // One month
		$_REQUEST['end'] = date ("Y-m-d", $endat);
	}

	$asb = $DB_site->query("
		DELETE
		FROM ".THIS_TABLE."linksdownloads
		WHERE usertime>=$startat AND usertime<=$endat
	");

	dohead();

	echo '<br /><br />';
	echo 'Log entries between '.$_REQUEST['start'].' and '.$_REQUEST['end'].' deleted';
	echo '<br /><br />';
	echo '<a href='.ADMIN_SCRIPT.'.php?action=logjumps&amp;set='.$adminset.'><b>Return</b></a>';

	dofoot();

}

// #################### Directory scan

function wild_explode($list) {
	$temp = explode(',', $list);
	$results = array();
	foreach ($temp as $t) {
		if (preg_match("/(.*\/)(\*)/", trim($t), $matches)) {
			$fulldir = cleanto_fopen(trim($matches[1]));
			if ($dir_handle = @opendir($fulldir)) {
			    while (false !== ($file = readdir($dir_handle))) {
					if ($file != '.' and $file != '..' and is_dir($fulldir.$file)) {
						$this = array($matches[1].$file.'/');
						$deeper = wild_explode($matches[1].$file.'/*');
						$results = array_merge($results, $this, $deeper);
					}
				}
				fclose ($dir_handle);
			}
		} else {
			if (substr($t,-1) != '/') {
				$this = $t.'/';
			} else {
				$this = $t;
			}
			$results[] = $this;
		}
	}
	return $results;
}

if ($_REQUEST['action'] == "doadmin" and $_REQUEST["submit"] == "Scan") {

	$this_navigation_title = "Directory Scan";

	// Make Links Nav Bar
	$navbits = array();
	$navbits[LINKS_SCRIPT.".php?$session[sessionurl]"] = "下载中心";
	$navbits[ADMIN_SCRIPT.".php?$session[sessionurl]action=admin&amp;set=".$adminset] = "下载管理";
	$navbits[""] = $this_navigation_title;
	$navbits = construct_navbits($navbits);

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

	$countd = 0;

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

	$m_catid = iif(isset($_REQUEST['m_catid']), $_REQUEST['m_catid'], 
		iif(isset($links_defaults['m_catid']), $links_defaults['m_catid'], 0));
	$m_dir = iif(isset($_REQUEST['m_dir']), $_REQUEST['m_dir'], 
		iif(isset($links_defaults['m_dir']), $links_defaults['m_dir'], ''));
		
	if (!isset($m_catid) or !isset($linkscat[$m_catid])) {
		$setting = 'Cannot proceed: monitor_catid not set correctly';
		eval("\$output .= \"".fetch_template('links_admin_scan_line')."\";");
	} else {

		$asb = $DB_site->query("SELECT linkid,linkurl FROM ".THIS_TABLE."linkslink");
		while ($data = $DB_site->fetch_array($asb)) {
			$links[$data["linkurl"]] = $data["linkid"];
		}

		$dirlist = wild_explode($m_dir);
		foreach ($dirlist as $thisdir) {
			$fulldir = cleanto_fopen(trim($thisdir));
			$ignore = array();
			if ($file_handle = @fopen($fulldir."ignore.dat", 'r')) {
				while (!feof ($file_handle)) {
					$line = trim(fgets($file_handle));
					if ($line != '') $ignore[$line] = 1;
				}
				fclose ($file_handle);
			}
			if ($dir_handle = @opendir($fulldir)) {
				$setting = $thisdir;
				eval("\$output .= \"".fetch_template('links_admin_scan_line')."\";");
			    $count_new = 0;
			    $count_old = 0;
			    $count_ign = 0;
			    while (false !== ($file = readdir($dir_handle))) {
					if (!is_dir($fulldir.$file)) {
						$type = substr(strrchr($file, "."), 1);
						if (get_mimetype($type) != '') {
							$this = $thisdir.$file;
							if (isset($links[$this])) {
								$count_old++;
							} else {
								$setting = $file;
								$settingvalue = addslashes($thisdir.$file);
								if (isset($ignore[$file])) {
									$check_hid = 'checked="checked"';
									$check_set = '';
									$count_ign++;
								} else {
									$check_set = 'checked="checked"';
									$check_hid = '';
									$count_new++;
								}
								eval("\$output .= \"".fetch_template('links_admin_scan_one')."\";");
							}
						}
					}
				}
				$setting = $count_new.' new files found, '.$count_old.' already read. ';
				if ($count_ign>0) $setting .= '('.$count_ign.' file skipped from ignore.txt)';
				eval("\$output .= \"".fetch_template('links_admin_scan_line')."\";");
				closedir($dir_handle); 
			} else {
				$setting = 'Unable to open '.$thisdir;
				eval("\$output .= \"".fetch_template('links_admin_scan_line')."\";");
			}
		}
	}

	eval("\$output .= \"".fetch_template('links_admin_scan_end')."\";");
	eval("\$output .= \"".fetch_template('links_footer')."\";");
	print_output($output);

}


if ($_REQUEST['action'] == "doadmin" and $_REQUEST["submit"] == "SelectScan") {

	if ($_REQUEST['go'] == "Cancel") {
		$url = ADMIN_SCRIPT.".php?action=admin&amp;set=".$adminset;
		eval(print_standard_redirect('Scan cancelled',0));
		exit;
	}

	dohead();
	$countd = 0;

	$m_catid = iif(isset($_REQUEST['m_catid']), $_REQUEST['m_catid'], 
		iif(isset($links_defaults['monitor_catid']), $links_defaults['monitor_catid'], 0));
	$m_dir = iif(isset($_REQUEST['m_dir']), $_REQUEST['m_dir'], 
		iif(isset($links_defaults['monitor_dir']), $links_defaults['monitor_dir'], ''));
		
	if (!$m_catid) {
		echo "Cannot proceed: monitor_catid not set correctly<br />";
	} else {

		$pcatid = array($m_catid);
		$pforum = $links_defaults['default_forumid'];
		$moderate = iif($links_defaults["moderate_links"] != '0', $LINK_TO_MODERATE, $LINK_ACCEPTED);
		$dirlist = wild_explode($m_dir);
		foreach ($dirlist as $thisdir) {
			$fulldir = cleanto_fopen(trim($thisdir));
			$ignore = array();
			if ($file_handle = @fopen($fulldir."ignore.dat", 'r')) {
				while (!feof ($file_handle)) {
					$file = trim(fgets($file_handle));
					if ($file != '') $ignore[$thisdir.$file] = 1;
				}
				fclose ($file_handle);
			}
		}

	    $countf = 0;
		foreach ($_REQUEST["scanfilename"] as $key=>$this) {
			$statuscheck = check_url($this);
			if (!preg_match("/(.*\/)(.*)\..*$/", $key, $matches)) continue;
			$dir = $matches[1];
			$title = $matches[2];
			if (isset($ignore[$key])) {
				if ($this>=0) {
					unset($ignore[$key]);
				}
			} elseif ($this<0) {
				$ignore[$key] = 1;
			}
			if ($this>0) {
				$linkid = insert_link ($bbuserinfo['username'], $bbuserinfo['userid'], $title, $key, 'Trawled during scan of '.$dir, $pcatid, $pforum, $statuscheck, $moderate, 0);
				$countf++;
				echo "($linkid) Inserting $key into category ".$m_catid."<br />";
			}
		}
		echo $countf.' new files inserted<br />';

		foreach ($dirlist as $thisdir) {
			$fulldir = cleanto_fopen(trim($thisdir));
			if ($file_handle = @fopen($fulldir."ignore.dat", 'w')) {
				foreach ($ignore as $key=>$this) {
					if (!preg_match("/(.*\/)(.*)/", trim($key), $matches)) continue;
					if ($matches[1] != $thisdir) continue;
					fwrite($file_handle, $matches[2]."\r\n");
				}
				fclose ($file_handle);
			}
		}

	}

	echo '<br />';
	echo '<a href='.ADMIN_SCRIPT.'.php?action=admin&amp;set='.$adminset.'><b>Return</b></a>';
	dofoot();
}


?>