<?php

  /*

      newissue.php

      New Issue. Allows the user to add a new issue to the system
      choosing all the pertinent values such as priority and site
      etc. [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-04-27 arne_sf: Replaced MySQL- and PostgreSQL-specific sequence ID code with call to db_next_id()
        
      ## 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
  if ($_SESSION['_usertype'] == '' || $_SESSION['_usertype'] == 'Root') {
    require_once 'system/security.php';
    ThrowOut();
  }
  
  // Page Title
  $ptitle = 'New Issue';

  // Includes
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/message.php';
  require_once 'system/user_preferences.php';
  require_once 'system/functions.php';
  require_once 'system/remark.php';
  require_once 'system/mail.php';
  require_once 'system/attachments.php';
  require 'header.php';

  // Language selection
  set_text_domain("newissue");
  
  // Retrieve Get/Post variables
  $act = $_POST['act'];
  $createdby = $_POST['createdby'];
  $level = $_POST['level'];
  $status = $_POST['status'];
  $reportedby = $_POST['reportedby'];
  $contact = $_POST['contact'];
  $site = $_POST['site'];
  $assignedto = $_POST['assignedto'];
  $location = $_POST['location'];
  $categories = $_POST['categories'];
  $details = $_POST['details'];
  $summary = $_POST['summary'];
  $description = $_POST['description'];
  $priority = $_POST['priority'];
  $level = $_POST['level'];
  $close = $_POST['close'];

  // Action: Add issue to the database
  if ($act == 'action') {
    $act = '';

    // Retrieve default value for level
    if ($level == '' || $level < 1) {
      $levelRS = db_recordset("SELECT id FROM tbl_Levels WHERE (sortorder=0 AND domain=$_SESSION[_domain]) OR domain=0 ORDER BY domain DESC");
      if (count($levelRS) > 0) {
        $level = $levelRS[0][id];
      } else {
        $level = 0;
      }
    }
      
    $closedon = 0;
    $closedby = 0;

    if ($close == 'true') {
      // Find the highest status (the terminal status) and treat it as closed
      $closedstatus = get_closed_status($_SESSION['_domain']);
      if ($closedstatus != '-1') {
          $closedon = time();
          $closedby = $_SESSION[_id];
          $status = $closedstatus;
      }
    } elseif ($status == '' || $status < 1) {
      // Retrieve default value for status
      $statusRS = db_recordset("SELECT id FROM tbl_Statuses WHERE (sortorder=0 AND domain=$_SESSION[_domain]) OR domain=0 ORDER BY domain DESC");
      if (count($statusRS) > 0) {
        $status = $statusRS[0][id];
      } else {
        $status = 0;
      }
    }
    
    $issue = db_next_id('tbl_Issues_id');
    db_send("INSERT INTO tbl_Issues (id, closedon, closedby, assignedto, createdon,
               createdby, reportedby, site, priority, location, contact, summary,
               description, level, status, detail, category, domain)
             VALUES ($issue, $closedon, $closedby, $assignedto, " . time() .
               ", $_SESSION[_id], $reportedby, $site, $priority, '$location',
               '$contact', '$summary', '$description', $level, $status, $details,
               $categories, $_SESSION[_domain])");

    $user_prefs = get_user_prefs($assignedto);
    $user_details = get_user_details($assignedto);
    // Mail user if they have just been assigned an issue
    if ($close != 'true' && $assignedto!=$_SESSION['_id'] &&
       ($user_prefs['email-assign'] == 'true' || $user_prefs['email-remark'] == 'true')
        && $user_details['email']!='') {
//     send_mail($user_prefs['language'],"newissue",$issue, $user_details['email'],gettext("You have been assigned a new issue in the helpdesk issue manager, please view this issue as soon as possible."),2);
      send_mail('assign', $user_prefs['language'], $user_details['email'], $issue, $_SESSION['_name'], "");
    }
    
    // Mail address if 
    $user_prefs = get_user_prefs($_SESSION['_id']);
    $address = $user_prefs['newissue-email'];
    if ($assignedto == 0 && $address != '') {
      $lng = db_recordset("SELECT value from tbl_domain_preferences where domain=$_SESSION[_domain] and identifier='language'");
      send_mail('newissue',$lng[0]['value'],$address,$issue,$_SESSION['_name'],"");
    }

    // Deal with adding an attachment
    if ($_FILES['attachment']['error'] == UPLOAD_ERR_OK) {
      $attachment_dir = get_attachment_dir($issue, true);
      move_uploaded_file($_FILES['attachment']['tmp_name'], $attachment_dir."/".$_FILES['attachment']['name']);
    }

    $act = 'thanks';
  }

  // Action: Thank the user for the submission
  if ($act == 'thanks') {
?>

  <h1><a href="issue.php?id=<?php echo $issue?>"><?php echo gettext("Issue")?> #<?php echo $issue?></a></h1>
  <h2><?php printf(gettext("Thank you for your submission. Please record the issue number: #%s as it may be required by support staff when communicating with you regarding your query."),$issue);?></h2>
  
  <div class="block">
    <p><?php echo gettext("Continue to")?> <a href="myissues.php"><?php echo gettext("my issues")?></a>.</p>
    <p><?php echo gettext("Or, alternatively you can submit another")?> <a href="newissue.php"><?php echo gettext("new issue")?></a>.</p>
  </div>

<?php
  }

  // Default action: request info for new issue
  if ($act == '') {
    // Find all the values for the site drop down list
    $sql = "SELECT tbl_Sites.* FROM tbl_UserSites,tbl_Sites WHERE tbl_UserSites.userid=$_SESSION[_id] AND tbl_UserSites.site=tbl_Sites.id AND domain=$_SESSION[_domain] AND active=1 ORDER BY tbl_Sites.site";
    $sitesRS = db_recordset($sql);
    
    // Find all the values for the category drop down list
    $categoriesRS = db_recordset("SELECT * FROM tbl_ProblemCategories WHERE (domain=$_SESSION[_domain] AND active=1) OR id=0 ORDER BY description");
    $num_categories = count($categoriesRS);
    
    // If there are no categories then don't both asking for details
    if ($num_categories > 0)
      // Find all the values for the details drop down list
      $detailsRS = db_recordset("SELECT * FROM tbl_ProblemDetails WHERE (domain=$_SESSION[_domain] AND active=1) OR id=0 ORDER BY description");
      
    // Find all the values for the priority drop down list
    $prioritiesRS = db_recordset("SELECT * FROM tbl_Priorities WHERE (domain=$_SESSION[_domain] AND active=1) OR id=0 ORDER BY sortorder");

    display($message);
?>

<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 ($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++;
      }
?>

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

<?php
    }
?>

  function focusAll() {
<?php
    if ($site != '') {
      if ($location == '') { print "    focusElement(document.mainform.location);\n"; }
      if ($contact == '') { print "    focusElement(document.mainform.contact);\n"; }
      if ($description == '') { print "    focusElement(document.mainform.description);\n"; }
      if ($summary == '') { print "    focusElement(document.mainform.summary);\n"; }
    }
?>
  }

  var submittable = true;

  function mainSubmit () {
    if (submittable) {
      var flag = true;
      if (document.mainform.site.value == '') {
      alert('<?php echo gettext("You must choose a site for this issue.")?>');
        flag = false;
      }
      if (flag && document.mainform.summary.value == document.mainform.summary.defaultValue) {
      alert('<?php echo gettext("You must give this issue a summary.")?>');
        flag = false;
      }
      if (flag && document.mainform.description.value == document.mainform.description.defaultValue) {
      alert('<?php echo gettext("You must give this issue a description.")?>');
        flag = false;
      }
      if (flag) {
        focusAll();
        document.mainform.submit();
        submittable = false;
      }
    }
  }

  function siteSubmit () {
    focusAll();
    document.mainform.act.value = '';
    document.mainform.submit();
  }

//-->
//]]>
</script>

  <h1><?php echo gettext("New Issue")?></h1>
  <h2><?php echo gettext("Please enter the following information to fully identify your issue")?>:</h2>
  
  <div class="block">
    <form name="mainform" id="mainform" method="post" action="" onsubmit="" enctype="multipart/form-data">
      <input type="hidden" name="act" value="action" />
      <input type="hidden" name="createdby" value="<?php echo $_SESSION['_id']?>" />
      <div class="labelfieldpair">
        <div class="name"><label><?php echo gettext("Created By")?></label></div>
        <div class="value"><?php echo $_SESSION['_name']?></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label><?php echo gettext("Created On")?></label></div>
        <div class="value"><?php echo strftime('%d/%m/%y &nbsp; %H:%M',time())?></div>
      </div>
<?php
    if (count($sitesRS) == 0 || count($sitesRS) == 1) {
      $site = (count($sitesRS) == 0) ? 0 : $site = $sitesRS[0][id];
?>
      <input type="hidden" name="site" id="site" value="<?php echo $site?>" />
<?php
    } else {
/*      if (count($sitesRS) == 1) {
?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="site"><?php echo gettext("Site")?></label>
        </div>
        <div class="value">
          <input type="hidden" name="site" id="site" value="<?php echo $site?>" />
          <?php echo $sitesRS[0][site]?>
        </div>
      </div>
<?php
      } else { 
        if ($site == '') { */
