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

	public function index(){
		$token = include_once(ROOT_PATH.'Data/Oauth/baidu_config.php');

		$date = Q('get.date');

		if (isset($date)){
			switch ($date){
				case 'today'://今天
				  $condition = "  FROM_UNIXTIME(pubtime,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d')  ";
				  break;
				case 'yesterday': //昨天
				  $condition = "  FROM_UNIXTIME(pubtime,'%Y-%m-%d') = date_sub(curdate(),interval 1 day)  ";
				  break;
			    case 'week': //近一个星期
			      $condition = "  FROM_UNIXTIME(pubtime,'%Y-%m-%d') <= date_sub(curdate(),interval 7 day)  ";
			     break;
			    case 'month': //近一个月
			     $condition = "  FROM_UNIXTIME(pubtime,'%Y-%m-%d') <= date_sub(curdate(),interval 30 day)  ";
			     break;
			}
		}

		$list = M('art_library')->where($condition)->all();
		$this->assign('token', $token['token']);
		$this->assign('list', $list);
		$this->display();
	}

	public function savetoken(){
		$token = Q('get.token');
		if(empty($token)) $this->error('请输入百度站长平台密钥');
		$content = "<?php ".PHP_EOL." return array(";
		$content .= PHP_EOL."'token'  =>'".$token."'";
		$content .= PHP_EOL.");".PHP_EOL."?>";
		Files::writeFiles(ROOT_PATH.'Data/Oauth/baidu_config.php',$content);
		$this->success('保存成功','?r=Linksubmit');
	}

	public function submit(){
		$urls  = array();
		$aid   = implode(',',Q('post.aid'));
		$surls = $_POST['surls'];
		$token = Q('post.token');
		$site  = 'http://'.$_SERVER['HTTP_HOST'];
		if (empty($aid) && empty($surls)){$this->error('请选择要推送的文档！');}
		//加载前端配置文件
		require(ROOT_PATH . 'Data/Config/config.php');

		if(!empty($aid) || !empty($surls)){

		$list = M()->join('__art_library__ a JOIN __class__ b ON a.catid=b.catid')->field('a.*,b.savepath,b.catroute,b.artroute')->where('a.id IN('.$aid.')')->all();

		$suri = $config['SYSTEM_MODE'] == 2 ? 2 : 1;

		foreach ($list as $data){
			//替换URL中的变量
			$route_arr = array('{cpath}'=>$data['savepath'],'{cid}'=>$data['catid'],'{aid}'=>$data['id'],'{y}'=>date('Y',$data['pubtime']),'{m}'=>date('m',$data['pubtime']),'{d}'=>date('d',$data['pubtime']));

			foreach ($route_arr as $key=>$value){
				$urlroute = str_ireplace($key,$value,$urlroute);
			}



			$uri=array(
				'1'=>array(
					'list'   =>'/?r=list'.'&id='.$data['catid'],
					'content'=>'/?r=list-content&id='.$data['id'],
				),
				'2'=>array(
					'channel'=>'/?r='.$data['model'],
					'list'   =>'/?r='.$data['model'].'&id='.$data['catid'],
					'content'=>'/?r='.$data['model'].'-content&id='.$data['id'],
				)
			);

			if($config['URL_REWRITE']){
				$urls[] = $site.$urlroute;
			}else{
				//如果是外链则直接返回
				if (!empty($data['linkurl'])){
					$urls[] = $data['linkurl'];
				}else{
					$urls[] = $site . $uri[$suri]['content'];
				}
			}
		}

		$aurls = array_filter(array_merge($urls,explode(PHP_EOL,$surls)));

		$api = 'http://data.zz.baidu.com/urls?site='.$site.'&token='.$token;

		$ch = curl_init();
		$options =  array(
			CURLOPT_URL => $api,
			CURLOPT_POST => true,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POSTFIELDS => implode("\n", $aurls),
			CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
		);
		curl_setopt_array($ch, $options);
		$result = analyJson(curl_exec($ch));
		if ($result->error==401){
			$this->error('百度站长平台密钥(token)错误！');
		}elseif($result->error==404){
			$this->error('接口地址填写错误');
		}elseif($result->error==500){
			$this->error('服务器偶然异常，请稍后再试');
		}elseif($result->error==400){
			$this->error($result->message.' (具体含义请参考百度站长平台官方说明)');
		}else{
			$msg = '推送成功！您成功推送了'.$result->success.' 条数URL，当天还可推送'.$result->remain.' URL条数';
			$this->success($msg,'?r=linksubmit');
		}

	}
	}
}