<?php
if (!defined('IN_CONTEXT')) die('access violation error!');

class ModAdvert extends Module {

	protected $_filters = array(
        'check_admin' => ''
    );
	
    public function admin_list() {
        $this->_layout = 'content';
        
        $mode =& ParamHolder::get('mode');
        $site_param =& ParamHolder::get('sparam', array());
        
        if( isset($mode) && !empty($mode) )
        {
        	$o_param = new Parameter();
        	
        	$type = $site_param['ADVERT_STATUS'];
        	// self-defined theme
    		$file_info =& ParamHolder::get('uptheme', array(), PS_FILES);
    		if ( isset($file_info['name']) && !empty($file_info['name']) )
    		{
    			$site_param['ADVERT_THEME'] = $this->upload_file($file_info);
    		}
    		if( $type == '3' ) {
	    		$file_info2 =& ParamHolder::get('uprtheme', array(), PS_FILES);
	        	if ( isset($file_info2['name']) && !empty($file_info2['name']) ) {
	    			$site_param['ADVERT_RTHEME'] = $this->upload_file($file_info2);
	    		}
	    	}
    		
	        // exec sql
	    	foreach ($site_param as $key => $val) {
	    	    $param =& $o_param->find('`key`=?', array($key));
	    	    if( $key == 'ADVERT_TEXT_COLOR' && empty($val) ) $val = '#000000';
	    	    if ($param) {
	    	        $param->val = $val;
	    	        $param->save();
	    	    }
	    	}
	    	
	    	// generate xml
	    	if( $type ) 
	    	{
	    		$text = $site_param['ADVERT_TEXT'];
		    	switch( $type ) {
		    		case '1':
		    			$width = '300';
		    			$height = '200';
		    			break;
		    		case '2':
		    			$width = '100';
		    			$height = '100';
		    			break;
		    		case '3':
		    			$width = '100';
		    			$height = '300';
		    			// auto break-line
		    			$text = $this->auto_break_line($site_param['ADVERT_TEXT']);
		    			$text2 = $site_param['ADVERT_RTEXT'];
		    			break;	
		    	}
	    			    		
		    	$xml = 'adtool/xml/config.xml';
		    	$bgimg = 'admin/'.$site_param['ADVERT_THEME'];
		    	$url = $site_param['ADVERT_URL'];
		    	$fsize = $site_param['ADVERT_TEXT_SIZE'];
		    	$fcolor = $site_param['ADVERT_TEXT_COLOR'];
		    	
		    	$adtext = '<?xml version="1.0" encoding="UTF-8"?>
<Content TheBannerWidth="'.$width.'" TheBannerHeight="'.$height.'" maxCellsize="1" NumberOfCells="30" CellsSpeed="1" CellsDirection="MoveDown" BackgroundImage="'.$bgimg.'">';
				// text list
				$txtArr = explode(';', $text);
				$ln = count($txtArr);
				for( $i=0; $i<$ln; $i++ ) {
					$text = '';
					$text .= $txtArr[$i];
					if( !empty( $url ) ) {
						$adtext .= "<title PauseText='2'><![CDATA[<font size='{$fsize}' color='{$fcolor}'><a href='{$url}' target='_blank'>{$text}</a></font>]]></title>";
					} else {
						$adtext .= "<title PauseText='2'><![CDATA[<font size='{$fsize}' color='{$fcolor}'>{$text}</font>]]></title>";
					}
				}
				
				$responsexml = <<<XML
$adtext
XML;
				$this->createXml($xml, $responsexml);
				if( $type == '3' ) {
					$input = array('gold', 'blue', 'green', 'ocean', 'aqua', 'ice', 'spark', 'silver', 'neon');
					$k = array_rand($input);
					$xml2 = 'adtool/xml/couplet.xml';
			    	$bgimg2 = 'admin/'.$site_param['ADVERT_RTHEME'];
			    	$url2 = $site_param['ADVERT_RURL'];
			    	$fsize2 = $site_param['ADVERT_RTEXT_SIZE'];
			    	$fcolor2 = str_replace('#', '0x', $site_param['ADVERT_RTEXT_COLOR']);
			    	$adtext2 = '<?xml version="1.0" encoding="UTF-8"?><messages><config stage_width="auto" stage_height="auto" /><image img_src="'.$bgimg2.'" />';
			    	
			    	// text list
					$txtArr2 = explode(';', $text2);
					$ln2 = count($txtArr2);
					for( $j=0; $j<$ln2; $j++ ) {
						$adtext2 .= '<text message_txt="'.$txtArr2[$j].'" text_url="'.$url2.'" text_size="'.$fsize2.'" text_color="'.$fcolor2.'" text_fade_speed="1" glow_color="'.$input[$k].'" glow_blur="4" glow_intensity="2" glow_quality="8" glow_width="100" glow_move_speed="5" glow_repeat_counter="2" />';
					}
					$adtext2 .= '</messages>';
					$responsexml2 = <<<XML
$adtext2
XML;
					$this->createXml($xml2, $responsexml2);					
				}
	    	}

	    	Content::redirect(Html::uriquery('mod_advert', 'admin_list'));
        }
    }
    