?>
      <div class="labelfieldpair">
        <div class="name">
          <label for="site"><?php echo gettext("Site")?></label>
        </div>
        <div class="field">
          <select name="site" id="site" onchange="siteSubmit();">
            <option value="" selected="selected">[<?php echo gettext("Choose Site to continue")?>...]</option>
<?php
          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>
<?php
/*        } else {
          print "      <input type=\"hidden\" name=\"site\" id=\"site\" value=\"$site\" />\n";
        }
      } */
    }
    
    if ($site != '') {

      if ($site == 0) {
        $usertype = 'Client';
      } else {
        ## $usertypesRS = db_recordset("SELECT usertypename FROM vw_UserTypes WHERE id=$_SESSION[_id] AND site=$site");
        $usertypesRS = db_recordset("SELECT tbl_UserTypes.type AS usertypename
                                     FROM  tbl_UserSites,tbl_UserTypes
                                     WHERE tbl_UserSites.userid=$_SESSION[_id]
                                       AND tbl_UserSites.site=$site
                                       AND tbl_UserSites.usertype=tbl_UserTypes.id");
        $usertype = $usertypesRS[0][usertypename];
      }

      if ($usertype == 'Client' || $usertype == 'Site Contact') {
?>
      <input type="hidden" name="reportedby" id="reportedby" value="<?php echo $_SESSION['_id']?>" />
<?php
      } else {
        // Find all the values for the reported by drop down list
        ## $usersRS = db_recordset("SELECT DISTINCT id,name FROM vw_UserTypes WHERE active=1 AND id>0 AND site=$site ORDER BY name");
        $usersRS = db_recordset("SELECT DISTINCT tbl_Users.id,tbl_Users.name
                                 FROM tbl_Users, tbl_UserSites, tbl_Sites
                                 WHERE tbl_Users.active=1
                                   AND tbl_Users.id>0
                                   AND tbl_UserSites.site=$site
                                   AND tbl_Users.id = tbl_UserSites.userid
                                   AND tbl_UserSites.site = tbl_Sites.id
                                 ORDER BY tbl_Users.name");
?>
      <div class="labelfieldpair">
        <div class="name">
       <label for="reportedby"><?php echo gettext("Reported By")?></label>
        </div>
        <div class="field">
          <select name="reportedby" id="reportedby">
<?php
        foreach ($usersRS as $record) {
          // Set issue to be reported by this user by default
          $checked = ($record[id] == $_SESSION['_id']) ? ' selected="selected"' : $checked = '';
          print ("            <option value=\"${record[id]}\"$checked>".$record[name]."</option>\n");
        }
?>
          </select>
        </div>
      </div>
<?php
      }
      
      // Find all the values for the assigned to drop down list
      ## $usersRS = db_recordset("(SELECT id,name FROM tbl_Users WHERE id=0) UNION (SELECT DISTINCT id,name FROM vw_UserTypes WHERE active=1 AND vw_Users.available=1 AND usertypesortorder IN (2,3,4) AND id>0 AND site=$site ORDER BY name);");
      $usersRS = db_recordset("(SELECT id,name
                                FROM tbl_Users
                                WHERE id=0)
                               UNION
                               (SELECT DISTINCT tbl_Users.id,tbl_Users.name
                                FROM tbl_Users, tbl_UserSites, tbl_Sites, tbl_UserTypes
                                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=$site
                                  AND tbl_Users.id = tbl_UserSites.userid
                                  AND tbl_UserSites.site = tbl_Sites.id
                                  AND tbl_UserSites.usertype = tbl_UserTypes.id
                                  ORDER BY tbl_Users.name)");
      if (0) { // Think a issue must not be assigned automatically. That's out of logic.
        print "      <input type=\"hidden\" name=\"assignedto\" id=\"assignedto\" value=\"" . $usersRS[0][id] . "\" />\n";
      } else {
        if ($usertype == 'Client' || $usertype == 'Site Contact') {
?>
      <input type="hidden" name="assignedto" id="assignedto" value="0" />
<?php
        } else {
?>
      <div class="labelfieldpair">
        <div class="name">
        <label for="assignedto"><?php echo gettext("Assigned To")?></label>
        </div>
        <div class="field">
          <select name="assignedto" id="assignedto">
<?php
          foreach ($usersRS as $record) {
            // Set issue to be assigned to this user by default
            $checked = ($record[id] == $_SESSION['_id']) ? ' selected="selected"' : '';
            if ($record[name] == "* unassigned *") {
              print ("            <option value=\"${record[id]}\"$checked>".gettext('* unassigned *')."</option>\n");
            } else {
              print ("            <option value=\"${record[id]}\"$checked>$record[name]</option>\n");
            }
          }
?>
          </select>
        </div>
      </div>
<?php
        }
      }
      $locationvalue = $location == '' ? gettext("[e.g. Room 3R5]") : $location;
      $contactvalue = $contact == '' ? gettext("[e.g. Extension 1970]") : $contact;
?>
      <div class="labelfieldpair">
        <div class="name">
       <label for="contact"><?php echo gettext("Contact Info")?></label>
        </div>
        <div class="field">
          <input name="contact" type="text" id="contact" size="50" maxlength="100" value="<?php echo $contactvalue?>"<?php echo ($contact == ''?' onfocus="focusElement(this)" onblur="blurElement(this)"':'')?> />
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">
       <label for="location"><?php echo gettext("Location")?></label>
        </div>
        <div class="field">
          <input name="location" type="text" id="location" size="50" maxlength="100" value="<?php echo $locationvalue?>"<?php echo ($location == ''?' onfocus="focusElement(this)" onblur="blurElement(this)"':'')?> />
        </div>
      </div>
<?php
      if ($num_categories > 1) {
?>
      <div class="labelfieldpair">
        <div class="name">
<label for="categories"><?php echo gettext("Problem Category")?></label>
        </div>
        <div class="field">
          <select name="categories" id="categories" onchange="SetupDetails()">

            <option value="0"<?php echo ($categories != ''?'':' selected="selected"')?>>[<?php echo gettext("Choose Category")?>]</option>
<?php
        foreach ($categoriesRS as $record) {
          // Set category by default
          if ($categories != '' && $record[id] == $categories) { $checked = ' selected="selected"'; } else { $checked = ''; }
          print ("            <option value=\"${record[id]}\"$checked>".preg_replace('/Unknown/',gettext('Unknown'),$record[description])."</option>\n");
        }
?>
          </select>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">
          <label for="details"><?php echo gettext("Problem Detail")?></label>
        </div>
        <div class="field">
          <select name="details" id="details">
            <option value="0" selected="selected">[<?php echo gettext("Choose Detail")?>]</option>
          </select>
        </div>
      </div>
<?php
      } else {
?>
      <input type="hidden" name="details" id="details" value="0" />
      <input type="hidden" name="categories" id="categories" value="0" />
<?php
      }
      
      $summaryvalue = $summary == '' ? gettext("[Please summarise the issue in a sentence or two]") : $summary;
      $descriptionvalue = $description == '' ? gettext("[Please describe the issue in full]") : $description;
?>
      <div class="labelfieldpair">
        <div class="name">
       <label for="summary"><?php echo gettext("Summary")?></label>
        </div>
        <div class="field">
          <textarea name="summary" id="summary" cols="60" rows="2"<?php echo ($summary == ''?' onfocus="focusElement(this)" onblur="blurElement(this)"':'')?>><?php echo $summaryvalue?></textarea>
        </div>
      </div>
      <div class="labelfieldpair">
        <div class="name">
       <label for="description"><?php echo gettext("Description")?></label>
        </div>
        <div class="field">
          <textarea name="description" id="description" cols="60" rows="6"<?php echo ($description == ''?' onfocus="focusElement(this)" onblur="blurElement(this)"':'')?>><?php echo $descriptionvalue?></textarea>
        </div>
      </div>
<?php
      // Should clients / site contacts be able to choose this?
      if ($_SESSION['_usertype'] == 'Client' || count($prioritiesRS) == 0) {
?>
      <input type="hidden" name="priority" id="priority" value="0" />
<?php
      } else {
?>
      <div class="labelfieldpair">
        <div class="name">
        <label for="priority"><?php echo gettext("Priority")?></label>
        </div>
        <div class="field">
          <select name="priority" id="priority">
<?php
        $defaultpriority = db_recordset("SELECT defaultpriority FROM tbl_Domains WHERE id=$_SESSION[_domain];");
        foreach ($prioritiesRS as $record) {
          // Choose the lowest priority as the default
          if ($record[id] == $defaultpriority[0][defaultpriority]) {
            $checked = ' selected="selected"';
          } else {
            $checked = '';
          }
          print ("            <option value=\"${record[id]}\"$checked>".preg_replace('/Ungraded/',gettext('Ungraded'),$record[priority])."</option>\n");
        }
?>
          </select>
        </div>
      </div>
<?php
      }
      
      // Should clients / site contacts be able to choose this?
      $levelsRS = db_recordset("SELECT * FROM tbl_Levels WHERE (active=1 AND domain=$_SESSION[_domain]) ORDER BY sortorder");
      if ($_SESSION['_usertype'] == 'Client' || $_SESSION['_usertype'] == 'Site Contact' || count($levelsRS) <= 1) {
        $level = (count($levelsRS) == 0) ? 0 : $level = $levelsRS[0][id];
?>
      <input type="hidden" name="level" id="level" value="<?php echo $level?>" />
<?php
      } else {
?>
      <div class="labelfieldpair">
        <div class="name">
      <label for="level"><?php echo gettext("Level")?></label>
        </div>
        <div class="field">
          <select name="level" id="level">
<?php
        foreach ($levelsRS as $record) {
          if ($record[id] == $level) { $checked = ' selected="selected"'; } else { $checked = ''; }
          print ("            <option value=\"${record[id]}\"$checked>".
          preg_replace('/None/',gettext('None'),$record[level])."</option>\n");
        }
?>
          </select>
        </div>
      </div>
<?php
      }
      if (function_exists('finfo_open')) {
?>
      <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 (($usertype == 'Support Agent' || $usertype == 'Administrator' ||
           $usertype == 'Domain Administrator') &&
           get_closed_status($_SESSION['_domain']) != '-1') {
?>
      <div class="labelfieldpair">
        <div class="name">&nbsp;</div>
        <div class="field">
          <input type="checkbox" name="close" id="close" value="true" />
      <label for="close"><?php echo gettext("Submit this as a closed issue.")?></label>
        </div>
      </div>
<?php
      }
?>
      <div class="buttonpanel">
        <input type="button" value="<?php echo gettext("Submit Issue")?>" onclick="mainSubmit()" />
        <input name="reset" type="reset" id="reset" value="<?php echo gettext("Reset")?>" />
        <input name="cancel" onclick="history.back();" type="button"
            id="cancel" value="<?php echo gettext("Cancel")?>" />
      </div>
<?php
    }
?>
    </form>
  </div>
  <br />
<?php
  if ($site != '' && $num_categories > 0) {
?>
<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

  SetupDetails();
<?php
    if ($details != '') {
?>
  var detailID = <?php echo $details?>;
  for (i=0;i<document.mainform.details.options.length;i++) {
    if (document.mainform.details.options[i].value == detailID) document.mainform.details.options[i].selected = true;
  }
<?php
    }
?>

// -->
//]]>
</script>
<?php
  }
}

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