<?

// #######################################################################
//
// This code is provided free on the basis that you do not claim that
// it is your own, sell it or use it as the basis for other products that you
// sell. But by all means extend it, modify it, upgrade it, correct it,
// suggest improvements, call me an idiot, etc.
//
// (c) 2004
// Andrew Dearing
// European Industrial Research Management Association
// www.eirma.asso.fr
//
// #######################################################################


// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);

// #################### DEFINE IMPORTANT CONSTANTS #######################
define('NO_REGISTER_GLOBALS', 1);
define('THIS_SCRIPT', 'local_links_install');
define('THAT_SCRIPT', '../local_links');
define('ADMIN_SCRIPT', '../local_links_admin');

define('THIS_VERSION', '1.51');

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

// pre-cache templates used by all actions
$globaltemplates = array();

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

// Table names: e,g, if you want to use the standard VBulletin database
// table prefix, comment out the following line and uncomment the line after it
define('THIS_TABLE', 'local_');
// define ('THIS_TABLE', TABLE_PREFIX);
//

// Initialise admin table
function require_admin_row($seq, $row, $initialvalue, $description) {
	global $DB_site;
	$query = "
		SELECT *
		FROM ".THIS_TABLE."linksadmin
		WHERE settingname='".$row."'
		LIMIT 1
	";
	$asb = $DB_site->query($query);
	if (!$DB_site->num_rows($asb)) {
		$DB_site->query("
			INSERT INTO ".THIS_TABLE."linksadmin (sequence, settingname, setting)
			VALUES (
			". $seq.",
			'".$row."',
			'".addslashes($initialvalue)."'
			)
		");
	}
	$asb = $DB_site->query("
		UPDATE ".THIS_TABLE."linksadmin
		SET sequence=".$seq.", description='".addslashes($description)."'
		WHERE settingname='".$row."'
	");
}

function init_admin_table() {

// permissions
	require_admin_row(101, 'can_add_link', '6', 'Usergroups that can add new links.');
	require_admin_row(102, 'can_edit_link', '6', 'Usergroups that can edit existing links. (Users can always edit their own links.)');
	require_admin_row(103, 'can_delete_link', '6', 'Usergroups that can delete links.');
	require_admin_row(104, 'can_add_category', '6', 'Usergroups that can add new categories.');
	require_admin_row(105, 'can_edit_category', '6', 'Usergroups that can edit existing categories.');
	require_admin_row(106, 'can_delete_category', '6', 'Usergroups that can delete categories.');
	require_admin_row(107, 'can_view_hits', '6', 'Usergroups that can view numbers of "hits" and names of who submitted entry.');
	require_admin_row(108, 'can_set_permissions','6', 'Usergroups that can set these permissions, i.e. administer.');
	require_admin_row(109, 'can_rate_link', '6', 'Usergroups that can rate links.');
	require_admin_row(110, 'can_moderate_links','6', 'Usergroups that can moderate links and add new links without moderation.');
	require_admin_row(111, 'can_set_display_order','6', 'Usergroups that can override the display order of links.');
	require_admin_row(112, 'can_see_protected_links_on_portal', '6', 'Usergroups that can see links regardless of whether they can then access them');
	require_admin_row(113, 'can_bypass_hit_recording', '-1', 'Downloads from selected usergroups are not recorded (useful if bots are tracking your site)');
	require_admin_row(114, 'can_mark_link', '6', 'Usergroups that can mark links as "My Favourites"');

// settings
	require_admin_row(201, 'this_version', THIS_VERSION, 'Do not change unless you know what you are doing!!!');

	require_admin_row(202, 'allow_html',    '0', 'Html in links/category entries. 0: ignore, 1: allow');
	require_admin_row(203, 'allow_images',  '1', 'Images in links/category entries. 0: ignore, 1: allow');
	require_admin_row(204, 'allow_smilies', '1', 'Smilies in links/category entries. 0: ignore, 1: allow');
	require_admin_row(205, 'allow_bbcode',  '1', 'Bbcode in links/category entries. 0: ignore, 1: allow');
	require_admin_row(206, 'allow_null_links',  '0', 'Links field can be left empty: 0: no, 1: yes');
	require_admin_row(207, 'cat_depth_display', '1', 'Depth of subcategories shown in category listing; 1: show categories at this level only.');
	require_admin_row(208, 'cat_sub_display', '0', 'Depth of categories <strong>below</strong> cat_depth_display to show as links within the catbit.');
	require_admin_row(209, 'categories_seen_on_portal', '', 'Comma-separated list: Categories of hottest links to show on portal; blank=all categories');
	require_admin_row(210, 'default_forumid', '-999', '-999: turn off the forum permissions system. <br />forumid:
	default category/link viewing permissions based on that forum. <br />Usergroups with
	<b>can_set_permissions</b> can always assign a permissions forum to a link/category.');
	require_admin_row(211, 'count_depth', '1', '0: Show total links/categories in subcategory.<br />1: Show totals in complete subtree.');
	require_admin_row(212, 'days_seen_on_portal', '30', 'Number of days\' new links to show on portal and with What\'s New');
	require_admin_row(213, 'default_sort_order', 'N', 'N/n: sort links in ascending/descending order by name, H/h: sort by hits, D/d: sort by submission date.');
	require_admin_row(214, 'default_link_dseq', '1', 'Default display group sequence number for new links.');
	require_admin_row(215, 'default_cat_dseq', '1', 'Default display group sequence number for new categories.');
	require_admin_row(216, 'file_icons_dir', '', 'Optional, directory containing gif icons (e.g. pdf.gif) for linklistbit.
	<b>NB:</b> This setting is relative to the <b>forums</b> directory</b>.');
	require_admin_row(217, 'force_redirect', '0', '0: read/rewrite entries with known mimetypes (i.e. files hidden, headers controlled), browser redirect otherwise; <br />
	1: use browser redirect regardless of filetype (quicker/less bandwidth but file location visible and no header control); <br /> 
	2: standard html hyperlink (file location visible, no checking, no hit counting).');
	require_admin_row(218, 'links_per_page', '0', 'Links shown per page, over-rides user setting.');
	require_admin_row(219, 'links_seen_on_portal', '10', 'Number of links to show on portal, and with Show What\'s Hot! and Anything!');
	require_admin_row(220, 'local_file_root', '0', 'Controls interpretation of local filenames entered as links/downloads and
	using monitor_dir setting. 0: relative to site url, i.e. http://this_site/dir/file.<br />
	1: interpreted relative to host filesystem; symbolic links and redirections ./ and ../ allowed.<br /><b>NB</b>, local_file_root=1
	creates security problems if file system not protected.');
	require_admin_row(221, 'moderate_links', '0', '0: No moderation.<br />1: New submissions require moderation.');
	require_admin_row(222, 'monitor_catid', '', 'Category id in which to place entries found during directory scans.');
	require_admin_row(223, 'monitor_dir', '', 'Comma-separated list of directories to scan for new links (check setting of local_file_root).');
	require_admin_row(224, 'robots_meta_tag', 'index, nofollow', 'Tells robots what to do: (no)index, (no)follow links/files.');

}

print_cp_header('Links and Files Database');

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

$step = $_REQUEST['step'];

// ######################################################################

// step 0 -- Master

if ($step == 0) {

	echo '<hr />';
	echo '<b>Install/Upgrade Links and Files ';
	echo THIS_VERSION;
	echo '</b><br />';

	echo 'Checking environment...<br />';
	$allow_url_fopen = ini_get('allow_url_fopen');
	if (!$allow_url_fopen) {
		echo '<br /><font color="red">';
		echo '<b>Warning ==========================</b><br />';
		echo '<b>allow_url_fopen</b> is turned <b>off</b> in your PHP installation<br />';
		echo 'Any attempts to provide downloadable files that are installed<br />';
		echo 'within your own site will fail without warning<br />';
		echo 'If you want to offer this functionality, you <b>must</b> switch <b>on</b> <br />';
		echo '<b>all_url_fopen</b> in your php.ini<br />';
		echo '<b>========================== Warning</b><br />';
		echo '</font><br />';
	} else {
		echo 'Good: <b>allow_url_fopen</b> is turned <b>on</b> in your PHP installation<br />';
		echo 'Please keep it that way or you *will* run into problems!<br />';
	}

	$zlib = ini_get('zlib.output_compression');
	if ($zlib) {
		echo '<br /><font color="red">';
		echo '<b>Warning ==========================</b><br />';
		echo '<b>zlib.output_compression</b> is turned <b>on</b> in your PHP installation<br />';
		echo 'This hack should be safe against that setting but there have<br />';
		echo 'been reported problems.<br />';
		echo '<b>========================== Warning</b><br />';
		echo '</font><br />';
	} else {
		echo 'Good: <b>zlib.output_compression</b> is turned <b>off</b> in your PHP installation<br />';
		echo 'If you turn it on, you *may* run into problems!<br />';
	}

	$obdir = ini_get('open_basedir');
	if ($obdir) {
		echo '<br /><font color="red">';
		echo '<b>Warning ==========================</b><br />';
		echo '<b>open_basedir</b> is set to <b>'.$obdir.'</b> in your PHP installation<br />';
		echo 'Please refer to the hack instructions for information on this setting<br />';
		echo '<b>========================== Warning</b><br />';
		echo '</font><br />';
	} else {
		echo 'Good: <b>open_basedir</b> is turned <b>off</b> in your PHP installation<br />';
		echo 'If set, you *may* run into problems!<br />';
	}

	$asb = $DB_site->query("SHOW VARIABLES LIKE 'version'");
	while ($myrow = $DB_site->fetch_array($asb)) {
		if ($myrow[Variable_name] == "version") {
			if (preg_match ("/(\d+)\.(\d+)\.(\d+)/", $myrow[Value], $matches) == 1) {
				if ($matches[1] == 3 and ($matches[2]<23 or ($matches[2]==23 and $matches[3]<23))) {
					echo '<br /><font color="red">';
					echo '<b>Warning ==========================</b><br />';
					echo 'You seem to be running MySQL version <b>'.$matches[1].".".$matches[2].".".$matches[3].'</b><br />';
					echo '<b>I was expecting version 4.x or greater than 3.23.23<br />';
					echo 'This version of MySQL will not work. Sorry<br />';
					echo '<b>========================== Warning</b><br />';
					echo '</font><br />';
				} else {
					echo 'Good: you seem to be running MySQL version <b>'.$matches[1].".".$matches[2].".".$matches[3].'</b><br />';
				}
			} else {
				echo '<br /><font color="red">';
				echo '<b>Warning ==========================</b><br />';
				echo '<b>Cannot determine version of MySQL.  Expecting version 4.x or greater than 3.23.23<br />';
				echo 'Installation may not work properly<br />';
				echo '<b>========================== Warning</b><br />';
				echo '</font><br />';
			}
		}
	}

	echo 'Environment checked<br />';

	echo 'Checking installation status...<br />';
	$hack_status = 0;

	$asb = $DB_site->query("SHOW TABLES");
	$hack_table_prefix = THIS_TABLE."links";
	$hack_tables = array();
	while ($myrow = $DB_site->fetch_array($asb)) {
		foreach ($myrow AS $table) {
			if (preg_match ("/^$hack_table_prefix/", $table)) {
				$hack_tables[] = $table;
			}
		}
	}
	if (count($hack_tables) > 0) {
		if (in_array($hack_table_prefix."admin", $hack_tables)) {
			$asb = $DB_site->query("SELECT * FROM ".THIS_TABLE."linksadmin");
			while ($admin_settings = $DB_site->fetch_array($asb)) {
				if ($admin_settings[settingname] == "this_version") {
					$hack_version = $admin_settings[setting];
					echo "Version ".$hack_version." is already installed<br />";
				}
			}
			if (!isset($hack_version)) {
				echo "Hack seems to be installed but I cannot tell which version<br />";
			}
			$hack_status = 1;
		} else {
			echo '<b>I do not recognise the version you have installed</b><br />';
			echo 'You must <b><a href="'.THIS_SCRIPT.'.php?step=101">uninstall</a></b> and start again.  Sorry<br />';
			$hack_status = -1;
		}
	} else {
		echo "<b>New installation</b><br />";
		$hack_status = 0;
	}

	echo '<hr />';

	if ($hack_status == 0) {
		echo '<b>Follow these steps to install</b><br />';
		echo '<b>Step 1</b>: <a href="'.THIS_SCRIPT.'.php?step=1">Create</a> Database Tables<br />';
		echo '<hr />';
	}

	if ($hack_status == 1) {
		echo '<b>Follow these steps to validate/upgrade</b><br />';
		echo '<b>Step 1</b>: <a href="'.THIS_SCRIPT.'.php?step=1">Verify</a> Database Tables<br />';
		echo '<b>Step 2</b>: <a href="'.THIS_SCRIPT.'.php?step=2">Verify</a> Templates<br />';
		echo '<b>Step 3</b>: <a href="'.ADMIN_SCRIPT.'.php?action=admin" target="_new">Goto</a> Links/Files AdminCP to check/initialise permissions<br />';
		echo 'Installation complete: <a href="'.THAT_SCRIPT.'.php?action=links" target="_new">Goto</a> Links/Files main page<br />';
		echo '<hr />';
	}

	echo '<b>De-install Links and Files</b><br />';
	echo 'Warning - this cannot be undone and you will lose any Links and Files you have created<br />';
	echo 'Please backup your links tables and templates before continuing!<br />';
	echo '<b><a href="'.THIS_SCRIPT.'.php?step=101">Remove</a></b> Links and Files<br />';
	echo '<hr />';
	echo '<b>Delete this script when done</b><br />';
	echo '<hr />';
}

// ######################################################################
// step 1 -- Database

if ($step == 1) {

	echo '<hr /><b>Step 1</b> - Set up database tables<br />';

	echo "--- Creating ".THIS_TABLE."linksadmin if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linksadmin (
		 adminid smallint(5) NOT NULL auto_increment,
		 settingname varchar(255) NOT NULL,
		 setting text NOT NULL,
		 description text NOT NULL,
		 sequence smallint(5) NOT NULL,
		 PRIMARY KEY (adminid)
	)
	");

	echo "--- Creating ".THIS_TABLE."linksdownloads if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linksdownloads (
		 dlid int(11) NOT NULL auto_increment,
		 linkid int(11) NOT NULL,
		 linkurl text NOT NULL,
		 username text NOT NULL,
		 userid int(10) NOT NULL,
		 userip text NOT NULL,
		 userbrowser text NOT NULL,
		 usertime int(10) NOT NULL,
		 PRIMARY KEY (dlid)
	)
	");

	echo "--- Creating ".THIS_TABLE."linkscat if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linkscat (
		 catid smallint(5) NOT NULL auto_increment,
		 catname varchar(255) NOT NULL,
		 catdesc text NOT NULL,
		 cattext mediumtext NOT NULL,
		 parentid smallint(5) NOT NULL,
		 parentlist varchar(250) NOT NULL,
		 catforum smallint(5) NOT NULL,
		 catusername text NOT NULL,
		 catuserid int(10) NOT NULL,
		 catentry mediumint(8) NOT NULL,
		 catdate int(10) NOT NULL,
		 catmoderate int(2) NOT NULL,
		 catclosed int(2) DEFAULT '0' NOT NULL,
		 catinstructions text NOT NULL,
		 displayorder int(11) DEFAULT '1' NOT NULL,
		 PRIMARY KEY (catid)
	)
	");

	echo "--- Creating ".THIS_TABLE."linksfavs if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linksfavs (
		 lfav int(11) NOT NULL auto_increment,
		 linkid int(11) NOT NULL,
		 userid int(10) NOT NULL,
		 PRIMARY KEY (lfav),
		 KEY (userid),
		 KEY (linkid)
	)
	");

	echo "--- Creating ".THIS_TABLE."linkslink if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linkslink (
		 linkid int(11) NOT NULL auto_increment,
		 linkname varchar(255) NOT NULL,
		 linkdesc text NOT NULL,
		 linkurl text NOT NULL,
		 linkhits mediumint(8) UNSIGNED DEFAULT '0' NOT NULL,
		 linkforum smallint(5) NOT NULL,
		 linkcheck int(10) unsigned NOT NULL,
		 linkstatus int(10) DEFAULT '0' NOT NULL,
		 linkdate int(10) NOT NULL,
		 linkusername text NOT NULL,
		 linkuserid int(10) NOT NULL,
		 linkmoderate int(2) NOT NULL,
		 linkmoddate int(10) DEFAULT '0' NOT NULL,
		 linkreviewfreq smallint(5) DEFAULT '0' NOT NULL,
		 PRIMARY KEY (linkid),
		 FULLTEXT KEY namedesc (linkname,linkdesc)
	)
	TYPE = MYISAM
	");

	echo "--- Creating ".THIS_TABLE."linksltoc if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linksltoc (
		 ltoc int(11) NOT NULL auto_increment,
		 linkid int(11) NOT NULL,
		 catid smallint(5) NOT NULL,
		 displayorder int(11) DEFAULT '1' NOT NULL,
		 PRIMARY KEY (ltoc),
		 KEY (linkid)
	)
	");

	echo "--- Creating ".THIS_TABLE."linksrate if it does not exist<br />";

	$asb = $DB_site->query("
	CREATE TABLE IF NOT EXISTS ".THIS_TABLE."linksrate (
		 lrate int(11) NOT NULL auto_increment,
		 linkid int(11) NOT NULL,
		 linkuserid int(10) NOT NULL,
		 linkvote smallint(5),
		 PRIMARY KEY (lrate)
	)
	");

	echo "--- Modifying tables where necessary<br />";

// simple changes, no need to check
	$asb = $DB_site->query("
	ALTER TABLE ".THIS_TABLE."linkslink
		CHANGE linkhits linkhits MEDIUMINT( 8 ) UNSIGNED DEFAULT '0' NOT NULL
	");
	$asb = $DB_site->query("
	ALTER TABLE ".THIS_TABLE."linkslink
		CHANGE linkstatus linkstatus INT( 10 ) DEFAULT '0' NOT NULL
	");
	$asb = $DB_site->query("
	ALTER TABLE ".THIS_TABLE."linksdownloads
		CHANGE dlid dlid INT( 11 ) NOT NULL AUTO_INCREMENT
	");

// linksadmin
	$asb = $DB_site->query("
	SHOW COLUMNS FROM ".THIS_TABLE."linksadmin
	");
	$index = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if (isset($myrow['Field'])) {
			if ($myrow['Field'] == "description") {
				$desc = 1;
			}
			if ($myrow['Field'] == "sequence") {
				$seq = 1;
			}
		}
	}
	if ($desc<1) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linksadmin
		ADD COLUMN description TEXT NOT NULL
		");
	}
	if ($seq<1) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linksadmin
		ADD COLUMN sequence SMALLINT(5) NOT NULL
		");
	}

// linksfavs
	$asb = $DB_site->query("
	SHOW INDEX FROM ".THIS_TABLE."linksfavs
	");
	$index = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if (isset($myrow[Column_name]) and $myrow[Column_name] == "linkid") {
			$index = 1;
		}
	}
	if ($index==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linksfavs ADD INDEX ( linkid )
		");
	}

// linkslink
	$asb = $DB_site->query("
	SHOW INDEX FROM ".THIS_TABLE."linkslink
	");
	$index = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if (isset($myrow[Column_name])) {
			if ($myrow[Column_name] == "linkname") {
				$index += 1;
			}
			if ($myrow[Column_name] == "linkdesc") {
				$index += 1;
			}
		}
	}
	if ($index<2) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkslink ADD FULLTEXT namedesc (linkname, linkdesc)
		");
	}

	$asb = $DB_site->query("
	SHOW COLUMNS FROM ".THIS_TABLE."linkslink
	");
	$moderate = 0;
	$expiry = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if ($myrow['Field'] == "linkmoderate") {
			$moderate = 1;
		}
		if ($myrow['Field'] == "linkreviewfreq") {
			$expiry = 1;
		}
	}
	if ($moderate==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkslink
			ADD COLUMN linkmoderate int(2) NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linkslink
			SET linkmoderate=0
		");
	}
	if ($expiry==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkslink
			ADD COLUMN linkmoddate int(10) DEFAULT '0' NOT NULL,
			ADD COLUMN linkreviewfreq smallint(5) DEFAULT '0' NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linkslink
			SET linkreviewfreq=0, linkmoddate=0
		");
	}

// linksltoc
	$asb = $DB_site->query("
	SHOW INDEX FROM ".THIS_TABLE."linksltoc
	");
	$index = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if (isset($myrow[Column_name]) and $myrow[Column_name] == "linkid") {
			$index = 1;
		}
	}
	if ($index==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linksltoc ADD INDEX ( linkid )
		");
	}

	$asb = $DB_site->query("
	SHOW COLUMNS FROM ".THIS_TABLE."linksltoc
	");
	$display = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if ($myrow['Field'] == "displayorder") {
			$display = 1;
		}
	}
	if ($display==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linksltoc
			ADD COLUMN displayorder INT(11) DEFAULT '1' NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linksltoc
			SET displayorder=1
		");
	}

// linkscat
	$asb = $DB_site->query("
	SHOW COLUMNS FROM ".THIS_TABLE."linkscat
	");
	$entry = 0;
	$moderate = 0;
	$closed = 0;
	$instruc = 0;
	$display = 0;
	while ($myrow = $DB_site->fetch_array($asb)) {
		if ($myrow['Field'] == "catentry") {
			$entry = 1;
		}
		if ($myrow['Field'] == "catmoderate") {
			$moderate = 1;
		}
		if ($myrow['Field'] == "catclosed") {
			$closed = 1;
		}
		if ($myrow['Field'] == "catinstructions") {
			$instruc = 1;
		}
		if ($myrow['Field'] == "displayorder") {
			$display = 1;
		}
	}
	if ($entry==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkscat
			ADD COLUMN catentry mediumint(8) NOT NULL,
			ADD COLUMN catdate int(10) NOT NULL
		");
		$asb = $DB_site->query("
			SELECT ltoc.catid AS catid, link.linkdate AS linkdate
			FROM ".THIS_TABLE."linkslink AS link
			LEFT JOIN ".THIS_TABLE."linksltoc AS ltoc
			ON link.linkid = ltoc.linkid
		");
		$catcount = array();
		$catdate = array();
		while ($myrow = $DB_site->fetch_array($asb)) {
			if (!isset($catdate[$myrow[catid]])) {
				$catcount[$myrow[catid]] = 1;
				$catdate[$myrow[catid]] = $myrow[linkdate];
			} else {
				$catcount[$myrow[catid]] +=1;
				$catdate[$myrow[catid]] = max($catdate[$myrow[catid]], $myrow[linkdate]);
			}
		}
		foreach ($catcount as $catid => $count) {
			$DB_site->query("
				UPDATE ".THIS_TABLE."linkscat
				SET catentry=".$count.", catdate=".$catdate[$catid]."
				WHERE catid='$catid'
				LIMIT 1
			");
		}
	}
	if ($moderate==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkscat
			ADD COLUMN catmoderate int(2) NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linkscat
			SET catmoderate=0
		");
	}
	if ($closed==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkscat
			ADD COLUMN catclosed int(2) NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linkscat
			SET catclosed=0
		");
	}
	if ($instruc==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkscat
			ADD COLUMN catinstructions text NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linkscat
			SET catinstructions=''
		");
	}
	if ($display==0) {
		$asb = $DB_site->query("
		ALTER TABLE ".THIS_TABLE."linkscat
			ADD COLUMN displayorder INT(11) DEFAULT '1' NOT NULL
		");
		$asb = $DB_site->query("
			UPDATE ".THIS_TABLE."linkscat
			SET displayorder=1
		");
	}

// done

	echo '<b>Step 1</b> - Database checks and modifications complete<br />';
	echo 'Recording version number ',THIS_VERSION.' in database<br />';

	$DB_site->query("
		DELETE
		FROM ".THIS_TABLE."linksadmin
		WHERE settingname='this_version'
	");
	$DB_site->query("
		INSERT INTO ".THIS_TABLE."linksadmin (settingname, setting)
		VALUES (
		'this_version',
		'".THIS_VERSION."'
		)
	");

	echo 'Initialising admin table if necessary<br />';
	init_admin_table();

	echo 'Optimising tables<br />';
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linksadmin");
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linksdownloads");
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linkscat");
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linksfavs");
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linkslink");
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linksltoc");
	$asb = $DB_site->query("OPTIMIZE TABLE ".THIS_TABLE."linksrate");

	echo 'Run <b>Step 2</b>: <a href="'.THIS_SCRIPT.'.php?step=2">Setup</a> Templates<br />';
	echo '<a href="'.THIS_SCRIPT.'.php?step=0">Go back</a> to the start<br />';

}


// ######################################################################
// templates, part 1

if ($step == 2) {

	echo '<hr /><b>Step 2</b> - Set up templates<br />';

	$asb = $DB_site->query("
		SELECT styleid, title
		FROM ".TABLE_PREFIX."style
		");

	$styles = array();
	while ($myrow=$DB_site->fetch_array($asb)) {
		$styles[$myrow[styleid]] = $myrow[title];
	};

	$asb = $DB_site->query("
		SELECT templateid, title, styleid
		FROM ".TABLE_PREFIX."template
		WHERE title LIKE 'links_%'
		");

	$ask = 0;
	while ($mytemp=$DB_site->fetch_array($asb)) {
		echo 'template '.$mytemp[title].' found in style '.$styles[$mytemp[styleid]].'<br />';
		$ask = 1;
	}

	if ($ask == 0) {
		$step = 21;
	} else {
		echo '<b>I am about to delete these templates</b><br />';
		echo 'If you have customised any of them, please back them up before continuing<br />';
		echo 'Click <a href="'.THIS_SCRIPT.'.php?step=21">here</a> when you are ready to continue<br />';
	}

}

// ######################################################################
// templates, part 2

if ($step == 21) {

	require_once('./includes/adminfunctions.php');
	require_once('./includes/adminfunctions_template.php');

	if (!($xml = file_read('./local_links_templates.xml'))) {
		echo '<b>Error</b>: I cannot find local_links_templates.xml<br />';
		echo 'Please upload then click <a href="'.THIS_SCRIPT.'.php?step=21">here</a> to continue<br />';
		exit;
	}

	echo '<hr /><b>Step 2</b> (continued) - Set up templates<br />';

	echo '--- Deleting any existing templates<br />';

	$asb = $DB_site->query("
		DELETE
		FROM ".TABLE_PREFIX."template
		WHERE title LIKE 'links_%'
		");

	echo '--- Importing local_links_templates.xml into root styles<br />';

	$asb = $DB_site->query("
		SELECT styleid, title
		FROM ".TABLE_PREFIX."style
		WHERE parentid=-1
		");

	while ($myrow=$DB_site->fetch_array($asb)) {
		echo '--- Inserting into style '.$myrow[title].'<br />';
		$styleid = $myrow[styleid];
		xml_import_style($xml, $styleid, -1, '', 1);
	}

	build_all_styles();

	echo '<b>Step 2</b> - Template import complete<br />';

	echo 'Run <b>Step 3</b>: <a href="'.ADMIN_SCRIPT.'.php?action=admin" target="_new">Goto</a> Links/Files AdminCP to check/initialise permissions?<br />';
	echo 'Installation complete: <a href="'.THAT_SCRIPT.'.php?action=links" target="_new">Goto</a> Links/Files main page<br />';
	echo '<b>Delete this script when done</b><br />';
	echo '<a href="'.THIS_SCRIPT.'.php?step=0">Go back</a> to the start<br />';

}


// ######################################################################
// deinstallation

if ($step == 101) {

	echo '<hr /><b>Remove</b> Links and Files<br />';
	echo '--- Deleting existing templates<br />';

	$asb = $DB_site->query("
		DELETE
		FROM ".TABLE_PREFIX."template
		WHERE title LIKE 'links_%'
		");

	echo '--- Deleting database tables<br />';

	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linksadmin");
	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linksdownloads");
	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linkscat");
	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linksfavs");
	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linkslink");
	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linksltoc");
	$asb = $DB_site->query("DROP TABLE IF EXISTS ".THIS_TABLE."linksrate");

	echo '<b>Links and Files removed</b><br />';
	echo '<b>Delete this script when done</b><br />';
	echo '<a href="'.THIS_SCRIPT.'.php?step=0">Go back</a> to the start<br />';

}

print_cp_footer();

?>
