<?php
  if (!isset($_COOKIE['joe'])) {
    header('Location: /login.php?goto=' . urlencode($_SERVER['REQUEST_URI']));
  }
?>
<?php
  include 'image_manip.php';
?>
<?php
  $messages = array();
?>
<?php
  $pieces = explode("/", getcwd());
  $name = end($pieces);
?>
<?php
  $db = mysql_connect('localhost', 'joe', 'fixture');
  $db_selected = mysql_select_db('udn', $db);
  if (!$db or !$db_selected) {
    die('Could not connect: ' . mysql_error());
  }
?>
<?php
  if (array_key_exists("Retrofit", $_POST)) {
    exec("perl ./retrofit.pl");
  }
?>
<?php
  if (array_key_exists("Purge", $_POST)) {
    unlink("index.php");
    mysql_query(sprintf("delete from gallery where id = %d", 
      (integer)$_POST["gallery_id"]));
    mysql_query(sprintf("delete from images where gallery_id = %d", 
      (integer)$_POST["gallery_id"]));
  }
?>
<?php
  if (array_key_exists("Save", $_POST) or 
      array_key_exists("Publish", $_POST) or
      array_key_exists("Upload", $_POST)) {
    $categories = join('|', $_POST["category"]);
    mysql_query(sprintf("update gallery set 
      title=\"%s\", subtitle=\"%s\", copyright=\"%s\", contributor=\"%s\",
      location=\"%s\", categories=\"%s\", extended_title = %s
      where id = %d", 
      mysql_real_escape_string($_POST["title"]), 
      mysql_real_escape_string($_POST["subtitle"]), 
      mysql_real_escape_string($_POST["copyright"]), 
      mysql_real_escape_string($_POST["contributor"]), 
      mysql_real_escape_string($_POST["location"]), 
      $categories,
      (array_key_exists("extended_title", $_POST) ? 'true' : 'false'),
      $_POST["gallery_id"]
    ));
    mysql_query(sprintf("update images set email = false where gallery_id = %d",
     (integer)$_POST["gallery_id"]));
    mysql_query(sprintf("update images set email = true where id = %d", 
      $_POST["email"]));
    foreach (array_keys($_POST) as $key) {
      if (preg_match('/^image_comment/', $key)) {
        preg_match('/\d+$/', $key, $matches); 
        $id = $matches[0];
        mysql_query(sprintf(
          "update images set comment = \"%s\" where id = %d", 
          mysql_real_escape_string($_POST[$key]), $id
        ));
      }
    }
  }
?>

<?php
  if (array_key_exists("Delete", $_GET)) {
    mysql_query(sprintf("delete from images where id = %d", 
      (integer)$_GET["image_id"]));
  }
?>
<?php
  if (array_key_exists("Publish", $_POST)) {
    copy("preview.php", "index.php");
    mysql_query(sprintf("update gallery set published = true where id = %d", 
      (integer)$_POST["gallery_id"]));
    if (!file_exists('index.html')) {
      exec(sprintf('/usr/local/udn_php/helper/update_mainindex.pl "%s" "%s" "%s"',
        $name, $_POST['title'], $_POST['location']));
    }
  }
?>
<?php
  if (array_key_exists("Unpublish", $_POST)) {
    unlink("index.php");
    mysql_query(sprintf("update gallery set published = false where id = %d", 
      (integer)$_POST["gallery_id"]));
  }
?>

<?php
  if (array_key_exists("Upload", $_POST)) {
    $target_filename = basename($_FILES['uploadedfile']['name']);
    $target_filename = preg_replace('/[^A-Za-z0-9_.]/', '', $target_filename);
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
        $target_filename)) {
      chmod($target_filename, 0644);
      $resize_filename = image_resize($target_filename);
      $size = image_size($resize_filename);
      $gallery_id = (integer)$_POST["gallery_id"];
      $result = mysql_query(
        "select count(*) from images where gallery_id = $gallery_id");
      $row = mysql_fetch_row($result);
      $image_count = $row[0];
      

      $insert = sprintf('insert into images 
        (gallery_id, src, width, height, sequence, email) 
        values (%d, "%s", %d, %d, %d, "%s")', 
        $gallery_id, 
        mysql_real_escape_string($resize_filename),
        $size['width'], 
        $size['height'],
        $image_count + 1,
        $image_count == 0
      );
      mysql_query($insert) or 
        array_push($messages, "uh oh there was a problem with the db insert");
      image_cleanup();
    } else {
      array_push($messages, "There was an error uploading the file "
        . basename($_FILES['uploadedfile']['name']) . ", please try again!");
    }
  }
?>

<?php
  $result = mysql_query(sprintf(
    "select * from gallery where name = '%s'",
    mysql_real_escape_string($name)
  ));
  $gallery = mysql_fetch_assoc($result);
  if (empty($gallery["copyright"])) {
    $gallery["copyright"] = 2013;
  }

  $result = mysql_query(sprintf("select * from images where gallery_id = %d order by sequence", $gallery["id"]));
  while ($row = mysql_fetch_assoc($result)) {
    $images[] = $row;
  }
?>

