<?php
if (!function_exists('add_action')) {
	echo 'You are not running WordPress.';
	exit();
}

function linkcloaker_activate() {
	global $wpdb;

	$x_tbl_name = $wpdb->prefix.'cloak_word';
	$sql = array();
	if ($wpdb->get_var('SHOW TABLES LIKE "'.$x_tbl_name.'"') != $x_tbl_name) {
		$sql[] = "CREATE TABLE " . $x_tbl_name . " (
				  cloak_word_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				  url_cloak varchar(255) NOT NULL,
				  new_url varchar(255) NOT NULL,
				  keyword varchar(255) NOT NULL,
				  clicks bigint(20) UNSIGNED NOT NULL DEFAULT  '0',
				  title varchar(100) NOT NULL,
				  digg_bar_text TEXT NOT NULL,
				  digg_bar_link varchar(255) NOT NULL,
				  PRIMARY KEY id (cloak_word_id)
		);";
	}

	$x_tbl_name = $wpdb->prefix.'cloak_word_clicks';

	if ($wpdb->get_var('SHOW TABLES LIKE "'.$x_tbl_name.'"') != $x_tbl_name) {
		$sql[] = "CREATE TABLE " . $x_tbl_name . " (
				  cloak_word_click_id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				  cloak_word_id bigint(20) UNSIGNED NOT NULL DEFAULT '0',
				  user_ip varchar(255) NOT NULL,
				  keyword varchar(255) NOT NULL,
				  http_referer varchar(255) NOT NULL,
				  insert_time BIGINT( 20 ) UNSIGNED NOT NULL DEFAULT '0',
				  today_time BIGINT( 20 ) UNSIGNED NOT NULL DEFAULT '0',
				  PRIMARY KEY (cloak_word_click_id)
		);";
	}

	if ($sql != array()) {
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		foreach ($sql as $s) {
			dbDelta($s);
		}
	}
}

function linkcloaker_add() {
	global $wpdb;
	linkcloaker_activate();
	$options = linkcloaker_get_options();
	$urlgw = get_bloginfo('url');
    $urlane = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
	?><img alt="Logo" width="59" height="59" src="<?php echo linkcloaker_img_dir(); ?>logo.png" style="float:left" /><h2><?php _e('Add Link Cloaker'); ?></h2>
	<div style="clear:both"></div>
	<?php
	$url = $slug = $keyword = $title = $digg_bar_text = $digg_bar_link = '';
	$target = '_blank';
	$rel = 'nofollow';
	if (isset($_POST['url'])) {
		$url = trim($_POST['url']);
	}
	if (isset($_POST['cloakslug'])) {
		$slug = trim($_POST['cloakslug']);
	}
	if (isset($_POST['keyword'])) {
		$keyword = trim($_POST['keyword']);
	}
	if (isset($_POST['title'])) {
		$title = trim($_POST['title']);
	}
	if (isset($_POST['digg_bar_text'])) {
		$digg_bar_text = trim($_POST['digg_bar_text']);
	}
	if (isset($_POST['digg_bar_link'])) {
		$digg_bar_link = trim($_POST['digg_bar_link']);
	}
    if (isset($_POST["go"])) {
        if ($url == '' || $slug == '' || $keyword == '' || $title == "") {
			?><div id="message" class="updated fade"><strong><?php _e('You must enter all required fields') ?></strong></div><?php
        } else {
			$qr = "SELECT url_cloak from ".$wpdb->prefix."cloak_word WHERE LOWER(new_url) = LOWER('$slug') OR LOWER(keyword) = LOWER('$keyword')";
			$qrs = $wpdb->get_row($qr);
			if (count($qrs->url_cloak) < 1){
				$insert = "INSERT INTO ".$wpdb->prefix."cloak_word (url_cloak, new_url, keyword, title, digg_bar_text, digg_bar_link) VALUES ('$url', '$slug', '$keyword', '$title', '$digg_bar_text', '$digg_bar_link')";
				$results = $wpdb->query($insert);
				?><div id="message" class="updated fade"><strong><?php _e('Url cloak Saved.') ?></strong></div><?php
			}else{
				?><div id="message" class="updated fade"><strong><?php _e('Url cloak is exist before.') ?></strong></div><?php
			}
        }
	}
	?>
	<form action="admin.php?page=linkcloakeradd" method="post">
	<input type="hidden" name="go" value="1" />
	<table cellpadding="5" cellspacing="0">
		<tr valign="top">
			<td style="padding:0.5em"><label for="url1"><b>URL to Cloak <span style="color:#FF0000">*</span></b></label></td>
			<td style="padding:0.5em">
				<input type="text" name="url" size="50" maxlength="200" id="url1" value="<?php echo $url; ?>" /><br />
				<small>Include http://</small>
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><label for="url"><b>New URL <span style="color:#FF0000">*</span></b></label></td>
			<td style="padding:0.5em">
				<?php echo get_bloginfo('url'); ?>/<?php echo $options['opturl']; ?>/<input type="text" name="cloakslug" maxlength="200" value="<?php echo $slug; ?>" />
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><label for="key"><b>Keyword(s) <span style="color:#FF0000">*</span></b></label></td>
			<td style="padding:0.5em">
				<input type="text" name="keyword" size="50" maxlength="255" id="key" value="<?php echo htmlentities($keyword, ENT_COMPAT, 'UTF-8'); ?>" /><br />
				*) separate each keyword with comma (,)
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><label for="id_title"><b>Title <span style="color:#FF0000">*</span></b></label></td>
			<td style="padding:0.5em">
				<input type="text" name="title" id="id_title" size="50" maxlength="100" value="<?php echo htmlentities($title, ENT_COMPAT, 'UTF-8'); ?>" />
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><label for="id_digg_bar_text"><b>Digg Bar Text</b></label></td>
			<td style="padding:0.5em">
				<input type="text" name="digg_bar_text" id="id_digg_bar_text" size="50" maxlength="100" value="<?php echo htmlentities($digg_bar_text, ENT_COMPAT, 'UTF-8'); ?>" />
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><label for="id_digg_bar_link"><b>Digg Bar Link</b></label></td>
			<td style="padding:0.5em">
				<input type="text" name="digg_bar_link" id="id_digg_bar_link" size="50" maxlength="100" value="<?php echo htmlentities($digg_bar_link, ENT_COMPAT, 'UTF-8'); ?>" />
			</td>
		</tr>
	</table>
	<span class="submit"><input type="submit" name="nextstep" value="Add Link" /></span>
	</form>
	<?php
}

