<?php
/* 
	trackback receive program trackback.php
	
	Receive trackback ping to item and save log to dataset 'trackback2item'
	
	trackback url:
	http://server_name/trackback.php?kind=item&item_id=(item_id_no)
	
	example: trackback to item_id 99
	http://server_name/trackback.php?kind=item&item_id=99

 ----------------------------------------------
	dataset trackback2item setteings
	
	id								type: id
	item_id						type: int
	title							type: text
	url								type: text
	blog_name				type: text
	excerpt						type: textarea
	x_rating					type: int
	x_rating_icon			type: text or select_text. value are 'star' or 'face'
	ip_address				type: text
	entry_datetime			type: entry_datetime
	update_datetime		type: entry_datetime
	status						type: int or select. value are 1 is OK. 0 is NG.

*/
require_once '../lib/myQuicty.php';

class post_trackback extends myQuicty {

	function dispatch_index() {

		mb_language("ja");
		mb_internal_encoding($this->C['ENCODING']);
		ini_set('mbstring.http_input','pass');

		try {
			if(!is_numeric((int) $_GET['item_id'])) $this->return_fail('Invalid parameter.');//new Exception('Invalid parameter.');
			if($this->is_japanese($_POST['title'].$_POST['excerpt'])===false) $this->return_fail('Invalid language.'); //new Exception('Invalid language.');
			$article = file_get_contents($_POST['url']);
			if($this->is_linked($article,$_SERVER['SERVER_NAME'])===false) $this->return_fail('Link not found.'); //new Exception('Link not found.');

			switch($_GET['kind']) {
				case 'item':
					$insert_set['item_id'] = $_GET['item_id'];
					$data_set_name = 'trackback2item';
					break;
				// If you want recieve trackback ping to review, prepare trackback2review dataset.
				case 'review':
					$insert_set['review_id'] = $_GET['item_id'];
					$data_set_name = 'trackback2review';
					break;
			}
			
			
			$_FORM = $this->new_data_set($data_set_name);
			mb_convert_variables('EUC-JP', 'auto', $_POST );
			if(!$_POST['title']) $_POST['title'] = $_POST['url'];
			if(!$_POST['excerpt']) $_POST['excerpt'] = $_POST['title'];
			if(mb_strlen($_POST['excerpt']) > 128) $_POST['excerpt'] = mb_substr($_POST['excerpt'],0,128)."...";
			if($v_result = $_FORM->validate()) {
				$insert_set['url'] = $_POST['url'];
				$insert_set['title'] = $_POST['title'];
				$insert_set['blog_name'] = $_POST['blog_name'];
				$insert_set['excerpt'] = $_POST['excerpt'];
				$insert_set['status'] = 1;
				$insert_set['ip_address'] = $_SERVER['REMOTE_ADDR'];
				list($d['Y'],$d['m'],$d['d'],$d['H'],$d['i']) = explode("-",date("Y-m-d-H-i"));
				$insert_set['entry_datetime'] = $d;
				$insert_set['update_datetime'] = $d;
				// livedoor Blog compatible rating
				if(is_numeric($_POST['x-rating']) and $_POST['x-rating']<6) {
					$insert_set['x_rating'] = (int) $_POST['x-rating'];
					if($_POST['x-rating-icon']) {
						$insert_set['x_rating_icon']['x_rating_icon'] = $_POST['x-rating-icon'];
					}
				} else {
					$insert_set['x_rating'] = 0;
				}
				$result = $_FORM->insert_table($insert_set);
				if($result[$data_set_name]['state']==1) {
					/*
					if($this->preference['notify_trackback']==1) {
						$trackback_id = $result[$data_set_name]['id'];
						$to = array('name'=>$this->user['family_name'].$this->user['given_name'],'email'=>$this->user['email']); 
						$this->notify_trackback($to,$trackback_id);
					}
					*/
					$this->return_success();
				} else {
					new Exception('your trackback is failed!');
				}
			} else {
				new Exception('missing url');
			}
		} catch (Exception $e) {
			$this->return_fail($e->getMessage());
		}
	}

/*
	function notify_trackback($to,$trackback_id) {
		$from = array('name'=>$this->C['WEB_MASTER'],'email'=>$this->C['WEB_MASTER_EMAIL']);
		$subject = $this->site['name'].$this->CE(' トラックバック通知');
		$url = $_POST['url'];
		$blog_title = $_POST['title'];
		$blog_name = $_POST['blog_name'];
		$excerpt = $_POST['excerpt'];
		$ip_address = $_SERVER['REMOTE_ADDR'];
		$entry = $this->get_entries('where id='.$_GET['book_id']);
		$title = $entry[0]['title']['value'];
		list($year,$month,$day) = explode('-',substr($entry[0]['latest']['value'],0,10));
		$permalink = $this->blog_url.'/'.$year.'/'.$month.'/'.$day.'/'.$entry[0]['id']['value'].'.html';
		$deletelink = 'http://'.$this->C['CMS_SERVER'].'/cms/trackback/delete/?id='.$trackback_id;
		$site_name = $this->site['name'];
		$article = "\n".<<<END_OF_MESSSAGE
「 $title 」にトラックバックがありました。
$permalink

Posted by $author
email:$email

title:$blog_title | $blog_name
URL:$url
IP:$ip_address

$excerpt

このコメントの削除用URL
$deletelink
※このメールには返信できません。ご注意ください。

----------------
$site_name

END_OF_MESSSAGE;
		$article = $this->CE($article);
		$mail = $this->new_mail_obj($from,$to,$subject,$article);
		$queue = $this->new_mail_queue('mail_queue.set.conf');
		$result = $queue->set_mail($mail);
		return $result;
	}
*/


	function is_japanese($string) {
		$encode = mb_detect_encoding ($string);
		$jp_encodes = array(
			'UTF-16',
			'UTF-16BE',
			'UTF-16LE',
			'UTF-8',
			//'ASCII',
			'EUC-JP',
			'SJIS',
			'eucJP-win',
			'SJIS-win',
			'ISO-2022-JP',
			'JIS',
		);
		if(in_array($encode,$jp_encodes)) {
			$result = $encode;
		} else {
			$result = false;
		}
		return $result;
	}
	
	
	function is_linked($string,$url) {
		$position = strpos($string,$url);
		if($position AND preg_match("/<a href=\".*?$url.*?\">/i",$string)) {
			$result = $position;
		} else {
			$result = false;
		}
		return $result;
	}

	function return_success() {
		$result = <<<END_OF_XML
<?xml version="1.0" encoding="iso-8859-1"?>
<response>
	<error>0</error>
</response>
END_OF_XML;
		header("Content-type: application/xml");
		echo $result;
		//echo "_POST=";print_r($_POST);
	}

	function return_fail($message) {
		$result = <<<END_OF_XML
<?xml version="1.0" encoding="iso-8859-1"?>
<response>
	<error>1</error>
	<message>$message</message>
</response>
END_OF_XML;
		header("Content-type: application/xml");
		echo $result;
		exit;
	}

} // end of post_trackback class
$quicty = new post_trackback();
$quicty->dispatch_index();
?>