<?php
/*
	Plugin Name: Khanh's Content Adder
	Version: 2.0.5
	Plugin URI: http://ink.bur.st/wordpress-plugins#kca
	Description: Allows the addition of content to any page via an easy to use interface. No need to edit any templates or core files ever again. Changes are saved into the database, so you won't have to remember to re-edit files everytime you upgrade Wordpress. Addon snippets can be activated/deactivated with ease, even for certain pages and userlevels. Head over to the <a href="admin.php?page=kca.php" title="Go to KCA Management Page">KCA->Manage</a> page to find out more. Click "?" to show/hide help panel.
	Author: John Ha
	Author URI: http://ink.bur.st

*******************************************************************************

	Copyright (C) 2005-2007  John Ha

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License along
	with this program; if not, write to the Free Software Foundation, Inc.,
	51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

******************************************************************************/

class kca {

var $kca_desc = array (
	'Description'	=> 'string',
	'Eval'			=> 'string',
	'Needle'		=> 'string',
	'Userlevel'		=> 'integer',
	'Active'		=> 'boolean',
	'Content'		=> 'string',
	'Reference'		=> 'string',
	'Location'		=> 'string',
	'Head'			=> 'string',
	'Foot'			=> 'string',
);
var $kca_options;
var $kca_keys;
var $kca_tot_sets;
var $kca_num_opts;
var $kca_tot_opts;
var $kca_sep = '<kca>'; // Escape RegExp reserved characters
var $kca_msg = '';
// Determines flags importance of message. 1 = orange, 2 = red
var $kca_msg_flag = 0;
var $kca_days = 365;
var $kca_upgraded;
var $kca_docs;
var $kca_timer_start;
var $kca_timer_stop;
var $kca_load_start;
var $debug = 0;
var $cdata_start = '';
var $cdata_end = '';

function kca() {
	global $is_opera;
	// Opera 9.01 does not like CDATA!
	if (!$is_opera) {
		$this->cdata_start = '/*<![CDATA[*/';
		$this->cdata_end = '//]]>';
	}

	$t = explode(' ', microtime());
	$this->kca_timer_start = $t[1] + $t[0];
	$this->kca_load_start = gmdate('H:i:s', current_time('timestamp'));

	$this->kca_options = get_option('kca_options');
	$this->kca_keys = array_keys($this->kca_desc);
	empty($this->kca_options) ? $this->kca_tot_sets = 0 : $this->kca_tot_sets = count($this->kca_options);
	$this->kca_num_opts = count($this->kca_keys);
	$this->kca_tot_opts = $this->kca_tot_sets * $this->kca_num_opts;
	$this->kca_docs = core::urlname(dirname(__FILE__)) . '/docs';

	//form was submitted using xmlhttp
	if(isset($_POST['xmlhttp'])) $this->kca_process_page();
	else {
		// Hooks for admin pages
		add_action('admin_head', array(&$this, 'kca_admin_head'));
		add_action('admin_menu', array(&$this, 'kca_admin_page'));
		add_action('admin_footer', array(&$this, 'kca_foot'));

		//  Hooks for content pages
		add_action('wp_head', array(&$this, 'kca_blog_head'));
		add_action('wp_footer', array(&$this, 'kca_foot'));
	}
}

function kca_admin_head() {
	if (strpos($_SERVER['REQUEST_URI'], 'page=kca.php')) $this->kca_process_page();
	$this->kca_add_content(true);
}

function kca_admin_page() {
	add_management_page('KCA Management', 'KCA', 8, basename(__FILE__), array(&$this, 'kca_manage_page'));
}

function kca_blog_head() {
	$this->kca_add_content(true);
}

function kca_foot() {
	$this->kca_add_content(false);
}


///////////////////////////////////////////////////////////////////////////
///////////////////////// Process Management Page /////////////////////////
///////////////////////////////////////////////////////////////////////////
function kca_process_page() {
empty($this->kca_options) ?
	$this->kca_upgraded = true
:	$this->kca_upgraded = array_key_exists('Description', $this->kca_options[0]) &&
	array_key_exists('Head', $this->kca_options[0]) &&
	array_key_exists('Foot', $this->kca_options[0]);
if(isset($_POST['kca-update'])) {
	$c = ($_POST['set'] - 1) * $this->kca_num_opts + 1; // Get _POST count start
	for ($i = $c; $i < $c + $this->kca_num_opts; $i++) {
		if ($_POST['kca_' . $i] == 'true') {
			$this->kca_options[$_POST['set'] - 1][$this->kca_keys[$i - $c]] = true;
		} elseif ($_POST['kca_' . $i] == 'false') {
			$this->kca_options[$_POST['set'] - 1][$this->kca_keys[$i - $c]] = false;
		} else {
			$this->kca_options[$_POST['set'] - 1][$this->kca_keys[$i - $c]] = stripslashes($_POST['kca_' . $i]);
		}
	}
	// highlight_string(print_r($this->kca_options[$_POST['set'] - 1],true),false);
	update_option('kca_options', $this->kca_options);
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>[Record Set #' . $_POST['set'] . ']</strong> updated</li></ul></li>';
	$this->kca_msg_flag = 1;
} elseif (isset($_POST['kca-update-all'])) {
	$c = 1;
	for ($i = 0; $i < $this->kca_tot_sets; $i++) {
		for ($j = 0; $j < $this->kca_num_opts; $j++) {
			if ($_POST['kca_' . $c] == 'true') {
				$this->kca_options[$i][$this->kca_keys[$j]] = true;
			} elseif ($_POST['kca_' . $c] == 'false') {
				$this->kca_options[$i][$this->kca_keys[$j]] = false;
			} else {
				$this->kca_options[$i][$this->kca_keys[$j]] = stripslashes($_POST['kca_' . $c]);
			}
			$c++;
		}
	}
	update_option('kca_options', $this->kca_options);
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>All</strong> record sets have been updated</li></ul></li>';
	$this->kca_msg_flag = 2;
} elseif (isset($_POST['kca-save'])) {
	for ($i = 0; $i < $this->kca_num_opts; $i++) {
		$this->kca_options[$this->kca_tot_sets][$this->kca_keys[$i]] = stripslashes($_POST['kca_' . ($this->kca_tot_opts + $i + 1)]);
	}
	update_option('kca_options', $this->kca_options);
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>[Record Set #' . ($this->kca_tot_sets + 1) . ']</strong> added</li></ul></li>';
	$this->kca_msg_flag = 1;
	$this->kca_tot_sets++;
	$this->kca_tot_opts = $this->kca_tot_sets * $this->kca_num_opts;
} elseif (isset($_POST['kca-save-ini'])) {
	$this->kca_save_ini();
} elseif (isset($_POST['kca-import'])) {
	$this->kca_import_all();
} elseif (isset($_POST['kca-delete'])) {
	if ($_POST['set'] - 1 != $this->kca_tot_sets) {
		for ($i = $_POST['set'] - 1; $i < $this->kca_tot_sets; $i++) {
			$this->kca_options[$i] = $this->kca_options[$i + 1];
		}
	}
	unset($this->kca_options[$this->kca_tot_sets - 1]);
	update_option('kca_options', $this->kca_options);
	if ($this->kca_tot_sets == 1) delete_option('kca_options');
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>[Record Set #' . $_POST['set'] . ']</strong> deleted</li></ul></li>';
	$this->kca_msg_flag = 1;
	$this->kca_tot_sets--;
	$this->kca_tot_opts = $this->kca_tot_sets * $this->kca_num_opts;
} elseif (isset($_POST['kca-purge-all'])) {
	$this->kca_purge_all();
} elseif (isset($_POST['kca-restore-all'])) {
	$this->kca_purge_all();
	$this->kca_import_all();
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>Default</strong> settings have been restored from default.ini</li></ul></li>';
	$this->kca_msg_flag = 2;
} elseif (isset($_POST['kca-upgrade-all'])) {
	// highlight_string(print_r($this->kca_options,true),false);
	if (empty($this->kca_options)) {
		$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li">Nothing to upgrade</li></ul></li>';
		$this->kca_msg_flag = 2;
	} else {
		// Upgrade from version 1.8.2
		if (!array_key_exists('Description', $this->kca_options[0])) {
			for ($i = 0; $i < $this->kca_tot_sets; $i++) {
				list($Description_,
					$Needle_,
					$Eval_,
					$Reference_,
					$Location_,
					$Content_,
					$Foot_,
					$Userlevel_,
					$Active_
				) = $this->kca_options[$i];
					$Head_ = '';

				unset($this->kca_options[$i]);

				$this->kca_options[$i] = array(
					'Description'	=> $Description_,
					'Eval'			=> $Eval_,
					'Needle'		=> $Needle_,
					'Userlevel'		=> $Userlevel_,
					'Active'		=> $Active_,
					'Content'		=> $Content_,
					'Reference'		=> $Reference_,
					'Location'		=> $Location_,
					'Head'			=> $Head_,
					'Foot'			=> $Foot_
				);
			}
			// highlight_string(print_r($this->kca_options,true),false);
			delete_option('kca_options');
			add_option('kca_options', $this->kca_options);
			$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>All</strong> record sets have been upgraded successfully</li></ul></li>';
			$this->kca_msg_flag = 2;
			$this->kca_upgraded = true;
		// Upgrade from version 1.9.1
		} else if (!array_key_exists('Head', $this->kca_options[0])) {
			for ($i = 0; $i < $this->kca_tot_sets; $i++) {
				list($Description_,
					$Eval_,
					$Needle_,
					$Userlevel_,
					$Active_,
					$Content_,
					$Reference_,
					$Location_,
					$Foot_
				) = array_values($this->kca_options[$i]);
					$Head_ = '';

				unset($this->kca_options[$i]);

				$this->kca_options[$i] = array(
					'Description'	=> $Description_,
					'Eval'			=> $Eval_,
					'Needle'		=> $Needle_,
					'Userlevel'		=> $Userlevel_,
					'Active'		=> $Active_,
					'Content'		=> $Content_,
					'Reference'		=> $Reference_,
					'Location'		=> $Location_,
					'Head'			=> $Head_,
					'Foot'			=> $Foot_
				);
			}
			//highlight_string(print_r($this->kca_options,true),false);
			delete_option('kca_options');
			add_option('kca_options', $this->kca_options);
			$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>All</strong> record sets have been upgraded successfully</li></ul></li>';
			$this->kca_msg_flag = 2;
			$this->kca_upgraded = true;
		// Upgrade from version 2.0.0
		} else if (!array_key_exists('Foot', $this->kca_options[0])) {
			for ($i = 0; $i < $this->kca_tot_sets; $i++) {
				list($Description_,
					$Eval_,
					$Needle_,
					$Userlevel_,
					$Active_,
					$Content_,
					$Reference_,
					$Location_,
					$Head_,
					$Foot_
				) = array_values($this->kca_options[$i]);

				unset($this->kca_options[$i]);

				$this->kca_options[$i] = array(
					'Description'	=> $Description_,
					'Eval'			=> $Eval_,
					'Needle'		=> $Needle_,
					'Userlevel'		=> $Userlevel_,
					'Active'		=> $Active_,
					'Content'		=> $Content_,
					'Reference'		=> $Reference_,
					'Location'		=> $Location_,
					'Head'			=> $Head_,
					'Foot'			=> $Foot_
				);
			}
			//highlight_string(print_r($this->kca_options,true),false);
			delete_option('kca_options');
			add_option('kca_options', $this->kca_options);
			$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>All</strong> record sets have been upgraded successfully</li></ul></li>';
			$this->kca_msg_flag = 2;
			$this->kca_upgraded = true;
		} else {
			$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li">Record sets not upgraded, since they seem to already be in the right format</li></ul></li>';
			$this->kca_msg_flag = 2;
		}
	}
}
if (isset($_POST['xmlhttp'])) echo $this->kca_msg;
else {
if (!$this->kca_upgraded) {
$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>Database upgrade notice:</strong><ul><li>It seems the KCA <strong>database needs to be upgraded</strong></li>
<li><strong>Displayed data may be incorrect</strong> until an upgrade has been performed</li>
<li>Please select <strong>"Upgrade"</strong> in Global (<a href="#kca_set_' . ($this->kca_tot_sets + 3) .
'" onclick="return kca_go_to(' . ($this->kca_tot_sets + 3) .
')">&Theta;</a>) to bring the database format up to date</li></ul></li></ul></li>';
$this->kca_msg_flag = 2;
}
if (empty($this->kca_options)) {
$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li">There are currently no record sets in the KCA database. You can:
<ul>
<li>manually enter your own data</li>
<li>import data using the Scratch-Pad (<a href="#kca_set_' . ($this->kca_tot_sets + 2) . '" onclick="return kca_go_to(' . ($this->kca_tot_sets + 2) . ')">#</a>)</li>
<li>restore data to default values using "Restore" in Global (<a href="#kca_set_' . ($this->kca_tot_sets + 3) . '" onclick="return kca_go_to(' . ($this->kca_tot_sets + 3) . ')">&Theta;</a>)</li>
</ul></li></ul></li>';
$this->kca_msg_flag = 2;
}
}
}

function kca_purge_all() {
	for ($i = 0; $i < $this->kca_tot_sets; $i++) {
		unset($this->kca_options[$i]);
	}
	update_option('kca_options', $this->kca_options);
	// Does not work as advertised! Bug?
	// Leaves artifact behind that disappears after a next load.
	// Same peculiarity exists in 1.6-ALPHA-2-still-dont-use.
	// update_option with empty array does the right thing.
	delete_option('kca_options');
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>All</strong> record sets were purged</li></ul></li>';
	$this->kca_msg_flag = 2;
	$this->kca_tot_sets = 0;
	$this->kca_tot_opts = 0;
}

function kca_import_all() {
	$data = split($this->kca_sep, stripslashes($_POST['kca-import-all']));
	// highlight_string(print_r($data,true),false);
	$c = $this->kca_tot_sets;
	$n = 1;
	$t = count($data);
	while ($n < $t) {
		for ($i = 0; $i < $this->kca_num_opts; $i++) {
			if ($data[$n] == 'true') {
				$this->kca_options[$c][$this->kca_keys[$i]] = true;
			} elseif ($data[$n] == 'false') {
				$this->kca_options[$c][$this->kca_keys[$i]] = false;
			} else {
				$this->kca_options[$c][$this->kca_keys[$i]] = $data[$n];
			}
			$n++;
		}
		$c++;
	}
	// highlight_string(print_r($this->kca_options,true),false);
	update_option('kca_options', $this->kca_options);
	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>' . ($c - $this->kca_tot_sets) . '</strong> record set' . (($c - $this->kca_tot_sets) > 1 ? 's' : '') .' have been imported</li></ul></li>';
	$this->kca_msg_flag = 2;
	$this->kca_tot_sets = $c;
	$this->kca_tot_opts = $this->kca_tot_sets * $this->kca_num_opts;
}

function kca_save_ini() {
	$data = stripslashes($_POST['kca-save-ini']);

	// Open the file and erase the contents if any
	$fp = fopen(dirname(__FILE__) . '/addons/default.ini', 'w');
	
	// Write the data to the file
	fwrite($fp, $data);
	
	// Close the file
	fclose($fp);

	$this->kca_msg .= '<li>[' . gmdate('H:i:s', current_time('timestamp')) . ']<ul class="kca_msg_ul"><li class="kca_msg_li"><strong>Scratch-Pad</strong> data has been saved to <strong>default.ini</strong></li></ul></li>';
	$this->kca_msg_flag = 2;
}





///////////////////////////////////////////////////////////////////////////
////////////////////////// Add Management Page ////////////////////////////
///////////////////////////////////////////////////////////////////////////
function kca_manage_page() {
global $is_IE;
?>
<ul id="kca-nav">
<li class="kca_nav_button"><a href="#" title="Toggle Font Size" onclick="return kca_toggle_font()">A</a></li>
<li class="kca_nav_button"><a href="#kca_help_panel" title="Toggle Help" onclick="return kca_toggle_help()">?</a></li>
<li class="kca_nav_button"><a href="#kca_msg_panel" id="kca_msg_button" title="Toggle Messages" onclick="return kca_toggle_msg()">&Xi;</a></li>
<li class="kca_nav_button"><a href="#" id="kca-disp-mode" title="Display Mode" onclick="return kca_toggle_display()">&infin;</a></li>
<li class="kca_nav_button"><a href="#" id="kca-nav-mode" title="Nav-Bar Mode" onclick="return kca_toggle_nav()">&Dagger;</a></li>
<li class="kca_nav_button"><a href="#footer" title="Bottom" onclick="return kca_go_to_bottom()">&darr;</a></li>
<li class="kca_nav_button"><a href="#wphead" title="Top" onclick="return kca_go_to_top()">&uarr;</a></li>
<li class="kca_nav_button"><a href="#kca_set_<?= $this->kca_tot_sets ? $this->kca_tot_sets : '1' ?>" title="Last" onclick="return kca_go_to_last()">&raquo;</a></li>
<li class="kca_nav_button"><a href="#" title="Next" onclick="return kca_go_to_next()">&rsaquo;</a></li>
<li class="kca_nav_button"><a href="#" title="Previous" onclick="return kca_go_to_prev()">&lsaquo;</a></li>
<li class="kca_nav_button"><a href="#kca_set_1" title="First" onclick="return kca_go_to_first()">&laquo;</a></li>
<li class="kca_info" id="kca-show-info" href="#"></li>
<li class="kca_info" href="#" title="Processes:Progress">[<span id="kca-ajax-ops">0</span>:<span id="kca-spinner">-</span>]</li>
<li class="kca_info" href="#" title="Closed Panels">[<span id="kca-show-closed">-</span>]</li>
<li class="kca_info" href="#" title="[Page Top|Nav-Bar Top]">[<span id="kca-show-loc">0:0</span>]</li>
<?php
for ($j = 1; $j <= $this->kca_tot_sets; $j++) {
?>
<li><a id="nav_tab_<?= $j ?>" href="#kca_set_<?= $j ?>" title="<?= $this->kca_options[$j - 1]['Description'] ? preg_replace('/\"/', '&quot;', $this->kca_options[$j - 1]['Description']) : 'No description' ?>" onclick="return kca_go_to(<?= $j ?>)"><?= $j ?></a></li>
<?php
}
// highlight_string(print_r($this->kca_options,true),false);
?>
<li><a id="nav_tab_<?= $this->kca_tot_sets + 1 ?>" href="#kca_set_<?= $this->kca_tot_sets + 1 ?>" title="Add [Record Set #<?= $this->kca_tot_sets + 1 ?>]" onclick="return kca_go_to(<?= $this->kca_tot_sets + 1 ?>)">+</a></li>
<li><a id="nav_tab_<?= $this->kca_tot_sets + 2 ?>" href="#kca_set_<?= $this->kca_tot_sets + 2 ?>" title="Scratch-Pad" onclick="return kca_go_to(<?= $this->kca_tot_sets + 2 ?>)">#</a></li>
<li><a id="nav_tab_<?= $this->kca_tot_sets + 3 ?>" href="#kca_set_<?= $this->kca_tot_sets + 3 ?>" title="Global" onclick="return kca_go_to(<?= $this->kca_tot_sets + 3 ?>)">&Theta;</a></li>
</ul>
<? // Copy innerHTML from nav to spacer, to copy dimensions ?>
<ul id="kca-nav-spacer">
<script type="text/javascript"><?= $this->cdata_start ?>document.getElementById('kca-nav-spacer').innerHTML = document.getElementById('kca-nav').innerHTML;<?= $this->cdata_end ?></script>
</ul>

<div id="kca_msg_panel" class="wrap clearfix">
<h2 class="clearfix">
<a href="#" class="close" title="Close Messages Panel" onclick="return kca_toggle_msg()">&times;</a>
<a href="#" id="kca_info_1_" class="rollup" title="Rollup Messages Panel" onclick="return kca_rollup_info(1)">&ndash;</a>
Messages
</h2>
<div id="kca_info_1">
<ul id="kca_msg_text"><li>Javascript has not been detected. This plugin will not function without Javascript.</li></ul>
<script type="text/javascript"><?= $this->cdata_start ?>document.getElementById('kca_msg_text').innerHTML = '<li>[<?= $this->kca_load_start ?>]<ul class="kca_msg_ul"><li class="kca_msg_li">Loading...</li></ul></li>';<?= $this->cdata_end ?></script>
</div>
</div>

<div id="kca_help_panel" class="wrap kca-hide">
<h2 class="clearfix">
<a href="#" class="close" title="Close Help Panel" onclick="return kca_toggle_help()">&times;</a>
<a href="#" id="kca_info_2_" class="rollup" title="Rollup Help Panel" onclick="return kca_rollup_info(2)">&ndash;</a>
Help
</h2>
<form id="kca_info_2" method="post">
<table width="100%" class="editform">
<tr><td>
<p><textarea id="kca_help_text" wrap="off" rows="20" readonly></textarea></p>
</td></tr>

<tr><td>
<p class="submit">
<input type="button" name="kca-get-readme" id="get_readme" value="<?php _e('Readme') ?> &raquo;" title="Browse Readme File" onclick="kca_help('<?= $this->kca_docs ?>/readme.txt')" />
<input type="button" name="kca-get-notes" id="get_notes" value="<?php _e('Notes') ?> &raquo;" title="Browse Notes File" onclick="kca_help('<?= $this->kca_docs ?>/notes.txt')" />
<input type="button" name="kca-get-faq" id="get_faq" value="<?php _e('FAQ') ?> &raquo;" title="Browse FAQ File" onclick="kca_help('<?= $this->kca_docs ?>/faq.txt')" />
<input type="button" name="kca-get-history" id="get_history" value="<?php _e('History') ?> &raquo;" title="Browse History File" onclick="kca_help('<?= $this->kca_docs ?>/history.txt')" />
</p>
</td></tr>
</table>
</form>
</div>


<?php
$c = 0;
for ($set = 1; $set <= $this->kca_tot_sets + 1; $set++) {
?>
<div id="kca_set_<?= $set ?>" class="wrap kca-hide">
<h2 class="clearfix">
<a href="#" class="close" title="Close [Record Set #<?= $set ?>] Panel" onclick="return kca_toggle_set(<?= $set ?>)">&times;</a>
<a href="#" id="kca_form_<?= $set ?>_" class="rollup" title="Rollup [Record Set #<?= $set ?>] Panel" onclick="return kca_rollup_set(<?= $set ?>)">&ndash;</a>
[<?= $set - 1 == $this->kca_tot_sets ? 'Add ' : '' ?>Record Set #<?= $set ?>]
</h2>
<form name="kca_form_<?= $set ?>" id="kca_form_<?= $set ?>" method="post">
<table width="100%" class="editform">


<tr valign="top">
<td rowspan="2" width="50%">
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Description</strong><br />
<textarea rows="4" name="kca_<?= $c ?>" id="kca_<?= $c ?>"><?= htmlspecialchars($this->kca_options[$set - 1]['Description']) ?></textarea></p>
</label>
</td>

<td rowspan="5" width="3%"></td>

<td colspan="4">
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Eval</strong><br />
<input class="kca-field" name="kca_<?= $c ?>" type="text" id="kca_<?= $c ?>" value="<?= htmlspecialchars($this->kca_options[$set - 1]['Eval']) ?>" /></p>
</label>
</td>
</tr>


<tr valign="top">
<td>
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Needle</strong><br />
<input class="kca-field" name="kca_<?= $c ?>" type="text" id="kca_<?= $c ?>" value="<?= htmlspecialchars($this->kca_options[$set - 1]['Needle']) ?>" /></p>
</label>
</td>

<td rowspan="3" width="3%"></td>

<td>
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Level</strong><br />
<select name="kca_<?= $c ?>" id="kca_<?= $c ?>">
<?php
echo '<option name="kca_<?= $c ?>_" value=""'.(!is_numeric($this->kca_options[$set - 1]['Userlevel']) ? '' : ' selected').'></option>';
for ($j = 0; $j <= 10; $j++) {
	echo '<option name="kca_' . $c . '_' . ($set - 1) . '" value="' . $j . '"'.(is_numeric($this->kca_options[$set - 1]['Userlevel']) && $this->kca_options[$set - 1]['Userlevel'] == $j ? ' selected' : '').'> ' . $j . ' </option>';
}
?>
</select></p>
</label>
</td>

<td>
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Active</strong><br />
<input type="checkbox" name="kca_<?= $c ?>" id="kca_<?= $c ?>" <?= $this->kca_options[$set - 1]['Active'] ? 'checked="checked"' : ''; ?> /></p>
</label>
</td>
</tr>


<tr valign="top">
<td rowspan="2">
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Content</strong><br />
<textarea wrap="off" rows="4" name="kca_<?= $c ?>" id="kca_<?= $c ?>"><?= htmlspecialchars($this->kca_options[$set - 1]['Content']); ?></textarea></p>
</label>
</td>

<td>
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Reference</strong><br />
<input class="kca-field" name="kca_<?= $c ?>" type="text" id="kca_<?= $c ?>" value="<?= htmlspecialchars($this->kca_options[$set - 1]['Reference']) ?>" /></p>
</label>
</td>
</tr>

<tr valign="top">
<td>
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Location</strong><br />
<select name="kca_<?= $c ?>" id="kca_<?= $c ?>">
<option name="kca_<?= $c ?>_" value=""></option>
<option name="kca_<?= $c ?>_0" value="beforeBegin"<?= $this->kca_options[$set - 1]['Location'] == 'beforeBegin' ? ' selected' : ''?>> beforeBegin </option>
<option name="kca_<?= $c ?>_1" value="afterBegin"<?= $this->kca_options[$set - 1]['Location'] == 'afterBegin' ? ' selected' : ''?>> afterBegin </option>
<option name="kca_<?= $c ?>_2" value="beforeEnd"<?= $this->kca_options[$set - 1]['Location'] == 'beforeEnd' ? ' selected' : ''?>> beforeEnd </option>
<option name="kca_<?= $c ?>_3" value="afterEnd"<?= $this->kca_options[$set - 1]['Location'] == 'afterEnd' ? ' selected' : ''?>> afterEnd </option>
</select></p>
</label>
</td>
</tr>

<tr valign="top">
<td>
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Head</strong><br />
<textarea wrap="off" rows="4" name="kca_<?= $c ?>" id="kca_<?= $c ?>"><?= htmlspecialchars($this->kca_options[$set - 1]['Head']); ?></textarea></p>
</label>
</td>

<td colspan="4">
<?php $c++; ?>
<label for="kca_<?= $c ?>"><p><strong>Foot</strong><br />
<textarea wrap="off" rows="4" name="kca_<?= $c ?>" id="kca_<?= $c ?>"><?= htmlspecialchars($this->kca_options[$set - 1]['Foot']); ?></textarea></p>
</label>
</td>
</tr>


<tr valign="top">
<td colspan="6">
<p class="submit">
<input type="button" name="clear" id="kca_clear_<?= $set ?>" value="<?php _e('Clear') ?> &raquo;" title="Clear form" onclick="kca_clear(<?= (($set - 1) * $this->kca_num_opts + 1) ?>)" />
<input type="button" name="reset_" value="<?php _e('Reset') ?> &raquo;" onclick="this.form.reset()" title="Reset form" />
<input type="button" name="extract" id="kca_extract_<?= $set ?>" value="<?php _e('Extract') ?> &raquo;" title="Extract to Scratch-Pad" onclick="document.getElementById('kca_scratch').value = kca_extract(<?= ($set - 1) ?>)" />
<input type="button" name="dump" id="kca_dump_<?= $set ?>" value="<?php _e('Dump') ?> &raquo;" title="Dump from Scratch-Pad" onclick="kca_dump(<?= (($set - 1) * $this->kca_num_opts + 1) ?>)" />
<?php if ($set - 1 == $this->kca_tot_sets) { ?>
<input type="submit" name="kca-save" id="kca_save_<?= $set ?>" value="<?php _e('Save') ?> &raquo;" title="Save form to database" <?= $this->kca_upgraded ? '' : 'disabled ' ?>onclick="return kca_save(<?= $set ?>);" />
<?php } else { ?>
<input type="submit" name="kca-update" id="kca_update_<?= $set ?>" value="<?php _e('Update') ?> &raquo;" title="Update record set to database" <?= $this->kca_upgraded ? '' : 'disabled ' ?>onclick="return kca_update(<?= $set ?>)"/>
<input type="submit" name="kca-delete" id="kca_delete_<?= $set ?>" value="<?php _e('Delete') ?> &raquo;" title="Delete from database" <?= $this->kca_upgraded ? '' : 'disabled ' ?>onclick="return kca_delete(<?= $set ?>);"/>
<input type="hidden" name="set" value="<?= $set ?>" />
<?php
}
?>
</p>
</td>
</tr>
</table>
</form></div>
<?php } ?>


<div id="kca_set_<?= $set ?>" class="wrap kca-hide">
<h2 class="clearfix">
<a href="#" class="close" title="Close Scratch-Pad Panel" onclick="return kca_toggle_set(<?= $set ?>)">&times;</a>
<a href="#" id="kca_form_<?= $set ?>_" class="rollup" title="Rollup Scratch-Pad Panel" onclick="return kca_rollup_set(<?= $set ?>)">&ndash;</a>
Scratch-Pad
</h2>
<form name="kca_scratch_pad" id="kca_form_<?= $set ?>" method="post">
<table width="100%" class="editform">

<tr valign="top">
<td>
<label for="kca_scratch"><p><strong>Make sure data is formatted correctly before importing.</strong><br />
<textarea wrap="off" rows="21" name="kca-scratch" id="kca_scratch"><?= stripslashes($_POST['kca-scratch']) ?></textarea></p>
</label>
</td>
</tr>

<tr>
<td>
<p class="submit">
<input type="button" name="select-text" id="select_text" value="<?php _e('Select') ?> &raquo;" onclick="document.getElementById('kca_scratch').select()" title="Select all clipboard data" />
<?php if ($is_IE) { ?>
<input type="button" name="copy-to-clip" id="copy_to_clip" value="<?php _e('Copy') ?> &raquo;" onclick="CopyToClipboard()" title="Copy selection to clipboard" />
<input type="button" name="paste-from-clip" id="paste_from_clip" value="<?php _e('Paste') ?> &raquo;" onclick="PasteFromClipboard()" title="Paste from clipboard" />
<?php } ?>
<input type="button" name="clear" value="<?php _e('Clear') ?> &raquo;" onclick="document.getElementById('kca_scratch').value = ''" title="Clear Scratch-Pad" />
<input type="button" name="extract-all" id="extract_all" value="<?php _e('Extract') ?> &raquo;" onclick="kca_extract_all()" title="Extract all data to Scratch-Pad" />
<input type="button" name="kca-load-ini" id="load-ini" value="<?php _e('Load') ?> &raquo;" onclick="return kca_load_ini()" title="Load from default.ini file" <?= $this->kca_upgraded ? '' : 'disabled ' ?>/>
<input type="button" name="kca-save-ini" id="save-ini" value="<?php _e('Save') ?> &raquo;" onclick="return kca_save_ini()" title="Save to default.ini file" <?= $this->kca_upgraded ? '' : 'disabled ' ?>/>
<input type="submit" name="kca-import" id="import" value="<?php _e('Import') ?> &raquo;" onclick="return kca_import()" title="Import Scratch-Pad data to database" <?= $this->kca_upgraded ? '' : 'disabled ' ?>/>
<input type="hidden" name="kca-import-all" id="import_all" value="" />
</p>
</td></tr>
</table>
</form></div>


<?php $set++; ?>
<div id="kca_set_<?= $set ?>" class="wrap kca-hide">
<h2 class="clearfix">
<a href="#" class="close" title="Close Global Panel" onclick="return kca_toggle_set(<?= $set ?>)">&times;</a>
<a href="#" id="kca_form_<?= $set ?>_" class="rollup" title="Rollup Global Panel" onclick="return kca_rollup_set(<?= $set ?>)">&ndash;</a>
Global
</h2>
<form name="kca_global" id="kca_form_<?= $set ?>" method="post">
<table width="100%" class="editform">
<tr valign="top">
<td>
<p><strong>These options operate on all record sets simultaneously, so use with caution.</strong></p>
<p class="submit">
<input type="submit" name="kca-purge-all" value="<?php _e('Purge') ?> &raquo;" onclick="return kca_purge_all()" title="Global purge of KCA database" <?= $this->kca_upgraded ? '' : 'disabled ' ?>/>
<input type="submit" name="kca-restore-all" id="kca_restore" value="<?php _e('Restore') ?> &raquo;" onclick="return kca_restore_all()" title="Restore everything with default values" <?= $this->kca_upgraded ? '' : 'disabled ' ?>/>
<input type="submit" name="kca-update-all" value="<?php _e('Update') ?> &raquo;" onclick="return kca_update_all()" title="Global update to database" <?= $this->kca_upgraded ? '' : 'disabled ' ?>/>
<input type="submit" name="kca-upgrade-all" value="<?php _e('Upgrade') ?> &raquo;" onclick="return kca_upgrade_all()" title="Upgrade database" <?= $this->kca_upgraded ? 'disabled ' : '' ?>/>
</p>
</td></tr>
</table>
</form></div>
<?php
}







///////////////////////////////////////////////////////////////////////////
//////////////////////// Insert Content into Page /////////////////////////
///////////////////////////////////////////////////////////////////////////
function kca_head() {
	$plugin = core::version(__FILE__);
	echo "\n"
		. $this->info('plugin', $plugin['plugin-name'] . ' v' . $plugin['version']) . "\n"
		. $this->info('uri', $plugin['plugin-uri']) . "\n"
		. $this->info('author', $plugin['author-name']) . "\n"
		. core::core_js(core::urlname(dirname(__FILE__)) . '/includes');
}

function kca_add_content($in_head) {
	global $user_level, $is_IE;
	$target = array();
	for ($i = 0; $i < count($this->kca_options); $i++) {
		if ($this->kca_options[$i]['Active']) {
			if ($this->kca_options[$i]['Needle']) {
				$pages = explode(',', $this->kca_options[$i]['Needle']);
				foreach ($pages as $page) {
					if (strpos($_SERVER['REQUEST_URI'], trim($page))) {
						if ($this->kca_options[$i]['Eval']) {
							eval('if (' . str_replace('"', "'", $this->kca_options[$i]['Eval']) . ') { $target[] = $this->kca_options[' . $i . ']; }');
						} else {
							$target[] = $this->kca_options[$i];
						}
					}
				}
			} else {
				if ($this->kca_options[$i]['Eval']) {
					eval('if (' . str_replace('"', "'", $this->kca_options[$i]['Eval']) . ') { $target[] = $this->kca_options[' . $i . ']; }');
				} else {
					$target[] = $this->kca_options[$i];
				}
			}
		}
	}

	$shortlist = array();
	for ($i = 0; $i < count($target); $i++) {
		if ($user_level >= $target[$i]['Userlevel']) {
			$shortlist[$i]['Reference'] = $target[$i]['Reference'];
			$shortlist[$i]['Location'] = $target[$i]['Location'];
			$shortlist[$i]['Content'] .= $this->scanvar($target[$i]['Content']);
			$shortlist[$i]['Head'] .= $this->scanvar($target[$i]['Head']);
			$shortlist[$i]['Foot'] .= $this->scanvar($target[$i]['Foot']);
		}
	}
	$content_str = '';
	$head_str = '';
	$foot_str = '';
	foreach ($shortlist as $content) {
		$content['Content'] ? $content_str .= "document.getElementById('" . $content['Reference'] . "') ? khanh.dom.insertAdjacentHTML(document.getElementById('" . $content['Reference'] . "'), '" . $content['Location'] . "', '" . addslashes($content['Content']) . "') : 0;" : '';
		$head_str .= $content['Head'] ? $content['Head'] . "\n" : '';
		$foot_str .= $content['Foot'] ? $content['Foot'] . "\n" : '';
	}
	$kca_page = strpos($_SERVER['REQUEST_URI'], 'page=kca.php');
	$data = core::version(__FILE__);
	if ($in_head) $this->kca_head();
	if (!empty($shortlist) || $kca_page) {
		if ($in_head) {
			if ($kca_page) {
				ob_start();
				require_once(dirname(__FILE__) . '/includes/kca.css');
				$head_str .= '<style type="text/css">' . core::comp_css(ob_get_contents()) . "</style>";
	
				ob_clean();
				if (function_exists('wp_enqueue_script')) {
					wp_enqueue_script('sack');
					do_action('admin_print_scripts');
					$head_str .= ob_get_contents();
					ob_clean();
				} else require_once(dirname(__FILE__) . '/includes/tw-sack.js');
				global $is_IE;
				require_once(dirname(__FILE__) . '/includes/admin-js.php');
				require_once(dirname(__FILE__) . '/includes/tw-sack.js');
				$head_str .= '<script type="text/javascript">' . $this->cdata_start . ($this->debug ? ob_get_contents() : core::comp_js(ob_get_contents())) . $this->cdata_end . "</script>\n";
				ob_end_clean();
			}
			if ($head_str) echo $head_str;
		} else {
			echo $foot_str
			. ($content_str ? '<script type="text/javascript">' . $this->cdata_start . $content_str . $this->cdata_end . '</script>' : '');

			$t = explode(' ', microtime());
			$this->kca_timer_stop = $t[1] + $t[0];
			echo "\n" . $this->info('run-time', ($this->kca_timer_stop - $this->kca_timer_start) . 's') . "\n\n";
		}
	}
}

function info($title, $value) {
	$str = $value . '] -->';
	return str_pad('<!-- [' . $title, 79 - strlen($str), '.') . $str;
}

function scanvar($var) {
	return preg_replace("/%%(.+?)%%/se", '$this->procvar(\'$1\')', $var); // Hunt for %% variables
}

// Replace found variables with the real thing
function procvar($var) {
	ob_start();

	if ($var{0} == '=') {
		$var = substr($var, 1);
		eval("echo $var;");
	} else if ($var == 'site_url') {
		echo core::urlname(dirname(__FILE__) . '/../../..');
	} else if ($var == 'kca_url') {
		echo core::urlname(dirname(__FILE__));
	} else eval("$var;");

	$out = stripslashes(ob_get_contents());
	ob_end_clean();
	return $out;
}

}

require_once(dirname(__FILE__) . '/includes/core.php');

if (!function_exists(get_option)) {
	chdir('../../../wp-admin');
	require_once('admin.php');
}

$kca = new kca();
?>