function linkcloaker_get_options() {
	$options = get_option('cloaker');
	if (!isset($options['custom_css'])) {
		$options['custom_css'] = '';
	}
	if (!isset($options['is_bold'])) {
		$options['is_bold'] = 0;
	}
	if (!isset($options['is_italic'])) {
		$options['is_italic'] = 0;
	}
	if (!isset($options['is_underline'])) {
		$options['is_underline'] = 0;
	}
	if (!isset($options['link_target'])) {
		$options['link_target'] = '_blank';
	}
	if (!isset($options['nofollow'])) {
		$options['nofollow'] = 1;
	}
	if (!isset($options['opturl'])) {
		$options['opturl'] = 'go';
	}
	if (!isset($options['max_all_replacement'])) {
		$options['max_all_replacement'] = 0;
	}
	if (!isset($options['max_replacement'])) {
		$options['max_replacement'] = 0;
	}
	return $options;
}

// as plugin
/*
function linkcloaker_img_dir() {
	return get_bloginfo('url').'/'.PLUGINDIR.'/'.LINKCLOAKER_DIR.'/img/';
}
*/
// as template plugin
function linkcloaker_img_dir() {
	return get_bloginfo('template_url').'/plugins/'.LINKCLOAKER_DIR.'/img/';
}

function linkcloaker_manage() {
	global $wpdb;
	$options = linkcloaker_get_options();
	?><img alt="Logo" width="59" height="59" src="<?php echo linkcloaker_img_dir(); ?>logo.png" style="float:left" /><h2><?php _e('Manage Links Cloaker'); ?></h2>
	<div style="clear:both"></div>
	<?php
	if (isset($_GET['edit']) && isset($_GET['idx'])){
		$cloak_word_id = intval($_GET['idx']);
		$q = "SELECT * FROM ".$wpdb->prefix."cloak_word WHERE cloak_word_id = $cloak_word_id LIMIT 1";
		$q = $wpdb->get_results($q, ARRAY_A);
		if ($q == array()) { ?>
			<p>Link is not found.</p>
		<?php } else {
			$q = $q[0];
			$url = $slug = $keyword = $title = $digg_bar_text = $digg_bar_link = '';
			$target = '_blank';
			$rel = 'nofollow';
			if (isset($_POST['url'])) {
				$url = trim($_POST['url']);
			}
			if (isset($_POST['cloakslug'])) {
				$slug = trim($_POST['cloakslug']);
			}
			if (isset($_POST['keyword'])) {
				$keyword = trim($_POST['keyword']);
			}
			if (isset($_POST['title'])) {
				$title = trim($_POST['title']);
			}
			if (isset($_POST['digg_bar_text'])) {
				$digg_bar_text = trim($_POST['digg_bar_text']);
			}
			if (isset($_POST['digg_bar_link'])) {
				$digg_bar_link = trim($_POST['digg_bar_link']);
			}
			if (isset($_POST["go"])) {
				if ($url == '' || $slug == '' || $keyword == '' || $title == "") {
					?><div id="message" class="updated fade"><strong><?php _e('You must enter all required fields') ?></strong></div><?php
				} else {
					$qr = "SELECT url_cloak from ".$wpdb->prefix."cloak_word WHERE LOWER(`new_url`) = LOWER('$slug') OR LOWER(`keyword`) = LOWER('$keyword')";
					$qrs = $wpdb->get_row($qr);
					if (true || count($qrs->url_cloak) < 1){
						$insert = "UPDATE ".$wpdb->prefix."cloak_word SET `url_cloak` = '$url', `new_url` = '$slug', `keyword` = '$keyword', `title` = '$title', `digg_bar_text` = '$digg_bar_text', `digg_bar_link` = '$digg_bar_link' WHERE cloak_word_id = $cloak_word_id LIMIT 1";
						$results = $wpdb->query($insert);
						$q = "SELECT * FROM wp_cloak_word WHERE cloak_word_id = $cloak_word_id LIMIT 1";
						$q = $wpdb->get_results($q, ARRAY_A);
						$q = $q[0];
						?><div id="message" class="updated fade"><strong><?php _e('URL has been Updated.') ?></strong></div><?php
					} else{
						?><div id="message" class="updated fade"><strong><?php _e('URL is exist before.') ?></strong></div><?php
					}
				}
			}
			?>
			<form action="admin.php?page=linkcloaker_manage&amp;edit=1&amp;idx=<?php echo $cloak_word_id; ?>" method="post">
			<input type="hidden" name="go" value="1" />
			<table cellpadding="5" cellspacing="0">
				<tr valign="top">
					<td style="padding:0.5em"><label for="url1"><b>URL to Cloak <span style="color:#FF0000">*</span></b></label></td>
					<td style="padding:0.5em">
						<input type="text" name="url" size="50" maxlength="200" id="url1" value="<?php echo $q['url_cloak']; ?>" /><br />
						<small>Include http://</small>
					</td>
				</tr>
				<tr valign="top">
					<td style="padding:0.5em"><label for="url"><b>New URL <span style="color:#FF0000">*</span></b></label></td>
					<td style="padding:0.5em">
						<?php echo get_bloginfo('url'); ?>/<?php echo $options['opturl']; ?>/<input type="text" name="cloakslug" maxlength="200" value="<?php echo $q['new_url']; ?>" />
					</td>
				</tr>
				<tr valign="top">
					<td style="padding:0.5em"><label for="key"><b>Keyword(s) <span style="color:#FF0000">*</span></b></label></td>
					<td style="padding:0.5em">
						<input type="text" name="keyword" size="50" maxlength="255" id="key" value="<?php echo htmlentities($q['keyword'], ENT_COMPAT, 'UTF-8'); ?>" /><br />
						*) separate each keyword with comma (,)
					</td>
				</tr>
				<tr valign="top">
					<td style="padding:0.5em"><label for="id_title"><b>Title <span style="color:#FF0000">*</span></b></label></td>
					<td style="padding:0.5em">
						<input type="text" name="title" id="id_title" size="50" maxlength="100" value="<?php echo htmlentities($q['title'], ENT_COMPAT, 'UTF-8'); ?>" />
					</td>
				</tr>
				<tr valign="top">
					<td style="padding:0.5em"><label for="id_digg_bar_text"><b>Digg Bar Text</b></label></td>
					<td style="padding:0.5em">
						<input type="text" name="digg_bar_text" id="id_digg_bar_text" size="50" maxlength="100" value="<?php echo htmlentities($q['digg_bar_text'], ENT_COMPAT, 'UTF-8'); ?>" />
					</td>
				</tr>
				<tr valign="top">
					<td style="padding:0.5em"><label for="id_digg_bar_link"><b>Digg Bar Link</b></label></td>
					<td style="padding:0.5em">
						<input type="text" name="digg_bar_link" id="id_digg_bar_link" size="50" maxlength="100" value="<?php echo htmlentities($q['digg_bar_link'], ENT_COMPAT, 'UTF-8'); ?>" />
					</td>
				</tr>
			</table>
			<span class="submit"><input type="submit" name="nextstep" value="Save Link" /></span>
			</form>
			<?php
		}
	} else if (isset($_GET['detail']) && isset($_GET['idx'])){
		$cloak_word_id = intval($_GET['idx']);
		$q = "SELECT * FROM wp_cloak_word WHERE cloak_word_id = $cloak_word_id LIMIT 1";
		$q = $wpdb->get_results($q, ARRAY_A);
		if ($q == array()) { ?>
		<p>Link is not found.</p>
		<?php } else {
		$q = $q[0];
		$keywords = explode(',', $q['keyword']);
		natcasesort($keywords);
		$temp = array();
		foreach ($keywords as $keyword) {
			$temp[] = trim($keyword);
		}
		$keywords = $temp;
		$click_history = array();
		$q2 = "SELECT * FROM wp_cloak_word_clicks WHERE cloak_word_id = $cloak_word_id AND LOWER(keyword) IN ('".implode("', '", $keywords)."') ORDER BY cloak_word_click_id DESC LIMIT 100";
		$click_history = $wpdb->get_results($q2, ARRAY_A);
		?>
		<h3>URL Statistic</h3>
		<table class="widefat" cellspacing="0">
			<thead>
				<tr>
					<th scope="col" class="manage-column">Keyword</th>
					<th scope="col" class="manage-column">All Clicks</th>
					<th scope="col" class="manage-column">Unique Clicks</th>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<th scope="col" class="manage-column">Keyword</th>
					<th scope="col" class="manage-column">All Clicks</th>
					<th scope="col" class="manage-column">Unique Clicks</th>
				</tr>
			</tfoot>
			<tbody class="plugins">
			<?php foreach ($keywords as $keyword) :
			$keyword = strtolower(trim($keyword));

			$q2 = "SELECT COUNT(cloak_word_click_id) AS x_count FROM wp_cloak_word_clicks WHERE cloak_word_id = $cloak_word_id AND LOWER(keyword) = '$keyword' LIMIT 1";
			$q2 = $wpdb->get_results($q2, ARRAY_A);
			$all_clicks = $q2[0]['x_count'];

			$q2 = "SELECT COUNT(DISTINCT(user_ip)) AS x_count FROM wp_cloak_word_clicks WHERE cloak_word_id = $cloak_word_id AND LOWER(keyword) = '$keyword' LIMIT 1";
			$q2 = $wpdb->get_results($q2, ARRAY_A);
			$unique_clicks = $q2[0]['x_count'];
			?>
				<tr>
					<td><?php echo htmlentities($keyword, ENT_COMPAT, 'UTF-8'); ?></td>
					<td><?php echo number_format($all_clicks); ?></td>
					<td><?php echo number_format($unique_clicks); ?></td>
				</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php if ($click_history != array()) : ?>
		<h3>Last 100 Clicks</h3>
		<table class="widefat" cellspacing="0">
			<thead>
				<tr>
					<th scope="col" class="manage-column">Keyword</th>
					<th scope="col" class="manage-column">User IP Address</th>
					<th scope="col" class="manage-column">Referrer URL</th>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<th scope="col" class="manage-column">Keyword</th>
					<th scope="col" class="manage-column">User IP Address</th>
					<th scope="col" class="manage-column">Referrer URL</th>
				</tr>
			</tfoot>
			<tbody class="plugins">
			<?php foreach ($click_history as $data) :
				$http_referer = base64_decode($data['http_referer']);
				?>
				<tr>
					<td><?php echo htmlentities($data['keyword'], ENT_COMPAT, 'UTF-8'); ?></td>
					<td><?php echo htmlentities($data['user_ip'], ENT_COMPAT, 'UTF-8'); ?></td>
					<td><a href="<?php echo htmlentities($http_referer, ENT_COMPAT, 'UTF-8'); ?>" target="_blank"><?php echo htmlentities($http_referer, ENT_COMPAT, 'UTF-8'); ?></a></td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
		<?php endif; ?>
		<?php
		}
	}elseif ($_GET["delete"]!='') {
        $ss = intval($_GET["delete"]);
        $qr3 = "DELETE FROM ".$wpdb->prefix."cloak_word WHERE cloak_word_id = '".$ss."'";
		$qrs3 = $wpdb->query($qr3);
		$qr4 = "DELETE FROM ".$wpdb->prefix."cloak_word_clicks WHERE cloak_word_id = '".$ss."'";
		$qrs4 = $wpdb->query($qr4);

		?><div id="message" class="updated fade"><strong><?php _e('Cloaked link removed successfully.') ?></strong></div><?php
		showdatas();
    }elseif ($_GET["clear"]!='') {
        $ss = $_GET["idx"];
		$ss = intval($ss);
        $qr3 = "UPDATE ".$wpdb->prefix."cloak_word SET clicks = 0 WHERE cloak_word_id = '".$ss."'";
		$qrs3 = $wpdb->query($qr3);
		 $qr4 = "DELETE FROM ".$wpdb->prefix."cloak_word_clicks WHERE cloak_word_id = '".$ss."'";
		$qrs4 = $wpdb->query($qr4);

		?><div id="message" class="updated fade"><strong><?php _e('Statistic has been cleared.') ?></strong></div><?php
		showdatas();
    }else{
		showdatas();
		echo "</div>";
	}
}

