<?php
/*

     WordPress免登录发布接口,支持最新Wordpress4.7.x版本。最新验证支持Wordpress4.7.x
     最后更新2017-01-03
     适用于火车头采集器等任意采集器或脚本程序进行日志发布。
     */
$auto_cate = true; // 是否自动建立分类 true | false
//$post_author = $_POST['post_author']; // 发布文章的用户名，必需是已注册用户
//$save    = "save";//发布到草稿箱
$post_status = 'publish'; // 发布文章的状态 "publish"：立即发布，
$next_time = 2500; // 随机时间发布，每篇帖子的间隔秒数；如果设置此项，提交的日期将会失效
$post_exists = true; // 是否判断标题重复 true | false

@$comment_users = $_POST['post_author']; // 本接口支持回复，可以采集回复的用户名，如果没有，可以从这些默认用户中选择，多个用户之间使用|||分开


## 配置段结束，下面的代码一般不需要修改 ##

// 加载接口所必需的文件
@header('Content-Type: text/html; charset=UTF-8');
require('./wp-load.php');
require_once(ABSPATH . 'wp-admin/includes/admin.php');
@extract($_REQUEST,EXTR_OVERWRITE);

// 手工重设初始时间
if (!empty($reset_time)) {
	echo "请重设最终发布时间，格式为：2012-02-02 11:11:11<br /><form method=\"post\" action=\"\">\r\n\t设置时间：<input type=\"text\" name=\"set_last_time\" value=\"".gmdate('Y-m-d H:i:s', time() + ( get_option( 'gmt_offset' ) * 3600 ))."\">\r\n\t删除设置：<input type=\"checkbox\" name=\"del_last_time\">\r\n\t<input type=\"submit\">\r\n</form>";

	if ($set_last_time) {
		if (get_option('locoy_post_time')) {
			update_option( 'locoy_post_time', strtotime( $set_last_time ));	
			echo "<hr>更新成功！";
		} else {
			add_option('locoy_post_time', strtotime( $set_last_time ));
			echo "<hr>设置成功！";
		}
	} 
	if ($del_last_time) {
		delete_option('locoy_post_time');
		echo "<hr>删除成功！";
	}
	echo "<hr>";

	if (get_option( 'locoy_post_time' )) {
		echo "当前最终发布时间设置为：" . gmdate('Y-m-d H:i:s', get_option( 'locoy_post_time' ));
	} else {
		echo "当前没有设置最终发布时间！";
	}
	exit();
}

// 判断标题是否重复
if ($post_exists) {
	if (post_exists($post_title)) {
		exit("[OK] Title exists");
	}
}

// 刷新分类列表
if (empty($post_title)) {
	wp_dropdown_categories(array(
		'hide_empty' => 0, 
		'hide_if_empty' => false, 
		'taxonomy' => 'category', 
		'name' => 'parent', 
		'orderby' => 'name', 
		'hierarchical' => true, 
		'show_option_none' => __('None'))
	);
	exit();
}

// 自动建立分类
if (!empty($post_category) && $auto_cate == true) {
	$post_category_id = array();
	$parent = 0;
	$cats = array_filter(explode('|||', $post_category));
	foreach ($cats as $key => $value) {
		$parent = wp_create_category($value, (int)$parent);
		$post_category_id[] = $parent;
	}	
} else {
	$post_category_id = @explode(",",$post_category_id);
}

// 获取发贴ID
$user_ID = get_user_by('login', $post_author) -> ID; 
$user_ID = !$user_ID ? 1 : $user_ID;

// 获取下次发布时间
if (is_numeric($next_time) && $next_time > 3) {
	if (get_option('locoy_post_time')) {
		$last_post_time = get_option( 'locoy_post_time' );
		$post_time = ( $last_post_time + $next_time );
		update_option( 'locoy_post_time', $post_time );		
	} else {
		$post_time =  time() ;
		add_option('locoy_post_time', $post_time);
	}
} elseif ($post_time) {
	$post_time = strtotime( $post_time );
} else {
	$post_time =  time() ;
}

// 初始化发贴信息
$post_info = array(
	'post_status' => $post_status, 
	'post_type' => 'post', 
	'post_author' => $user_ID,
	'ping_status' => get_option( 'default_ping_status' ), 
	'comment_status' => get_option( 'default_comment_status' ),
	'post_pingback' => get_option( 'default_pingback_flag' ),
	'post_parent' => 0,
	'menu_order' => 0, 
	'to_ping' => '', 
	'pinged' => '', 
	'post_password' => '',
	'guid' => '', 
	'post_content_filtered' => '', 
	'post_excerpt' => $post_excerpt, 
	'import_id' => 0,
	'post_content' => $post_content, 
	'post_title' => $post_title, 
	'post_category' => $post_category_id,
	'post_name' => trim($post_name),
	'post_date_gmt' => get_gmt_from_date(gmdate('Y-m-d H:i:s', $post_time + ( get_option( 'gmt_offset' ) * 3600 ))),
	'post_date' => gmdate('Y-m-d H:i:s', $post_time + ( get_option( 'gmt_offset' ) * 3600 )), 
	'tags_input' => array_unique(array_filter(explode('|||', $tags))),
);

