<?php
include '../env.php';
require_once(LIB.'common.inc.php');
require_once(LIB.'Post.class.php');
if (can_action('post')) {
	$post = new Post();

	$anonymous = @$_POST['anonymous'];
	$user = empty($_SESSION['user']) ? NULL : $_SESSION['user'];
	if (empty($user)) {
		$anonymous = TRUE;
		if (!can_action('anonymous'))
			$_SESSION['trip'] = $_POST['trip'] = '';
	} else {
		if ($anonymous && !can_action('anonymous')) {
			$anonymous = FALSE;
			$_SESSION['trip'] = $_POST['trip'] = '';
		}
	}

	$_SESSION['anonymous'] = $anonymous;
	if ($anonymous)
		$_SESSION['trip'] = @$_POST['trip'];

	$c = @$_POST['c'];

	if (ENABLE_IMG_UPLOAD && !empty($_FILES['f'])) {
		require_once(LIB.'TImage.class.php');
		$imgObj = new TImage($_FILES['f']);
		if (! $imgObj->check()) {
			_a_log_fail('post', 'create', 'invalid image type');
			header('HTTP/1.0 500 Internal Server Error');
			die;
		}

		$url = $imgObj->save();
		if (! $url) {
			_a_log_fail('post', 'create', 'failed save image');
			header('HTTP/1.0 500 Internal Server Error');
			die;
		}

		$c = $url."\n".$c;
	}

	$log_ret = _a_log2('post', 'create', array('detail' => $c));
	if ($log_ret) {
		$ret = $post->post(
			$c,
			$anonymous ? TRUE : FALSE,
			$user,
			$_SESSION['trip'],
			$_GET
		);
		if ($ret === FALSE) {
			_a_log_fail('post', 'create', $c. ': '.serialize($_GET));
			header('HTTP/1.0 500 Internal Server Error');
			die;
		}
		_a_log_write($log_ret, array(
			'target_id' => $ret,
			//これのが若干DBにやさしい 'detail' => NULL
		));

		require_once(LIB.'User.class.php');
		$user = new User();
		$user->tryUpdateSetting();

		$content = $post->readBasic($ret);
		echo json_encode($content);
	} else {
		header('HTTP/1.0 500 Internal Server Error');
		die;
	}
}
?>