<?php
extract($_GET);
extract($_POST);

session_cache_expire(60*24);
session_set_cookie_params(60*60*24);
session_start();

require "../inc/top.inc.php";
require "../lib/db.class.php";

if ($delete)
  $what = "create_article_delete";

if ($delete_picture)
  $what = "article_pictures_delete";

if (!$what) {
  if (! $_SESSION["${prefix}reporter_id"])
    $what = "login";
  elseif ($pictures)
    $what = "article_pictures_form";
  else
    $what = "create_article_form";
}

$DOCUMENT = basename(__FILE__);
$DEFAULT_UPLOAD_FILES = 3;

/*
 * Fill variables UPLOAD_PATH and UPLOAD_PATH_WEB
 */
switch ($what) {
  case "create_article_insert":
  case "create_article_edit":
    setUPLOAD_PATH($articles_table);
    break;
  case "article_pictures_insert":
  case "article_pictures_delete":
    setUPLOAD_PATH($pictures_table);
    break;
}

/*
 * Login
 * verify that both username and password are present
 */
if ($login) {
/*
 * We keep information about current user in session variables so that we can use them
 * without querying for them each time (e.g. e-mail notification on Client Uploads)
 */
  unset($_SESSION["${prefix}reporter_usr"]);
  unset($_SESSION["${prefix}reporter_pwd"]);
  extract($_POST);
  // overwrite global variables that came from session with those from form

  if ( (!$newsscript_reporter_usr) || (!$newsscript_reporter_pwd) )
    $error = "Please enter both Username and Password.";
  else {
    $_SESSION["${prefix}reporter_usr"] = $newsscript_reporter_usr;
    $_SESSION["${prefix}reporter_pwd"] = $newsscript_reporter_pwd;
  }
}

/*
 * Authorization
 * verify that user with given username and password exists
 */
if ($_SESSION["${prefix}reporter_usr"] && $_SESSION["${prefix}reporter_pwd"]) {
/*
 * Cache this user's data for further usage (e.g. e-mail notification on Client Uploads)
 */
  list(
    $_SESSION["${prefix}reporter_id"], 
    $_SESSION["${prefix}reporter_name"]) =
  mysql_fetch_row(mysql_debug(sprintf(
    "SELECT id, name ".
    "FROM ${prefix}reporters ".
    "WHERE user_name='%s' AND user_password='%s'",
    addslashes($_SESSION["${prefix}reporter_usr"]), addslashes($_SESSION["${prefix}reporter_pwd"]))));

  if (!$_SESSION["${prefix}reporter_id"]) {
    $error = "Username and/or Password don't match. Please try again.";
    $what = "login";

//    session_destroy();
//    setcookie("PHPSESSID", false);
  } else {
    $_SESSION["${prefix}reporter_name"] = stripslashes($_SESSION["${prefix}reporter_name"]);
  }

} else
  $what = "login";

/*
 * Upon successful login redirect to itself to get rid of submitted info and to enable refresh
 */
if ($login && $_SESSION["${prefix}reporter_id"]) {
  redirect($DOCUMENT);
}

/*
 * Security
 */
$_SESSION["${prefix}reporter_id"] = intval($_SESSION["${prefix}reporter_id"]);

/*
 * Template
 */
if ($PATHS["news-client-area"])
  $load_template = true;
else
  $load_template = false;

if ($load_template) {
  list($template_top, $template_bottom) = plusTemplate($PATHS["news-client-area"]);
  print $template_top;

  print '<style type="text/css">';
  print file_get_contents("./news.css");
  print '</style>';
  print '<div class="body">';

} else {

/*
 * Without template
 */
?>
<html>
<head>
<title>Reporter Area</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-2">
<meta http-equiv="Content-Language" content="en">
<link rel="stylesheet" href="news.css" type="text/css">
</head>

<body class="body">
<?php
}

if ($_SESSION["${prefix}reporter_name"]) {
  $loginName = $_SESSION["${prefix}reporter_name"];
  print <<<KONEC
<div class="logged_user">
Logged in as <B>$loginName</B>.
<a href="$DOCUMENT?what=logout" target="_top">Click here to log out</a>.
</div>
KONEC;
}

/*
 * Standard switch
 */
