<!DOCTYPE html>
<html lang="es">
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['recaptcha_response'])) {
  $title;$text;$captcha;
  $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
  $text = filter_input(INPUT_POST, 'text', FILTER_SANITIZE_STRING);
  $captcha = filter_input(INPUT_POST, 'recaptcha_response', FILTER_SANITIZE_STRING);

  if(!$captcha){
    echo '<h2>Por favor, rellene el captcha</h2>';
    exit;
  }

  $secretKey = "6Lemu_4UAAAAAFzGfmohVtEUrvb8Xxfh3mR9Bmnn";
  $ip = $_SERVER['REMOTE_ADDR'];
  $url = 'https://www.google.com/recaptcha/api/siteverify';
  $data = array('secret' => $secretKey, 'response' => $captcha);
  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
  );

  $context  = stream_context_create($options);
  $response = file_get_contents($url, false, $context);
  $responseKeys = json_decode($response,true);

  if($responseKeys["success"]) {
    $string = utf8_encode($title);
    $string = iconv('UTF-8', 'ASCII//TRANSLIT', $string);   
    $string = preg_replace('/[^a-z0-9- ]/i', '', $string);
    $string = str_replace(' ', '-', $string);
    $string = trim($string, '-');
    $string = strtolower($string);

    if (empty($string)) {
        return 'n-a';
    }

    $fp = fopen("/srv/www/terranetworks/posts/${string}.post","w+");
    flock($fp, LOCK_EX);

    fwrite($fp, "$title\n");
    fwrite($fp, "$text\n");

    flock($fp, LOCK_UN);
    fclose($fp);

	exec("/srv/www/terranetworks/nuevopost.sh");

	echo '<meta http-equiv="refresh" content="5;url=/" />';

	$result = "created";
  } else {
	$result = "fail";
    $msg = "Invalid captcha!";
  }
}
?>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv='content-type' content='text/html;charset=utf-8' />
  <meta name="description" content="Terra Networks Blog"/>
  <title>Terra Networks Blog</title>
  <link rel="shortcut icon" href="/favicon.png"/>
  <link rel="apple-touch-icon" href="/apple-touch-icon.png"/>
  <link rel="stylesheet" type="text/css" href="/main.css" media="all" />
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="https://www.google.com/recaptcha/api.js?render=6Lemu_4UAAAAAMbIepO_Lgq9tFvWJG7tsdD32QJ9"></script>
  <script>
    grecaptcha.ready(function () {
      grecaptcha.execute('6Lemu_4UAAAAAMbIepO_Lgq9tFvWJG7tsdD32QJ9', { action: 'contact' }).then(function (token) {
        var recaptchaResponse = document.getElementById('recaptchaResponse');
        recaptchaResponse.value = token;
      });
    });
  </script>
</head>
<body>
  <div class="header">
    <a class="logo" href="/">Terra Networks Blog</a>
    <a class="title" href="/posts/historia-de-terra.html">Historia de Terra</a>
    <a class="enlacemenu" href="/contacto.php">Contacto</a>
    <a class="separamenu"></a>
    <a class="enlacemenu" href="/conocenos.html">Conócenos</a>
    <a class="separamenu"></a>
    <a class="enlacemenu" href="/historia.html">Historia de Terra</a>
    <a class="separamenu"></a>
    <a class="enlacemenu" href="/addpost.php">Crear artículo</a>
    <a class="separamenu"></a>
  </div>   

  <div class="content">
<?php
if ($result === "fail") {
  echo "<div class=\"alert alert-danger display-error\" style=\"display: block\">";
  echo "$msg";
  echo "</div>";
} elseif ($result === "created") {
  echo "<br/>";
  echo "<br/>";
  echo "El artículo ha sido creado y se ha enviado a revision!";
  echo "<br/>";
  echo "<br/>";
  echo "Redirigiento a la página principal...";
} else {
echo '        <div class="text-center">';
echo '          <h1 class="entry-title">Crear artículo</h1>';
echo '        </div>';
echo '          <form class="frmNewPost" id="form" method="post">';
echo '				<label>Título</label>';
echo '              <input type="text" class="frmTitle" id="title" name="title" required>';
echo '              <br/>';
echo '				<label>Contenido (formato Markdown)</label>';
echo '      		<textarea class="frmText" id="text" name="text" rows="10" required></textarea>';
echo '              <input type="hidden" name="recaptcha_response" id="recaptchaResponse">';
echo '              <h6>El artículo se envía a revisión antes de ser publicado</h6>';
echo '              <input type="submit" name="submit" value="Crear artículo"><br><br>';
echo '              <input type="button" value="Cancelar" onclick="history.back()">';
echo '          </form>';
}
?>
  </div>
  <div class="footer">
    Copyright &copy; Telefónica de España S.A.U.
  </div>
</body>
</html>