    public function ad_picker() {
    	$this->_layout = 'blank';
    	
    	$act = '';
    	$type =& ParamHolder::get('adtype');
    	$tag =& ParamHolder::get('tag');
    	$position =& ParamHolder::get('p');
    	switch( $type ) {
    		case '1':
    			$act = (isset($tag) && !empty($tag)) ? $tag.'t' : 't';
    			$width = '300';
    			$height = '200';
    			break;
    		case '2':
    			$act = (isset($tag) && !empty($tag)) ? $tag.'f' : 'f';;
    			$width = '100';
    			$height = '100';
    			break;
    		case '3':
    			$act = (isset($tag) && !empty($tag)) ? $tag.'d' : 'd';;
    			$width = '100';
    			$height = '300';
    			break;	
    	}

		$this->assign('act', $act);
		$this->assign('tag', $tag);
		$this->assign('type', $type);
		$this->assign('width', $width);
		$this->assign('height', $height);
		$this->assign('position', $position);
    }
    
    private function auto_break_line( $str ) {
		$enmatches = $cnmatches = array();
		
		// for english
		if( preg_match_all( '/[\x01-\x7f]+/', $str, $enmatches ) ) {
			$ln1 = count($enmatches[0]);
			for( $i=0; $i<$ln1; $i++ ) {
				$str = str_replace($enmatches[0][$i], $enmatches[0][$i].'<br/>', $str);
				if( strpos($enmatches[0][$i], ' ') ) {
					$str = str_replace(' ', '<br/>', $str);
				}
			}
		}
		// for chinese
		if( preg_match_all( '/[^\x01-\x7f]+/', $str, $cnmatches ) ) {
			$ln2 = count($cnmatches[0]);
			for( $j=0; $j<$ln2; $j++ ) {
				$strln = mb_strlen($cnmatches[0][$j], 'UTF-8');
				if( intval($strln) > 1 ) {
					$temp = '';
					for( $k=0; $k<$strln; $k++ ) {
						$temp = mb_substr($cnmatches[0][$j], $k, 1, 'UTF-8');
						$str = str_replace($temp, $temp.'<br/>', $str);
					}
				} else {
					$str = str_replace($cnmatches[0][$j], $cnmatches[0][$j].'<br/>', $str);
				}
			}
		}
		
		return ereg_replace('<br\/>$', '', $str);
    }
    
    private function upload_file($file_info) {
    	$err = '';
		$maxsize = 2 * 1024 * 1024;
		$typeArr = array('image/gif','image/png','image/x-png','image/jpeg','image/pjpeg');
		// 文件大小
        if ( ($file_info['size'] == 0) || ($file_info['size'] > $maxsize) ) {
        	$err = __('Upload size limit').':2M';
        // 文件类型
    	} elseif ( !in_array( $file_info['type'], $typeArr ) ) {
        	$err = __('Supported file format').':gif|jpg|png';	
        } else {
        	$dest = ROOT.'/admin/adtool/theme/';
        	// rename file name
	        $file_info["name"] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
        	if ( move_uploaded_file( $file_info['tmp_name'], $dest.$file_info['name'] ) ) {
        		$upfile = 'adtool/theme/'.$file_info['name'];
        	} else { $err = __('Uploading file failed!'); }
        }
        // show error
        if( $err ) {
        	Notice::set('mod_advert/msg', $err);
        	Content::redirect(Html::uriquery('mod_advert', 'admin_list'));
        }
        
        return $upfile;
    }
    
    private function createXml($xml, $responsexml) {
    	if( !$fp = fopen( $xml, 'wb' ) ) {
	         Notice::set('mod_advert/msg', __('Can\'t open file')." $xml");
	         Content::redirect(Html::uriquery('mod_advert', 'admin_list'));
	    }
		
		if( fwrite($fp, $responsexml) === FALSE ) {
	        Notice::set('mod_advert/msg', __('Can\'t write to the file')." $xml");
	        Content::redirect(Html::uriquery('mod_advert', 'admin_list'));
	    }

	    fclose($fp);
    }
}
?>