<html><head><title>Admin Entry</title>
<script type="text/javascript">
<!--
  function quoteSelected(el) {
    if (el.setSelectionRange) {
      el.value = el.value.substring(0,el.selectionStart) + 
        "<font face=\"arial\">" + 
        el.value.substring(el.selectionStart,el.selectionEnd) + 
        "</font>" + el.value.substring(el.selectionEnd,el.value.length)
    }
    else {
      var selectedText = document.selection.createRange().text;
      if (selectedText != "") {
        var newText = "<font face=\"arial\">" + selectedText + "</font>";
        document.selection.createRange().text = newText;
      }
    }
  }
//-->
</script>
 <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
   <script type="text/javascript" src="/style/mapping.js"></script>
   <script>var oldIE = false;</script>
<!--[if lte IE 8]><script>oldIE = true;</script><![endif]-->
</head>
<body bgcolor="black" link="#cc00cc" text="#ffffff" vLink="#bb00bb" onload="initPage('<?php print str_replace("'", "", $gallery["location"]) ?>');">
<h1>Admin Entry</h1>
<?php
  foreach ($messages as $message) {
    print "<font size=+1 color=red>$message</font><br>";
  }
?>
<h3><?php 
  printf("<a href=\"/%s/\" target=\"_new\">%s</a>", $name, $name); 
  printf(" - <a href=\"/%s/preview.php\" target=\"_new\">Preview</a>", $name); 
?></h3>
<form enctype="multipart/form-data" action="" method="POST">
<input type="hidden" name="gallery_id" value="<?php print $gallery["id"]; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
<table>
<tr valign="top"><td>Title:</td><td><input name="title" value="<?php print htmlspecialchars($gallery["title"]) ?>" size=80> extended title: <input type="checkbox" name="extended_title" value="true" <?php if ($gallery["extended_title"]) { print " checked"; } ?>></td></tr>
<tr valign="top"><td>Subtitle:</td><td><textarea cols="80" rows="2" name="subtitle"><?php print $gallery["subtitle"]; ?></textarea></td></tr>
<tr valign="top"><td>Location:</td><td><input name="location" value="<?php print $gallery["location"] ?>" size=40>
<br>
							<div id="actuatorDiv" title="Click for map" style="margin-top:5px;	width:150px;
	height:125px;
	border-radius: 8px;"></div>
							<div id="captionDiv" title="Click for map" onClick="Slide();" style="position:relative;
	top:-26px;
	width:150px;
	height:32px;
	color:#E2DBD8;
	background-color:#82490D;
	border-bottom-right-radius: 8px;
	border-bottom-left-radius: 8px;"></div>

</td></tr>
<?php
  if (!empty($images)) {
    foreach ($images as $image) {
        printf("<tr valign=top><td><a href=\"%s\" target=\"_new\">%s</a><br><a href=\"?Delete=Delete&image_id=%d\" onClick=\"return confirm('Delete: are you sure?')\">Delete</a><br><a href=\"#\" onClick=\"quoteSelected(document.getElementById('image_comment_%d'));\">Quote</a></td><td><textarea cols=\"80\" rows=\"10\" id=\"image_comment_%s\" name=\"image_comment_%s\">%s</textarea></td></tr>", $image["src"], $image["src"], $image["id"], $image["id"], $image["id"], $image["id"], $image["comment"]);
    } 
  }
?>
<tr valign="top"><td>Email:</td><td>
<?php
  if (!empty($images)) {
    foreach ($images as $image) {
      printf("<input type=\"radio\" name=\"email\" value=\"%s\"%s>%s", $image["id"], $image["email"] ? " checked" : "", $image["src"]);
    }
  }
?></td></tr>
<tr valign="top"><td>Contributor:</td><td><input name="contributor" value="<?php print htmlspecialchars($gallery["contributor"]); ?>"></td></tr>
<tr valign="top"><td>Copyright:</td><td><input name="copyright" value="<?php print $gallery["copyright"]; ?>"></td></tr>
<tr valign="top"><td>Categories:</td><td>
<?php
  $category_list = array(
    "Bars & Restaurants",
    "Airports", "Business", "Hotels", "Cool Installations", "Vessels",
    "National Parks", "Landmarks", "Private Residence",
    "Sporting & Concert Venues", "Museums", "Eductional Institutions",
    "Public", "Women's",
    "Miscellaneous"
  );
  $categories = split("\|", $gallery["categories"]);
  foreach ($category_list as $category) {
    $checked = "";
    if (in_array($category, $categories)) {
      $checked = " checked";
    }
    print "<input type=checkbox name=\"category[]\" value=\"$category\"$checked>&nbsp;$category ";
  }
  
?>
</td></tr>
<tr valign="top"><td colspan="2">
  <input type="submit" name="Save" value="Save">
<?php
  if ($gallery["published"]) {
    print '  <input type="submit" name="Unpublish" value="Unpublish">';
  } else {
    print '  <input type="submit" name="Publish" value="Publish">';
  }
?>
</td></tr>
<tr><td colspan="2">
<?php if (file_exists('index.html')) { 
print '
  <input type="submit" name="Retrofit" value="Retrofit">
'; }
?>
<input type="submit" name="Purge" value="Purge" onClick="return confirm('Purge: are you sure?')">
</td></tr>

</table>
<hr>
Upload an image: <input name="uploadedfile" type="file" /><br />
<input type="submit" name="Upload" value="Upload" />
</form>
<p><a href="/"><img src="../back.gif" width="39" height="52" border="0"></a></p>
</body></html>