function linkcloaker_menu() {
    add_menu_page('Link Cloaker', 'Link Cloaker', 8, 'linkcloakeradd', 'linkcloaker_add');
    add_submenu_page('linkcloakeradd', 'Add Link', 'Add Link', 8, 'linkcloakeradd', 'linkcloaker_add');
    //add_submenu_page('linkcloakeradd', 'Options', 'Options', 8, 'linkcloakeroptions', 'linkcloaker_option_page');
    add_submenu_page('linkcloakeradd', 'Manage Links', 'Manage Links', 8, 'linkcloaker_manage', 'linkcloaker_manage');
}

function linkcloaker_option_page() {
	if (!current_user_can('manage_options')) {
		wp_die( __('You do not have sufficient permissions to access this page.') );
	}
	if (isset($_POST['go'])) {
		$opturl = 'go';
		$link_target = '_blank';
		$custom_css = '';
		$max_all_replacement = $max_replacement = $is_bold = $is_italic = $is_underline = $nofollow = 0;
		if (isset($_POST['custom_css'])) {
			$custom_css = trim($_POST['custom_css']);
		}
		if (isset($_POST['is_bold'])) {
			$is_bold = intval($_POST['is_bold']);
		}
		if (isset($_POST['is_italic'])) {
			$is_italic = intval($_POST['is_italic']);
		}
		if (isset($_POST['is_underline'])) {
			$is_underline = intval($_POST['is_underline']);
		}
		if (isset($_POST['link_target'])) {
			$link_target = trim($_POST['link_target']);
		}
		if (isset($_POST['nofollow'])) {
			$nofollow = intval($_POST['nofollow']);
		}
		if (isset($_POST['opturl'])) {
			$opturl = trim($_POST['opturl']);
		}
		if (isset($_POST['max_replacement'])) {
			$max_replacement = intval($_POST['max_replacement']);
		}
		if (isset($_POST['max_all_replacement'])) {
			$max_all_replacement = intval($_POST['max_all_replacement']);
		}
		$opt = array(
			'custom_css' => $custom_css,
			'is_bold' => $is_bold,
			'is_italic' => $is_italic,
			'is_underline' => $is_underline,
			'link_target' => $link_target,
			'nofollow' => $nofollow,
			'opturl' => $opturl,
			'max_replacement' => $max_replacement,
			'max_all_replacement' => $max_all_replacement
		);
		update_option('cloaker', $opt);
		_e('<div id="message" class="updated fade"><p>Options updated.</p></div>');
	}
	$opt = linkcloaker_get_options();
	?>
	<div class="wrap">
	<img alt="Logo" width="59" height="59" src="<?php echo linkcloaker_img_dir(); ?>logo.png" style="float:left" /><h2><?php _e('Link Cloaker Options'); ?></h2>
	<div style="clear:both"></div>
	<form name="form1" method="post" action="">
	<input type="hidden" name="go" value="1" />
	<table>
		<tr>
			<td style="padding:0.5em"><strong>Global Slug</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<?php echo get_bloginfo('siteurl'); ?>/<input type="text" name="opturl" value="<?php echo htmlentities($opt['opturl']); ?>" maxlength="100" />/<strong>keyword</strong>/
			</td>
		</tr>
		<tr>
			<td style="padding:0.5em"><strong>Max replacement per keyword</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<input type="text" name="max_replacement" value="<?php echo intval($opt['max_replacement']); ?>" maxlength="3" size="4" /> (set to 0 to disable)
			</td>
		</tr>
		<tr>
			<td style="padding:0.5em"><strong>Max replacement per page</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<input type="text" name="max_all_replacement" value="<?php echo intval($opt['max_all_replacement']); ?>" maxlength="3" size="4" /> (set to 0 to disable)
			</td>
		</tr>
		<tr>
			<td style="padding:0.5em"><strong>Open link on</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<select name="link_target">
				<option value="_blank">New window</option>
				<option value="_self"  <?php if ($opt['link_target'] == '_self') { echo ' selected="selected" '; } ?>>Same window</option>
				</select>
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><strong>Link style</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<input type="checkbox" name="is_bold" value="1" id="id_is_bold" <?php if ($opt['is_bold'] == 1) { echo ' checked="checked" '; } ?> /><label for="id_is_bold"> <strong>Bold</strong> &lt;strong&gt;...&lt;/strong&gt;</label><br />
				<input type="checkbox" name="is_italic" value="1" id="id_is_italic" <?php if ($opt['is_italic'] == 1) { echo ' checked="checked" '; } ?> /><label for="id_is_italic"> <em>Italic</em> &lt;em&gt;...&lt;/em&gt;</label><br />
				<input type="checkbox" name="is_underline" value="1" id="id_is_underline" <?php if ($opt['is_underline'] == 1) { echo ' checked="checked" '; } ?> /><label for="id_is_underline"> <u>Underline</u> &lt;u&gt;...&lt;/u&gt;</label><br />
			</td>
		</tr>
		<tr>
			<td style="padding:0.5em"><strong>Custom CSS Class</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<input type="text" name="custom_css" value="<?php echo trim($opt['custom_css']); ?>" maxlength="100" /> Leave blank to ignore.
			</td>
		</tr>
		<tr valign="top">
			<td style="padding:0.5em"><strong>Add Nofolow Attribute</strong></td>
			<td style="padding:0.5em">:</td>
			<td style="padding:0.5em">
				<input type="checkbox" name="nofollow" value="1" id="id_nofollow" <?php if ($opt['nofollow'] == 1) { echo ' checked="checked" '; } ?> /><label for="id_nofollow"> Yes, add &quot;nofollow&quot; attribute to all links.</label>
			</td>
		</tr>
	</table>
	<p class="submit">
		<input type="submit" name="Submit" class="button-primary" value="Save Changes" />
	</p>
	</form>
	</div>
	<?php
}

