Skip to content

Instantly share code, notes, and snippets.

@amarilindra
Created October 18, 2015 07:37
Show Gist options
  • Save amarilindra/d89a0e2b90615e0f0c28 to your computer and use it in GitHub Desktop.
Save amarilindra/d89a0e2b90615e0f0c28 to your computer and use it in GitHub Desktop.
<?php
/*
* License: Copyright (c) 2008 Pawan Agrawal. All rights reserved.
*
* This code is part of commercial software and for your personal use
* only. You are not allowed to resell or distribute this script.
*
*/
/**
* MBPNinjaAffiliate - MaxBlogPress Ninja Affiliate Class
* Holds all the necessary functions and variables
*/
class MBPNinjaAffiliate {
var $naff_path = '';
var $naff_records_per_page = 25;
var $naff_table = 'mbp_ninja_affiliate';
var $naff_options_table = 'mbp_ninja_affiliate_options';
var $naff_referrers_table = 'mbp_ninja_affiliate_referrers';
var $naff_posts_table = 'mbp_ninja_affiliate_posts';
var $naff_comments_table = 'mbp_ninja_affiliate_comments';
var $naff_clicklog_table = 'mbp_ninja_affiliate_clicklog_table'; // analytics - added table
var $naff_date_references_table = 'mbp_ninja_affiliate_date_ref_table'; // analytics - added table
/**
* Constructor.
*/
function MBPNinjaAffiliate() {
}
/**
* Creates a main table
*/
function __naffCreateTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_table . " (
link_id int(11) NOT NULL auto_increment, parent_id int(11),
link_name text, link_dest text NOT NULL,
link_cute text NOT NULL, link_group text,
cloak enum('0','1') NOT NULL, cloak_title varchar(250),
link_raw_clicks int(11) NOT NULL default '0', link_unique_clicks int(11) NOT NULL default '0',
show_in_editor enum('0','1') NOT NULL default '1', link_keywords enum('0','1'),
keywords text, modify_status_txt enum('0','1'),
status_txt_type tinyint(2), status_txt_custom varchar(200),
overwrite_global enum('0','1'), overwrite_in_new_win enum('0','1'),
overwrite_nofollow enum('0','1'), link_expire varchar(20) , alternate_url text, link_note text , link_status enum('0','1') default '1', cookie_prefix varchar(5) NOT NULL DEFAULT 'mbpni',
PRIMARY KEY (`link_id`)
);
";
mysql_query($sql) or die(mysql_error());
return true;
}
return false;
}
/**
* Creates an options table
*/
function __naffCreateOptionsTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_options_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_options_table . " (
option_name varchar(250) NOT NULL,
option_value longtext NOT NULL,
PRIMARY KEY (`option_name`)
);
";
mysql_query($sql);
return true;
}
return false;
}
/**
* Creates a referrers table
*/
function __naffCreateReferrersTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_referrers_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_referrers_table . " (
link_id int(11) NOT NULL,
referrer varchar(250),
ip varchar(150),
ref_date datetime
);
";
mysql_query($sql);
return true;
}
return false;
}
/**
* Creates a posts table
*/
function __naffCreatePostsTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_posts_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_posts_table . " (
naff_post_id int(11) NOT NULL,
naff_post_content longtext,
post_cached_on datetime,
post_cached_version varchar(100),
PRIMARY KEY (`naff_post_id`)
);
";
mysql_query($sql);
return true;
}
return false;
}
/**
* Creates a comments table
*/
function __naffCreateCommentsTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_comments_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_comments_table . " (
naff_comment_id int(11) NOT NULL,
naff_comment_content longtext,
comment_cached_on datetime,
comment_cached_version varchar(100),
PRIMARY KEY (`naff_comment_id`)
);
";
mysql_query($sql);
return true;
}
return false;
}
function __naffCreateClickLogTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_clicklog_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_clicklog_table . " (
link_id int(11) NOT NULL,
date varchar(20),
click_type varchar(3));
";
mysql_query($sql) or die(" Click Log Table " . mysql_error());
return true;
}
return false;
}
function __naffcreateDateReferencesTable() {
$rs = mysql_query("SHOW TABLES LIKE '$this->naff_date_references_table'");
$exists = mysql_fetch_row($rs);
if (!$exists) {
$sql = "CREATE TABLE " . $this->naff_date_references_table . " (date varchar(10));";
mysql_query($sql) or die("Date Reference Table : " . mysql_error());
// Add dates 15 days back
$date = date('Y-m-d');
for ($i = 1; $i <= 15; $i++) {
$converted = date("Y-m-d", strtotime(date("Y-m-d", strtotime($date)) . " +$i day"));
mysql_query("insert into $this->naff_date_references_table values('$converted')");
}
// Add 90 days front
for ($i = 0; $i <= 90; $i++) {
$converted = date("Y-m-d", strtotime(date("Y-m-d", strtotime($date)) . " -$i day"));
mysql_query("insert into $this->naff_date_references_table values('$converted')");
}
return true;
}
return false;
}
/*
*Alter table to change table collation
*/
function __naffalterTable(){
$rs = mysql_query('SELECT T.table_collation, CCSA.character_set_name FROM information_schema.`TABLES` T,
information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = "latin1_swedish_ci"
AND T.table_name = "'.$this->naff_options_table.'"');
$exists = mysql_fetch_row($rs);
if($exists){
mysql_query("ALTER TABLE $this->naff_options_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
mysql_query("ALTER TABLE $this->naff_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
mysql_query("ALTER TABLE $this->naff_referrers_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
mysql_query("ALTER TABLE $this->naff_posts_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
mysql_query("ALTER TABLE $this->naff_comments_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
mysql_query("ALTER TABLE $this->naff_clicklog_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
mysql_query("ALTER TABLE $this->naff_date_references_table CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}
return true;
}
/**
* Adds default options to the options table
*/
function __naffAddDefaultOptions($flag = '') {
if ($flag == 2 && NAFF_VERSION < '1.5.5') {
$naff_options = array("disable_ninja_dropdown" => 0);
foreach ($naff_options as $key => $val) {
$val = $this->__naffFormatString($val);
$sql = "INSERT INTO $this->naff_options_table (option_name,option_value) VALUES ('$key','$val')";
mysql_query($sql);
}
} else {
$naff_default_options = array(
"version" => NAFF_VERSION, "max_repeat_keyword" => '-1', "max_links_per_page" => '-1',
"in_new_win" => 0, "nofollow" => 1, "custom_link_format" => 0, "link_color" => '',
"link_font_family" => '', "link_font_size" => '', "link_bold" => 0, "link_italic" => 0,
"link_underline" => 0, "cache_expire_time" => 24, "disable" => 0, "cache_version" => 0,
"disable_ninja_dropdown" => 0, 'max_links_per_comment' => '-1'
);
foreach ($naff_default_options as $key => $val) {
$val = $this->__naffFormatString($val);
$sql = "INSERT INTO $this->naff_options_table (option_name,option_value) VALUES ('$key','$val')";
mysql_query($sql);
}
}
}
/**
* Alters tables to suit the upgraded version
*/
function __naffAlterTables($db_name) {
$rs1 = mysql_query("SHOW COLUMNS FROM $this->naff_table FROM $db_name LIKE 'link_status'");
if (mysql_num_rows($rs1) <= 0) {
mysql_query("ALTER TABLE $this->naff_table ADD link_status enum('0','1') DEFAULT '1'");
}
$rs2 = mysql_query("SHOW COLUMNS FROM $this->naff_table FROM $db_name LIKE 'link_expire'");
if (mysql_num_rows($rs2) <= 0) {
mysql_query("ALTER TABLE $this->naff_table ADD link_expire varchar(20) ");
}
$rs3 = mysql_query("SHOW COLUMNS FROM $this->naff_table FROM $db_name LIKE 'alternate_url'");
if (mysql_num_rows($rs3) <= 0) {
mysql_query("ALTER TABLE $this->naff_table ADD alternate_url TEXT ");
}
$rs4 = mysql_query("SHOW COLUMNS FROM $this->naff_table FROM $db_name LIKE 'link_note'");
if (mysql_num_rows($rs4) <= 0) {
mysql_query("ALTER TABLE $this->naff_table ADD link_note TEXT ");
}
$rs5 = mysql_query("SHOW COLUMNS FROM $this->naff_table FROM $db_name LIKE 'cookie_prefix'");
if (mysql_num_rows($rs5) <= 0) {
mysql_query("ALTER TABLE $this->naff_table ADD cookie_prefix varchar(5) NOT NULL DEFAULT 'mbpni' ");
}
return true;
}
/**
* Get default options from options table
*/
function __naffGetOptions($option_name = '') {
$sql = "SELECT option_name,option_value FROM $this->naff_options_table";
if (trim($option_name) != '') {
$sql .= " WHERE option_name='$option_name'";
}
$rs = mysql_query($sql);
if ($rs) {
$num_rows = mysql_num_rows($rs);
if ($num_rows > 0) {
while ($row = mysql_fetch_assoc($rs)) {
$this->{$row['option_name']} = $this->__naffReverseFormatString($row['option_value']);
}
}
}
}
/**
* Returns true if ninja link has been added and is active
*/
function __naffHasNinjaLinks() {
$sql = "SELECT link_id FROM $this->naff_table WHERE link_status='1'";
$rs = mysql_query($sql);
if ($rs) {
$num_rows = mysql_num_rows($rs);
if ($num_rows <= 0)
return false;
else
return true;
}
else {
die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
}
}
/**
* Page Header
*/
function __naffHeader() {
$naff_version_chk = $this->naffRecheckData();
if (($naff_version_chk == '') || strtotime(date('Y-m-d H:i:s')) > (strtotime($naff_version_chk['last_checked_on']) + $naff_version_chk['recheck_interval'] * 60 * 60)) {
$update_arr = $this->naffExtractUpdateData();
if (count($update_arr) > 0) {
$latest_version = $update_arr[0];
$recheck_interval = $update_arr[1];
$download_url = $update_arr[2];
$msg_in_plugin = $update_arr[3];
$msg_in_plugin = $update_arr[4];
$upgrade_url = $update_arr[5];
if (NAFF_VERSION < $latest_version) {
$naff_version_check = array('recheck_interval' => $recheck_interval, 'last_checked_on' => date('Y-m-d H:i:s'));
$this->naffRecheckData($naff_version_check);
$msg_in_plugin = str_replace("%latest-version%", $latest_version, $msg_in_plugin);
$msg_in_plugin = str_replace("%plugin-name%", NAFF_NAME, $msg_in_plugin);
$msg_in_plugin = str_replace("%upgrade-url%", $upgrade_url, $msg_in_plugin);
$msg_in_plugin = '<div style="border-bottom:1px solid #CCCCCC;background-color:#FFFEEB;padding:6px;font-size:11px;text-align:center">' . $msg_in_plugin . '</div>';
} else {
$msg_in_plugin = '';
}
}
}
echo '<h2>' . NAFF_NAME . ' ' . NAFF_VERSION . '</h2>';
if (trim($msg_in_plugin) != '' && !isset($_GET['dnl']))
echo $msg_in_plugin;
}
/**
* Page Footer
*/
function __naffFooter() {
echo '<p style="text-align:center;margin-top:3em;"><i>' . NAFF_NAME . ' ' . NAFF_VERSION . ' by <a href="http://www.maxblogpress.com/" target="_blank" style="color:#2D46D6;text-decoration:none;" >MaxBlogPress</a></i></p>';
}
/**
* Stylesheet and javascript
*/
function __naffInit() {
if ($_GET['page'] == NAFF_PATH) {
?>
<style type="text/css">
.naffimg {
border-bottom: none;
text-decoration: none;
}
</style>
<script type="text/javascript">
<!--
function __naffValidateCuteLinkForm(Div,Img) {
var error = '';
var link_name = document.getElementById('naff_link_name');
var link_dest = document.getElementById('naff_link_dest');
var link_cute = document.getElementById('naff_link_cute');
var link_group= document.getElementById('naff_group');
var new_group = document.getElementById('naff_new_group');
var cloak = document.getElementById('naff_cloak');
var clk_title = document.getElementById('naff_cloak_title');
var link_keywords = document.getElementById('naff_link_keywords');
var keywords = document.getElementById('naff_keywords');
var modify_status_txt = document.getElementById('naff_modify_status_txt');
var status_txt_type = document.getElementById('naff_status_txt_type_2');
var status_txt_custom = document.getElementById('naff_status_txt_custom');
if ( link_name.value == '' )
error = '- Link Name Required!\n';
if ( link_dest.value == '' )
error += '- Affiliate/Destination Link Required!\n';
if ( link_cute.value == '' )
error += '- Ninja Link Required!\n';
if ( link_cute.value.indexOf('-') != -1 )
error += '- "-" Not Allowed In Ninja Link!\n';
if ( link_group.value == 'new' && new_group.value == '' )
error += '- Group Name Required!\n';
if ( cloak.checked == true && clk_title.value == '' )
error += '- Cloak Title Required!\n';
if ( link_keywords.checked == true ) {
if ( keywords.value == '' )
error += '- Keywords Required!\n';
if ( modify_status_txt.checked == true && status_txt_type.checked == true && status_txt_custom.value == '' )
error += '- Status Bar Text Required!\n';
}
if ( error != '' ) {
alert(error);
return false;
}
return true;
}
function __naffNewGroupShowHide() {
var link_group = document.getElementById('naff_group');
var new_grp = document.getElementById('new_grp');
if ( link_group.value == "new" ) {
new_grp.style.display = "block";
} else {
new_grp.style.display = "none";
}
}
function __naffShowHideRow(curr, target) {
if ( curr.checked == true ) {
target.style.display = 'block';
} else {
target.style.display = 'none';
}
}
function __naffShowHide(curr, img, path) {
var curr = document.getElementById(curr);
if ( img != '' ) {
var img = document.getElementById(img);
}
var showRow = 'block'
if ( navigator.appName.indexOf('Microsoft') == -1 && curr.tagName == 'TR' ) {
var showRow = 'table-row';
}
if ( curr.style == '' || curr.style.display == 'none' ) {
curr.style.display = showRow;
if ( img != '' ) img.src = path + 'ninja-affiliate-library/images/minus.gif';
} else if ( curr.style != '' || curr.style.display == 'block' || curr.style.display == 'table-row' ) {
curr.style.display = 'none';
if ( img != '' ) img.src = path + 'ninja-affiliate-library/images/plus.gif';
}
}
//-->
</script>
<?php
}
}
/**
* Formats a string
* Adds slashes, converts special characters to HTML entities
* @param string $str
*/
function __naffFormatString($str) {
if (!get_magic_quotes_gpc())
$str = addslashes($str);
$str = htmlspecialchars($str, ENT_QUOTES);
$str = trim($str);
return $str;
}
/**
* Reverse of htmlentities() and addslashes()
* @param string $str
* @param integer $type
*/
function __naffReverseFormatString($str, $type = '') {
$trans_tbl = get_html_translation_table(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
$str = stripslashes($str);
if (!$type)
$str = htmlentities($str);
$str = strtr($str, $trans_tbl);
return $str;
}
/**
* Collects and returns GET vars
* @param string $var
*/
function __naffBuildGetVars($var = '') {
$get_vars = '';
foreach ((array) $_GET as $key => $val) {
if ($key == $var) {
$get_vars = $key . '=' . $val . '&';
break;
} else {
$get_vars .= $key . '=' . $val . '&';
}
}
return $get_vars;
}
/**
* Adds backquotes to tables and db-names in SQL queries.
*/
function __naffBackQuote($a_name) {
if (!empty($a_name) && $a_name != '*') {
if (is_array($a_name)) {
$result = array();
reset($a_name);
while (list($key, $val) = each($a_name))
$result[$key] = '`' . $val . '`';
return $result;
} else {
return '`' . $a_name . '`';
}
} else {
return $a_name;
}
}
/**
* Better addslashes for SQL queries.
*/
function __naffSqlAddSlashes($a_string = '', $is_like = false) {
if ($is_like)
$a_string = str_replace('\\', '\\\\\\\\', $a_string);
else
$a_string = str_replace('\\', '\\\\', $a_string);
return str_replace('\'', '\\\'', $a_string);
}
/**
* Write to the backup file
*/
function __naffWrite($query_line) {
if (@fwrite($this->fp, $query_line) === false) {
$this->err_msg .= '<br>There was an error writing a line to the backup file - ' . $query_line;
}
}
/**
* Creates a backup directory
*/
function __naffIsWritable($dir) {
$naff_bkp_dir = rtrim($dir, '/');
if (is_admin() && !is_dir($naff_bkp_dir)) {
@mkdir($naff_bkp_dir, 0777);
}
if (is_writable($naff_bkp_dir))
return true;
else
return false;
}
/**
* Pagination function
* @param integer $naff_pg Current page number
* @param integer $total_records Total number of records
* @param integer $start_no Record to start at
*/
function __naffPagination($naff_pg, $total_records, $start_no) {
$plugin_pg = ($this->wp_version >= 2.7) ? 'tools.php' : 'edit.php';
$get_vars = $this->__naffBuildGetVars('page');
$records_per_page = $this->naff_records_per_page;
$noof_pages = ceil($total_records / $records_per_page);
$show_pages = '';
$pages_shown = '';
for ($i = 1; $i <= $noof_pages; $i++) {
if ($i == $naff_pg) {
$show_pages .= '&nbsp;<strong>' . $i . '</strong>&nbsp;';
} else {
$show_pages .= '&nbsp;<a href="' . NAFF_SITEURL . '/wp-admin/' . $plugin_pg . '?' . $get_vars . 'naff_pg=' . ($i - 1) . '">' . $i . '</a>&nbsp;';
}
}
?>
<table align="center">
<tr>
<?php if ($naff_pg > 1) {
$pages_shown = 1; ?>
<td>
<a href="<?php echo NAFF_SITEURL; ?>/wp-admin/<?php echo $plugin_pg; ?>?<?php echo $get_vars; ?>naff_pg=<?php echo ($naff_pg - 2); ?>">&laquo; Prev</a>
<?php echo $show_pages; ?>
</td>
<?php } ?>
<?php if ($total_records > $records_per_page && ($total_records - $start_no) >= $records_per_page) { ?>
<td>
<?php if ($pages_shown != 1) echo $show_pages; ?>
<a href="<?php echo NAFF_SITEURL; ?>/wp-admin/<?php echo $plugin_pg; ?>?<?php echo $get_vars; ?>naff_pg=<?php echo $naff_pg; ?>">Next &raquo;</a>
</td>
<?php } ?>
</tr>
</table>
<?php
}
/**
* Generates unique code
*/
function __naffGenerateUniqueCode() {
$microtime = microtime();
$unique_code = substr(md5($microtime), 0, 8);
return $unique_code;
}
/**
* Escapes special characters to suppress their special meaning, for regular expression
*/
function __naffEscapeRegexSpecialChars($string) {
$special_chars = array("[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "/");
foreach ($special_chars as $spchar) {
$string = str_replace($spchar, "\\$spchar", $string);
}
return $string;
}
/**
* Get the microtime
*/
function __naffGetMicroTime() {
list($usec, $sec) = explode(" ", microtime());
return ((float) $usec + (float) $sec);
}
/**
* Get global options. Build keyword array
*/
function __naffBuildKeywordArray($content) {
// If keywords to ninja link option is diabled, return the content as it is
if ($this->disable == 1) {
return $content;
}
if (is_array($this->_naff_kw_links_arr) && count($this->_naff_kw_links_arr) > 0) {
$links_fetched_from_db = 0;
$this->naff_kw_links_arr = $this->_naff_kw_links_arr;
} else {
$links_fetched_from_db = 1;
$sql = "SELECT link_id, link_cute, keywords, modify_status_txt, status_txt_type, status_txt_custom, overwrite_global,
overwrite_in_new_win, overwrite_nofollow FROM $this->naff_table WHERE link_keywords='1' AND keywords<>''
AND link_status='1'";
$rs = mysql_query($sql);
if ($rs) {
$num_rows = mysql_num_rows($rs);
if ($num_rows > 0) {
$i = 0;
while ($row = mysql_fetch_assoc($rs)) {
$i++;
// Link properties for each linkid
$this->naff_link_arr[$row['link_id']]['link'] = NAFF_BLOGURL . '/' . $row['link_cute'];
if ($row['modify_status_txt'] == 1) {
if ($row['status_txt_type'] == 2) {
$this->naff_link_arr[$row['link_id']]['status_txt'] = $row['status_txt_custom'];
} else {
$this->naff_link_arr[$row['link_id']]['status_txt'] = '%keyword%'; // replace later while displaying
}
} else {
$this->naff_link_arr[$row['link_id']]['status_txt'] = '';
}
if ($row['overwrite_global'] == 1) {
$this->naff_link_arr[$row['link_id']]['in_new_win'] = $row['overwrite_in_new_win'];
$this->naff_link_arr[$row['link_id']]['nofollow'] = $row['overwrite_nofollow'];
} else {
$this->naff_link_arr[$row['link_id']]['in_new_win'] = $this->in_new_win;
$this->naff_link_arr[$row['link_id']]['nofollow'] = $this->nofollow;
}
// Link style
if ($this->custom_link_format == 1) {
if ($i <= 1) {
if (strlen($this->link_font_family) > 3)
$this->link_style .= 'font-family:' . $this->link_font_family . ';';
if (intval($this->link_font_size) != 0)
$this->link_style .= 'font-size:' . $this->link_font_size . 'px;';
if (strlen($this->link_color) > 3)
$this->link_style .= 'color:' . $this->link_color . ';';
if (strlen($this->link_bold) > 3)
$this->link_style .= 'font-weight:' . $this->link_bold . ';';
if (strlen($this->link_underline) > 3)
$this->link_style .= 'text-decoration:' . $this->link_underline . ';';
if (strlen($this->link_italic) > 3)
$this->link_style .= 'font-style:' . $this->link_italic . ';';
}
} else {
$this->link_style = '';
}
$_keywords = explode("\n", $row['keywords']);
$this->naff_keywords_links[$row['link_id']] = $_keywords;
}
ksort($this->naff_keywords_links);
reset($this->naff_keywords_links); // Sort by link ID
}
} else {
die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
}
// Create array, keyword=>link1,link2,link3...
$this->naff_kw_links_arr = array();
while (count($this->naff_keywords_links) > 0) {
foreach ($this->naff_keywords_links as $link_id => $kw_arr) {
$kw_cnt = count($kw_arr);
$kw_rand = rand(0, $kw_cnt - 1);
$keyword = trim(strtolower($kw_arr[$kw_rand]));
$this->naff_kw_links_arr[$keyword][] = $link_id;
unset($kw_arr[$kw_rand]);
sort($kw_arr);
reset($kw_arr);
$this->naff_keywords_links[$link_id] = $kw_arr;
if (count($this->naff_keywords_links[$link_id]) <= 0)
unset($this->naff_keywords_links[$link_id]);
}
}
}
// Save the original array for reuse. Fetch the links from DB only for first post and use the same for the rest
if ($links_fetched_from_db == 1)
$this->_naff_kw_links_arr = $this->naff_kw_links_arr;
}
/**
* Converts keywords in the text to ninja affiliate link
*/
function __naffAddNinjaAffiliate($content = '', $theID = '', $type = '') {
$this->debug = 0;
$this->show_time_taken = 0; /// For debugging purpose only
if ($this->show_time_taken)
$starttime = $this->__naffGetMicroTime();
// If keywords to ninja link option is diabled, return the content as it is
if ($this->disable == 1) {
return $content;
}
// Check for cache version
if ($type == 'comment') {
$sql = "SELECT naff_comment_content,comment_cached_on FROM $this->naff_comments_table
WHERE naff_comment_id='$theID' AND comment_cached_version>=$this->cache_version
AND DATE_ADD(comment_cached_on, INTERVAL $this->cache_expire_time HOUR) > NOW()";
} else if ($type == 'post') {
$sql = "SELECT naff_post_content,post_cached_on FROM $this->naff_posts_table
WHERE naff_post_id='$theID' AND post_cached_version>=$this->cache_version
AND DATE_ADD(post_cached_on, INTERVAL $this->cache_expire_time HOUR) > NOW()";
}
$rs = mysql_query($sql);
if ($rs) {
$num_rows = mysql_num_rows($rs);
if ($num_rows <= 0) { // Apply Ninja Algorithm to the post and store in ninja table
$update_cache = 1;
//echo "UNCACHED"; ///
} else { // Return the cached version of the post from ninja table
if ($type == 'comment') {
$content = mysql_result($rs, 0, 'naff_comment_content');
} else {
$content = mysql_result($rs, 0, 'naff_post_content');
}
$update_cache = 0;
//echo "CACHED"; ///
return $content;
}
} else {
die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
}
// Get ninja keywords-links array
$this->__naffBuildKeywordArray($content);
// Check for keywords between and within html tags.
// If found replace each with unique code and build array to replace it back to original at the end
$i = 0;
$loop_cnt = 0;
$this->replace_back_arr = array();
foreach ((array) $this->naff_kw_links_arr as $keyword => $links) {
$loop_cnt++;
$reg_keyword = $this->__naffEscapeRegexSpecialChars($keyword);
$kwd_within_tag = '/<([a-z][a-z0-9]*)\s[^>]*(' . $reg_keyword . ')[^>]*>/is';
$kwd_between_anchor_tags = '/<a\s[^>]*>(.*?)<\/a>/is';
$kwd_between_php_tags = '/<\?.*(' . $reg_keyword . ').*\?>/is';
// Check for anchor tags and replace all of them with unique code. Do this one time only.
if ($loop_cnt == 1) {
preg_match_all($kwd_between_anchor_tags, $content, $_matches_between, PREG_PATTERN_ORDER);
foreach ((array) $_matches_between[0] as $key => $val) {
$unique_code = $this->__naffGenerateUniqueCode();
$content = str_replace($val, $unique_code, $content);
$this->replace_back_arr[$unique_code] = $val;
}
}
// Check for keywords within html tag
preg_match_all($kwd_within_tag, $content, $_matches_within, PREG_PATTERN_ORDER);
foreach ((array) $_matches_within[0] as $key => $val) {
$unique_code = $this->__naffGenerateUniqueCode();
$content = str_replace($val, $unique_code, $content);
$this->replace_back_arr[$unique_code] = $val;
}
// Check for keywords within php tag
preg_match_all($kwd_between_php_tags, $content, $_matches_within_php, PREG_PATTERN_ORDER);
foreach ((array) $_matches_within_php[0] as $key => $val) {
$unique_code = $this->__naffGenerateUniqueCode();
$content = str_replace($val, $unique_code, $content);
$this->replace_back_arr[$unique_code] = $val;
}
}
///if ( $this->debug == 1 ) {echo "<br><br> Complete Keyword Array>>><br>";print_r($this->naff_kw_links_arr);}
// Select keyword linking algorithm
if ($type == 'post') {
if ($this->disable_randomization == 1) {
$content = $this->__naffFIFOLinks($content, $this->max_links_per_page);
} else {
$content = $this->__naffRandomizeLinks($content, $this->max_links_per_page);
}
}
if ($type == 'comment') {
if ($this->disable_randomization == 1) {
$content = $this->__naffFIFOLinks($content, $this->max_links_per_comment);
} else {
$content = $this->__naffRandomizeLinks($content, $this->max_links_per_comment);
}
}
// Replace back all the unique codes to their original values
$content = str_replace(array_keys($this->replace_back_arr), array_values($this->replace_back_arr), $content);
// Cache the post content
if ($update_cache == 1) {
if ($type == 'comment') {
$comment_content = addslashes($content);
$query = "INSERT INTO $this->naff_comments_table (naff_comment_id,naff_comment_content,comment_cached_on,comment_cached_version)
VALUES('$theID','$comment_content',NOW(),'$this->cache_version')";
$success = mysql_query($query);
if (!$success) { // If comment_id already exists
$query = "UPDATE $this->naff_comments_table SET
naff_comment_content='$comment_content', comment_cached_on=NOW(), comment_cached_version='$this->cache_version'
WHERE naff_comment_id='$theID'";
mysql_query($query);
}
} else {
$post_content = addslashes($content);
$query = "INSERT INTO $this->naff_posts_table (naff_post_id,naff_post_content,post_cached_on,post_cached_version)
VALUES('$theID','$post_content',NOW(),'$this->cache_version')";
$success = mysql_query($query);
if (!$success) { // If post_id already exists
$query = "UPDATE $this->naff_posts_table SET
naff_post_content='$post_content', post_cached_on=NOW(), post_cached_version='$this->cache_version'
WHERE naff_post_id='$theID'";
mysql_query($query);
}
}
}
if ($this->show_time_taken)
$endtime = $this->__naffGetMicroTime();
if ($this->show_time_taken)
echo '<br><br>Results in ' . number_format(($endtime - $starttime), 2) . ' Sec.';
return $content;
}
/**
* Selects and links ninja keywords on first come first serve basis
*/
function __naffFIFOLinks($content, $maxLinks) {
// Start converting Ninja Keywords to Ninja Links
// Outer loop start
$total_keyword_replaced = 0;
$outer_loop_count = 0;
while (count($this->naff_kw_links_arr) > 0) {
// Exit, if total number of keywords replaced in a page equals or exceeds the maximum per page value set by admin
if ($total_keyword_replaced >= $maxLinks && $maxLinks != -1) {
break;
}
// Exit, if each keyword replaced equals or exceeds the maximum repeat value set by admin
if ($outer_loop_count >= $this->max_repeat_keyword && $this->max_repeat_keyword != -1) {
break;
}
$outer_loop_count++;
// Inner loop start
$inner_loop_count = 0;
if ($this->debug == 1) {
echo "<br><br> Keywords Array >>><br>";
print_r($this->naff_kw_links_arr);
}
foreach ($this->naff_kw_links_arr as $keyword => $links) {
$inner_loop_count++;
$rand_link = $outer_loop_count % count($links);
$link = $this->naff_link_arr[$links[$rand_link]]['link'];
$in_new_win = $this->naff_link_arr[$links[$rand_link]]['in_new_win'];
$nofollow = $this->naff_link_arr[$links[$rand_link]]['nofollow'];
$status_txt = $this->naff_link_arr[$links[$rand_link]]['status_txt'];
if ($in_new_win == 1)
$in_new_win = 'target="_blank"';
else
$in_new_win = '';
if ($nofollow == 1)
$nofollow = 'rel="nofollow"';
else
$nofollow = '';
if (trim($status_txt) == '') {
$status_txt = '';
} else {
$status_txt = str_replace('%keyword%', $keyword, $status_txt);
$status_txt = 'onmouseover="self.status=\'' . $status_txt . '\';return true;" onmouseout="self.status=\'\'"';
}
$reg_keyword = $this->__naffEscapeRegexSpecialChars($keyword);
$reg_keyword = str_replace("&#039;", "'", $reg_keyword);
$pattern = "/\b(" . $reg_keyword . ")\b/is";
$replace = '<a href="' . $link . '" style="' . $this->link_style . '" ' . $in_new_win . ' ' . $nofollow . ' ' . $status_txt . '>\\1</a>';
// If keyword found
if (preg_match($pattern, $content) == true) {
$content = preg_replace($pattern, $replace, $content, 1);
$total_keyword_replaced++;
// Check if keyword is between anchor tags, if so replace with unique code and build array to replace it back at the end
$kwd_between_anchor_tags = '/<a\s[^>]*>(.*?)<\/a>/is';
if (preg_match($kwd_between_anchor_tags, $content, $matches_between) == true) {
if (trim($matches_between[0]) != '') {
$unique_code = $this->__naffGenerateUniqueCode();
$content = str_replace($matches_between[0], $unique_code, $content);
$this->replace_back_arr[$unique_code] = $matches_between[0];
}
}
} else {
// Remove the unused keyword array
unset($this->naff_kw_links_arr[$keyword]);
}
// Exit, if total number of keywords replaced in a post/comment equals or exceeds the maximum per page value set by admin
if ($total_keyword_replaced >= $maxLinks && $maxLinks != -1) {
break;
}
// If the keyword array is empty, remove from the list
if (count($this->naff_kw_links_arr[$keyword]) <= 0) {
unset($this->naff_kw_links_arr[$keyword]);
}
} // Eof inner loop
} // Eof outer loop
return $content;
}
/**
* Selects and links ninja keywords randomly
*/
function __naffRandomizeLinks($content, $maxLinks) {
// Find no. of ninja keywords in a post.
// For exact count this should be after all anchor tags and keyword within tags have been replaced with unique code
$this->noof_kw_in_post = array();
$ninja_keywords_only = array_keys($this->naff_kw_links_arr);
foreach ((array) $ninja_keywords_only as $kw) {
$reg_kw = $this->__naffEscapeRegexSpecialChars($kw);
$reg_kw = str_replace("&#039;", "'", $reg_kw);
$pattern = "/\s(" . $reg_kw . ")\s/is";
if (preg_match_all($pattern, $content, $matches) == true) {
$this->noof_kw_in_post[$kw] = count($matches[0]);
} else {
unset($this->naff_kw_links_arr[$kw]);
}
arsort($this->noof_kw_in_post);
reset($this->noof_kw_in_post);
}
///if ( $this->debug == 1 ) {echo "<br><br> Main Keyword Array for a Post >>><br>";print_r($this->naff_kw_links_arr);}
if ($this->debug == 1) {
echo "<br><br> Noof keywords in post >>><br>";
print_r($this->noof_kw_in_post);
}
// Start converting Ninja Keywords to Ninja Links
// Outer loop start. Loop number of times the unique keyword count
$outer_loop = 0;
foreach ((array) $this->naff_kw_links_arr as $keyword => $links) {
$outer_loop++;
// Find how many times each keyword can be replaced
// If max_links_per_page=5 and noof_unique_keywords=3 then 1st kw can be replaced 2 times, 2nd kw 2 times, 3rd kw 1 time
if ($outer_loop == 1) {
$kw_loop = 0;
$ninja_replace_kw_posb = array();
$ninja_keywords_in_post = array_keys($this->noof_kw_in_post);
if ($maxLinks > 0) {
for ($k = 1; $k <= $maxLinks; $k++) {
if ($kw_loop % count($this->naff_kw_links_arr) == 0)
$kw_loop = 0;
$kw_loop++;
$ninja_replace_kw_posb[$kw_loop]++;
}
foreach ((array) $ninja_replace_kw_posb as $key => $val) {
$ninja_replace_kw_possible[$ninja_keywords_in_post[$key - 1]] = $val;
}
} else {
$ninja_replace_kw_possible = $this->noof_kw_in_post;
}
if ($this->debug == 1) {
echo "<br><br> No. of keywords that can be replaced >>><br>";
print_r($ninja_replace_kw_possible);
}
}
// Inner loop start. Loop number of times the keyword count in a post
$keyword_rand_pos = array();
for ($i = 1; $i <= $this->noof_kw_in_post[$keyword]; $i++) {
if ($i == 1) {
$kw_occurrence_arr = array();
for ($j = 1; $j <= $this->noof_kw_in_post[$keyword]; $j++)
$kw_occurrence_arr[$j] = $j;
// Find actual no. of keywords to be replaced. Don't change the if..else.. order
if ($this->max_repeat_keyword == 0 || $maxLinks == 0)
$noof_entries = 0;
else if ($this->max_repeat_keyword > 0) {
if ((count($kw_occurrence_arr) <= $ninja_replace_kw_possible[$keyword]) && (count($kw_occurrence_arr) <= $this->max_repeat_keyword))
$noof_entries = count($kw_occurrence_arr);
else if (($ninja_replace_kw_possible[$keyword] <= count($kw_occurrence_arr)) && ($ninja_replace_kw_possible[$keyword] <= $this->max_repeat_keyword))
$noof_entries = $ninja_replace_kw_possible[$keyword];
else
$noof_entries = $this->max_repeat_keyword;
} else {
if ((count($kw_occurrence_arr) <= $ninja_replace_kw_possible[$keyword]))
$noof_entries = count($kw_occurrence_arr);
else
$noof_entries = $ninja_replace_kw_possible[$keyword];
}
if (intval($noof_entries) > 0) {
$keyword_rand_pos = array_rand($kw_occurrence_arr, $noof_entries);
}
if (!is_array($keyword_rand_pos))
$keyword_rand_pos = array($keyword_rand_pos);
if ($this->debug == 1) {
echo "<br><br>Total Keywords=" . count($kw_occurrence_arr) . " || Kw replace possible=" . $ninja_replace_kw_possible[$keyword] . " || Actual replace possible=" . $noof_entries;
}
if ($this->debug == 1) {
echo "<br>Random Kwd Position for '$keyword': ";
print_r($keyword_rand_pos);
}
}
$unique_code = $this->__naffGenerateUniqueCode(); // Generate Unique Code
if (in_array($i, (array) $keyword_rand_pos)) { // Convert keyword to ninja link
if ($this->debug == 1) {
echo "<br> Converted >>>>> $i";
}
// Link properties
$rand_link = $i % count($links);
$link = $this->naff_link_arr[$links[$rand_link]]['link'];
$in_new_win = $this->naff_link_arr[$links[$rand_link]]['in_new_win'];
$nofollow = $this->naff_link_arr[$links[$rand_link]]['nofollow'];
$status_txt = $this->naff_link_arr[$links[$rand_link]]['status_txt'];
if ($in_new_win == 1)
$in_new_win = 'target="_blank"';
else
$in_new_win = '';
if ($nofollow == 1)
$nofollow = 'rel="nofollow"';
else
$nofollow = '';
if (trim($status_txt) == '')
$status_txt = $link;
$status_txt = str_replace('%keyword%', $keyword, $status_txt);
$status_txt = 'onmouseover="self.status=\'' . $status_txt . '\';return true;" onmouseout="self.status=\'\'"';
$reg_keyword = $this->__naffEscapeRegexSpecialChars($keyword);
$reg_keyword = str_replace("&#039;", "'", $reg_keyword);
$pattern = "/(" . $reg_keyword . ")/is";
$replace = '<a href="' . $link . '" style="' . $this->link_style . '" ' . $in_new_win . ' ' . $nofollow . ' ' . $status_txt . '>\\1</a>';
$content = preg_replace($pattern, $replace, $content, 1);
// Replace the recent ninja link with unique code and build array to replace it back at the end
$kwd_between_anchor_tags = '/<a\s[^>]*>(.*?)<\/a>/is';
if (preg_match($kwd_between_anchor_tags, $content, $matches_between) == true) {
if (trim($matches_between[0]) != '') {
$content = str_replace($matches_between[0], $unique_code, $content);
$this->replace_back_arr[$unique_code] = $matches_between[0];
}
}
// Remove the replacement position once being replaced
$curr_pos = array_keys($keyword_rand_pos, $i);
unset($keyword_rand_pos[$curr_pos[0]]);
} else { // Replace keyword with unique code without converting to ninja link
if ($this->debug == 1) {
echo"<br>Not Converted == $i";
}
$reg_keyword = $this->__naffEscapeRegexSpecialChars($keyword);
$reg_keyword = str_replace("&#039;", "'", $reg_keyword);
$pattern = "/\b(" . $reg_keyword . ")\b/is";
if (preg_match($pattern, $content, $the_matches) == true) {
$content = preg_replace($pattern, $unique_code, $content, 1);
$this->replace_back_arr[$unique_code] = $the_matches[0];
}
}
// Break the loop if keyword in all the positions has been replaced, and start loop for another kw
if (count($keyword_rand_pos) <= 0)
break;
} // Eof inner loop
} // Eof outer loop
return $content;
}
/**
* Encrypts Page Source
* @param string $txt
*/
function __naffEncrypt($txt) {
for ($i = 0; $i < strlen($txt); $i++) {
$char = substr($txt, $i, 1);
$ascii = ord($char);
$hex .= '%' . dechex($ascii);
}
?>
<script type="text/javascript">
var data = '<?php echo $hex; ?>';
document.write(unescape(data));
</script>
<?php
}
/**
* Redirects ninja link to its destination link
*/
function __naffRedirectTo($link_id, $link_dest, $cloak_it = '', $cloak_title = '', $cookie_prefix) {
$ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$remote_addr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
$referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
if (trim($referrer) == '')
$referrer = 'none';
//if(isset($_COOKIE['NAFF_SET'])) {
$cookie_name = $cookie_prefix . '_' . $link_id;
//}
//die($cookie_name);
$sql_clicks = "UPDATE $this->naff_table SET link_raw_clicks=link_raw_clicks+1";
if (!isset($_COOKIE[$cookie_name])) {
$sql_clicks .= ",link_unique_clicks=link_unique_clicks+1";
}
$sql_clicks .= " WHERE link_id='$link_id'";
mysql_query($sql_clicks) or die(mysql_error());
$sql_referrers = "INSERT INTO $this->naff_referrers_table (link_id,referrer,ip,ref_date)
VALUES('$link_id','$referrer','$ip',NOW())";
mysql_query($sql_referrers);
/*
* Add data to analytics
*/
$date = date('Y-m-d m:h:s');
if (!isset($_COOKIE[$cookie_name])) {
$sql = "insert into $this->naff_clicklog_table Values('$link_id','$date','unq')";
mysql_query($sql);
}
$sql = "insert into $this->naff_clicklog_table Values('$link_id','$date','raw')";
mysql_query($sql);
$url = parse_url(NAFF_BLOGURL);
$a = setcookie($cookie_name, '1', time() + (3600 * 24) * 30, $url['path'] . '/');
if ($cloak_it == 1) {
?>
<script language="JavaScript"><!--
var clk = null;
function __SystemError() {
return true;
}
function __naffST() {
window.status = '<?php echo $cloak_title; ?>';
}
function __naffST2() {
if (clk != null) {
clearInterval(clk);
}
}
window.onerror = __SystemError;
clk = setInterval('__naffST()', 100);
//--></script>
<script language="JavaScript" type="text/javascript">__naffST();</script>
<?php
$the_code .= '<html><head><title>' . $cloak_title . '</title></head>';
$the_code .= '<frameset border="0" framespacing="0" rows="*" frameborder="0" marginbottom="0" marginright="0" margintop="0" marginleft="0">';
$the_code .= '<frame border="0" src="' . $this->__naffcheckUrl($link_dest) . '" frameborder="no" noresize="noresize" onload="__naffST2()" id="frmMain" name="naff">';
$the_code .= '<noframes><body onload=\'document.location="' . $this->__naffcheckUrl($link_dest) . '"\'></body></noframes></frameset></html>';
echo $this->__naffEncrypt($the_code);
exit;
} else {
header("Location: " . $this->__naffcheckUrl($link_dest));
exit;
}
}
/**
* Redirects ninja link to its destination link
*/
function __naffRedirect($request_url, $link_cute, $post_exist) {
$sql = "SELECT link_id,link_dest,link_expire,alternate_url,cloak,cloak_title,cookie_prefix FROM $this->naff_table WHERE link_cute='$link_cute'";
$rs = mysql_query($sql) or die(mysql_error());
$rowdata = mysql_fetch_assoc($rs);
$link_id = $rowdata['link_id'];
$link_dest = $rowdata['link_dest'];
$cloak_it = $rowdata['cloak'];
$cloak_title = $rowdata['cloak_title'];
$link_expire = $rowdata['link_expire'];
$alternate_url = $rowdata['alternate_url'];
$expiredate = strtotime($link_expire);
$today = strtotime(date('Y-m-d m:h:s'));
$cookie_prefix = $rowdata['cookie_prefix'];
if ($link_dest) {
if ($expiredate >= $today || $link_expire == '' || !is_int($expiredate))
$this->__naffRedirectTo($link_id, $link_dest, $cloak_it, $cloak_title, $cookie_prefix);
elseif ($expiredate <= $today && $alternate_url != '')
$this->__naffRedirectTo($link_id, $alternate_url, $cloak_it, $cloak_title, $cookie_prefix);
else {
$sql = "UPDATE $this->naff_table SET link_status='0' WHERE link_id='$link_id'";
mysql_query($sql) or die(mysql_error());
header("location:$request_url");
}
} else if (strpos($_SERVER['REQUEST_URI'], '-') !== false ) { // Create subcampaign
$link_portions = explode('-', $link_cute);
$link_parent = trim($link_portions[0]);
$link_child = trim($link_portions[1]);
$link_cute = $link_parent . '-' . $link_child;
$sql = "SELECT * FROM $this->naff_table WHERE link_cute='$link_parent' AND parent_id=0";
$rs = mysql_query($sql);
$rowdata = mysql_fetch_assoc($rs);
$link_id = $rowdata['link_id'];
$parent_id = $rowdata['parent_id'];
$link_name = $rowdata['link_name'] . ' ' . $link_child;
$link_dest = $rowdata['link_dest'];
$link_expire = $rowdata['link_expire'];
$alternate_dest = $rowdata['alternate_dest'];
$link_note = $rowdata['link_note'];
$link_group = $rowdata['link_group'];
$cloak = $rowdata['cloak'];
$cloak_title = $rowdata['cloak_title'];
$link_keywords = $rowdata['link_keywords'];
$keywords = $rowdata['keywords'];
$modify_status_txt = $rowdata['modify_status_txt'];
$status_txt_type = $rowdata['status_txt_type'];
$status_txt_custom = $rowdata['status_txt_custom'];
$overwrite_global = $rowdata['overwrite_global'];
$overwrite_in_new_win = $rowdata['overwrite_in_new_win'];
$overwrite_nofollow = $rowdata['overwrite_nofollow'];
$cloak_it = $cloak;
$cookie_prefix = $rowdata['cookie_prefix'];
if ($link_id > 0) {
$sql_chk = "SELECT link_id FROM $this->naff_table WHERE link_cute='$link_cute' AND parent_id<>0";
$rs_chk = mysql_query($sql_chk) or die(mysql_error());
$exists = mysql_num_rows($rs_chk);
if (!$exists && !$post_exist && current_user_can( 'manage_options' )) { // to insure only admin can create subcampaign
$sql = "INSERT INTO $this->naff_table (parent_id, link_name, link_dest, link_cute, link_group, cloak, cloak_title,
link_keywords, keywords, modify_status_txt, status_txt_type, status_txt_custom,
overwrite_global, overwrite_in_new_win, overwrite_nofollow,link_expire,alternate_url,link_note)
VALUES ('$link_id', '$link_name', '$link_dest', '$link_cute', '$link_group', '$cloak', '$cloak_title',
'$link_keywords', '$keywords', '$modify_status_txt', '$status_txt_type', '$status_txt_custom',
'$overwrite_global', '$overwrite_in_new_win', '$overwrite_nofollow','$link_expire','$alternate_dest','$link_note')";
$rs = mysql_query($sql) or die(mysql_error());
$link_id = mysql_insert_id();
if ($link_dest != '') {
$this->__naffRedirectTo($link_id, $link_dest, $cloak_it, $cloak_title, $cookie_prefix);
}
}else {
if (!$exists && !$post_exist && $link_dest != '') {
$this->__naffRedirectTo($link_id, $link_dest, $cloak_it, $cloak_title, $cookie_prefix);
}
}
}
}
}
/**
* Extracts all the group names
* @param string $group_name
*/
function __naffGetGroups($group_name = '', $dropdown = 1) {
$groups = array();
$naff_new_group = (isset($_POST['naff']['new_group'])) ? $_POST['naff']['new_group'] : '';
$sql = "SELECT distinct link_group FROM $this->naff_table WHERE link_group<>'none' ORDER BY link_group ASC";
$rs = mysql_query($sql) or die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
while ($row = mysql_fetch_assoc($rs)) {
$groups[] = $row['link_group'];
}
if (!$dropdown)
return $groups; // If groups aren't to be shown in dropdown box
$new_sel = '';
$new_grp_show = 'none';
if ($group_name == 'new') {
$new_sel = 'selected';
$new_grp_show = 'block';
}
$the_groups = '
<select name="naff[link_group]" style="width:200px;" id="naff_group" onChange="__naffNewGroupShowHide()">
<option value="none" selected>None</option>
<option value="new" ' . $new_sel . '>*New</option>';
foreach ((array) $groups as $grp) {
if (trim($grp) == trim($group_name))
$_selected = ' selected';
else
$_selected = '';
$the_groups .= "<option value='$grp' $_selected>$grp</option>";
}
$the_groups .= '
</select>
<div id="new_grp" style="display:' . $new_grp_show . '"><input type="text" name="naff[new_group]" id="naff_new_group" value="' . stripslashes(htmlspecialchars($naff_new_group)) . '" size="15" /></div>';
return $the_groups;
}
/**
* Increse the global cache value
*/
function __naffIncreaseCacheVersion() {
$sql_inc = "UPDATE $this->naff_options_table SET option_value=option_value+1 WHERE option_name='cache_version'";
mysql_query($sql_inc);
}
/**
* Carries out all the operations
*/
function __naffManagePg() {
$naff_post_data = isset($_POST['naff']) ? $_POST['naff'] : '';
$action = isset($_GET['naff']) ? $_GET['naff'] : '';
$naff_id = isset($_GET['naffID']) ? $_GET['naffID'] : '';
$msg = '';
if (isset($naff_post_data['fast_action_go'])) {
$action_type = $naff_post_data['fast_action_type'];
$id_arr = $naff_post_data['fast_action'];
if (count($id_arr) > 0) {
$ids = implode(',', $id_arr);
if ($action_type == 'enable') {
$sql = "UPDATE $this->naff_table SET link_status='1' WHERE link_id IN ($ids)";
mysql_query($sql);
$msg = 'Selected Links have been enabled';
} else if ($action_type == 'disable') {
$sql = "UPDATE $this->naff_table SET link_status='0' WHERE link_id IN ($ids)";
mysql_query($sql);
$msg = 'Selected Links have been disabled';
} else if ($action_type == 'delete') {
$this->naffConfirmDeletion($ids);
exit;
} else if ($action_type == 'reset') {
foreach ($id_arr as $naff_id) {
$cookie_prefix = substr(md5(microtime()), rand(0, 26), 5);
$sql_1 = "UPDATE $this->naff_table SET link_raw_clicks=0, link_unique_clicks=0 , cookie_prefix='$cookie_prefix' WHERE link_id='$naff_id'";
$sql_2 = "DELETE FROM $this->naff_referrers_table WHERE link_id='$naff_id'";
$sql_3 = "DELETE from $this->naff_clicklog_table WHERE link_id='$naff_id'";
mysql_query($sql_1) or die(mysql_error());
mysql_query($sql_2);
mysql_query($sql_3) or die(mysql_error());
$msg = 'Clicks Reset!';
}
}
}
$this->__naffIncreaseCacheVersion(); // Increment global cache value
return $msg;
} else if (isset($naff_post_data['linkIDs'])) {
$ids = $naff_post_data['linkIDs'];
if ($naff_post_data['delete_yes']) {
$sql_1 = "DELETE FROM $this->naff_table WHERE link_id IN ($ids)";
$sql_2 = "DELETE FROM $this->naff_table WHERE parent_id IN ($ids)";
$sql_3 = "DELETE FROM $this->naff_clicklog_table where link_id IN ($ids)";
mysql_query($sql_1);
mysql_query($sql_2);
mysql_query($sql_3) or die(mysql_error());
$msg = 'Selected Links have been deleted';
}
return $msg;
} else if (isset($_POST['naff_get_stats']) || isset($_POST['naff_search'])) {
return;
}
if (isset($naff_post_data['update_options']) || isset($naff_post_data['save_tbs'])) {
$options['max_repeat_keyword'] = $naff_post_data['max_repeat_keyword'];
$options['max_links_per_page'] = $naff_post_data['max_links_per_page'];
$options['in_new_win'] = isset($naff_post_data['in_new_win']) ? intval($naff_post_data['in_new_win']) : 0;
$options['nofollow'] = isset($naff_post_data['nofollow']) ? intval($naff_post_data['nofollow']) : 0;
$options['custom_link_format'] = isset($naff_post_data['custom_link_format']) ? intval($naff_post_data['custom_link_format']) : 0;
$options['link_color'] = $naff_post_data['link_color'];
$options['link_font_family'] = $naff_post_data['link_font_family'];
$options['link_font_size'] = $naff_post_data['link_font_size'];
$options['link_bold'] = (isset($naff_post_data['link_bold'])) ? $naff_post_data['link_bold'] : '';
$options['link_italic'] = (isset($naff_post_data['link_italic'])) ? $naff_post_data['link_italic'] : '';
$options['link_underline'] = (isset($naff_post_data['link_underline'])) ? $naff_post_data['link_underline'] : '';
$options['cache_expire_time'] = $naff_post_data['cache_expire_time'];
$options['disable'] = isset($naff_post_data['disable']) ? intval($naff_post_data['disable']) : 0;
$options['disable_ninja_dropdown'] = (isset($naff_post_data['disable_ninja_dropdown'])) ? $naff_post_data['disable_ninja_dropdown'] : '';
$options['disable_randomization'] = isset($naff_post_data['disable_randomization']) ? intval($naff_post_data['disable_randomization']) : 0;
$options['exclude_pages'] = isset($naff_post_data['exclude_pages']) ? intval($naff_post_data['exclude_pages']) : 0;
$options['exclude_categories'] = isset($naff_post_data['exclude_categories']) ? intval($naff_post_data['exclude_categories']) : 0;
$options['max_links_per_comment'] = $naff_post_data['max_links_per_comment'];
if ($options['link_color'] == '')
$options['link_color'] = 0;
if (isset($naff_post_data['exclude_cat'])) {
foreach ((array) $naff_post_data['exclude_cat'] as $key => $cat) {
if ($key == 0)
$excluded_categories = ',';
$excluded_categories .= $cat . ',';
}
}
$options['excluded_categories'] = $excluded_categories;
if (isset($options)) {
foreach ((array) $options as $key => $val) {
$sql = "UPDATE $this->naff_options_table SET option_value='$val' WHERE option_name='$key'";
$rs = mysql_query($sql);
if (mysql_affected_rows() <= 0) {
$sql = "INSERT INTO $this->naff_options_table (option_name,option_value) VALUES ('$key','$val')";
mysql_query($sql);
}
}
}
$this->__naffIncreaseCacheVersion(); // Increment global cache value
$msg = 'Options Saved.';
return $msg;
}
if (isset($naff_post_data['backup'])) { // Backup ninja affiliate tables
$filename = 'ninja_' . substr(md5(microtime()), -5) . date('YmdHis') . '.sql';
if ($this->__naffIsWritable(NAFF_BACKUP_DIR)) {
$this->fp = @fopen(NAFF_BACKUP_DIR . $filename, 'w');
if ($this->fp) {
// Begin new backup of Ninja Affiliate Tables
$this->__naffWrite("# " . 'WordPress MySQL database backup' . "\n");
$this->__naffWrite("#\n");
$this->__naffWrite("# " . sprintf('Generated: %s', date("l j. F Y H:i T")) . "\n");
$this->__naffWrite("# " . sprintf('Hostname: %s', DB_HOST) . "\n");
$this->__naffWrite("# " . sprintf('Database: %s', $this->__naffBackQuote(DB_NAME)) . "\n");
$this->__naffWrite("# --------------------------------------------------------\n");
foreach ($this->naff_bkp_tables as $table) {
if (!ini_get('safe_mode'))
@set_time_limit(15 * 60);
$this->__naffWrite("# --------------------------------------------------------\n");
$this->__naffWrite("# " . sprintf('Table: %s', $this->__naffBackQuote($table)) . "\n");
$this->__naffWrite("# --------------------------------------------------------\n");
$ret = $this->naffBackupTable($table);
}
} else {
$msg = 'Could not open the backup file for writing. ';
}
if ($ret == true) {
$file = NAFF_SITEURL . '/wp-content/' . basename(trim(NAFF_BACKUP_DIR, '/')) . '/' . $filename;
$msg = 'Ninja Affiliate Tables Backup Successful.<br><br>';
$msg .= '<a href="' . NAFF_SITEURL . '/wp-content/' . basename(trim(NAFF_BACKUP_DIR, '/')) . '/' . $filename . '" style="padding:2px 12px 2px 12px;background-color:#FFFEE8;border:1px solid #c9c9c9;">Click Here To Download</a> &nbsp;&nbsp;';
///$msg .= '<a href="'.NAFF_FULLPATH.'ninja-affiliate-library/include/dnl.php?f='.urlencode($file).'" style="padding:2px 12px 2px 12px;background-color:#FFFEE8;border:1px solid #c9c9c9;">Click Here To Download</a>';
} else {
$msg1 = $msg . $this->err_msg . '<br>';
$msg = $msg1 . 'Ninja Affiliate Tables Backup fail.';
}
} else {
$msg = 'The backup directory is not writeable. Please check the permissions for writing to your backup directory and try again.';
}
@fclose($this->fp);
return $msg;
}
if (isset($naff_post_data['restore'])) { // Restore ninja affiliate tables
$sql_dump_file = $_FILES['restore_file']['tmp_name'];
$ret = $this->naffRestoreTable($sql_dump_file);
if ($ret == true) {
mysql_query("DELETE FROM $this->naff_posts_table");
mysql_query("DELETE FROM $this->naff_comments_table");
$msg = 'Ninja Affiliate Tables Restored successfully.';
} else {
$msg = 'Ninja Affiliate Tables Restore failed.';
}
return $msg;
}
if (isset($naff_post_data['addedit_link'])) {
$link_name = $this->__naffFormatString($naff_post_data['link_name']);
$parent_id = intval($naff_post_data['parent_id']);
$link_dest = $naff_post_data['link_dest'];
$link_expire = $naff_post_data['link_expire'];
$alternate_url = $naff_post_data['alternate_url'];
$link_note = $naff_post_data['link_note'];
$link_cute = $this->__naffFormatString(ltrim($naff_post_data['link_cute'], '/'));
$link_group = $this->__naffFormatString($naff_post_data['link_group']);
$new_group = $this->__naffFormatString($naff_post_data['new_group']);
$cloak = isset($naff_post_data['cloak']) ? intval($naff_post_data['cloak']) : 0;
$cloak_title = $this->__naffFormatString($naff_post_data['cloak_title']);
$unique_clicks = isset($naff_post_data['unique_clicks']) ? intval($naff_post_data['unique_clicks']) : 0;
$raw_clicks = isset($naff_post_data['raw_clicks']) ? intval($naff_post_data['raw_clicks']) : 0;
$show_in_editor = isset($naff_post_data['show_in_editor']) ? intval($naff_post_data['show_in_editor']) : 0;
$link_keywords = isset($naff_post_data['link_keywords']) ? intval($naff_post_data['link_keywords']) : 0;
$keywords = $this->__naffFormatString($naff_post_data['keywords']);
$modify_status_txt = isset($naff_post_data['modify_status_txt']) ? intval($naff_post_data['modify_status_txt']) : 0;
$status_txt_type = isset($naff_post_data['status_txt_type']) ? intval($naff_post_data['status_txt_type']) : 0;
$status_txt_custom = $this->__naffFormatString($naff_post_data['status_txt_custom']);
$overwrite_global = isset($naff_post_data['overwrite_global']) ? intval($naff_post_data['overwrite_global']) : 0;
$overwrite_in_new_win = isset($naff_post_data['overwrite_in_new_win']) ? intval($naff_post_data['overwrite_in_new_win']) : 0;
$overwrite_nofollow = isset($naff_post_data['overwrite_nofollow']) ? intval($naff_post_data['overwrite_nofollow']) : 0;
if ($parent_id > 0) {
$link_cute = $naff_post_data['parent_link'] . $link_cute;
}
if ($link_group == 'new' && trim($new_group) != '') {
$link_group = $new_group;
}
$cloak == 1 ? $cloak = 1 : $cloak = 0;
$keywords = $this->__naffRemoveEmptyLines($keywords);
if (intval($naff_post_data['ID']) > 0 && ($naff_post_data['do_action'] == 'edit' || $naff_post_data['do_action'] == 'editsub')) { //edit
$action_taken = "edited";
$id = $naff_post_data['ID'];
// $sql = "UPDATE $this->naff_table SET parent_id='$parent_id', link_name='$link_name', link_dest='$link_dest', link_cute='$link_cute',
// link_unique_clicks='$unique_clicks', link_raw_clicks='$raw_clicks', link_group='$link_group',
// cloak='$cloak', cloak_title='$cloak_title', show_in_editor='$show_in_editor',
// link_keywords='$link_keywords', keywords='$keywords', modify_status_txt='$modify_status_txt',
// status_txt_type='$status_txt_type', status_txt_custom='$status_txt_custom', overwrite_global='$overwrite_global',
// overwrite_in_new_win='$overwrite_in_new_win', overwrite_nofollow='$overwrite_nofollow' ,link_expire ='$link_expire',alternate_url='$alternate_url'
// WHERE link_id='$id'";
$sql = "UPDATE $this->naff_table SET parent_id='$parent_id', link_name='$link_name', link_dest='$link_dest', link_cute='$link_cute',
link_group='$link_group',
cloak='$cloak', cloak_title='$cloak_title', show_in_editor='$show_in_editor',
link_keywords='$link_keywords', keywords='$keywords', modify_status_txt='$modify_status_txt',
status_txt_type='$status_txt_type', status_txt_custom='$status_txt_custom', overwrite_global='$overwrite_global',
overwrite_in_new_win='$overwrite_in_new_win', overwrite_nofollow='$overwrite_nofollow' ,link_expire ='$link_expire',alternate_url='$alternate_url',link_note='$link_note'
WHERE link_id='$id'";
} else { //add
$action_taken = "added";
$id = '';
$sql = "INSERT INTO $this->naff_table (parent_id, link_name, link_dest, link_cute, link_group, cloak, cloak_title,
link_keywords, keywords, modify_status_txt, status_txt_type, status_txt_custom,
overwrite_global, overwrite_in_new_win, overwrite_nofollow,link_expire,alternate_url,link_note)
VALUES ('$parent_id', '$link_name', '$link_dest', '$link_cute', '$link_group', '$cloak', '$cloak_title',
'$link_keywords', '$keywords', '$modify_status_txt', '$status_txt_type', '$status_txt_custom',
'$overwrite_global', '$overwrite_in_new_win', '$overwrite_nofollow','$link_expire','$alternate_url','$link_note')";
}
$sql_chk = "SELECT link_id FROM $this->naff_table WHERE (link_name='$link_name' OR link_cute='$link_cute')";
if (intval($naff_post_data['ID']) > 0) {
$sql_chk .= " AND link_id<>'$id'";
}
$rs_chk = mysql_query($sql_chk);
if ($rs_chk) {
$already_exists = mysql_num_rows($rs_chk);
if (!$already_exists) {
$this->__naffIncreaseCacheVersion(); // Increment global cache value
mysql_query($sql);
$msg = 'Link has been ' . $action_taken . '.<br>Use this ninja link for "' . $link_name . '": (Right click and copy the link)<br><a href="' . NAFF_BLOGURL . '/' . $link_cute . '">' . NAFF_BLOGURL . '/' . $link_cute . '</a>';
return $msg;
} else {
$msg = 'Duplicate "Link Name" and/or "Ninja Link"';
}
} else {
die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
}
}
if ($action == 'opt') {
$this->naffOptionsPg($msg);
exit;
} else if ($action == 'bkp') {
$this->naffBackupAndRestorePg($msg);
exit;
} else if ($action == 'addsub' && $naff_id != '') {
$this->naffAddEditLink($msg);
exit;
} else if ($action == 'add' || (($action == 'edit' || $action == 'editsub') && $naff_id != '')) {
$this->naffAddEditLink($msg);
exit;
} elseif ($action == 'detail' && $naff_id != '') {
$this->naffDetailInfo($naff_id);
exit;
} else if ($action == 'delete') {
$sql_1 = "DELETE FROM $this->naff_table WHERE link_id='$naff_id'";
$sql_2 = "DELETE FROM $this->naff_table WHERE parent_id='$naff_id'";
$sql_3 = "DELETE FROM $this->naff_referrers_table WHERE link_id='$naff_id'";
$sql_4 = "delete from $this->naff_clicklog_table where link_id='$naff_id'";
mysql_query($sql_1);
mysql_query($sql_2);
mysql_query($sql_3);
mysql_query($sql_4);
$msg = 'Link Deleted!';
return $msg;
} else if ($action == 'reset') {
$cookie_prefix = substr(md5(microtime()), rand(0, 26), 5);
$sql_1 = "UPDATE $this->naff_table SET link_raw_clicks=0, link_unique_clicks=0 , cookie_prefix='$cookie_prefix' WHERE link_id='$naff_id'";
$sql_2 = "DELETE FROM $this->naff_referrers_table WHERE link_id='$naff_id'";
$sql_3 = "Delete from $this->naff_clicklog_table where link_id='$naff_id'";
mysql_query($sql_1);
mysql_query($sql_2);
mysql_query($sql_3);
$msg = 'Clicks Reset!';
return $msg;
} else if ($action == 'referrers') {
$this->naffLinkReferrers($naff_id);
exit;
} else if ($action == 'analytics') { //Analytics
$this->naffAnalyticsPg();
exit;
}
}
/**
* Delete confirmation
*/
function __naffConfirmDeletion($ids = '') {
$this->__naffHeader();
echo '<p><form name="naffDelForm" method="post" action=""><br>';
echo '<strong>All the selected links will be deleted. Are you sure?</strong> &nbsp;';
echo '<input type="hidden" name="naff[linkIDs]" value="' . $ids . '">';
echo '<input type="submit" name="naff[delete_yes]" value="Yes"> &nbsp;';
echo '<input type="submit" name="naff[delete_no]" value="&nbsp;No&nbsp;">';
echo '</form></p>';
$this->__naffFooter();
}
/**
* Displays referrer data
* @param integer $naff_id Link ID
*/
function __naffLinkReferrers($naff_id) {
$get_vars = $this->__naffBuildGetVars('page');
$sql = "SELECT link_name FROM $this->naff_table WHERE link_id='$naff_id'";
$rs = mysql_query($sql);
$link_name = mysql_result($rs, 0, 'link_name');
$sql = "SELECT referrer,count(referrer) AS RefCount FROM $this->naff_referrers_table
WHERE link_id='$naff_id' GROUP BY referrer ORDER BY RefCount DESC";
$rs = mysql_query($sql) or die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
$num_rows = mysql_num_rows($rs);
$this->__naffHeader();
require_once('form-referrers.php');
$this->__naffFooter();
}
/**
* Displays ninja link's detail and edit page
* @param integer $naff_id Link ID
* @param string $action
*/
function __naffDetailInfo($naff_id) {
$msg = '';
$naff_post_data = isset($_POST['naff']) ? $_POST['naff'] : '';
$get_vars = $this->__naffBuildGetVars('page');
$sql = "SELECT * FROM $this->naff_table WHERE link_id='$naff_id'";
$rs = mysql_query($sql);
if ($rs) {
$rowdata = mysql_fetch_assoc($rs);
$link_name = $this->__naffReverseFormatString($rowdata['link_name']);
$link_dest = $this->__naffReverseFormatString($rowdata['link_dest']);
$link_expire = $this->__naffReverseFormatString($rowdata['link_expire']);
$alternate_url = $this->__naffReverseFormatString($rowdata['alternate_url']);
$link_note = $this->__naffReverseFormatString($rowdata['link_note']);
$link_cute = $this->__naffReverseFormatString($rowdata['link_cute']);
$link_group = $this->__naffReverseFormatString($rowdata['link_group']);
$cloak = $rowdata['cloak'];
$cloak_title = $this->__naffReverseFormatString($rowdata['cloak_title']);
$link_raw_clicks = $rowdata['link_raw_clicks'];
$link_unique_clicks = $rowdata['link_unique_clicks'];
$show_in_editor = $rowdata['show_in_editor'];
$link_keywords = $rowdata['link_keywords'];
$keywords = $this->__naffReverseFormatString($rowdata['keywords']);
$modify_status_txt = $rowdata['modify_status_txt'];
$status_txt_type = $rowdata['status_txt_type'];
$status_txt_custom = $this->__naffReverseFormatString($rowdata['status_txt_custom']);
$overwrite_global = $rowdata['overwrite_global'];
$overwrite_in_new_win = $rowdata['overwrite_in_new_win'];
$overwrite_nofollow = $rowdata['overwrite_nofollow'];
$link_dest = '<a href="' . $link_dest . '" target="_blank">' . $link_dest . '</a>';
$link_cute = '<a href="' . NAFF_BLOGURL . '/' . $link_cute . '" target="_blank">' . NAFF_BLOGURL . '/' . $link_cute . '</a>';
}
if ($overwrite_global != 1) {
$overwrite_in_new_win = ($this->in_new_win == 1) ? 'Yes' : 'No';
$overwrite_nofollow = ($this->nofollow == 1) ? 'Yes' : 'No';
} else {
$overwrite_in_new_win = ($overwrite_in_new_win == 1) ? 'Yes' : 'No';
$overwrite_nofollow = ($overwrite_nofollow == 1) ? 'Yes' : 'No';
}
$show_in_editor = ($show_in_editor == 1) ? 'Yes' : 'No';
$link_keywords = ($link_keywords == 1) ? 'Yes' : 'No';
$modify_status_txt = ($modify_status_txt == 1) ? 'Yes' : 'No';
$overwrite_global = ($overwrite_global == 1) ? 'Yes' : 'No';
if ($status_txt_type == 2 && $status_txt_custom != '') {
$status_txt_custom_disp = '<strong>Custom Text:</strong> ' . $status_txt_custom;
} else {
$status_txt_custom_disp = '';
}
$this->__naffHeader();
require_once('form-detail.php');
$this->__naffFooter();
}
/**
* Adds/Edits Link
*/
function __naffAddEditLink() {
$rowdata = array();
$naff_id = isset($_GET['naffID']) ? $_GET['naffID'] : '';
$action = isset($_GET['naff']) ? $_GET['naff'] : '';
$naff_post_data = isset($_POST['naff']) ? $_POST['naff'] : '';
$show_in_editor_tooltip = "If you uncheck it then the link will not appear in the drop down box of write post page";
$get_vars = $this->__naffBuildGetVars('page');
$addedit_title = "Add New Link";
$addedit_action = "Add Link";
$parent_id = 0;
$parent_link = '';
$cloak_chk = '';
$link_keywords_chk = '';
$modify_status_txt_chk = '';
$status_txt_type_1_chk = '';
$status_txt_type_2_chk = '';
$overwrite_global_chk = '';
$in_new_win_chk = '';
$nofollow_chk = '';
$cloak_show = 'none';
$link_keywords_show = 'none';
$modify_status_txt_show = 'none';
$status_txt_custom_show = 'none';
$overwrite_global_show = 'none';
//
$cloak = '';
$cloak_title = '';
$link_keywords = '';
$modify_status_txt = '';
$status_txt_type = '';
$overwrite_global = '';
$status_txt_type = '';
$overwrite_in_new_win = '';
$overwrite_nofollow = '';
$show_in_editor = '';
$link_name = '';
$link_dest = '';
$link_cute = '';
$link_group = '';
$keywords = '';
$status_txt_custom = '';
//
if (isset($naff_post_data['addedit_link'])) { // if duplicate
$parent_link = $naff_post_data['parent_link'];
$link_name = stripslashes(htmlspecialchars($naff_post_data['link_name']));
$link_dest = stripslashes(htmlspecialchars($naff_post_data['link_dest']));
$link_expire = stripslashes(htmlspecialchars($naff_post_data['link_expire']));
$link_cute = stripslashes(htmlspecialchars($naff_post_data['link_cute']));
$link_group = stripslashes($naff_post_data['link_group']);
$new_group = stripslashes(htmlspecialchars($naff_post_data['new_group']));
$cloak = stripslashes($naff_post_data['cloak']);
$cloak_title = stripslashes(htmlspecialchars($naff_post_data['cloak_title']));
$link_keywords = stripslashes($naff_post_data['link_keywords']);
$keywords = stripslashes(htmlspecialchars($naff_post_data['keywords']));
$modify_status_txt = stripslashes($naff_post_data['modify_status_txt']);
$status_txt_type = stripslashes($naff_post_data['status_txt_type']);
$status_txt_custom = stripslashes(htmlspecialchars($naff_post_data['status_txt_custom']));
$overwrite_global = stripslashes($naff_post_data['overwrite_global']);
$overwrite_in_new_win = stripslashes($naff_post_data['overwrite_in_new_win']);
$overwrite_nofollow = stripslashes($naff_post_data['overwrite_nofollow']);
} else if (($action == 'edit' || $action == 'editsub' || $action == 'addsub') && $naff_id != '') {
$addedit_title = "Edit Link";
$addedit_action = "Save Link";
$sql = "SELECT * FROM $this->naff_table WHERE link_id='$naff_id'";
$rs = mysql_query($sql);
if ($rs) {
$rowdata = mysql_fetch_assoc($rs);
$parent_id = intval($rowdata['parent_id']);
$link_name = $this->__naffReverseFormatString($rowdata['link_name']);
$link_dest = $this->__naffReverseFormatString($rowdata['link_dest']);
$link_expire = $this->__naffReverseFormatString($rowdata['link_expire']);
$alternate_url = $this->__naffReverseFormatString($rowdata['alternate_url']);
$link_note = $this->__naffReverseFormatString($rowdata['link_note']);
$link_cute = $this->__naffReverseFormatString($rowdata['link_cute']);
$link_group = $this->__naffReverseFormatString($rowdata['link_group']);
$cloak = $rowdata['cloak'];
$cloak_title = $this->__naffReverseFormatString($rowdata['cloak_title']);
$link_raw_clicks = $rowdata['link_raw_clicks'];
$link_unique_clicks = $rowdata['link_unique_clicks'];
$show_in_editor = $rowdata['show_in_editor'];
$link_keywords = $rowdata['link_keywords'];
$keywords = $this->__naffReverseFormatString($rowdata['keywords']);
$modify_status_txt = $rowdata['modify_status_txt'];
$status_txt_type = $rowdata['status_txt_type'];
$status_txt_custom = $this->__naffReverseFormatString($rowdata['status_txt_custom']);
$overwrite_global = $rowdata['overwrite_global'];
$overwrite_in_new_win = $rowdata['overwrite_in_new_win'];
$overwrite_nofollow = $rowdata['overwrite_nofollow'];
}
}
if ($action == 'addsub') {
if (trim($parent_link) == '') {
$parent_link = $link_cute . '-';
$link_cute = '';
}
$parent_id = $naff_id;
$addedit_title = "Add Subcampaign for \"" . $link_name . "\"";
$addedit_action = "Save Subcampaign";
$link_name = '';
if (isset($naff_post_data['link_name']) && trim($naff_post_data['link_name']) != '') {
$link_name = stripslashes(htmlspecialchars($naff_post_data['link_name']));
}
} else if ($action == 'editsub') {
if (trim($parent_link) == '') {
$link_cute = explode('-', $link_cute);
$parent_link = $link_cute[0] . '-';
$link_cute = $link_cute[1];
}
}
if ($cloak == 1) {
$cloak_chk = 'checked';
$cloak_show = 'block';
}
if ($link_keywords == 1) {
$link_keywords_chk = 'checked';
$link_keywords_show = 'block';
}
if ($modify_status_txt == 1) {
$modify_status_txt_chk = 'checked';
$modify_status_txt_show = 'block';
}
if ($status_txt_type == 2) { //custom
$status_txt_type_2_chk = 'checked';
$status_txt_custom_show = 'block';
}
if ($overwrite_global == 1) {
$overwrite_global_chk = 'checked';
$overwrite_global_show = 'block';
}
if ($status_txt_type == 1)
$status_txt_type_1_chk = 'checked';
if ($overwrite_in_new_win == 1)
$in_new_win_chk = 'checked';
if ($overwrite_nofollow == 1)
$nofollow_chk = 'checked';
if ($show_in_editor == 1)
$show_in_editor_chk = 'checked';
if($link_note !='')
$show_note=true;
$this->__naffHeader();
require_once('form-add.php');
$this->__naffFooter();
}
/**
* Displays the various options available
*/
function __naffOptionsPg() {
$get_vars = $this->__naffBuildGetVars('page');
$unlimited_tooltip = "Use -1 for unlimited";
$naff_find_ids_tooltip = "<b>Where to find the post/page id?</b><br><br><b>In wordpress 2.5 or higher</b><br>-------------------------<br>Goto Manage >> Posts/Pages. Under \'Title\' column, put the mouse over the title text and you\'ll see it\'s link in the status bar. Now note the number after \'post=\' which is the ID for that post/page.<br><br><b>In wordpress below 2.5</b><br>-------------------------<br>Goto Manage >> Posts/Pages. There you\'ll see post/page ID in the first column named \'ID\'<br>";
$custom_link_format_show = 'none';
$custom_link_format_chk = '';
if (strlen($this->link_color) < 7)
$this->link_color = '';
$link_bold_chk = $this->link_bold ? 'checked' : '';
$link_italic_chk = $this->link_italic ? 'checked' : '';
$link_underline_chk = $this->link_underline ? 'checked' : '';
$in_new_win_chk = ($this->in_new_win == 1 ) ? 'checked' : '';
$nofollow_chk = ($this->nofollow == 1 ) ? 'checked' : '';
$disable_chk = ($this->disable == 1) ? 'checked' : '';
$exclude_pages_chk = ($this->exclude_pages == 1) ? 'checked' : '';
$exclude_categories_chk = ($this->exclude_categories == 1) ? 'checked' : '';
$disable_ninja_dropdown_chk = ($this->disable_ninja_dropdown == 1) ? 'checked' : '';
$disable_randomization_chk = ($this->disable_randomization == 1) ? 'checked' : '';
if ($this->custom_link_format == 1) {
$custom_link_format_show = 'block';
$custom_link_format_chk = 'checked';
}
$this->__naffHeader();
require_once('form-options.php');
$this->__naffFooter();
}
/*
* Analytics page
*/
function __naffAnalyticsPg() {
$get_vars = $this->__naffBuildGetVars('page');
$this->__naffHeader();
/*
* isAdvancedOptionEnabled?
* isNinjaLinks?ProcessForNinjaLinks
* isNinjaGroup?ProcesssForGroups
*/
if (isset($_POST['advance_option'])) {
$advance_option = true;
if ($_POST['radio'] == 'links') {
$links_selected = true;
$links_arr = $_POST['links'];
if (!empty($links_arr)) {
$links_implode = implode(',', $links_arr);
$links_sql = " and link_id IN ($links_implode)";
;
$sql = "select link_name from $this->naff_table where link_id in($links_implode)";
$links_name = mysql_query($sql);
$links_list = array();
while ($row = mysql_fetch_assoc($links_name))
$links_list[] = $row['link_name'];
}
} elseif ($_POST['radio'] == 'group') {
$group_selected = true;
$group = $_POST['group'];
$sql = "select link_id from $this->naff_table where link_group='$group'";
$links_ids = mysql_query($sql);
$link_ids_arr = array();
while ($row = mysql_fetch_assoc($links_ids))
$link_ids_arr[] = $row['link_id'];
$group_id_list = implode(' , ', $link_ids_arr);
$groups_sql = " and link_id IN ($group_id_list)";
$group_name = $group;
}
}
/*
* End of Advanced Options
*/
/*
* Check if date reference is greater then today if not remove date referances and click logs before 90 days
*/
$sql = "SELECT MAX( DATE ) maxdate FROM $this->naff_date_references_table";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if (strtotime(date("Y-m-d")) > strtotime($row['maxdate'])) {
$date = $row['maxdate'];
for ($i = 1; $i <= 15; $i++) {
$converted = date("Y-m-d", strtotime(date("Y-m-d", strtotime($date)) . " +$i day"));
mysql_query("insert into $this->naff_date_references_table values('$converted')") or die("Failure on Adding dates : " . mysql_error());
}
//remove reference date old then 90 days
$date_before_three_month = strtotime(date("Y-m-d", strtotime("-3 months ")));
mysql_query("delete from $this->naff_date_references_table where date(date)< '$date_before_three_month'") or die(mysql_error());
mysql_query("delete from $this->naff_clicklog_table where date(date) < '$date_before_three_month'") or die(mysql_error());
}
/*
* Referance Date Operation ends
*/
/*
* DateOperations to extract startdate and enddate
* Date logic
* From < to
* max start date = today;
* min start day = 3 months before
*/
if (isset($_POST['init']) && $_POST['init'] != '') {
// todays date
$maxstart = strtotime(date("Y-m-d"));
//date before 3 month
$minstart = strtotime(date("Y-m-d", strtotime("-3 months ")));
if (strtotime($_POST['init']) > $minstart && strtotime($_POST['init']) < $maxstart)
$start = date('Y-m-d', strtotime($_POST['init']));
else {
$start = date('Y-m-d', strtotime($_POST['init']));
$notice = "<div class='ninja_error'>Date Range Error : Please select date range within 3 months. </div>";
}
}
else
$start = date("Y-m-d", strtotime("-1 months ")); // default start 1 months before today
if (isset($_POST['final']) && $_POST['final'] != '') {
$min_end = strtotime(date("Y-m-d", strtotime("-85 days ")));
if (strtotime($_POST['final']) <= strtotime(date('Y-m-d')) && strtotime($_POST['final']) >= $min_end)
$end = date('Y-m-d', strtotime($_POST['final']));
else {
$notice = "<div class='ninja_error'>Date Range Error : End date is greater than current date </div>";
$end = date('Y-m-d');
}
}
else
$end = date('Y-m-d');
/*
* check if startDate < endDate
*/
if ((isset($_POST['final']) && $_POST['final'] != '') && (isset($_POST['init']) && $_POST['init'] != '')) {
if (strtotime($_POST['init']) >= strtotime($_POST['final'])) {
$start = date("Y-m-d", strtotime("-1 months "));
$end = $end = date('Y-m-d');
$notice = "<div class='ninja_error'>Date Range Error : Start date cannot be greater then End date</div>";
}
}
/*
* Date Operation Ends
*/
/*
* $a to create a Google map data matrix
*/
$a = "['Date','Raw clicks','Unique clicks']";
/*
* Drop view unq,raw if any
*/
//mysql_query('drop view unq,raw') or die(mysql_error());
/*
* Create Unq View
*/
mysql_query("DROP VIEW IF EXISTS unq,raw");
$sql = "
create view unq as
SELECT DATE(date) AS myd , count(date) as total from $this->naff_clicklog_table
WHERE DATE( date ) <= '$end'
AND DATE( date ) >= '$start'
and click_type='unq'";
if (isset($links_sql)) {
$sql.=$links_sql;
} elseif (isset($groups_sql)) {
$sql.=$groups_sql;
} elseif (isset($_GET['naffID']) && !isset($links_sql) && !isset($group_sql)) {
$id = $_GET['naffID'];
$sql.=" and link_id='$id' ";
}
$sql.=" group by myd
union
SELECT DATE(date) ,0
FROM $this->naff_date_references_table
WHERE (DATE( date ) <= '$end'
AND DATE( date ) >= '$start')
and date(date) not in (select Date(date) from $this->naff_clicklog_table where click_type='unq')";
mysql_query($sql) or die(mysql_error());
/*
* Create Raw View
*/
$sql = " create view raw as
SELECT DATE(date) AS myd , count(date) as total from $this->naff_clicklog_table
WHERE DATE( date ) <= '$end'
AND DATE( date ) >= '$start'
and click_type='raw' ";
if (isset($links_sql)) {
$sql.=$links_sql;
} elseif (isset($group_sql)) {
$sql.=$group_sql;
} elseif (isset($_GET['naffID']) && !isset($links_sql) && !isset($group_sql)) {
$id = $_GET['naffID'];
$sql.=" and link_id='$id' ";
}
$sql.="
group by myd
union
SELECT DATE(date) ,0
FROM $this->naff_date_references_table
WHERE (DATE( date ) <= '$end'
AND DATE( date ) >= '$start')
and date(date) not in (select Date(date) from $this->naff_clicklog_table where click_type='raw')";
mysql_query($sql) or die(mysql_error());
/*
* Select raw total click and unique total click
*/
$sql = 'select sum(raw.total) raw_total, sum(unq.total) unique_total from raw,unq where
unq.myd=raw.myd';
$total_clicks = mysql_query($sql) or die(mysql_error());
$total = mysql_fetch_array($total_clicks);
/*
* Select Date, Raw ,Unq
*/
$sql = "select raw.myd as dates ,raw.total raw,unq.total unq from raw,unq where raw.myd=unq.myd order by dates asc";
$csvresult = mysql_query($sql) or die(mysql_error());
/*
* Get Link Name if naffID in Get
*/
if (isset($_GET['naffID'])) {
$id = $_GET['naffID'];
$sql = "select link_name from $this->naff_table where link_id='$id'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$link_name = $row['link_name'];
}
/*
* script to create csv file
*/
if ($this->__naffIsWritable(NAFF_BACKUP_DIR)) {
$csv_folder = NAFF_BACKUP_DIR;
array_map('unlink', glob($csv_folder."*.csv"));
$filename = "Ninja-Analytics($start,$end)";
$CSVFileName = $csv_folder . $filename . '.csv';
$FileHandle = fopen($CSVFileName, 'w+') or die("can't open file");
fclose($FileHandle);
$csv_fields = array();
$csv_fields[0] = array();
$csv_fields[1]=array();
$csv_fields[1][] = 'Date';
$csv_fields[1][] = 'raw clicks';
$csv_fields[1][] = 'unique clicks';
$text="";
if(isset($links_list)){$text=" for link(s) - ' ". implode(' ',$links_list)." ' ";}
if(isset($group_name)){$text=" for links group - ' ".$group_name." ' ";}
if(isset($link_name) and !isset($links_list) && !isset($group_name)){$text=" for link - ' ".$link_name." ' " ;}
$csv_fields[0][]="stats for Ninja links from ".date('M-d Y ', strtotime($start) )." to ".date('M-d Y ', strtotime($end) )." $text";
$i = 2;
while ($rows = mysql_fetch_assoc($csvresult)) {
$csv_fields[$i][0] = $rows['dates'];
$csv_fields[$i][1] = $rows['raw'];
$csv_fields[$i][2] = $rows['unq'];
$i++;
}
$fp = fopen($CSVFileName, 'w');
foreach ($csv_fields as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
} else {
$msg='<div class="ninja_error">The backup directory is not writeable. Please check the permissions for writing to your backup directory and try again.</div>';
}
/*
* End csv script
*/
/*
* Prepare data for Google Analytics
*/
$tabledata = '';
$sql = "select raw.myd as dates ,raw.total raw,unq.total unq from raw,unq where raw.myd=unq.myd order by dates asc";
$result = mysql_query($sql) or die(mysql_error());
$sql = '';
mysql_query('drop view unq,raw') or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$date = date('M-d', strtotime($row['dates']));
$raw = $row['raw'];
$unique = $row['unq'];
$a.=",['$date',$raw,$unique]";
$tabledata.=",['$date','$raw','$unique']";
}
$tabledata = substr($tabledata, 1);
/*
* Get links and groups for advanced options
*/
$sql1 = "select link_id,link_name from $this->naff_table";
$links = mysql_query($sql1) or die(mysql_error());
$sql2 = "select DISTINCT link_group from $this->naff_table";
$groups = mysql_query($sql2) or die(mysql_error());
require_once('analytics.php');
$this->__naffFooter();
}
/**
* Backup and Restore options page
*/
function __naffBackupAndRestorePg() {
$get_vars = $this->__naffBuildGetVars('page');
$this->__naffHeader();
require_once('form-bkp-restore.php');
$this->__naffFooter();
}
/**
* Displays all the links and options to manage them
*/
function __naffShowManagePg() {
$groups = array();
$naff_group = isset($_POST['naff_group']) ? $_POST['naff_group'] : null;
$naff_search_txt = isset($_POST['naff_search_txt']) ? $_POST['naff_search_txt'] : null;
$get_vars = $this->__naffBuildGetVars('page');
$naff_show_total_chk = isset($_POST['naff_show_total']) ? 'checked' : '';
$groups = $this->__naffGetGroups('', '');
$sql = "SELECT * FROM $this->naff_table";
if ($naff_group != 'all' && $naff_group != '') {
$sql .= " WHERE link_group='" . $naff_group . "'";
}
if (isset($_POST['naff_search']) || trim($naff_search_txt) != '') {
if ($naff_group != 'all' && $naff_group != '')
$sql .= " AND";
else
$sql .= " WHERE";
$sql .= " (link_name LIKE '%$naff_search_txt%' OR link_group LIKE '%$naff_search_txt%' OR link_cute LIKE '%$naff_search_txt%' OR link_dest LIKE '%$naff_search_txt%' OR link_note LIKE '%$naff_search_txt%')";
}
$sql .= " ORDER BY link_id DESC";
$rs = mysql_query($sql) or die("Invalid query: " . mysql_errno() . ': ' . mysql_error());
$num_rows = mysql_num_rows($rs);
$this->__naffHeader();
require_once('form-list.php');
$this->__naffFooter();
}
/**
* Curl operation for sending request to autoresponders
*
* @param string autoresponder url where requesr is to be sent
* @param string post parameters
*/
function __naff_CurlRequest($url, $post_params) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
function __naff_process() {
$showForm = true;
if ($_POST['Submit'] == 'Submit' && isset($_POST['key']) && !empty($_POST['key'])) {
$licenseNumber = $_POST['key'];
$url = 'http://maxblogpress.com/license-management/api-atv.php'; // IMP DO NOT CHANGE...
$params = array('lic' => $licenseNumber, 'actUrl' => base64_encode(NAFF_SITEURL), 'plugV' => NAFF_VERSION, 'plugname' => base64_encode(NAFF_NAME), 'libpth' => base64_encode(NAFF_RECALLPTH), 'licfile' => base64_encode(NAFF_FILEPTH));
if (function_exists('curl_init')) {
$crul_Msg = $this->__naff_CurlRequest($url, $params);
$message = explode("%", $crul_Msg);
$this->naffactivemsg = $message[0];
$showForm = false;
if ($message[1] != '') {
$Licensekey = trim($message[1]);
$config = "<?php\n";
$config .= "\$key='$Licensekey';\n";
$config .= "?>";
if (@fopen(NAFF_FILEPTH, "w")) {
if (($fp = fopen(NAFF_FILEPTH, "w"))) {
fputs($fp, $config, strlen($config));
fclose($fp);
}
} else {
echo '<div class="updated"><p>
Error:Could not create license file in your blog.
Please change the permission of the folder
<strong>"maxblogpress-ninja-affiliate\ninja-affiliate-library\include\" </strong>
to 755 then click try again link below.<br>
<a href="tools.php?' . $this->__naffBuildGetVars('page') . '">try again </a>
</p></div>';
}
} else {
$showForm = true;
}
} else {
$response = @file_get_contents($url);
if (!$response) {
echo '<div class="updated"><p>
Error: cURL is not installed on this server. file_get_contents failed.
</p></div>';
} else {
$check = true;
}
}
}
if ($showForm == true) {
$this->__naffHeader();
?>
<br>
<form action="" method="post">
<table width="580" border="0">
<tr>
<td width="116">License Number: </td>
<td width="374"><label>
<input type="text" value="" name="key" size="40px;" /><br>
</label></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><small><i>Please enter your license number, provided at plugin download page.</i></small></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Submit" /></td>
</tr>
</table>
</form>
<?php
}
}
/*
* check Destination Url and append http:// if protocol is missing
*/
function __naffcheckUrl($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
function __naffRemoveEmptyLines($keywords) {
$lines = explode("\n", $keywords);
$array = array_filter(array_map('trim', $lines));
$lines = implode("\n", $array);
return $lines;
}
}
// Eof Class
$MBPNinjaAffiliate = new MBPNinjaAffiliate();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment