<?php
 /**
 * Magic CMS 读取最新消息
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Date:2014/12/31
**/

if (!defined('KERNEL_PATH'))exit('No direct script access allowed');
class IndexModule extends CommonModule{

	/*
	 * 消息文件命名规则
	 * 消息类型-数据库字段ID-消息时间-随机字符串
	*/
	public function index(){
		if (IS_AJAX && IS_GET) {
			$path = C('MESSAGE_PATH');
			$list = scandir($path);

			$msgtips = array(
				'order'      => array(
					'0'      => '您有{number}个新订单',
					'1'      => '您有{number}个订单尚未发货',
					'url'    => '?r=order',
					'sounds' => 'msg_2.mp3'
				),
				'gbook'      => array(
					'0'      => '您有{number}条新留言',
					'url'    => '?r=guestbook',
					'sounds' => 'msg_1.mp3'
				),
				'comment' => array(
					'0'      => '您有{number}条新评论',
					'url'    => '?r=comment',
					'sounds' => 'msg_1.mp3'
				),
			);
			unset($list[0],$list[1]);

			if (!empty($list)){
				foreach ($list  as $file) {
					$status = file_get_contents($file);
					$file   = base64_decode($file);
					if (strpos($file,'.msg')) {
						$temp_content = explode('-',$file);

						$temp_message[$temp_content[0]][$status] = $temp_message[$temp_content[0]][$status]+1;
						$last_message[$temp_content[2]] = $temp_content[0];
					}
				}

				foreach ($temp_message  as $key=>$value) {
					foreach ($value  as $keys=>$count) {
						$msgcont   += $count;
						$message[] = '<a href="'.$msgtips[$key]['url'].'" target="rightframe">'.str_ireplace('{number}',$count,$msgtips[$key][$keys]).'</a>';
					}
				}
			}

			if (!empty($message)) {
				if ($msgcont>intval($_COOKIE['magic_message_count'])) {
					ksort($last_message,SORT_NUMERIC);
					$sounds = $msgtips[end($last_message)]['sounds'];
					$news = 1;
				}else{
					$news = 0;
				}
				setcookie('magic_message_count',$msgcont);
				$this->assign('sounds',$sounds);
				$this->assign('news',$news);
				$this->assign('message',$message);
				$content = $this->display('Message/index',null,  null,null,null,false);
				echo json_encode(array('success'=>1,'news'=>$news,'count'=>$msgcont,'content'=>$content));
			}else{
				setcookie('magic_message_count',0);
				echo json_encode(array('success'=>0,'count'=>0));
			}
		}
	}
}