<?php

  /*

      issue.php

      Issue. Allows an issue to be viewed or edited in full. [Commented]

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-02 arne_sf: Replaced all instances of column name 'user'
          for table tbl_UserSites with 'userid'
        2005-07-02 arne_sf: Replaced all instances of column name 'user'
          for table tbl_Times with 'userid'
        
      ## PAGE CONTAINS HANDYANDY MYSQL MODS ##
      ## Copyright (C) 2005 Andy Deakin (handyandy.org.uk) ##

      ----

      Copyright (C) 2003  Central Manchester CLC
      Copyright (C) 2003  David Thorne (davethorne@gmail.com)

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation version 2.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  */

  // Start session and populate it with data
  session_start();

  // Page security
  require_once 'system/security.php';
  if ($_SESSION['_usertype'] == '') {
    ThrowOut();
  }

  // Page Title
  $ptitle = 'Issues';

  // Includes
  require_once 'config/global.conf.php';
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/attachments.php';
  require_once 'system/message.php';
  require_once 'system/remark.php';
  require_once 'system/user_preferences.php';
  require_once 'system/global_preferences.php';
  require_once 'system/functions.php';
  require 'header.php';

  // Language selection
  set_text_domain("issue");

  // Retrieve Get/Post variables
  $act = $_REQUEST['act'];
  $level = $_POST['level'];
  $oldlevel = $_POST['oldlevel'];
  $oldlevelname = $_POST['oldlevelname'];
  $publish = $_POST['publish'];
  $keywords = $_POST['keywords'];
  $existingkeywords = $_POST['existingkeywords'];
  $status = $_POST['status'];
  $oldstatus = $_POST['oldstatus'];
  $oldstatusname = $_POST['oldstatusname'];
  $contact = $_POST['contact'];
  $site = $_REQUEST['site'];
  $newsite = $_POST['newsite'];
  $sitename = $_REQUEST['sitename'];
  $newsitename = $_POST['newsitename'];
  $createdby = $_REQUEST['createdby'];
  $reportedby = $_REQUEST['reportedby'];
  $assignedto = $_REQUEST['assignedto'];
  $oldassignedto = $_REQUEST['oldassignedto'];
  $oldassignedtoname = $_REQUEST['oldassignedtoname'];
  $location = $_POST['location'];
  $details = $_POST['details'];
  $categories = $_POST['categories'];
  $summary = $_POST['summary'];
  $description = $_POST['description'];
  $solution = $_POST['solution'];
  $remark = $_POST['remark'];
  $remarkaction = $_POST['remarkaction'];
  $confidential = $_POST['confidential'];
  $selectremark = $_POST['selectremark'];
  $priority = $_POST['priority'];
  $oldpriority = $_POST['oldpriority'];
  $oldpriorityname = $_POST['oldpriorityname'];
  $id = $_REQUEST['id'];
  $timehours = $_POST['timehours'];
  $timeminutes = $_POST['timeminutes'];
  $delete_attachments = $_POST['delete_attachments'];

  if ($details == '') $details = 0;

  if (!$id) {
    print "  <div class=\"maintitle\">\n    <h1>".gettext('Error')."</h1>\n  </div>\n
      <div class=\"maindark\">\n    <p>".gettext('You must select an issue')."</p>\n    </div>\n  <div class=\"main\">\n</div>";
    require 'footer.php';
    exit;
  }

  if ($conf_db['dsn']['phptype'] == 'pgsql') {
    $is_pgsql = true;
  }

  // Retrieve issue information
  if ($is_pgsql) {
    $sql = "SELECT * FROM vw_Issues WHERE id=$id";
  } else {
    $sql = "SELECT $aselects FROM $afrom WHERE tbl_Issues.id=$id";
  }

  $issue = db_recordset($sql);

  // What access does the user have

  require_once 'system/acl_issue.inc';
  $acl = get_issue_acl($issue[0],$_SESSION[_id]);

//   $sql = "SELECT tbl_UserTypes.type AS usertypename
//     FROM tbl_UserTypes LEFT JOIN tbl_UserSites ON tbl_UserSites.usertype = tbl_UserTypes.id
//   WHERE tbl_UserSites.userid=".$_SESSION[_id]."
//   AND tbl_UserSites.site=".$issue[0][site]."";
//   $usertypesRS = db_recordset($sql);