// 发布文章
$pid = wp_insert_post($post_info); 
set_post_format($pid, '');
if ($pid) {
	echo "[OK] $pid";
} else {
	exit('error');
}

// 更新自定义字段
if (is_array($tax_input) && !empty($tax_input)) {
	foreach (array_unique(array_filter($_POST['tax_input'])) as $key => $value) {
		add_post_meta($pid, $key, $value, true);
	}
}
// 添加回复
if (!empty($post_comment)) { 
	$comm_array = explode('|||', $post_comment);
	$comm_user_array = array_filter(explode('|||', $comment_users));
	$comm_date = empty($comment_date) ? gmdate('Y-m-d H:i:s', $post_time + ( get_option( 'gmt_offset' ) * 3600 )) : $comment_date;

	foreach ($comm_array as $comm_key => $comm_value) {
		$comm_date = gmdate('Y-m-d H:i:s' , (strtotime($comm_date) + rand(6000, 12000)));
		$comm = array(
			"comment_post_ID" => $pid,
			"comment_author"=>$comm_user_array[array_rand($comm_user_array)], 
			"comment_date"=>$comm_date,
			"comment_date_gmt" =>  get_gmt_from_date($comm_date),
			);

		preg_match_all("~\[(user|time)#([^\]<>]*?)\]~i", $comm_value, $temp);
		if (is_array($temp[1]) && is_array($temp[2]) && !empty($temp[1])) {
			$comm_info_new = array_combine($temp[1],$temp[2]);
			print_r($comm_info_new);
			if (!empty($comm_info_new['user'])) {
				$comm['comment_author'] = $comm_info_new['user'];
			}
			if (!empty($comm_info_new['time'])) {
				$comm['comment_date'] = gmdate('Y-m-d H:i:s' , strtotime($comm_info_new['time']));
				$comm['comment_date_gmt'] =  get_gmt_from_date($comm['comment_date']);
			}
		}

		$comm['comment_content'] =preg_replace("~\[(user|time)#([^\]<>]*?)\]~i", "", $comm_value);
		$comm['comment_approved'] = 1;
		
		wp_insert_comment($comm);
		unset($comments,$comm_info);
	}
}
// 添加特色图
if ($post_image) {
	$post_image = trim($post_image);
	$extension = pathinfo($post_image,PATHINFO_EXTENSION);
	$file_extension = !$extension ? "jpg" : $extension;
	$file_name = uniqid() . "." . $file_extension;
	$uploads = wp_upload_dir($post_time);
	$file_path = $uploads["path"].$file_name;

	if (httpcopy($post_image,$file_path)) {
	    /*
		$type = @getimagesize($file_path);
		$attachment = array(
				'post_mime_type' => $type["mime"],
				'guid' => $uploads["url"].$file_name,
				'post_parent' => $pid,
				'post_title' => $file_name,
				'post_content' => "",
			);
		$thumbnail_id = wp_insert_attachment($attachment, $file_path, $pid);
		set_post_thumbnail( $pid, $thumbnail_id );
		*/
	//var_dump($uploads);
	//var_dump($file_name);
	$post_parent = $pid;
	$image = "wp-content/uploads".$uploads['subdir'].$file_name;
	$imginfo = @getimagesize($image);
	$picfile = str_replace('wp-content/uploads/','',$image);
	$post_mime_type = $imginfo['mime'];
	$post_name = trim($post_name);
	$post_date  = gmdate('Y-m-d H:i:s', $post_time + ( get_option( 'gmt_offset' ) * 3600 ));
	$post_date_gmt = get_gmt_from_date(gmdate('Y-m-d H:i:s', $post_time + ( get_option( 'gmt_offset' ) * 3600 )));
	$att_data = compact('post_author', 'post_date', 'post_date_gmt','post_parent','post_name','post_mime_type');
	$att_data = add_magic_quotes($att_data);
    $attID = wp_insert_attachment($att_data);
	$row = $wpdb ->get_results("SELECT * FROM $wpdb->options where option_name in ('thumbnail_size_w','thumbnail_size_h');");
	$thumbcfg =array();
    foreach($row as $row){
    $thumbcfg[$row->option_name] = $row->option_value;
    }
	$thumb = $image."_thumb.".pathinfo($image,PATHINFO_EXTENSION);
	new resizeimage($image, $thumbcfg['thumbnail_size_w'], $thumbcfg['thumbnail_size_h'], 1 ,$thumb);
	$thumbfile = basename($thumb);
	$thumbinfo= getimagesize($thumb);
	$context =Array('width' =>$imginfo[0],'height' => $imginfo[1],'file' =>$picfile,'sizes' => Array('thumbnail' => Array('file' =>$thumbfile,'width' => $thumbinfo[0],'height' =>$thumbinfo[1],'mime-type' =>$post_mime_type)),'image_meta' => Array('aperture' => 0,'credit' =>'','camera' =>'','caption' =>'','created_timestamp' => 0,'copyright' => '','focal_length' => 0,'iso' => 0,'shutter_speed' => 0,'title' =>''));
	add_post_meta( $attID, '_wp_attached_file', $picfile);
	add_post_meta( $attID, '_wp_attachment_metadata', $context);
	add_post_meta( $pid, '_thumbnail_id',$attID);
	$guid = wp_get_attachment_url($attID);
	$wpdb->get_results("update $wpdb->posts set guid = '$guid' where ID='$attID'");
	}
}



