<?
  function performQuery($query)
  {
    include("../conf/mysql.conf");
    $id = mysql_connect($host, $user, $pass) or die("[ Service temporairement inactif ]");
    mysql_select_db($bdd) or die("[ Base de données inacessible ]");
    if ($host == 'localhost')
      $result = mysql_query($query, $id) or die("[ ".mysql_error()." ]");
    else
      $result = mysql_query($query, $id) or die("[ Service temporairement inactif ]");
    mysql_close($id);
    return $result;
  }

  $title      = htmlspecialchars($_POST["title"]);
  $comment    = nl2br(htmlspecialchars($_POST["comment"]));
  $categoryid = $_POST["categoryid"];
  $image      = $_FILES["image"]["tmp_name"];
  $image_name = urlencode($_FILES["image"]["name"]);

  $array = explode(".", $image_name);
  if ($array[0] != $_POST["maxfilesize"])
    exit();

  if ($title == "")
  {
    print "Aucun titre";
    exit();
  } else {
    $img_temp = @imagecreatefromjpeg($image);
    if (!$img_temp)
    {
      print "L'image n'est pas au format JPEG.";
      exit();
    } else {
      $image_name = "" . time() . ".jpg";
      copy($image, "../gallery/$image_name");

      $img_width  = imagesx($img_temp);
      $img_height = imagesy($img_temp);
      $new_width = $img_width;
      $new_height = $img_height;

      if ($img_width > $img_height)
      {
        $ratio = $img_width * 1.0 / 128;
        $new_height = $img_height / $ratio;
        $new_width  = 128;
      } else {
        $ratio = $img_height * 1.0 / 96;
        $new_width  = $img_width / $ratio;
        $new_height = 96;
      }

      $thumb = imagecreatetruecolor($new_width, $new_height);
      imagecopyresampled($thumb, $img_temp, 0, 0, 0, 0, $new_width, $new_height,
                         imagesx($img_temp), imagesy($img_temp));
      imagejpeg($thumb, "../gallery/thumbs/".$image_name);

      $date   = date("d/m/Y - H:i"); 
      $query  = "INSERT INTO gallery VALUES ('', '$image_name', '$title', '$comment', '$categoryid', '$date')";
      $result = performQuery($query);
      if ($result)
        print "Image ajoutée.";
      else
        print "Problème d'insertion dans la base de données.";
    }
  }
?>