//   if ($_SESSION[_usertype] != '')
//   {
//     $usertypesRS[0][usertypename] = $_SESSION[_usertype];
//     $usertype = $usertypesRS[0][usertypename];
//   }
  ### MAJOR SECURITY ISSUE HERE ###
  // if the above query returns NO result, then the usertypename is BLANK

  if ($acl['denyall']) {
    print "  <h1>".gettext('Error')."</h1>\n
    <h2 class=\"warning\">".gettext('You cannot view this issue')."</h2><div class=\"block\">\n</div>";
    require 'footer.php';
    exit;
  }

  // Action worktimer.
  if ($acl['use_wrktimer']) {
    if ($is_pgsql) {
      require_once 'system/worktimer_pg.inc';
    } else {
      require_once 'system/worktimer_mysql.inc';
    }

    if ($act == 'wrktm') {
      wrktm_act();
      $act = '';
    }
  }

  // Action: Edit issue
  if ($act == 'action' && $acl['edit_issue']) {
    // Retrieve the status that is equivalent to closed ##1
    $closedstatus = get_closed_status($_SESSION['_domain']);
    // Update issue
    $sql = 'UPDATE tbl_Issues SET ';
    //if ($assignedto == 0) $assignedto = $_SESSION['_id'];
    if ($closedstatus == $status && $status != $oldstatus) {
      $acl_reload = true;
      db_send("DELETE from tbl_Wrktimer where issue=$id");
      // Assigned an unassigned issue to the user opon closing
      // Clients shouldn't be assigned issues
      if ($_SESSION['_usertype'] != 'Client') {
          if ($assignedto == 0) $assignedto = $_SESSION['_id'];
      }

      $sql .= "recalled=0,closedon=" . time() . ",closedby=" . $_SESSION['_id'] . ',';

      // Send email to associated users, but only if they wouldnt normally get
      // one anyway by having emails sent for any change.
      $recip = array();
      $user_prefs = get_user_prefs($reportedby);
      $user_details = get_user_details($reportedby);
      if ($reportedby!=$_SESSION['_id'] && $user_prefs['email-remark'] == 'false'&& $user_prefs['email-resolve'] == 'true' && $user_details['email']!='') {
        $recip[ $user_details[email] ] = $user_prefs['language'];
      }
      $user_prefs = get_user_prefs($createdby);
      $user_details = get_user_details($createdby);
      if ($createdby!=$_SESSION['_id'] && $user_prefs['email-remark'] == 'false' && $user_prefs['email-resolve'] == 'true' && $user_details['email']!='') {
        $recip[ $user_details[email] ] = $user_prefs['language'];
      }
      $user_prefs = get_user_prefs($assignedto);
      $user_details = get_user_details($assignedto);
      if ($assignedto!=$_SESSION['_id'] && $user_prefs['email-remark'] == 'false' && $user_prefs['email-resolve'] == 'true' && $user_details['email']!='') {
        $recip[ $user_details[email] ] = $user_prefs['language'];
      }
      foreach ($recip as $rcpt => $lng) {
        send_mail('resolve',$lng,$rcpt,$id,$_SESSION['_name'],"$solution");
      }
    }
    if ($closedstatus != $status && $status != $oldstatus) {
      $acl_reload = true;
    }
    $sql .= "contact='$contact',solution='$solution',location='$location',summary='$summary',description='$description',assignedto=$assignedto,detail=$details,category=$categories,priority=$priority,status=$status,level=$level WHERE id=$id";
    db_send($sql);

    // Update time spent
    if ($timehours != '' || $timeminutes != '') { // Has user entered anything
      if ($timeminutes == '') $timeminutes = 0;
      if ($timehours == '') $timehours = 0;

      settype($timeminutes, 'integer');
      settype($timehours, 'integer');

      if (($timeminutes + $timehours) == 0) {
        // User hasnt spent any time, so do nothing
      } elseif ($timeminutes >= 60) {
        $message = gettext("ERROR: There are only 60 minutes in an hour. Please specify time spent in hours and minutes.");
      } else {
        // Get old time from db, add to total, and put it back
        $time = db_recordset("SELECT time FROM tbl_Times WHERE issue = " .
        $id . " AND userid = " . $_SESSION['_id']);
        if ($is_pgsql) {
          if (count($time) < 1) {
            db_send("INSERT INTO tbl_Times (issue, \"userid\", time)
                     VALUES ($id, {$_SESSION['_id']}, '$timehours hours $timeminutes min')");
          } else {
            db_send("UPDATE tbl_Times SET time = time + '$timehours hours $timeminutes min' WHERE issue = $id AND \"userid\" = {$_SESSION['_id']}");
          }
        } else {
          $stime = makeseconds("$timehours:$timeminutes:00");
          if (count($time) < 1) {
            db_send("INSERT INTO tbl_Times (issue, userid, time)
                     VALUES ($id, {$_SESSION['_id']}, '$stime')");
          } else {
            $stime +=$time[0]['time'];
            db_send("UPDATE tbl_Times SET time = '$stime' WHERE issue = $id AND userid = {$_SESSION['_id']}");
          }
        }
        // And of course, add remark
        $timestring='';
        if ($timehours > 0) {
          if ($timehours != 1) $hs = 's';
          $timestring .= "$timehours hour$hs";
        }
        if ($timeminutes > 0) {
          if ($timeminutes != 1) $ms = 's';
          if ($timehours > 0) $and = " and";
          $timestring .= "$and $timeminutes minute$ms";
        }
        if (count($time)>0) $an_additional = " an additional";
        $timetrack =  "Spent$an_additional $timestring on the problem.";
        $time = "$timehours:$timeminute:00";
      }
    }

    $track = '';
    
    // Deal with deleting attachments
    if (count($delete_attachments) > 0) {
      if (function_exists('finfo_open')) {
        foreach ($delete_attachments as $attachment) {
          $attachment_dir = get_attachment_dir($id, true);
          $cwd = getcwd();
          chdir($attachment_dir);
          unlink(urldecode($attachment));
          $track .= "File \'".$attachment."\' removed from issue.\n";
          chdir($cwd);
        }
      }
    }

    if ($assignedto != $oldassignedto) {
      $name = db_recordset("SELECT name FROM tbl_Users WHERE id=$assignedto");
    if ($oldassignedtoname == '') {$oldassignedtoname='Nobody';}
      $track .= "Issue reassigned from \'$oldassignedtoname\' to \'" . $name[0]['name'] . "\'.\n";
    }
    if ($level != $oldlevel) {
      $name = db_recordset("SELECT level FROM tbl_Levels WHERE id=$level");
      $track .= "Issue level changed from \'$oldlevelname\' to \'" . addslashes($name[0]['level']) . "\'.\n";
    }
    if ($priority != $oldpriority) {
      $name = db_recordset("SELECT priority FROM tbl_Priorities WHERE id=$priority");
      $track .= "Issue priority changed from \'$oldpriorityname\' to \'" . addslashes($name[0]['priority']) . "\'.\n";
    }
    if ($status != $oldstatus) {
      $name = db_recordset("SELECT status FROM tbl_Statuses WHERE id=$status");
      $track .= "Issue status changed from \'$oldstatusname\' to \'" . addslashes($name[0]['status']) . "\'.\n";
    }
    if ($assignedto != $oldassignedto) {
        $recipients = array($reportedby, $createdby, $assignedto, $oldassignedto);
    } else {
        $recipients = array($reportedby, $createdby, $assignedto);
    }
    
    // Deal with adding an attachment
    if ($_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
      $attachment_dir = get_attachment_dir($id, true);
      move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment_dir."/".$_FILES['attachment']['name']);
      $track .= "File \'".$_FILES['attachment']['name']."\' attached to issue.\n";
    }
    
    if (isset($timetrack)) {
        makeremark($id,$timetrack . "\n" . $track,'false', $recipients, $time);
    } else {
        makeremark($id, $track, 'false', $recipients);
    }

    if ($selectremark != '') {
      $flag = 0;
      $remarks = '';
      foreach ($selectremark as $remarkid) {
        if ($flag == 0) { $flag = 1; } else { $remarks .= ','; }
        $remarks .= $remarkid;
      }
      if ($remarkaction == 'confidential') {
        db_send("UPDATE tbl_Remarks SET confidential=1 WHERE id IN ($remarks)");
      } elseif ($remarkaction == 'public') {
        db_send("UPDATE tbl_Remarks SET confidential=0 WHERE id IN ($remarks)");
      } elseif ($remarkaction == 'remove') {
        foreach ($selectremark as $remarkid) {
            $results = db_recordset("SELECT time, issue, reportedby FROM
            tbl_Remarks WHERE id=$remarkid AND time IS NOT NULL");
            if (count($results) > 0) {
                $results = $results[0];
                db_send("UPDATE tbl_Times SET time=time-'{$results['time']}'
                WHERE issue={$results['issue']} AND
                userid={$results['reportedby']}");
            }
        }
        db_send("DELETE FROM tbl_Remarks WHERE id IN ($remarks)");
      }
    }

    $act = 'remark';

    if (!isset($message)) $message = gettext("NOTE: Issue successfully updated.");

  }

  // Action: Edit issue
  if ($act == 'remark') {
    if ($remark != '') {
      makeremark($id,$remark,$confidential, array($reportedby, $createdby, $assignedto));
    }

    if ($publish == 'publish') {
      $act = 'publish';
    } else {
      $act = '';
    }
  }

  // Action: Revoke an issue
  if ($act == 'revoke') {
    // Recall the issue
    $sql = "UPDATE tbl_Issues SET recalled=1 WHERE id=$id";
    db_send($sql);
    makeremark($id,'Issue recalled by the client.','false', array($reportedby, $createdby, $assignedto));

?>

  <h1><?php echo gettext("Issue")?> #<?php echo $id?></h1>
  <h2><?php echo gettext("You have recalled this issue. Support staff will be informed and this issue will be closed as soon as possible.")?></h2>
  
  <div class="block" align="center">
    <p><?php echo gettext('Back to <a href="myissues.php">my issues</a>.')?></p>
  </div>

<?php
  }

  // Action: publish an issue
  if ($act == 'publishaction' && $acl['edit_publish']) {
    $act = '';
    $acl_reload = true;

    // tokenise keyword string
    $keywordlist = array();
    $tok = strtok($keywords,'\"\',:; ');
    while ($tok) {
      if (strlen($tok) > 0) $keywordlist[] = strtolower($tok);
      $tok = strtok('\"\',:; ');
    }

    // Ensure the thesaurus is updated with these keywords
    $flag = 0;
    $keywords = '';
    foreach ($keywordlist as $keyword) {
      if ($flag == 0) { $flag = 1; } else { $keywords .= ','; }
      $keywords .= "'$keyword'";
    }
    if ($keywords != '') {
      $registeredkeywords = db_recordset("SELECT term FROM tbl_Thesaurus WHERE term IN ($keywords)");
      foreach ($keywordlist as $keyword) {
        $current = filter_records($registeredkeywords,'term',$keyword);
        if (count($current) == 0) {
          db_send("INSERT INTO tbl_Thesaurus (term) VALUES ('$keyword');");
        }
      }

      // Create mappings
      $registeredkeywords = db_recordset("SELECT id FROM tbl_Thesaurus WHERE term IN ($keywords)");
      foreach ($registeredkeywords as $record) {
        db_send("INSERT INTO tbl_Thesaurus_Mappings (term,issue) VALUES ('$record[id]',$id);");
      }
    }

    // Create mappings for keywords selected from the list
    if (isset($existingkeywords)) {
      foreach ($existingkeywords as $wordid) {
        db_send("INSERT INTO tbl_Thesaurus_Mappings (term,issue) VALUES ('$wordid',$id);");
      }
    }

    db_send("UPDATE tbl_Issues SET published=1,publishedon='".time()."',publishedby=$_SESSION[_id] WHERE id=$id");
  }

  // Action: publish an issue
  if ($act == 'publish' && $acl['edit_publish']) {
    // Can't publish an open issue
    if ($is_pgsql) {
      $updatedissue = db_recordset("SELECT * FROM vw_Issues WHERE id=$id");
    } else {
      $updatedissue = db_recordset("SELECT $aselects FROM $afrom WHERE tbl_Issues.id=$id");
    }
    if ($updatedissue[0]['status'] != $closedstatus) {
      $message = gettext("ERROR: You must close an issue before publishing it.");
      $act = '';
    } else {
      $thesaurus = db_recordset("SELECT * FROM tbl_Thesaurus");
?>

  <h1><?php echo gettext("Issue")?> #<?php echo $id?></h1>
  <h2><?php echo gettext("Please fill in the following information in order to publish this issue.")?></h2>
  
  <div class="block">
    <p><?php echo gettext("<strong>Warning:</strong> publishing an issue makes all information regarding an issue
      (except the confidential issue history) publicly available on this domain.")?></p>
    <form name="mainform" id="mainform" method="post" action="">
      <input type="hidden" name="id" value="<?php echo $id?>" />
      <input type="hidden" name="act" value="publishaction" />
      <div class="labelfieldpair">
        <div class="name"><?php echo gettext("Published By")?>:</div>
        <div class="value">
          <?php echo $_SESSION['_name']?>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><?php echo gettext("Published On")?>:</div>
        <div class="value">
          <?php echo strftime('%d/%m/%y &nbsp; %H:%M')?>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <?php echo gettext("Please select several keywords from the list that you can associate with this issue.")?>
        </div>
      </div>
      <div class="labelfieldpair">
    <div class="name"><?php echo gettext("Keywords")?>:</div>
        <div class="field">
            <select name="existingkeywords[]" multiple="multiple">
<?php
      foreach ($thesaurus as $keyword) {
?>
                <option value="<?php echo $keyword['id']?>"><?php echo $keyword['term']?></option>
<?php
      }
?>
            </select>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <?php echo gettext("In addition, you can enter a space separated list of keywords to associate with the issue.
          You MAY NOT use quotes to mark out phrases, specify single words only.")?>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">
          <label for="keywords">&nbsp;</label>
        </div>
        <div class="field">
          <input type="text" name="keywords" id="keywords" value="" maxchars="200" size="60" />
        </div>
      </div>
      <div class="buttonpanel">
        <input type="submit" value="<?php echo gettext("Submit Change")?>" />
        <input name="reset" type="reset" id="reset1" value="<?php echo gettext("Reset")?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext("Cancel")?>" onclick="document.location='issue.php?id=<?php echo $id?>'" />
      </div>
    </form>
  </div>

<?php
    }
  }

  // Action: Unpublish and already published issue
  if ($act == 'unpublish') {
    // Only administrators and domain administrators can unpublish issues
    if ($usertype != 'Administrator' && $usertype != 'Domain Administrator') {
      AccessDenied();
    }

    if (isset($id)) {
      db_send("DELETE FROM tbl_Thesaurus_Mappings WHERE issue=$id");
      db_send("UPDATE tbl_Issues SET published=0 WHERE id=$id");
      $message = gettext("Issue successfully unpublished");
    } else {
      $message = gettext("ERROR: No issue selected to unpublish");
    }
    $acl_reload = true;
    $act = '';
  }

  // Action: Change the associated site of an issue
  if ($act == 'changesite') {

?>

  <h1><?php echo gettext("Issue")?> #<?php echo $id?></h1>
  <h2><?php echo gettext("Choose the site to which you would like to move this issue.")?></h2>
  
  <div class="block">
<?php
    if ($assignedto == $_SESSION['_id']) {
?>
    <?php echo gettext("<p><strong>Warning:</strong> If you change the site of this issue to one that you do not have sufficient
      access for, it will cause the issue to become unassigned.")?></p>
<?php
    } else {
?>
    <p><?php echo gettext("<strong>Warning:</strong> Changing the site of this issue will cause the issue to become unassigned.")?></p>
<?php
    }
?>
    <form name="mainform" id="mainform" method="post" action="">
      <input type="hidden" name="id" value="<?php echo $id?>" />
      <input type="hidden" name="assignedto" value="<?php echo $assignedto?>" />
      <input type="hidden" name="act" value="changesiteaction" />
      <input type="hidden" name="site" value="<?php echo $site?>" />
      <input type="hidden" name="sitename" value="<?php echo $sitename?>" />
      <div class="labelfieldpair">
        <div class="name">
     <label for="newsite"><?php echo gettext("Change To")?></label>
        </div>
        <div class="field">
          <select name="newsite" id="newsite">
<?php
    // Find all the values for the site drop down list
    ## $sql = "SELECT tbl_Sites.* FROM vw_UserTypes,tbl_Sites WHERE vw_UserTypes.id=$_SESSION[_id] AND vw_UserTypes.site=tbl_Sites.id AND vw_UserTypes.domain=$_SESSION[_domain] AND tbl_Sites.active=1 AND vw_UserTypes.usertypesortorder>1 ORDER BY tbl_Sites.site";
    $sql = "SELECT DISTINCT tbl_Sites.*
            FROM tbl_Sites, tbl_UserTypes, tbl_UserSites
            WHERE tbl_UserSites.userid=$_SESSION[_id]
            AND tbl_UserSites.site=tbl_Sites.id
            AND tbl_Sites.domain=$_SESSION[_domain]
            AND tbl_Sites.active=1
            AND tbl_UserTypes.sortorder>1
            ORDER BY tbl_Sites.site";
  
    $sitesRS = db_recordset($sql);
    foreach ($sitesRS as $record) {
      // Set as default if chosen
      if ($record[id] == $site) { $checked = ' selected="selected"'; } else { $checked = ''; }
      print "            <option value=\"${record[id]}\"$checked>${record[site]}</option>\n";
    }
?>
          </select>
        </div>
      </div>
      <div class="buttonpanel">
        <input type="submit" value="<?php echo gettext("Submit Change")?>" />
        <input name="reset" type="reset" id="reset2" value="<?php echo gettext("Reset")?>" />
        <input name="cancel" type="button" id="cancel" value="<?php echo gettext("Cancel")?>" onclick="document.location='issue.php?id=<?php echo $id?>'" />
      </div>
    </form>
  </div>

<?php
  }

  // Action: Change the associated site of an issue
  if ($act == 'changesiteaction') {
    $act = '';

    if ($newsite == $site) {
    $message = gettext('CORRECTION: You chose the same site, so no action was taken.');
    } else {
    $message = gettext('NOTE: You have successfully changed the site of this issue.');

      $sql = "UPDATE tbl_Issues SET site=$newsite";
      if ($assignedto != $_SESSION['_id']) {
        $sql .= ',assignedto=0';
        $message .= gettext(' It is now unassigned.');
      }
      $sql .= " WHERE id=$id";
      db_send($sql);

      $track = '';
      if ($site != $newsite) {
        $name = db_recordset("SELECT site FROM tbl_Sites WHERE id=$newsite");
        $track .= "Issue site changed from \"$sitename\" to \"" . $name[0]['site'] . "\".\n";
      }

      $sql = "SELECT reportedby, createdby FROM tbl_Issues WHERE id=$id";
      $recordset = db_recordset($sql);
      $createdby = $recordset[0]['createdby'];
      $reportedby = $recordset[0]['reportedby'];
      makeremark($id,$track,'false', array($reportedby, $createdby, $assignedto));
    }
  }

  // Default action: display the issue and allow editting
  if ($act == '') {

    // Retrieve issue information
    if ($is_pgsql) {
      $sql = "SELECT * FROM vw_Issues WHERE id=$id";
    } else {
      $sql = "SELECT $aselects FROM $afrom WHERE tbl_Issues.id=$id";
    }
    $issue = db_recordset($sql);

    if ($acl_reload) {
      $acl = get_issue_acl($issue[0],$_SESSION[_id]);
    }

    $categoriesRS = db_recordset("SELECT * FROM tbl_ProblemCategories WHERE (active=1 AND domain=$_SESSION[_domain]) OR id=" . $issue[0][category] . " ORDER BY description");
    $num_categories = count($categoriesRS);
    if ($num_categories > 0)
      $detailsRS = db_recordset("SELECT * FROM tbl_ProblemDetails WHERE (active=1 AND domain=$_SESSION[_domain]) OR id=" . $issue[0][detail] . " ORDER BY description");

    // Find the highest status (the terminal status) and treat it as closed
    $closedstatus=get_closed_status($_SESSION['_domain']);

    // Should we hide user/site names and remarks?
    $user_prefs = get_user_prefs($_SESSION['_id']);
    $hidesu = (
        ($issue[0]['published'] == 1) &&
        ($user_prefs['pub-hide-su'] == 'true')
   );
    $hideremarks = (
        ($issue[0]['published'] == 1) &&
        ($user_prefs['pub-hide-remarks'] == 'true')
   );
    // Testing
    //$hidesu = true;
    //$hideremarks = true;

    display($message);
?>

<script language="javascript" type="text/javascript" src="system/xplatform.js"></script>
<script language="javascript" type="text/javascript" src="system/forms.js"></script>
<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

<?php

  /*

      Dynamically create a set of javascript arrays that will be used for the
      client side interface for choosing between the heirarchical mappings of
      categories and details.

      The arrays holds the 'children' of each top level category. By choosing
      the appropriate category using a <select> list the following SetupDetails
      function causes the details list to be rebuilt, on the fly.

  */

    if ($acl['edit_details'] && $num_categories > 0) {
      $index = 0;
      foreach ($categoriesRS as $record) {
        $current = filter_records($detailsRS,"category",$record[id]);
        $flag = TRUE;
        print ("  var problems_$index = new Array('");
        foreach ($current as $res_record) {
          if ($flag) {
            $flag = FALSE;
          } else {
            print ("','");
          }
          print ($res_record[id] . "','" . addslashes(preg_replace('/Unknown/',gettext('Unknown'),$res_record[description])));
        }
        print ("');\n");
        $index++;
      }
?>

  var initialflag = 1;

  function SetupDetails () {
    var noDetails = document.mainform.categories.options.length;
    var DetailsList = document.mainform.details.options;
    var strTemp = '';
    DetailsList.length = 0;
    for (i=0;i<noDetails;i++) {
      if (document.mainform.categories.options[i].selected && eval('problems_' + i + '[0]') != '') {
        var shift = 0;
        if (document.mainform.categories.options[document.mainform.categories.selectedIndex].value > 0) {
          DetailsList[0] = new Option('<?php echo gettext("Unknown")?>');
          DetailsList[0].value = 0;
          if (DetailsList[0].value == <?php echo $issue[0][detail]?> && initialflag == 1) {
            DetailsList[0].selected = true;
            initialflag = 0;
          }
          shift = 1;
        }
        for (loop=0;loop<eval('problems_' + i + '.length')/2;loop++) {
          DetailsList[loop+shift] = new Option(eval('problems_' + i + '[loop*2+1]'));
          DetailsList[loop+shift].value = eval('problems_' + i + '[loop*2]');
          if (DetailsList[loop+shift].value == <?php echo $issue[0][detail]?> && initialflag == 1) {
            DetailsList[loop+shift].selected = true;
            initialflag = 0;
          }
        }
      }
    }
  }

<?php
    }
    if ($acl['show_confidential']) {
?>

  function showConfidentiality(checkbox,elmnt,bgColor) {
    if (checkbox.checked) {
      setBGCOLOR(elmnt,bgColor);
    } else {
      setBGCOLOR(elmnt,'#FFBBBB');
    }
  }

  function hideConfidentiality(checkbox,elmnt,bgColor) {
    if (!checkbox.checked) {
      setBGCOLOR(elmnt,bgColor);
    } else {
      setBGCOLOR(elmnt,'#FFBBBB');
    }
  }
<?php }?>
  function mainSubmit () {
    var flag = true;
<?php
    // Clients cant have issues assigned to them
    if ($usertype != 'Client') {
      // Can't re-assign an issue to yourself if you are already assigned it
      if ($_SESSION['_id'] != $issue[0]['assignedto']) {
?>
    if (document.mainform.assignedto.value == <?php echo $_SESSION['_id']?> && !confirm('<?php echo gettext("Committing this action will re-assign this issue to yourself.\\n\\nAre you sure you wish to commit?")?>')
) flag = false;
<?php
      }

      // If an issue is currently unassigned, and will stay unassigned upon
      // closing, then warn the user
      if ($issue[0]['assignedto'] == 0) {
?>
    if (document.mainform.status.value == <?php echo $closedstatus?> &&
    document.mainform.assignedto.value == 0 && !confirm('<?php echo gettext("Closing this issue will assign the issue to yourself.\\n\\nAre you sure you wish to commit?")?>')) flag =
    false;
<?php
      }
    }
?>
    if (document.mainform.assignedto.value != <?php echo $issue[0][assignedto]?> && document.mainform.assignedto.value != <?php echo $_SESSION['_id']?> && !confirm('<?php echo gettext("Committing this action will re-assign this issue to another support agent.\\n\\nAre you sure you wish to commit?")?>')) flag = false;
<?php
    if ($acl['edit_time']) {
?>
    if (document.mainform.timehours.value >= <?php echo $global_prefs['excessivehours']?> && !confirm('<?php echo gettext("Committing this action will specify a large amount of time spent on the problem.\\n\\nAre you sure you wish to commit?")?>')) flag = false;
<?php
    }

    if ($acl['edit_publish']) {
?>
    if (document.mainform.publish.checked && !confirm('<?php echo gettext("Committing this action will PUBLICLY publish this issue.\\n\\nAre you sure you wish to commit?")?>')) flag = false;
<?php
    }
?>
    if (flag) {
<?php
    if ($usertype == 'Client' || $usertype == 'Site Contact') {
?>
      document.mainform.act.value = 'remark';
<?php
    }
    if ($issue[0]['recalled'] == 0) {
?>
      focusElement(document.mainform.remark);
<?php
    }
?>
      document.mainform.submit();
    }
  }

<?php if ($acl['recall_issue']) { ?>
  function recallSubmit () {
    if (confirm('<?php echo gettext("Are you sure you wish to recall the issue?")?>')) {
      document.mainform.submit();
    }
  }
<?php } ?>
//-->
//]]>
</script>

  <h1><?php echo gettext("Issue")?> #<?php echo $issue[0][id] . ($issue[0][published] == 0 ? ($closedstatus == $issue[0][status] ? ' ('.gettext('Closed').')' : '') : ' ('.gettext('Published').')')?></h1>
<?php

    // If this issue was recalled then say so!
    if ($issue[0][published] == 1) {
?>
  <h2><?php echo gettext('Here is the information pertaining to the knowledge base item.')?>
<?php if ($acl['view_remarks']) { echo gettext('Please check the <a href="#history">issue history</a> for the audit trail of this issue.');}?></h2>
<?php
    } elseif ($issue[0][recalled] == 1) {
      if ($usertype != 'Client' && $usertype != 'Site Contact') {
?>
  <h2 class="warning"><?php echo gettext("This issue has been cancelled and recalled by it's creator, please close this issue at the earliest convenience")?>:</h2>
<?php
      } else {
?>
  <h2 class="warning"><?php echo gettext("This issue has been cancelled and recalled by it's creator")?>:</h2>
<?php
      }
    } else {
?>
  <h2><?php echo gettext('Here is the information pertaining to the issue. Please check the <a href="#history">issue history</a> for updates on the status of this issue.')?></h2>
<?php
    }
    if ($acl['view_wrktimer']) {
      $wrktm_labels = array (
        gettext('Start Timer'),
        gettext('Stop Timer'),
        gettext('Restart Timer'),
        gettext('Reset Timer'),
        gettext('Add Time to Issue'),
        gettext('The time has been copied to the "Spend Time" fields below.\n\nPlease submit the issue to finally save it with the issue.')
       );
      if ($is_pgsql) {
        require_once 'system/worktimer_pg.inc';
      } else {
        require_once 'system/worktimer_mysql.inc';
      }
      wrktm_display();
    }
?>
  <div class="block">
        <form name="mainform" id="mainform" method="post" action="" class="login" enctype="multipart/form-data">
        <br />
<?php if ($acl['edit_issue']) {?>
      <input type="hidden" name="act" value="action" />
      <input type="hidden" name="oldlevel" value="<?php echo $issue[0][level]?>" />
      <input type="hidden" name="oldstatus" value="<?php echo $issue[0][status]?>" />
      <input type="hidden" name="oldpriority" value="<?php echo $issue[0][priority]?>" />
      <input type="hidden" name="oldassignedto" value="<?php echo $issue[0][assignedto]?>" />
      <input type="hidden" name="oldlevelname" value="<?php echo $issue[0][levelname]?>" />
      <input type="hidden" name="oldstatusname" value="<?php echo $issue[0][statusname]?>" />
      <input type="hidden" name="oldpriorityname" value="<?php echo $issue[0][priorityname]?>" />
      <input type="hidden" name="oldassignedtoname" value="<?php echo $issue[0][assignedtoname]?>" />
<?php } elseif ($acl['recall_issue']) {?>
      <input type="hidden" name="act" value="revoke" />
<?php } elseif ($acl['unpublish_issue']) {?>
      <input type="hidden" name="act" value="unpublish" />
<?php }?>
      <input type="hidden" name="reportedby" value="<?php echo $issue[0][reportedby]?>" />
      <input type="hidden" name="createdby" value="<?php echo $issue[0][createdby]?>" />
      <input type="hidden" name="id" value="<?php echo $issue[0][id]?>" />
<?php
  //if ($usertype != 'Client' && $usertype != 'Site Contact' && $issue[0]['published'] == 0) {
    if ($acl['edit_style']) {
    // Top submit button, floating inline at the top - right
    // Note also the closing div tag just before the bottom submit button
?>
    <div class="rcolumn">
      <div class="buttonpanel">
<?php    if ($acl['edit_issue']) { ?>
        <input type="button" value="<?php echo gettext("Submit Changes")?>" onclick="mainSubmit()" />
<?php  }  if ($acl['reset_issue']) { ?>
        <input name="reset" type="reset" id="reset3" value="<?php echo gettext("Reset")?>" onclick="document.location='issue.php?id=<?php echo $issue[0][id]?>'" />
<?php  }  if ($acl['recall_issue']) { ?>
        <input type="button" value="<?php echo gettext("Recall Issue")?>" onclick="recallSubmit()" />
<?php }  ?>
      </div>
    </div>
<?php
    }
?>
<?php if ($acl['view_createdby']) { ?>
      <div class="labelfieldpair">
        <div class="name"><?php echo gettext("Created By")?>:</div>
          <div class="value"><?php echo $issue[0][createdbyname]?></div>
      </div>
<?php   } ?>
      <div class="labelfieldpair">
        <div class="name"><?php echo gettext("Created On")?>:</div>
        <div class="value"><?php echo strftime('%d/%m/%y &nbsp; %H:%M',$issue[0][createdon])?></div>
      </div>
<?php if ($acl['view_reportedby']) { ?>
      <div class="labelfieldpair">
        <div class="name"><?php echo gettext("Reported By")?>:</div>
          <div class="value"><?php echo $issue[0][reportedbyname]?>
            [<a href="find.php?act=action&amp;reset=yes&amp;reportedby%5B%5D=<?php
             echo $issue[0][reportedby]; ?>"
        ><?php echo gettext("Other issues reported by this person")?></a>]
            </div>
      </div>
<?php   } ?>
<?php if ($acl['view_site']) { ?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="site"><?php echo gettext("Site")?></label>
        </div>
       <div class="value" id="site"><?php echo $issue[0][sitename]?>
<?php if ($acl['edit_site']) {?>
                [<a <?php print 'href="issue.php?id=' . $issue[0][id] . '&amp;site=' . $issue[0][site] . '&amp;sitename=' . $issue[0][sitename] . '&amp;assignedto=' . $issue[0][assignedto] . '&amp;act=changesite">'.gettext('Change Site');?></a>]
<?php  }?>
         </div>
      </div>
<?php   } ?>
<?php if ($acl['view_assignedto']) {?>
      <div class="labelfieldpair">
        <div class="name">
      <label for="assignedto"><?php echo gettext("Assigned To")?></label>
        </div>
<?php if (! $acl['edit_assignedto']) {?>
        <div class="value">
          <input type="hidden" name="assignedto" id="assignedto" value="<?php echo $issue[0][assignedto]?>" />
      <?php echo preg_replace('/\* unassigned \*/',gettext('* unassigned *'),$issue[0][assignedtoname])?>
        </div>
<?php  } else {
  $sql = "SELECT DISTINCT tbl_Users.id, tbl_Users.name
  FROM tbl_Users, tbl_UserTypes, tbl_UserSites
  WHERE (
    tbl_Users.active=1
  AND tbl_Users.available=1
  AND tbl_UserTypes.sortorder IN (2,3,4)
  AND tbl_Users.id>0
  AND tbl_UserSites.site=".$issue[0][site]."
  AND tbl_Users.id = tbl_UserSites.userid
  AND tbl_UserSites.usertype = tbl_UserTypes.id
) OR tbl_Users.id=".$issue[0][assignedto]."
  ORDER BY tbl_Users.name";
  $usersRS = db_recordset($sql);
?>
        <div class="field">
          <select name="assignedto" id="assignedto">
<?php
    if ($issue[0][assignedto] == 0) {
      print "            <option value=\"0\" selected=\"selected\">[".gettext("Assign Issue...")."]</option>\n";
    } else {
      print "            <option value=\"0\">[".gettext("Unassign issue...")."]</option>\n";
    }
    foreach ($usersRS as $record) {
      // Set as default if chosen
      if ($record[id] == $issue[0][assignedto]) { $checked = ' selected="selected"'; } else { $checked = ''; }
      print "            <option value=\"${record[id]}\"$checked>".preg_replace('/\* unassigned \*/',gettext('* unassigned *'),$record[name])."</option>\n";
    }
?>
          </select>
        </div>
<?php        }?>
      </div>
<?php  }?>
<?php if ($acl['view_contactinfo']) { ?>
      <div class="labelfieldpair">
        <div class="name">
      <label for="contact"><?php echo gettext("Contact Info")?></label>
        </div>
<?php if ($acl['edit_contactinfo']) {?>
        <div class="field">
          <input name="contact" type="text" id="contact" size="60" maxlength="100" value="<?php echo $issue[0][contact]?>" />
        </div>
<?php } else {?>
        <div class="value">
          <input name="contact" type="hidden" id="contact" value="<?php echo $issue[0][contact]?>" />
          <?php echo $issue[0][contact]?>
        </div>
<?php  }?>
      </div>
<?php  }?>
<?php if ($acl['view_location']) { ?>
      <div class="labelfieldpair">
        <div class="name">
      <label for="location"><?php echo gettext("Location")?></label>
        </div>
<?php if ($acl['edit_location']) {?>
        <div class="field">
          <input name="location" type="text" id="location" size="60" maxlength="100" value="<?php echo $issue[0][location]?>" />
        </div>
<?php  } else {?>
        <div class="value">
          <input name="location" type="hidden" id="location" value="<?php echo $issue[0][location]?>" />
          <?php echo $issue[0][location]?>
        </div>
<?php   }?>
      </div>
<?php   }?>
<?php  if ($num_categories > 0) {//#3?>
<?php  if ($acl['view_category']) {?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="categories"><?php echo gettext("Problem Category")?></label>
        </div>
<?php    if ($num_categories > 1 && $acl['edit_category']) {?>
        <div class="field">
          <select name="categories" id="categories" onchange="SetupDetails()">
<?php foreach ($categoriesRS as $record) {
    if ($record[id] == $issue[0][category]) { $checked = ' selected="selected"'; } else { $checked = ''; }
    print ("            <option value=\"${record[id]}\"$checked>".gettext($record['description'])."</option>\n");
  }?>
          </select>
        </div>
<?php  } else {?>
        <div class="value">
          <input type="hidden" name="categories" id="categories" value="<?php echo $issue[0][category]?>" />
      <?php echo preg_replace('/Unknown/',gettext('Unknown'),$issue[0][categoryname])?>
        </div>
<?php    }?>
      </div>
<?php    }?>
<?php  if ($acl['view_details']) {?>
      <div class="labelfieldpair">
        <div class="name">
      <label for="details"><?php echo gettext("Problem Detail")?></label>
        </div>
<?php if (count($detailsRS) > 1 && $acl['edit_details']) {?>
        <div class="field">
          <select name="details" id="details">
            <option value="0" selected="selected">[<?php echo gettext("Choose...")?>]</option>
          </select>
          [<a href="find.php?act=action&amp;reset=yes&amp;detail%5B%5D=<?php
            echo $issue[0][detail]; ?>"
            ><?php echo gettext("Other issues with the same problem detail")?></a>]
        </div>
<?php  } else {?>
        <div class="value">
          <input type="hidden" name="details" id="details" value="0" />
        <?php echo preg_replace('/Unknown/',gettext('Unknown'),$issue[0][detailname])?>
          [<a href="find.php?act=action&amp;reset=yes&amp;detail%5B%5D=<?php
            echo $issue[0][detail];?>"
            ><?php echo gettext("Other issues with the same problem detail")?></a>]
        </div>
<?php   }?>
      </div>
<?php   }?>
<?php }?>

<?php
    // Ensure clients cannot edit the summary/description
    if ($usertype == 'Client' || $usertype == 'Site Contact' || $issue[0]['published'] == 1) {
        $readonly=' readonly="readonly"';
    } else {
        $readonly='';
    }
?>
<?php  if ($acl['view_summary']) {?>
      <div class="labelfieldpair">
        <div class="name">
       <label for="summary"><?php echo gettext("Summary")?></label>
        </div>
        <div class="field">
<?php  if ($acl['edit_summary']) {?>
          <textarea name="summary" id="summary" cols="60" rows="2"><?php echo $issue[0][summary]?></textarea>
<?php  } else {?>
          <textarea name="summary" id="summary" cols="60" rows="2" readonly="readonly"><?php echo $issue[0][summary]?></textarea>
<?php  }?>
        </div>
      </div>
<?php  }?>
<?php  if ($acl['view_description']) {?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="description"><?php echo gettext("Description")?></label>
        </div>
        <div class="field">
<?php  if ($acl['edit_description']) {?>
          <textarea name="description" id="description" cols="60" rows="6"><?php echo $issue[0][description]?></textarea>
<?php  } else {?>
          <textarea name="description" id="description" cols="60" rows="6" readonly="readonly"><?php echo $issue[0][description]?></textarea>
<?php  }?>
        </div>
      </div>
<?php  }?>
<?php if ($acl['view_solution']) {?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="solution"><?php echo gettext("Solution")?></label>
        </div>
        <div class="field">
<?php if ($acl['edit_solution']) {?>
           <textarea name="solution" id="solution" cols="60" rows="4"><?php echo $issue[0][solution]?></textarea>
<?php  } else {?>
           <textarea name="solution" id="solution" cols="60" rows="4" readonly="readonly"><?php echo $issue[0][solution]?></textarea>
<?php  }?>
        </div>
      </div>
<?php  }?>
<?php if ($acl['edit_publish']) {?>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <input name="publish" id="publish" type="checkbox" value="publish" />
                     <label for="publish"><?php echo gettext("Publish this issue to the knowledge base.")?></label>
        </div>
      </div>
<?php  }?>
<?php if ($acl['view_time']) {
    if ($is_pgsql) {
      $userTimes=db_recordset('SELECT SUM(time) AS totaltime FROM tbl_Times, tbl_Users WHERE tbl_Times.userid = tbl_Users.id AND tbl_Times.issue = ' . $issue[0]['id']);
      $utime = $userTimes[0]['totaltime'];
    } else {
      $userTimes=db_recordset('SELECT SUM(time) AS ts FROM tbl_Times, tbl_Users
  WHERE tbl_Times.userid = tbl_Users.id AND tbl_Times.issue = ' . $issue[0]['id']);
      $utime = maketime($userTimes[0]['ts']);
  ## Just a thought, does this need to be SUM or not?
  ## Answer: Yes, cause one issue can have times from more then one user.
    }
    if ($utime) {
?>
      <div class="labelfieldpair">
        <div class="name">
          <?php echo gettext("Total time")?>:
        </div>
        <div class="value">
            <?php echo $userTimes[0]['totaltime']?>
        </div>
      </div>
<?php   }
     }
?>
<?php if ($acl['edit_time']) {?>
      <div class="labelfieldpair">
        <div class="name">
            <?php echo gettext("(Add to) Time spent")?>:
        </div>
        <div class="field">
            <input type="text" size="2" maxlength="3" name="timehours" id="timehours" class="time" />
            <label for="timehours"><?php echo gettext("hours")?></label>
        <input type="text" size="2" maxlength="3" name="timeminutes" id="timeminutes" class="time" />
            <label for="timeminutes"><?php echo gettext("minutes")?></label>
        </div>
      </div>
<?php    }?>
<?php if ($acl['view_priority']) {
  $prioritiesRS = db_recordset("SELECT * FROM tbl_Priorities WHERE (active=1 AND domain=$_SESSION[_domain]) OR id=" . $issue[0][priority] . " ORDER BY sortorder");
?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="priority"><?php echo gettext("Priority")?></label>
        </div>
<?php if (count($prioritiesRS) > 1 && $acl['edit_priority']) {?>
        <div class="field">
          <select name="priority" id="priority">
<?php
    foreach ($prioritiesRS as $record) {
      if ($record[id] == $issue[0][priority]) { $checked = ' selected="selected"'; } else { $checked = ''; }
      print ("            <option value=\"${record[id]}\"$checked>".
      preg_replace('/Ungraded/',gettext('Ungraded'),$record[priority])."</option>\n");
    }
?>
          </select>
        </div>
<?php  } else {?>
        <div class="value">
          <input type="hidden" name="priority" id="priority" value="<?php echo $issue[0][priority]?>" />
          <?php echo preg_replace('/Ungraded/',gettext('Ungraded'),$issue[0][priorityname])?>
        </div>
<?php  }?>
      </div>
<?php    }?>
<?php if ($acl['view_status']) {
  $statusesRS = db_recordset("SELECT * FROM tbl_Statuses WHERE (active=1 AND domain=$_SESSION[_domain]) OR id=" . $issue[0][status] . " ORDER BY sortorder");?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="status"><?php echo gettext("Status")?></label>
        </div>
<?php if (count($statusesRS) > 1 && $acl['edit_status']) {?>
        <div class="field">
          <select name="status" id="status">
<?php
    foreach ($statusesRS as $record) {
      if ($record[id] == $issue[0][status]) { $checked = ' selected="selected"'; } else { $checked = ''; }
      print ("            <option value=\"${record[id]}\"$checked>${record[status]}</option>\n");
    }
?>
          </select>
        </div>
<?php  } else {?>
        <div class="value">
          <input type="hidden" name="status" id="status" value="<?php echo $issue[0][status]?>" />
          <?php echo $issue[0][statusname]?>
        </div>
<?php  }?>
      </div>
<?php  }?>
<?php if ($acl['view_level']) {
  $levelsRS = db_recordset("SELECT * FROM tbl_Levels WHERE (active=1 AND domain=$_SESSION[_domain]) OR id=" . $issue[0][level] . " ORDER BY sortorder");?>
      <div class="labelfieldpair">
        <div class="name">
      <label for="level"><?php echo gettext("Level")?></label>
        </div>
<?php if (count($levelsRS) > 1 && $acl['edit_level']) {?>
        <div class="field">
          <select name="level" id="level">
<?php
    foreach ($levelsRS as $record) {
      if ($record[id] == $issue[0][level]) { $checked = ' selected="selected"'; } else { $checked = ''; }
      print ("            <option value=\"${record[id]}\"$checked>".
      preg_replace('/None/',gettext('None'),$record[level])."</option>\n");
    }
?>
          </select>
        </div>
<?php  } else {?>
        <div class="value">
          <input type="hidden" name="level" id="level" value="<?php echo $issue[0][level]?>" />
          <?php echo preg_replace('/None/',gettext('None'),$issue[0][levelname])?>
        </div>
<?php  }?>
      </div><!--0-->
<?php
    }
    if (function_exists('finfo_open')) {
?>
    <div class="labelfieldpair">
        <div class="name">
          <label for="attachments"><?php echo gettext("Attachments")?></label>
        </div>
        <div class="field">
<?php
        // Get a list of attachment files for this issue.
        $attachments = get_attachments($id);
        $first = true;
        if ($attachments) {
          $attachment_path = get_attachment_dir($id);
          foreach ($attachments as $attachment) {
            if ($first) {
              $first = false;
            } else {
              echo "<br />";
            }
            $filesize = filesize($attachment_path."/".$attachment);
            if ($filesize < 1024) {
              $filesize = "<1K";
            } elseif (round($filesize/1024) < 1024) {
              $filesize = round($filesize/1024, 1) . "K";
            } elseif (round($filesize/(1024*1024)) < 1024) {
              $filesize = round($filesize/(1024*1024), 1) . "M";
            } elseif (round($filesize/(1024*1024*1024)) < 1024) {
              $filesize = round($filesize/(1024*1024*1024), 1) . "G";
            }
            echo "<input type=\"checkbox\" name=\"delete_attachments[]\" value=\"".urlencode($attachment)."\" />  ";
            echo "<a href=\"files.php?issue_id=".$id."&amp;filename=".urlencode($attachment)."\">$attachment</a> (".$filesize.")\n";
          }
            echo "<br /><em>(tick and submit to delete an attachment)</em>";
        } else {
            echo "None";
        }
?>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">
          <label for="attachment"><?php echo gettext("Add attachment")?></label>
        </div>
        <div class="field">
          <input type="file" name="attachment" />
        </div>
      </div>
<?php
    }

    if ($acl['edit_style']) {?>
      <hr class="hide" />
      <div class="buttonpanel">
<?php if ($acl['edit_issue']) { ?>
        <input type="button" value="<?php echo gettext("Submit Changes")?>" onclick="mainSubmit()" />
<?php } if ($acl['reset_issue']) { ?>
        <input name="reset" type="reset" id="reset4" value="<?php echo gettext("Reset")?>" onclick="document.location='issue.php?id=<?php echo $issue[0][id]?>'" />
<?php
} elseif ($acl['recall_issue']) {
?>
        <input type="button" value="<?php echo gettext("Recall Issue")?>" onclick="recallSubmit()" />
<?php
    } elseif ($acl['unpublish_issue']) {
?>
        <input type="button" value="<?php echo gettext("Unpublish this item")?>" onclick="document.mainform.act.value = 'unpublish';document.mainform.submit()" />
<?php  }?>
    </div>
<?php  }?>
   </div><!--1-->
<?php if ($acl['edit_details'] && $num_categories > 0) {
?>
<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

  SetupDetails();

//-->
//]]>
</script>
<?php } ?>
   <br />
<?php  if ($acl['view_remarks'] || $acl['add_remark'] || $acl['edit_remark']) {
    if (count($issue) > 0) {
      // Get all the remarks for this issue
      $sql = "SELECT tbl_Remarks.*,tbl_Users.name AS reportedbyname FROM tbl_Remarks,tbl_Users WHERE tbl_Remarks.issue=" . $issue[0][id] . " AND tbl_Remarks.reportedby=tbl_Users.id";
      //if ($usertype == 'Client' || $usertype == 'Site Contact') {
    if (! $acl['show_confidential']) {
        $sql .= " AND tbl_Remarks.confidential=0";
      }
      $sql .= " ORDER BY tbl_Remarks.reportedon DESC";
      $remarks = db_recordset($sql);
?>
        </div><div class="workspace">
  <a name="history" id="history"></a><h1><?php echo gettext("Issue History")?></h1>
  <h2><?php echo gettext("This issue's history can be found below.")?>
<?php if ($acl['add_remark']) { ?>
            <?php echo gettext('Please follow this link to <a href="#addremark">add a remark</a>.')?>
<?php } ?>
    </h2>
        
  <div class="block">
<?php
      if (count($remarks) == 0) {
        // If there are no remarks then say so
?>
    <p><?php echo gettext("There are no remarks in this history so far.")?></p>
<?php } else {  if ($acl['edit_remark']) {?>
    <div class="remarklabelfieldpairtop">
      <div class="remarklabelright">
        <select name="remarkaction" id="remarkaction">
          <option value="" selected="selected">[<?php echo gettext("Choose action...")?>]</option>
          <option value="confidential"><?php echo gettext("Make confidential")?></option>
          <option value="public"><?php echo gettext("Make public")?></option>
          <option value="remove"><?php echo gettext("Delete!")?></option>
        </select> <?php echo gettext("the selected remarks.")?></div>
    </div>
<?php
          $flag = 1;
        } else {
          $flag = 0;
        }
    /*
      Workaround to get localisation work on remark entries.
    */

    $rmitems = array(
      gettext('Issue priority changed from'), // 0
      gettext('Issue level changed from'),    // 1
      gettext('Issue status changed from'),   // 2
      gettext('to'),                          // 3
      gettext('Spent'),                       // 4
      gettext('Spent an additional'),         // 5
      gettext('hour'),                        // 6
      gettext('hours'),                       // 7
      gettext('minute'),                      // 8
      gettext('minutes'),                     // 9
      gettext('on the problem.'),             // 10
      gettext('Issue site changed from'),     // 11
      gettext('Issue reassigned from'),       // 12
      gettext('* unassigned *'),              // 13
      gettext('Issue recalled by the client'),// 14
      gettext('Ungraded')                     // 15
    );

    include "system/i18n_remarks.inc";

        foreach ($remarks as $record) {
          if ($flag == 0) {
            print "    <div class=\"remarklabelfieldpairtop\" id=\"remark$record[id]\">\n";
            $flag = 1;
          } else {
            print "    <div class=\"remarklabelfieldpair\" id=\"remark$record[id]\">\n";
          }
?>
      <div class="remarklabel">
        <?php echo strftime('%d/%m/%y &nbsp; %H:%M',$record[reportedon])?><br />
<?php if ($acl['view_reportedby']) {
            echo $record['reportedbyname'];
        }?>
      </div>
<?php if ($acl['edit_remark']) {?>
      <div class="remarklabelright">
        <input type="checkbox" name="selectremark[]" id="selectremark<?php echo $record[id]?>" value="<?php echo $record[id]?>" onclick="hideConfidentiality(this,'remark<?php echo $record[id]?>','#FFFFFF')" />
      </div>
<?php         }?>
      <div class="remark"><?php echo ($record[confidential] == 1?'<strong>['. gettext("Confidential") .']</strong> &nbsp; ':'')?><?php loc_remarks($rmitems, $record[remark])?></div>
    </div>
<?php
        }
      }
?>
    <a name="addremark" id="addremark"></a>
        <div class="remarklabelfieldpair" id="addremarklabelfieldpair">
        <br />
        <!--    <form name="historyform" id="historyform" method="post" action="">  -->
<?php  if ($acl['add_remark']) {?>
      <div class="labelfieldpair">
        <div class="name"><label for="remark"><?php echo gettext("Add Remark")?></label></div>
        <div class="field">
<textarea name="remark" id="remark" cols="60" rows="6" onfocus="focusElement(this)" onblur="blurElement(this)">[<?php echo gettext("Please enter remark")?>]</textarea>
        </div>
      </div>
<?php if ($acl['show_confidential']) {?>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <input type="checkbox" name="confidential" id="confidential" checked="checked" value="true" onclick="showConfidentiality(this,'remark','#EEEEFF')" />
          <label for="confidential"><?php echo gettext("Make this remark confidential.")?></label>
        </div>
      </div>
<?php        } else {?>
      <input type="hidden" name="confidential" id="confidential" value="false" />
<?php      }?>
<?php  }?>
<?php if ($acl['edit_remark'] || $acl['add_remark']) {?>
      <div class="buttonpanel">
        <input name="submitremark" type="button" id="submitremark" value="<?php echo gettext("Submit Changes")?>" onclick="mainSubmit()" />
        <input name="resetremark" type="reset" id="resetremark" value="<?php echo gettext("Reset")?>" />
      </div>
<?php  }?>
    </div>
  </div>
<?php     }?>
<?php    }?>
  </form>

<?php
  }

  // Include
  require 'footer.php';
?>