function httpcopy($url, $file="", $timeout=60) {
	$file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
	$dir = pathinfo($file,PATHINFO_DIRNAME);
	!is_dir($dir) && @mkdir($dir,0755,true);
	$url = trim(str_replace(" ","%20",$url));

	if(function_exists('curl_init')) {
	 	$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		$temp = curl_exec($ch);
		if(@file_put_contents($file, $temp) && !curl_error($ch)) {
			return $file;
		} else {
			return false;
		}
	} else {
		$opts = array(
			"http"=>array(
			"method"=>"GET",
			"header"=>"",
			"timeout"=>$timeout)
		);
		$context = stream_context_create($opts);
		if(@copy($url, $file, $context)) {
			return $file;
		} else {
			return false;
		}
	}
}
class resizeimage
{
    //图片类型
    var $type;
    //实际宽度
    var $width;
    //实际高度
    var $height;
    //改变后的宽度
    var $resize_width;
    //改变后的高度
    var $resize_height;
    //是否裁图
    var $cut;
    //源图象
    var $srcimg;
    //目标图象地址
    var $dstimg;
    //临时建的图象
    var $im;
    function resizeimage($img, $wid, $hei,$c,$dimg)
    {
        $this->srcimg = $img;
        $this->resize_width = $wid;
        $this->resize_height = $hei;
        $this->cut = $c;
        //图片的类型
        $this->type = substr(strrchr($this->srcimg,"."),1);
        //初始化图象
        $this->initi_img();
        //目标图象地址
        $this -> dstimg = $dimg;
        //--
        $this->width = imagesx($this->im);
        $this->height = imagesy($this->im);
        //生成图象
        $this->newimg();
        ImageDestroy ($this->im);
    }
    function newimg()
    {
        //改变后的图象的比例
        $resize_ratio = ($this->resize_width)/($this->resize_height);
        //实际图象的比例
        $ratio = ($this->width)/($this->height);
        if(($this->cut)=="1")
        //裁图
        {
            if($ratio>=$resize_ratio)
            //高度优先
            {
                $newimg = imagecreatetruecolor($this->resize_width,$this->resize_height);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width,$this->resize_height, (($this->height)*$resize_ratio), $this->height);
                ImageJpeg ($newimg,$this->dstimg);
            }
            if($ratio<$resize_ratio)
            //宽度优先
            {
                $newimg = imagecreatetruecolor($this->resize_width,$this->resize_height);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width, $this->resize_height, $this->width, (($this->width)/$resize_ratio));
                ImageJpeg ($newimg,$this->dstimg);
            }
        }
        else
        //不裁图
        {
            if($ratio>=$resize_ratio)
            {
                $newimg = imagecreatetruecolor($this->resize_width,($this->resize_width)/$ratio);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, $this->resize_width, ($this->resize_width)/$ratio, $this->width, $this->height);
                ImageJpeg ($newimg,$this->dstimg);
            }
            if($ratio<$resize_ratio)
            {
                $newimg = imagecreatetruecolor(($this->resize_height)*$ratio,$this->resize_height);
                imagecopyresampled($newimg, $this->im, 0, 0, 0, 0, ($this->resize_height)*$ratio, $this->resize_height, $this->width, $this->height);
                ImageJpeg ($newimg,$this->dstimg);
            }
        }
    }
    //初始化图象
    function initi_img()
    {
        if($this->type=="jpg")
        {
            $this->im = imagecreatefromjpeg($this->srcimg);
        }
        if($this->type=="gif")
        {
            $this->im = imagecreatefromgif($this->srcimg);
        }
        if($this->type=="png")
        {
            $this->im = imagecreatefrompng($this->srcimg);
        }
    }

}
?>