function linkcloaker_rewrite_content($content) {
	global $wpdb;
	$options = linkcloaker_get_options();
	$url = $_SERVER['REQUEST_URI'];
	$go = $options['opturl'];

	$urlku = get_bloginfo('url');
	$qu= "SELECT * FROM ".$wpdb->prefix."cloak_word";
	$pu = $wpdb->get_results($qu);
	$arr = array();
	$replace_setting = array();
	$pum = count($pu);
	$replace = '';
	for ($j=0;$j<$pum;$j++){
		$kw = trim($pu[$j]->keyword);
		if (strpos($kw, ',') === false) {
			$replace_setting[] = array(
				'hash' => $replace,
				'real' => $kw,
				'url' => $pu[$j]->new_url,
				'title' => $pu[$j]->title,
				'index' => false
			);
		} else {
			$kws = explode(',', $kw);
			$i = 0;
			foreach ($kws as $kws2) {
				$kws2 = trim($kws2);
				$replace_setting[] = array(
					'hash' => $replace,
					'real' => $kws2,
					'url' => $pu[$j]->new_url,
					'title' => $pu[$j]->title,
					'index' => $i
				);
				$i++;
			}
		}
	}
	if ($replace_setting != array()) {
		foreach ($replace_setting as $rs) {
			$replace = ':PROTECTSTART2:'.md5(__FILE__.$rs['real']).':PROTECTEND2:';
			$arr[] = array(
				'hash' => $replace,
				'real' => $rs['real'],
				'url' => $rs['url'],
				'title' => $rs['title'],
				'index' => $rs['index']
			);
			$content = xrvel_link_cloaker_replace($rs['real'], $replace, $content, array('a', 'iframe', 'img'), $options);
		}
	}
	if ($arr != array()) {
		$before = array();
		$after = array();
		$rel = '';
		$class = '';
		if ($options['is_bold'] == 1) {
			$before[] = '<strong>';
			$after[] = '</strong>';
		}
		if ($options['is_italic'] == 1) {
			$before[] = '<em>';
			$after[] = '</em>';
		}
		if ($options['is_underline'] == 1) {
			$before[] = '<u>';
			$after[] = '</u>';
		}
		if ($options['nofollow'] == 1) {
			$rel = ' rel="nofollow"';
		}
		if ($options['custom_css'] != '') {
			$class = ' '.$options['custom_css'];
		}
		$before = implode('', $before);
		$after = implode('', $after);
		foreach ($arr as $arr_2) {
			$link_index = '';
			if ($arr_2['index'] !== false) {
				$link_index = '/'.$arr_2['index'];
			}
			$replace_to = '<a href="'.$urlku.'/'.$go.'/'.$arr_2['url'].$link_index.'" target="'.$options['link_target'].'"'.$rel.' title="'.$arr_2['title'].'" class="cloak'.$class.'">'.$before.$arr_2['real'].$after.'</a>';
			$content = str_replace($arr_2['hash'], $replace_to, $content);
		}
	}
	return $content;
}

