<?php
!function_exists('adminmsg') && exit('Forbidden');

if ($job == 'add' || $job == 'edit') {
	$adtype= array();
	$query = $db->query("SELECT varname,title FROM pw_modules WHERE type=6 AND title!='' GROUP BY varname");
	while ($rt = $db->fetch_array($query)) {
		if (!in_array($rt['varname'], array('header','footer','text','article','rightfloat','leftfloat','popup', 'float'))) {
			$adtype[] = $rt;
		}
	}
}
if (empty($job)) {

	InitGP(array('varname','keyword'));
	InitGP(array('page'),'GP',2);
	$sql = '';
	$varname && $sql .= " AND m.varname=".pwEscape($varname);
	$keyword && $sql .= " AND m.title LIKE ".pwEscape("%$keyword%");

	require_once(R_P.'require/forum.php');
	$rt = $db->get_one("SELECT COUNT(*) AS sum FROM pw_modules m WHERE m.type=6 $sql");
	$page<1 && $page = 1;
	$limit = pwLimit(($page-1)*$db_perpage,$db_perpage);
	$pages = numofpage($rt['sum'],$page,ceil($rt['sum']/$db_perpage), "$basename&varname=$varname&keyword=".rawurlencode($keyword).'&');
	$query = $db->query("SELECT m.id,m.varname,m.state,m.vieworder,m.title,m.ifhire,m.config,b.id AS bid FROM pw_modules m LEFT JOIN pw_buyadvert b ON m.id = b.id WHERE m.type=6 $sql GROUP BY id ORDER BY m.ifhire DESC,m.id DESC $limit");
	while ($rt = $db->fetch_array($query)) {
		$config = unserialize($rt['config']);
		$rt['fid']		 = explode(',',$config['fid']);
		$rt['adtitle']	 = $config['title'];
		$rt['starttime'] = $config['starttime'];
		$rt['endtime']	 = $config['endtime'];
		$rt['ifhavebuy'] = $rt['bid'] == null ? '0' : '1';
		$rt['ifhire'] && $rt['title'] = "<a href=\"".$basename."&job=check&id=".$rt['id']."\" ><font color=\"red\">".$rt['title']."</font></a>";
		$moduledb[] = $rt;
	}

	include_once PrintHack('admin');exit;

} elseif ($job == 'add') {

	if (empty($_POST['step'])) {

		require_once(R_P.'require/credit.php');
		InitGP(array('s','n'));
		include_once(D_P.'data/bbscache/forumcache.php');
		foreach ($forum as $k => $v) {
			if ($v['type'] == 'category') {
				$forumcache = str_replace("<option value=\"$v[fid]\">>> $v[name]</option>","<optgroup label=\"$v[name]\" />",$forumcache);
			}
		}
		$CreditList = '';
		foreach ($credit->cType as $key => $value) {
			$CreditList	.= "<option value=\"$key\"" . ($rt['creditype'] == $key ? ' selected' : '') . ">$value</option>";
		}
		$style     = 'txt';
		$adtype    = '';
		$ifhire_N = $pst_1   = 'checked';
		$selids_01 = $lou_01 = 'selected';
		$config = array(
			'starttime'	=> get_date($timestamp,'Y-m-d'),
			'endtime'	=> get_date($timestamp + 31536000,'Y-m-d'),
			'htmlcode'	=> $s ? stripslashes($s) : '',
			'operator'	=> $admin_name
		);
		$rt['title'] = $n ? stripslashes($n) : '';

		include_once PrintHack('admin');exit;

	} elseif ($_POST['step']=='2') {

		InitGP(array('module'),'GP',0);
		InitGP(array('ifhire'),'GP',2);
		InitGP(array('varname','vieworder','title','selids','lou'));
		$basename = "$amind_file?adminjob=hack&hackset=advert&job=add";
		!$varname && adminmsg('module_adderror');
		if ($module['style'] == 'code' && !$module['htmlcode']) {
			adminmsg('advert_code_error');
		} elseif ($ifhire==0 && $module['style'] == 'txt' && (!$module['title'] || !$module['link'])) {
			adminmsg('advert_txt_error');
		} elseif ($ifhire==0 && $module['style'] == 'img' && (!$module['url'] || !$module['link'])) {
			adminmsg('advert_img_error');
		} elseif ($module['style'] == 'flash' && !$module['link']) {
			adminmsg('advert_flash_error');
		} elseif ($module['style'] == 'code' && ($varname == 'leftfloat' || $varname == 'rightfloat') && preg_match('/<script[^>]*?>.*?<\/script>/si',$module['htmlcode'])) {
			adminmsg('advert_float_error');
		} elseif ($ifhire==1 && $module['style'] == 'txt' && !$module['title']) {
			adminmsg('advert_txt_hire_error');
		} elseif ($ifhire==1 && $module['style'] == 'img' && !$module['url']) {
			adminmsg('advert_img_hire_error');
		} elseif ($ifhire==1 && $module['style'] == 'code') {
			adminmsg('advert_code_hire_error');
		}

		if (empty($title)) {
			if ($module['style'] == 'code') {
				$title = substrs(strip_tags($module['htmlcode']),30);
			} elseif ($module['style'] == 'txt') {
				$title = $module['title'];
			}
			empty($title) && adminmsg('advert_descrip');
		}

		$fids = '';
		foreach ($selids as $key => $val) {
			if (is_numeric($val)) {
				$fids .= $fids ? ','.$val : $val;
			}
		}
		$module['fid'] = $fids;
		if ($varname == 'article') {
			$lous = '';
			foreach ($lou as $key=>$val) {
				is_numeric($val) && $lous .= $lous ? ','.$val : $val;
			}
			$module['lou'] = $lous;
		}
		if ($ifhire == 1) {
			$module['price'] = (int)$module['price'];
			!$module['price'] && adminmsg('advert_price_error');
		} else {
			unset($module['price'],$module['creditype'],$module['operator']);
		}
		foreach ($module as $key => $value) {
			if (in_array($key,array('url','link'))) {
				$value = str_replace(array('&#61;','&amp;'),array('=','&'),$value);
			}
			$module[$key] = stripslashes($value);
		}
		$config = addslashes(serialize($module));
		$db->update("INSERT INTO pw_modules SET " . pwSqlSingle(array(
			'type'		=> 6,
			'varname'	=> $varname,
			'state'		=> 1,
			'vieworder'	=> $vieworder,
			'title'		=> $title,
			'ifhire'	=> $ifhire,
			'config'	=> $config
		)));
		updatecache_c();
		adminmsg('operate_success');
	}
} elseif ($job == 'edit') {

	if (empty($_POST['step'])) {

		require_once(R_P.'require/credit.php');
		InitGP(array('id'));
		include_once(D_P.'data/bbscache/forumcache.php');
		foreach ($forum as $k => $v) {
			if ($v['type'] == 'category') {
				$forumcache = str_replace("<option value=\"$v[fid]\">>> $v[name]</option>","<optgroup label=\"$v[name]\" />",$forumcache);
			}
		}
		$rt = $db->get_one("SELECT * FROM pw_modules WHERE type=6 AND id=".pwEscape($id));
		if (!$rt) {
			adminmsg('module_id_error');
		}
		$config = unserialize($rt['config']);
		HtmlConvert($rt);
		HtmlConvert($config);
		ifcheck($rt['ifhire'],'ifhire');
		$ifhire = $rt['ifhire'];
		$style  = $config['style'];
		$adtype = $rt['varname'];
		${'style_'.$config['style']} = 'selected';
		${'method_'.$config['method']} = 'checked';
		${'order_'.$config['order']} = "selected";
		$CreditList = '';
		foreach ($credit->cType as $key => $value) {
			$CreditList	.= "<option value=\"$key\"".($config['creditype']==$key ? ' selected' : '').">$value</option>";
		}
		$fids = explode(',',$config['fid']);
		foreach ($fids as $k => $v) {
			if ($v > 0) {
				$forumcache = str_replace("<option value=\"$v\">","<option value=\"$v\" selected>",$forumcache);
			} else {
				${'selids_0'.abs($v)} = 'selected';
			}
		}
		if ($adtype == 'article') {
			$lou = explode(',',$config['lou']);
			foreach ($lou as $k => $v) {
				$v > 0 ? ${'lou_'.$v} = 'selected' : ${'lou_0'.abs($v)} = 'selected';
			}
			${'pst_'.$config['position']} = 'checked';
		} else {
			$pst_1 = 'checked';
			$lou_01= 'selected';
		}
		include_once PrintHack('admin');exit;

	} elseif ($_POST['step'] == '2') {

		InitGP(array('module'),'P',0);
		InitGP(array('ifhire'),'P',2);
		InitGP(array('id','varname','vieworder','title','selids','lou'),'P');
		$basename = "$amind_file?adminjob=hack&hackset=advert&job=edit&id=$id";
		!$varname && adminmsg('module_adderror');
		if ($module['style'] == 'code' && !$module['htmlcode']) {
			adminmsg('advert_code_error');
		} elseif ($ifhire==0 && $module['style'] == 'txt' && (!$module['title'] || !$module['link'])) {
			adminmsg('advert_txt_error');
		} elseif ($ifhire==0 && $module['style'] == 'img' && (!$module['url'] || !$module['link'])) {
			adminmsg('advert_img_error');
		} elseif ($module['style'] == 'flash' && !$module['link']) {
			adminmsg('advert_flash_error');
		} elseif ($module['style'] == 'code' && ($varname == 'leftfloat' || $varname == 'rightfloat') && preg_match('/<script[^>]*?>.*?<\/script>/si',$module['htmlcode'])){
			adminmsg('advert_float_error');
		} elseif ($ifhire==1 && $module['style'] == 'img' && !$module['url']) {
			adminmsg('advert_img_hire_error');
		} elseif ($ifhire==1 && $module['style'] == 'code') {
			adminmsg('advert_code_hire_error');
		}
		if (empty($title)) {
			if ($module['style'] == 'code') {
				$title = substrs(strip_tags($module['htmlcode']),30);
			} elseif ($module['style'] == 'txt') {
				$title = $module['title'];
			}
			empty($title) && adminmsg('advert_descrip');
		}

		if ($varname == 'popup') {
			!$module['height'] && $module['height'] = 100;
			!$module['width'] && $module['width'] = 200;
			!$module['close'] && $module['close'] = 5;
		}
		if (is_array($selids)) {
			$fids = '';
			foreach ($selids as $key=>$val) {
				if (is_numeric($val)) {
					$fids .= $fids ? ','.$val : $val;
				}
			}
			$module['fid'] = $fids;
		} else {
			$module['fid'] = '';
		}
		if ($varname == 'article') {
			$lous = '';
			foreach ($lou as $key=>$val) {
				is_numeric($val) && $lous .= $lous ? ','.$val : $val;
			}
			$module['lou'] = $lous;
		}
		if ($ifhire == 1) {
			$module['price'] = (int)$module['price'];
			!$module['price'] && adminmsg('advert_price_error');
		} else {
			unset($module['price'],$module['creditype'],$module['operator']);
		}
		$module['descrip'] = str_replace("\n",'<br />',$module['descrip']);
		foreach ($module as $key => $value) {
			if (in_array($key,array('url','link'))) {
				$value = str_replace(array('&#61;','&amp;'),array('=','&'),$value);
			}
			$module[$key] = stripslashes($value);
		}
		$config = addslashes(serialize($module));
		$db->update("UPDATE pw_modules SET " . pwSqlSingle(array(
			'varname'	=> $varname,
			'vieworder'	=> $vieworder,
			'title'		=> $title,
			'ifhire'	=> $ifhire,
			'config'	=> $config
		)) . " WHERE type='6' AND id=".pwEscape($id));

		updatecache_c();
		$basename = "$amind_file?adminjob=hack&hackset=advert";
		adminmsg('operate_success');
	}
} elseif ($job == 'check') {

	require_once(R_P.'require/credit.php');
	InitGP(array('id','step'),'GP',2);
	!$id && adminmsg('module_id_error');
	$advert = $db->get_one("SELECT * FROM pw_modules WHERE type=6 AND id=".pwEscape($id)."AND ifhire=1");
	!$advert && adminmsg('module_id_error');
	$config = unserialize($advert['config']);
	HtmlConvert($advert);
	HtmlConvert($config);
	if (empty($step)) {
		require_once(R_P.'require/forum.php');
		$fids  		= explode(',',$config['fid']);
		InitGP(array('page'),'GP',2);
		$page<1 && $page = 1;
		$prenumber 	= 20;
		$total 		= $db->get_one("SELECT count(*) as count FROM pw_buyadvert WHERE id=".pwEscape($id));
		$total 		= $total['count'];
		$start 		= ($page - 1) * $prenumber;
		$numofpage 	= ceil($total/$prenumber);
		$pages 		= numofpage($total,$page,$numofpage,$basename."&job=check&id=".$id."&");
		$arr_buyer 	= array();
		$query = $db->query("SELECT b.*,m.username FROM pw_buyadvert b LEFT JOIN pw_members m USING(uid) WHERE b.id=".pwEscape($id)."LIMIT $start,$prenumber");
		while ($rt = $db->fetch_array($query)) {
			$rt['config'] 	= unserialize($rt['config']);
			$arr_buyer[]	= $rt;
		}
		include_once PrintHack('admin');exit;
	} else {
		require_once(R_P.'require/msg.php');
		InitGP(array('uid'),'GP',2);
		!$uid && adminmsg('unituser_username_empty');
		$buyer = $db->get_one("SELECT b.*,m.username FROM pw_buyadvert b LEFT JOIN pw_members m USING(uid) WHERE b.id=".pwEscape($id)."AND b.uid=".pwEscape($uid));
		!$buyer && adminmsg('unituser_newname_error');
		$buyer_config = unserialize($buyer['config']);
		HtmlConvert($buyer_config);
		$buyer_config['days'] = (int)$buyer_config['days'];
		!$buyer_config['days'] && adminmsg('advert_days_error');
		$usercredit = array();
		foreach ($credit->get($uid) as $key => $value) {
			$usercredit[$key] = $value;
		}
		!array_key_exists($config['creditype'],$usercredit) && adminmsg('advert_creditype_error');
		$price = 0;
		if ($config['price']) {
			 $config['price'] = (int)$config['price'];
			 $price = $config['price']*$buyer_config['days'];
			 $price>$usercredit[$config['creditype']] && adminmsg('advert_creditype_lack');
		}
		if ($config['style'] == 'txt') {
			if ($buyer_config['title']) {
				$config['title'] = $buyer_config['title'];
				$buyer_config['title'] 	= addslashes($buyer_config['title']);
			} else {
				adminmsg('advert_txt_hire_error');
			}
			if ($buyer_config['link']) {
				$config['link'] = str_replace(array('&#61;','&amp;'),array('=','&'),$buyer_config['link']);
			} else {
				adminmsg('advert_txt_error');
			}
		} elseif ($config['style'] == 'img') {
			if ($buyer_config['title']) {
				$buyer_config['title'] = addslashes($buyer_config['title']);
			} else {
				adminmsg('advert_descrip');
			}
			if ($buyer_config['link']) {
				$config['link'] = str_replace(array('&#61;','&amp;'),array('=','&'),$buyer_config['link']);
			} else {
				adminmsg('advert_img_hire_error');
			}
			if ($buyer_config['url']) {
				$config['url'] = str_replace(array('&#61;','&amp;'),array('=','&'),$buyer_config['url']);
			} else {
				adminmsg('advert_img_error');
			}
		} elseif ($config['style'] == 'flash') {
			if ($buyer_config['title']) {
				$buyer_config['title'] = addslashes($buyer_config['title']);
			} else {
				adminmsg('advert_txt_hire_error');
			}
			if ($buyer_config['link']) {
				$config['link'] = str_replace(array('&#61;','&amp;'),array('=','&'),$buyer_config['link']);
			} else {
				adminmsg('advert_txt_error');
			}
		} else {
			adminmsg('undefined_action');
		}
		$config['starttime']= get_date($timestamp,'Y-m-d');
		$config['endtime']	= get_date($timestamp+$buyer_config['days']*86400,'Y-m-d');
		$creditype 			= $config['creditype'];
		$creditypename 		= $credit->cType[$config['creditype']];
		$creditnum 			= $config['price'];
		$config 			= addslashes(serialize($config));

		$db->update("UPDATE pw_modules SET ".pwSqlSingle(array(
			'title'		=> $buyer_config['title'],
			'ifhire'	=> 0,
			'config'	=> $config
		)) . "WHERE type='6' AND id=".pwEscape($id));

		$db->update("DELETE FROM pw_buyadvert WHERE id=".pwEscape($id));
		$credit->set($uid,$creditype,-$price);

		$message = array(
			'toUser'	=> $buyer['username'],
			'subject'	=> 'advert_buy_title',
			'content'	=> 'advert_buy_content',
			'other'		=> array(
				'creditnum'		=> $creditnum,
				'creditypename'	=> $creditypename,
				'days'			=> $buyer_config['days']
			)
		);
		pwSendMsg($message);
		updatecache_c();
		adminmsg('operate_success');
	}

} elseif ($job == 'del') {

	InitGP(array('selid','applyid','allid'),'P');
	if ($selid = checkselid($selid)) {
		$db->update("DELETE FROM pw_modules WHERE type='6' AND id IN($selid)");
	}
	if ($allid = checkselid($allid)) {
		$db->update("UPDATE pw_modules SET state=0 WHERE type='6' AND id IN($allid)");
	}
	if ($applyid = checkselid($applyid)) {
		$db->update("UPDATE pw_modules SET state=1 WHERE type='6' AND id IN($applyid)");
	}
	updatecache_c();
	adminmsg('operate_success');
}
?>