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

// 06/08/2010 Add >>
include_once(P_LIB.'/image.class.php');
// 06/08/2010 Add <<

class ModMedia extends Module {
    protected $_filters = array(
        'check_login' => '{show_image}{show_flash}{flash_slide}'
    );
    
    private $_available_types = array('file', 'image', 'flash');
    
    public function show_image() {
    	$this->_layout = 'frontpage';
    	
        $img_src = trim(ParamHolder::get('img_src', ''));
        if (strlen($img_src) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('No Image!')));
            return '_error';
        }
        $img_desc = trim(ParamHolder::get('img_desc', ''));
        $img_width = trim(ParamHolder::get('img_width', ''));
        $str_img_width = '';
        if (strlen($img_width) != 0) {
            $str_img_width = sprintf(' width="%s"', $img_width);
        }
        $img_height = trim(ParamHolder::get('img_height', ''));
        $str_img_height = '';
        if (strlen($img_height) != 0) {
            $str_img_height = sprintf(' height="%s"', $img_height);
        }
        
        // show title
        $blockid = ParamHolder::get('block_id', '');
        $showtitle = $this->show_title($blockid);
        $this->assign('showtitle', $showtitle);
       
        $this->assign('img_src', $img_src);
        $this->assign('img_desc', $img_desc);
        $this->assign('str_img_width', $str_img_width);
        $this->assign('str_img_height', $str_img_height);
    }
    
    public function show_flash() {
    	$this->_layout = 'frontpage';
    	
        $flv_src = trim(ParamHolder::get('flv_src', ''));
        if (strlen($flv_src) == 0) {
            $this->assign('json', Toolkit::jsonERR(__('No Flash!')));
            return '_error';
        }
        $flv_width = trim(ParamHolder::get('flv_width', ''));
        $str_flv_width = '';
        if (strlen($flv_width) != 0) {
            $str_flv_width = sprintf(' width="%s"', $flv_width);
        }
        $flv_height = trim(ParamHolder::get('flv_height', ''));
        $str_flv_height = '';
        if (strlen($flv_height) != 0) {
            $str_flv_height = sprintf(' height="%s"', $flv_height);
        }
        
        // show title
        $blockid = ParamHolder::get('block_id', '');
        $showtitle = $this->show_title($blockid);
        $this->assign('showtitle', $showtitle);
        
        $this->assign('flv_src', $flv_src);
        $this->assign('str_flv_width', $str_flv_width);
        $this->assign('str_flv_height', $str_flv_height);
    }
    
    /**
     * for sitestarv1.3
     * Flash slide 
     */
    public function flash_slide() {
    	$this->_layout = 'frontpage';
    	
    	$params = array();
    	$blockid = trim(ParamHolder::get('block_id', ''));
    	
    	$o_mod_block = new ModuleBlock();
    	$blocks = $o_mod_block->findAll("`id`=?", array($blockid));
    	$params = unserialize($blocks[0]->s_param);
        
        $k = 0; // flag
        $imgtemp = $imglist = array();
        foreach ($params as $ky => $val) {
        	$math = array();
        	if (preg_match("/^slide\_img\_src(\d+)$/i", $ky, $math)) {
        		$i = $math[1];
        		$temp_img_src = $temp_img_order = $temp_img_uri = $temp_img_desc = '';
        		$temp_img_src = $params['slide_img_src'.$i];
        		$temp_img_order = $params['slide_img_order'.$i];
        		$temp_img_uri = $params['slide_img_uri'.$i]?$params['slide_img_uri'.$i]:'#';
        		$temp_img_desc = $params['slide_img_desc'.$i]?$params['slide_img_desc'.$i]:'&nbsp;';
	        	if (!empty($temp_img_src)) {
	        		$imgtemp['order'] = $temp_img_order;
	        		$imgtemp['src'] = $temp_img_src;
	        		$imgtemp['uri'] = (substr($temp_img_uri,0,4)=='http') ? $temp_img_uri : "http://".$temp_img_uri;
	        		$imgtemp['desc'] = $temp_img_desc;
	        		
	        		$imglist[] = $imgtemp;
	        		$k++;
	        	}
        	}
        }
        if (!$k) {
            $this->assign('json', Toolkit::jsonERR(__('No Image!')));
            return '_error';
        } else {
        	asort($imglist);
        	$imgSrc = $imgUri = $imgText = '';       	
        	foreach ($imglist as $val) {
        		$imgSrc .= $val['src'].'|';
        		$imgUri .= urlencode($val['uri']).'|';
        		$imgText .= $val['desc'].'|';
        	}
        	// filter '|'
        	$imgSrc = ereg_replace("\|$", '', $imgSrc);
        	$imgUri = ereg_replace("\|$", '', $imgUri);
        	$imgText = ereg_replace("\|$", '', $imgText);
        }
        
        $img_width = is_numeric($params['slide_img_width'])?intval($params['slide_img_width']):240;
        $img_height = is_numeric($params['slide_img_height'])?intval($params['slide_img_height']):200;

        $this->assign('img_width', $img_width);
        $this->assign('img_height', $img_height);
        $this->assign('imgSrc', $imgSrc);
        $this->assign('imgUri', $imgUri);
        $this->assign('imgText', $imgText);
        $this->assign('showtitle', $blocks[0]->show_title);
    }
    
    public function file_picker() {
        $this->_layout = 'content';
        
        if (!$this->_requireAdmin()) {
            return '_error';
        }
    }
    
    public function image_picker() {
        $this->_layout = 'content';
        
        if (!$this->_requireAdmin()) {
            return '_error';
        }
        
        // 5/5/2010 Add >>
        $err = '';
        $wincls = 'NG';
        $maxsize = 2 * 1024 * 1024;
        $typeArr = array('image/bmp','image/gif','image/png','image/x-png','image/jpeg','image/pjpeg');
        $file_info =& ParamHolder::get('localfile', array(), PS_FILES);
        if ( sizeof($file_info) > 0 && isset($file_info['name']) )
        {
	        // 文件大小
	        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|bmp';	
	        } else {
	        	$dest = ROOT.'/upload/image/';
		        $file_info['name'] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
	        	if ( move_uploaded_file( $file_info['tmp_name'], $dest.$file_info['name'] ) ) {
	        		$wincls = 'OK';
	        		// 图片水印
		        	if( WATERMARK_STATUS ) {
		        		$extend = array('_e' => 'mod_media/msg', 
	        			            '_a' => 'mod_media', 
	        						'_m' => 'image_picker'
	        				  );
		        		$watermark = $this->image_mark( $dest.$file_info['name'], $extend );
		        		$file_info["name"] = !empty($watermark) ? $watermark : $file_info["name"];
		        	}
	        		$this->assign('fname', $file_info['name']);
	        	} else { $err = __('Uploading file failed!'); }
	        }
        }
        $this->assign('err', $err);
        $this->assign('wincls', $wincls);
        // 5/5/2010 Add <<
        