function linkcloaker_uninstall() {
	global $wpdb;
	delete_option('cloaker');
	$x_tbl_name = $wpdb->prefix.'cloak_word';
	$wpdb->query("DROP TABLE IF EXISTS $x_tbl_name");
	$x_tbl_name = $wpdb->prefix.'cloak_word_clicks';
	$wpdb->query("DROP TABLE IF EXISTS $x_tbl_name");
}

function showdatas(){
	$options = linkcloaker_get_options();
	global $wpdb;
	?>
	<table class="widefat" cellspacing="0">
		<thead>
		<tr>
			<th scope="col" class="manage-column">Redirect To</th>
			<th scope="col" class="manage-column">Cloaked URL</th>
			<th scope="col" class="manage-column">Keyword(s)</th>
			<th scope="col" class="manage-column">Title</th>
			<th scope="col" class="manage-column">Action</th>
		</tr>
		</thead>
		<tfoot>
		<tr>
			<th scope="col" class="manage-column">Redirect To</th>
			<th scope="col" class="manage-column">Cloaked URL</th>
			<th scope="col" class="manage-column">Keyword(s)</th>
			<th scope="col" class="manage-column">Title</th>
			<th scope="col" class="manage-column">Action</th>
		</tr>
		</tfoot>
		<tbody class="plugins">
		<?php
		$qr2 = "SELECT * FROM ".$wpdb->prefix."cloak_word ORDER BY keyword ASC, new_url ASC";
		$qrs2 = $wpdb->get_results($qr2);
		//print_r($qrs2);
		for ($k=0;$k<count($qrs2);$k++){
			$bi_url = get_bloginfo('url');
			$fake_url = $bi_url.'/'.$options['opturl'].'/'.trim($qrs2[$k]->new_url).'/';
			$keywords = explode(',', $qrs2[$k]->keyword);
			natcasesort($keywords);
			?>
			<tr class="active" valign="top">
			<td>
				<a href="<?php echo $qrs2[$k]->url_cloak; ?>" target="_blank"><?php echo $qrs2[$k]->url_cloak; ?></a>
			</td>
			<td>
				<a href="<?php echo $fake_url; ?>" target="_blank"><?php echo $fake_url; ?></a>
			</td>
			<td>
				<?php echo htmlentities($qrs2[$k]->keyword, ENT_COMPAT, 'UTF-8'); ?>
			</td>
			<td>
				<?php echo htmlentities($qrs2[$k]->title, ENT_COMPAT, 'UTF-8'); ?>
			</td>
			<td>
				<a href="admin.php?page=linkcloaker_manage&amp;edit=1&amp;idx=<?php echo $qrs2[$k]->cloak_word_id; ?>" title="Edit"><img width="16" height="16" alt="Edit" border="0" src="<?php echo linkcloaker_img_dir(); ?>pencil.png" /></a> | 
				<!--<a href="admin.php?page=linkcloaker_manage&amp;detail=1&amp;idx=<?php echo $qrs2[$k]->cloak_word_id; ?>" title="View Statistic"><img width="16" height="16" alt="View Statistic" border="0" src="<?php echo linkcloaker_img_dir(); ?>chart_bar.png" /></a> | 
				<a href="admin.php?page=linkcloaker_manage&amp;clear=view&amp;idx=<?php echo $qrs2[$k]->cloak_word_id; ?>" title="Clear Statistic"><img width="16" height="16" alt="Clear Statistic" border="0" src="<?php echo linkcloaker_img_dir(); ?>chart_bar_delete.png" /></a> |-->
				<a href="admin.php?page=linkcloaker_manage&amp;delete=<?php echo $qrs2[$k]->cloak_word_id; ?>" title="Delete"><img width="16" height="16" alt="Delete" border="0" src="<?php echo linkcloaker_img_dir(); ?>cancel.png" /></a>
			</td>
			</tr>
			<?php
		}
		?>
		</tbody>
	</table>
	<?php
}