switch ($what) {
# --------------------------------------------------------------------------- #
case "create_article_form":
# --------------------------------------------------------------------------- #

/*
 * List last x articles
 */
  $last = 5;

  print "<h2>Last $last articles</h2>\n\n";
  print "<table>\n";

  $farticle = <<<KONEC
[ <a href="#" onClick="if (confirm('Are you sure?')) location.href='$DOCUMENT?delete=%d';">delete</a> 
| <a href="$DOCUMENT?edit=%d">edit</a> 
| <a href="$DOCUMENT?pictures=%d">pictures</a> 
] &nbsp; %s<br>

KONEC;
  $sql = 
    "SELECT id, title FROM $articles_table ".
    "WHERE deleted IS NULL AND reporter = ".$_SESSION["${prefix}reporter_id"]." " .
    "ORDER BY date_from DESC, rank ASC LIMIT $last";
  $articles_db = mysql_debug($sql);
  while ($article = mysql_fetch_assoc($articles_db))
    printf($farticle, $article["id"], $article["id"], $article["id"], $article["title"]);

  print "</table>\n\n";

/*
 * Error/Result message
 */
  if ($message) echo "<H3>$message</H3><HR>";

/*
 * Read values of edited article
 */
  if ($edit) {
    $article = mysql_fetch_assoc(mysql_debug("SELECT * FROM $articles_table WHERE id=".intval($edit)));
    array_map("htmlspecialchars", $article);

    $default_position[$article["photo_position"]] = "checked";
    $default_date_from = $article["date_from"];
    $label = "Edit article";
  } else {
    $default_date_from = date("Y-m-d");
    $label = "New article";
  }

/*
 * New/Edit article form
 */
?>
<form method="post" action="<?php echo $DOCUMENT; ?>" class="newarticleform" enctype="multipart/form-data">
<h2>Reporter Area</h2>

<fieldset class="fieldset">
<legend><?php echo $label; ?></legend><br>
<label for="article_title">Title</label>
<input type="text" name="article_title" value="<?php echo $article["title"]; ?>" class="textfield">
<br>
<label for="article_annotation">Annotation</label>
<textarea name="article_annotation" class="textarea">
<?php echo $article["annotation"]; ?>
</textarea>
<br>
<label for="article_body">Text</label>
<textarea name="article_body" class="textarea">
<?php echo $article["contents"]; ?>
</textarea>
<br>
<label for="article_section">Section</label>
<select name="article_section" class="datetextfield">
<?php echo join("\n", makeFORMITEMsql($SELECT_SECTIONS[$SL_SQL], array($article["section"]), "select", "id", "name")); ?>
</select>
<br>
<label for="article_rank">Order #</label>
<input type="text" name="article_rank" value="<?php echo $article["rank"]; ?>" class="textfield">
<br>
<label for="article_date_from">Display date</label>
<input type="text" name="article_date_from" value="<?php echo $default_date_from; ?>" class="datetextfield">
to
<input type="text" name="article_date_to" value="<?php echo $article["date_to"]; ?>" class="datetextfield"><br>
<div style="margin-left: 75px;"><small>(Leave empty for any date.)</small></div>
<br>
<label for="article_photo">Lead picture</label>
<input type="file" name="article_photo" class="filefield">
<br>
<label for="article_photo_position">Alignment</label>
<input type="radio" name="article_photo_position" value="left"   <?php echo $default_position["left"]; ?>> Left
<input type="radio" name="article_photo_position" value="center" <?php echo $default_position["center"]; ?>> Centre
<input type="radio" name="article_photo_position" value="right"  <?php echo $default_position["right"]; ?>> Right
<br><br>
<label for="submit">&nbsp;</label>
<?php
  if ($edit) {
?>
<input type="submit" name="submit" value="Submit changes" class="submit">
<input type="hidden" name="what" value="create_article_edit">
<input type="hidden" name="record_id" value="<?php echo $edit; ?>">
<?php
  } else {
?>
<input type="submit" name="submit" value="Submit new article" class="submit">
<input type="hidden" name="what" value="create_article_insert">
<?php
  }
?>
</fieldset>
</form>
<?
  break;
# --------------------------------------------------------------------------- #
case "create_article_insert":
# --------------------------------------------------------------------------- #
  $record_id = false;
  $sqlAttributes = array('reporter', 'section', 'title', 'annotation', 'contents', 'rank', 'photo_position');
  $sqlValues = array($_SESSION["${prefix}reporter_id"], $article_section, $article_title, $article_annotation, $article_body, $article_rank, $article_photo_position);
  
  $file_name = $_FILES["article_photo"]['name'];
  if ($file_name) {
    $sqlAttributes[] = 'photo';
    $sqlValues[] = $file_name;
  }
  if ($article_date_from) {
    $sqlAttributes[] = 'date_from';
    $sqlValues[] = $article_date_from;
  }
  if ($article_date_to) {
    $sqlAttributes[] = 'date_to';
    $sqlValues[] = $article_date_to;
  }
  $db = Db::connect();
  $sql = $db->buildSQL(
    "INSERT INTO $articles_table " .
      "(".join(', ', $sqlAttributes).") ".
      "VALUES (".join(', ', array_fill(0, count($sqlValues), '%s')).")",
    $sqlValues
  );
  $articleId = $db->Query($sql);

  if ($articleId) {
    $tmp_file_name = $_FILES["article_photo"]['tmp_name'];

    if (is_array($_FILES) && is_uploaded_file($tmp_file_name)) {
      $extension = substr(strrchr($file_name, "."), 1);
      $move_to = "$UPLOAD_PATH/$articleId-photo.$extension";
      $move_from = $tmp_file_name;
      move_uploaded_file($move_from, $move_to);
    }
  }

  redirect("$DOCUMENT?message=".urlencode("Article was successfully added."));
  // to avoid re-submit with refresh button
  break;

# --------------------------------------------------------------------------- #
case "create_article_edit":
# --------------------------------------------------------------------------- #

  if (!$article_date_from) $article_date_from = "NULL"; else $article_date_from = "'$article_date_from'";
  if (!$article_date_to) $article_date_to = "NULL"; else $article_date_to = "'$article_date_to'";

  $file_name = $_FILES["article_photo"]['name'];

  if ($file_name)
    $photo_column = "photo = '".addslashes($file_name)."',";
  else
    $photo_column = "";

  mysql_debug(sprintf(
    "UPDATE $articles_table ".
      "SET section=%d, title='%s', annotation='%s', contents='%s', date_from=%s, date_to=%s, rank=%d, $photo_column photo_position='%s' ".
      "WHERE id=%d",
      $article_section, $article_title, $article_annotation, $article_body, $article_date_from, $article_date_to,
      $article_rank, $article_photo_position, $record_id));

  $tmp_file_name = $_FILES["article_photo"]['tmp_name'];

  if (is_array($_FILES) && is_uploaded_file($tmp_file_name)) {
/**
 * First delete old picture and its resized copies to avoid confusion of the resizing script
 */
    foreach (glob("$UPLOAD_PATH/$record_id-photo.*") as $filename)
      unlink($filename);

    $extension = substr(strrchr($file_name, "."), 1);
    $move_to = "$UPLOAD_PATH/$record_id-photo.$extension";
    $move_from = $tmp_file_name;
    move_uploaded_file($move_from, $move_to);
  }

  redirect("$DOCUMENT?message=".urlencode("Article was successfully modified."));
  // to avoid re-submit with refresh button
  break;

# --------------------------------------------------------------------------- #
case "create_article_delete":
# --------------------------------------------------------------------------- #

  mysql_debug("UPDATE $articles_table SET deleted=1 WHERE id=".intval($delete));
  // we intentionally don't delete it's photographs

  redirect("$DOCUMENT?message=".urlencode("Deleted!"));
  // to avoid re-submit with refresh button
  break;

# --------------------------------------------------------------------------- #
case "article_pictures_form":
# --------------------------------------------------------------------------- #

  if (!$upload_file_number) $upload_file_number = $DEFAULT_UPLOAD_FILES;

/*
 * Error/Result message
 */
  if ($message) echo "<H3>$message</H3><HR>";

?>
<form method="post" action="<?php echo $DOCUMENT; ?>" class="articlepicturesform" enctype="multipart/form-data">
<h2>Picture Area</h2>

<div style="margin-bottom: 15px;"><a href="<?php echo $DOCUMENT; ?>?what=create_article_form">Back to Article Area</a></div>

<?php
  $fpicture = <<<KONEC
[ <a href="#" onClick="if (confirm('Are you sure?')) location.href='$DOCUMENT?delete_picture=%d&article=%d';">delete</a> ] &nbsp; %d. %s<br>

KONEC;
  $DESCRIPTION_LIMIT = 20;

  $pictures_db = mysql_debug(
    "SELECT id, photo, article, description FROM $pictures_table ".
    "WHERE article=".intval($pictures)." AND deleted IS NULL ORDER BY id ASC");
  while ($picture = mysql_fetch_assoc($pictures_db)) {

    if ( ($picture["description"]) && (strlen($picture["description"]) > $DESCRIPTION_LIMIT) )
      $picture["description"] = substr($picture["description"], 0, $DESCRIPTION_LIMIT)."...";
      // cut long descriptions

    printf($fpicture, $picture["id"], $picture["article"], $picture["id"], $picture["description"]);
  }
?>
<br>

<fieldset class="fieldset">
<legend>Article Pictures</legend><br>

<label for="upload_file_number">Number of files</label>
<input type="text" name="upload_file_number" value="<?php echo $upload_file_number; ?>" class="textfield" style="width: 25px;">
<input type="button" name="tmp" value="Refresh" onClick="<?php
  echo "location.href='index.php?what=details&project=$project&upload_file_number='+document.upload_form.upload_file_number.value;"; ?>">
<br style="clear: left;">

<?php
  for ($i=0; $i<$upload_file_number; $i++) {
?>
<hr>

<label for="picture_description[]">Description (optional)</label>
<textarea name="picture_description[]" class="textarea">
</textarea>
<br>
<label for="picture_file[]">File</label>
<input type="file" name="picture_file[]" class="filefield">

<?php
  }
?>
<br><br>
<label for="submit">&nbsp;</label>
<input type="submit" name="submit" value="Submit new pictures" class="submit">
<input type="hidden" name="what" value="article_pictures_insert">
<input type="hidden" name="article" value="<?php echo $pictures; ?>">
</fieldset>
</form>
<?php
  break;

# --------------------------------------------------------------------------- #
case "article_pictures_insert":
# --------------------------------------------------------------------------- #
  $article = intval($article);
/*
 * First we store all uploaded files and make the database records
 */
  for ($i=0; $i<count($_FILES["picture_file"]['tmp_name']); $i++) {
    $file_name = $_FILES["picture_file"]['name'][$i];
    $tmp_file_name = $_FILES["picture_file"]['tmp_name'][$i];

    if (is_array($_FILES) && is_uploaded_file($tmp_file_name)) {
      $extension = substr(strrchr($file_name, "."), 1);

      $record_id = mysql_debug(sprintf(
        "INSERT INTO $pictures_table (article, description, photo) VALUES (%d, '%s', '%s')",
        $article, addslashes(stripslashes($picture_description[$i])), addslashes(stripslashes($file_name)) ));
        // returns id of this records

      if ($record_id)
        $result = move_uploaded_file($tmp_file_name, "$UPLOAD_PATH/$record_id-photo.$extension");
    }
  }
  redirect("$DOCUMENT?pictures=$article&message=".urlencode("Pictures were successfuly uploaded!"));

  break;

# --------------------------------------------------------------------------- #
case "article_pictures_delete":
# --------------------------------------------------------------------------- #
  $delete_picture = intval($delete_picture);
  mysql_debug("DELETE FROM $pictures_table WHERE id=$delete_picture");

  foreach (glob("$UPLOAD_PATH/$delete_picture-photo.*") as $filename)
    unlink($filename);

  redirect("$DOCUMENT?pictures=$article&message=".urlencode("Picture deleted!"));
  // to avoid re-submit with refresh button
  break;

# --------------------------------------------------------------------------- #
case "login":
# --------------------------------------------------------------------------- #
?>
<form method="post" action="<?php echo $DOCUMENT; ?>" class="loginform">
<h2>Reporter Area</h2>

<?php if ($error) echo "<h3>$error</h3>\n"; ?>

<fieldset class="fieldset">
<legend>Login</legend><br>
<label for="newsscript_reporter_usr">Username</label>
<input type="text" name="newsscript_reporter_usr" value="" class="textfield">
<br>
<label for="newsscript_reporter_pwd">Password</label>
<input type="password" name="newsscript_reporter_pwd" value="" class="textfield">
<br>
<label for="login">&nbsp;</label>
<input type="submit" name="login" value="Login" class="submit">
</fieldset>
</form>
<?
  break;
# --------------------------------------------------------------------------- #
case "logout":
# --------------------------------------------------------------------------- #
  session_destroy();
  print <<<KONEC
You have been successfully logged out. <a href="$DOCUMENT?what=login">Click here to login again.</a>
KONEC;
}

if ($load_template) {
  echo "</div>";
  print $template_bottom;
} else {
?>
</body>
</html>
<?php
}

require "../inc/bottom.inc.php";
?>