//        $curr_entry = trim(ParamHolder::get('ep', ''));
//        $dir_info =& $this->_listDir('image', $curr_entry);
        
        $image_id = trim(ParamHolder::get('imgid', ''));
        
//        $this->assign('dirs', $dir_info['dirs']);
//        $this->assign('files', $dir_info['files']);
//        $this->assign('pager', $dir_info['pager']);
//        $this->assign('curr_entry', str_replace("\\", "/", $dir_info['curr_entry']));
        
        $this->assign('imgid', $image_id);
    }
    
    public function flash_picker() {
        $this->_layout = 'content';
        
        if (!$this->_requireAdmin()) {
            return '_error';
        }
        
         // 5/5/2010 Add >>
        $err = '';
        $wincls = 'NG';
        $maxsize = 2 * 1024 * 1024;
        $typeArr = array('application/x-shockwave-flash','application/octet-stream');
        $file_info =& ParamHolder::get('localfile', array(), PS_FILES);
        if ( sizeof($file_info) > 0 && isset($file_info['name']) )
        {
	        // 文件大小
	        if ( ($file_info['size'] == 0) || ($file_info['size'] > $maxsize) ) {
	        	$err = '上传大小限制:2M';
	        // 文件类型
        	} elseif ( !in_array( $file_info['type'], $typeArr ) ) {
	        	$err = '支持的文件类型:swf|flv';
	        } else {
	        	$dest = ROOT.'/upload/flash/';
	        	$file_info['name'] = Toolkit::randomStr(8).strrchr($file_info["name"],".");
	        	if ( move_uploaded_file( $file_info['tmp_name'], $dest.$file_info['name'] ) ) {
	        		$wincls = 'OK';
	        		$this->assign('fname', $file_info['name']);
	        	} else { $err = '上传失败'; }
	        }
        }
        $this->assign('err', $err);
        $this->assign('wincls', $wincls);
        // 5/5/2010 Add <<
        
//        $curr_entry = trim(ParamHolder::get('ep', ''));
//        $dir_info =& $this->_listDir('flash', $curr_entry);
        
        $flash_id = trim(ParamHolder::get('flvid', ''));
        
//        $this->assign('dirs', $dir_info['dirs']);
//        $this->assign('files', $dir_info['files']);
//        $this->assign('pager', $dir_info['pager']);
//        $this->assign('curr_entry', $dir_info['curr_entry']);
        
        $this->assign('flvid', $flash_id);
    }
    
    private function _requireAdmin() {
        if (!ACL::requireRoles(array('admin'))) {
            $this->setVar('json', Toolkit::jsonERR(__('No Permission!')));
            return false;
        }
        return true;
    }
    
    private function &_listDir($media_type, $curr_entry) {
    	$root = ROOT.DS.'upload'.DS.strtolower($media_type);
		if (strpos(realpath($root.DS.$curr_entry), $root) === false) {
		    $curr_entry = '';
		}
		$curr_entry = str_replace($root, '', realpath($root.DS.$curr_entry));
		if ($curr_entry != DS) {
		    $curr_entry .= DS;
		}
		
		$dirs = array();
		$files = array();
		
		if (is_dir($root.$curr_entry)) {
		    $o_dir = dir($root.$curr_entry);
		    while (false !== ($entry = $o_dir->read())) {
		        if (preg_match('/^\./', $entry)) {
		            continue;
		        }
		
		        if (is_dir($root.$curr_entry.$entry)) {
		            $dirs[$curr_entry.$entry] = $curr_entry.$entry;
		        } else {
		            $files[] = $entry;
		        }
		    }
		    $o_dir->close();
		}
		
		asort($dirs);
		sort($files);
		
		$files_data =& $this->_pageFiles($files);
		
		$dir_info['dirs'] = $dirs;
		$dir_info['files'] = $files_data['files'];
		$dir_info['pager'] = $files_data['pager'];
		$dir_info['curr_entry'] = $curr_entry;
		
		return $dir_info;
    }
    
    private function &_pageFiles(&$files, $page_param = 'p') {
        $files_data = array();
        
        $pagefiles = array();
        $curr_page =& ParamHolder::get($page_param, 1);
        $start_index = intval(PAGE_SIZE) * ($curr_page - 1);
        $end_index = $start_index + PAGE_SIZE;
        if (sizeof($files) > 0) {
            for ($i = $start_index; $i < $end_index; $i++) {
                if (isset($files[$i])) {
                    $pagefiles[] = $files[$i];
                }
            }
        }
        $pager =& Pager::genPagerLinks($curr_page, sizeof($files), $page_param);
        
        $files_data['files'] = $pagefiles;
        $files_data['pager'] = $pager;
        
        return $files_data;
    }
    
    // 08/06/2010 Add >>
    private function image_mark( $upload_file, $extend )
    {
    	$watermark = '';
    	$image = new Image( $upload_file, $extend );

		// 水印位置
		$watermarkstatus = WATERMARK_STATUS;
		// 水印图片类型(1:PNG 类型水印 2:文本类型水印)
		$watermarktype = WATERMARK_TYPE;
		// 水印添加条件
		$watermarkminwidth = WATERMARK_MIN_WIDTH;
		$watermarkminheight = WATERMARK_MIN_HEIGHT;
		// JPEG 水印质量
		$watermarkquality = WATERMARK_QUALITY;
		
		if( $watermarktype == 2 ) {
			// 文本水印属性
			$watermarktext = array(
				'angle' => WATERMARK_TEXT_ANGLE, 
				'fontpath' => ROOT.'/locale/fangxue.ttf', 
				'color' => WATERMARK_TEXT_COLOR, 
				'shadowcolor' => WATERMARK_TEXT_SHADOW_COLOR, 
				'size' => WATERMARK_TEXT_SIZE, 
				'shadowx' => WATERMARK_TEXT_SHADOWX, 
				'shadowy' => WATERMARK_TEXT_SHADOWY, 
				'text' => WATERMARK_TEXT
			);
			
			$watermarktext['color'] = preg_replace('/#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/e', 
			                          "hexdec('\\1').','.hexdec('\\2').','.hexdec('\\3')", $watermarktext['color']);
			$watermarktext['shadowcolor'] = preg_replace('/#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/e', 
			                          "hexdec('\\1').','.hexdec('\\2').','.hexdec('\\3')", $watermarktext['shadowcolor']);
			                          
			$watermarkpng = '';
		} else {
			// 水印图片
			$watermarkpng = ROOT.'/admin/'.WATERMARK_PNG;
			
			$watermarktext = array();
		}
		
		$watermark = $image->Watermark($watermarkstatus, $watermarktype, $watermarkquality, $watermarkminwidth, 
		                                           $watermarkminheight, $watermarkpng, $watermarktext);
		
		return $watermark;
    }
    // 08/06/2010 Add <<
    
    /**
     * for show title
     */
    private function show_title($blockid)
    {
    	$o_mod_block = new ModuleBlock();
    	
    	$blocks = $o_mod_block->findAll("`id`=?", array($blockid));
    	return $blocks[0]->show_title;
    }
    
    /**
     * delete image
     */
    public function del_image() {
    	$img = urldecode(ParamHolder::get('img', ''));
    	chmod($img, 0755);
    	@unlink($img);
    }
    
}
?>