function xrvel_link_cloaker_replace($from, $to, $str, $ignore_tags = true, $options = array()) {
	$tags = '';
	if (is_array($ignore_tags) && count($ignore_tags) > 0) {
		$tags = implode('|', $ignore_tags);
	}
	if ($tags == '') {
		$protect = preg_match_all('/\<(.*)'.xrvel_link_cloaker_safe_regexp($from).'(.*)\>/iU', $str, $match);
	} else {
		$protect = preg_match_all('/\<('.$tags.')(.*)'.xrvel_link_cloaker_safe_regexp($from).'(.*)\>/iU', $str, $match);
	}
	$safe = array();
	foreach ($match[0] as $m) {
		$replace = ':PROTECTSTART:'.md5(__FILE__.$m).':PROTECTEND:';
		$safe[$replace] = $m;
		$str = str_replace($m, $replace, $str);
	}
	$str = xrvel_str_replace_max($from, $to, $str, $options['max_replacement']);
	if ($safe != array()) {
		foreach ($safe as $name=>$value) {
			$str = str_replace($name, $value, $str);
		}
	}
	
	return $str;
}
function xrvel_link_cloaker_safe_regexp($str) {
	$str = str_replace('"', '\"', $str);
	$str = str_replace('.', '\.', $str);
	$str = str_replace('*', '\*', $str);
	$str = str_replace('(', '\(', $str);
	$str = str_replace(')', '\)', $str);
	$str = str_replace('-', '\-', $str);
	$str = str_replace('_', '\_', $str);
	$str = str_replace('?', '\?', $str);
	$str = str_replace('+', '\+', $str);
	$str = str_replace('!', '\!', $str);
	$str = str_replace('[', '\[', $str);
	$str = str_replace(']', '\]', $str);
	$str = str_replace(',', '\,', $str);
	$str = str_replace('<', '\<', $str);
	$str = str_replace('>', '\>', $str);
	$str = str_replace('|', '\|', $str);
	return $str;
}

function xrvel_str_replace_max($from, $to, $str, $max_replacement = 0) {
	$max_replacement = intval($max_replacement);
	$max_replacement = 0;
	if ($max_replacement == 0) {
		$str = str_ireplace($from, $to, $str);
	} else {
		for ($i=1;$i<=$max_replacement;$i++) {
			$pos = stripos($str, $from);
			$cut_from = $pos + strlen($from);
			$str = substr($str, 0, $pos).$to.substr($str, $cut_from);
		}
	}
	return $str;
}

$options = linkcloaker_get_options();
$url = $_SERVER['REQUEST_URI'];
if (strpos($url, '/'.$options['opturl'].'/') !== false) {
	$slug = '';
	$keyword = '';
	if (preg_match('/'.$options['opturl'].'\/(.*)\/(.*)(\/)?/i', $url, $match)) {
		$slug = preg_replace('/([^a-z0-9\-\_]+)/i', '', trim($match[1]));
		$keyword = preg_replace('/([^0-9]+)/i', '', trim($match[2]));
	} else if (preg_match('/'.$options['opturl'].'\/(.*)(\/)?/i', $url, $match)) {
		$slug = preg_replace('/([^a-z0-9\-\_]+)/i', '', trim($match[1]));
	}
	if ($slug != '') {
		$qs = "SELECT cloak_word_id, keyword, url_cloak, digg_bar_text, digg_bar_link FROM ".$wpdb->prefix."cloak_word WHERE LOWER(new_url) = LOWER('".$slug."') LIMIT 1";
		$qss = $wpdb->get_results($qs, ARRAY_A);
		if ($qss != array()) {
			$qss = $qss[0];
			if (strpos($qss['keyword'], ',') === false) {
				$keyword = $qss['keyword'];
			} else {
				$keywords = explode(',', $qss['keyword']);
				if (isset($keywords[$keyword])) {
					$keyword = trim($keywords[$keyword]);
				} else {
					$keyword = trim($keywords[0]);
				}
			}
			$q = "UPDATE ".$wpdb->prefix."cloak_word SET clicks = clicks + 1 WHERE cloak_word_id = ".$qss['cloak_word_id']." LIMIT 1";
			$wpdb->query($q);

			$ip = $_SERVER['REMOTE_ADDR'];
			$ref = base64_encode($_SERVER['HTTP_REFERER']);
			$now = time();
			$today = strtotime('Today', $now);
			$q = "INSERT INTO ".$wpdb->prefix."cloak_word_clicks (cloak_word_id, user_ip, keyword, http_referer, insert_time, today_time) VALUES (".$qss['cloak_word_id'].", '$ip', '$keyword', '$ref' , $now, $today)";
			$wpdb->query($q);
			//header('Location: '.$qss->url_cloak, true);
			$digg_bar = false;
			if ($qss['digg_bar_text'] != '') {
				$digg_bar = true;
			}
			$frame_height = 100;
			if ($digg_bar) {
				$frame_height = 96;
			}
			?><html>
<head>
	<title><?php echo get_bloginfo('name') ; ?> - Visit Link</title>
	<meta name="robots" content="noindex,nofollow" />
	<style type="text/css">
	a {
		color:#FF0000;
		font-weight:900;
	}
	body {
		background-color:#FFFFFF;
		margin:0;
		padding:0;
	}
	</style>
</head>
<?php if ($digg_bar) : ?>
	<frameset cols="*" rows="60,*" framespacing="0" border="0" frameborder="0" border="0">
		<frame src="<?php echo get_bloginfo('url') ; ?>/linkcloakergo-<?php echo $qss['cloak_word_id']; ?>/" name="nav" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" border="no" /> 
		<frame src="<?php echo $qss['url_cloak']; ?>" name="nav2" scrolling="yes" frameborder="0" marginwidth="0" marginheight="0" border="no" /> 
	</frameset>
	<body>
	</body>
<?php else : ?>
	<body>
		<iframe src="<?php echo $qss['url_cloak']; ?>" height="<?php echo $frame_height; ?>%" frameborder="0" scrolling="yes" style="width:100%"></iframe>
		<noframes>
			Your browser does not support frame. <a href="<?php echo $qss['url_cloak']; ?>" rel="external nofollow">Click here to proceed</a>.
		</noframes>
	</body>
<?php endif; ?>
</html><?php
			exit();
		}
	}
}

if (preg_match('/\/linkcloakergo\-([0-9]+)\//i', $url, $match)) {
	$id = intval($match[1]);
	$qs = "SELECT cloak_word_id, keyword, url_cloak, digg_bar_text, digg_bar_link FROM ".$wpdb->prefix."cloak_word WHERE cloak_word_id = $id LIMIT 1";
	$qss = $wpdb->get_results($qs, ARRAY_A);
	if ($qss != array()) {
		$qss = $qss[0];
		$title = 'Digg Bar';
		$digg_bar_text = $qss['digg_bar_text'];
		$digg_bar_link = $qss['digg_bar_link'];
		$url_cloak = $qss['url_cloak'];
		require_once(dirname(__FILE__).'/digg_bar_template.php');
	} else {
		echo 'Link cloaker not found.';
	}
	exit();
}

if(is_admin()) :
	linkcloaker_activate();
endif;

//

global $linkcloaker_data;

function linkcloaker_get_database()
{
	global $wpdb,$linkcloaker_data;
	
	$query	= "SELECT * FROM ".$wpdb->prefix."cloak_word";
	$result	= $wpdb->get_results($query,ARRAY_A);
	
	foreach($result as $data) :

		$linkcloaker_data[$data['url_cloak']]	= $data;
		
	endforeach;
}

function linkcloaker_only_link($link,$inside = "Visit Site",$class = NULL) 
{
	global $linkcloaker_data;
	
	if(empty($linkcloaker_data) || sizeof($linkcloaker_data) == 0) { linkcloaker_get_database(); }
	
	
	if(isset($linkcloaker_data[$link])) :
		$new_link	= get_bloginfo('url').'/go/'.$linkcloaker_data[$link]['new_url'];
		
		?><a class="<?php echo $class; ?>" href="<?php echo $new_link; ?>" 
        	 title="<?php echo $linkcloaker_data[$link]['title']; ?>" target="_blank"><?php echo $inside; ?></a><?php
		
		return 0;
	endif;
	
	?><a href="<?php echo $link; ?>" title="" target="_blank"><?php echo $inside; ?></a><?php
	
}



add_action('admin_menu', 'linkcloaker_menu');
add_filter('the_content','linkcloaker_rewrite_content');
add_filter('the_excerpt','linkcloaker_rewrite_content');

?>