<?php

  /*

      find.php

      Find Issues by entering a free text search string or by restricting
      certain fields to a chosen set of values. [Commented]

      Changelog:
        2006-01-14 dave: Cleaned up code for v1.0 release
        2005-07-03 arne_sf: Replaced all instances of column name 'user' for table tbl_UserSites with 'userid'
          
      ----

      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 = 'Find';

  // Includes
  require_once 'system/db.php';
  require_once 'system/lang.php';
  require_once 'system/message.php';
  require_once 'system/sorting.php';
  require_once 'system/global_preferences.php';
  require_once 'system/functions.php';
  require_once 'config/db.conf.php';
  require 'header.php';
  require 'system/calendar.inc';
  
  // Language selection
  set_text_domain("find");

  // Retrieve Get/Post variables
  ## There are a lot of variables here to protect!
  $act = $_REQUEST['act'];
  $id = $_REQUEST['id'];
  $orderby = $_GET['orderby'];
  $orderdir = $_GET['orderdir'];
  $page = $_GET['page'];
  $freetextscope = $_REQUEST['freetextscope'];
  $freetext = $_REQUEST['freetext'];
  $site = $_REQUEST['site'];
  $reportedby = $_REQUEST['reportedby'];
  $priority = $_REQUEST['priority'];
  $level = $_REQUEST['level'];
  $status = $_REQUEST['status'];
  $category = $_REQUEST['category'];
  $detail = $_REQUEST['detail'];
  $datefrom = $_REQUEST['datefrom'];
  $dateto = $_REQUEST['dateto'];
  $assignedto = $_REQUEST['assignedto'];
  $createdby = $_REQUEST['createdby'];

  $reset = $_REQUEST['reset'];

  if ($reset == 'yes') {
    // Reset remembered sql restrictions
    $_SESSION['_searchsql'] = '';
  }

  // Action: Retrieve issues that match the search and dsiplay them
  if ($act == 'action') {

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

    // Set up sorting and grouping values for the unresolved issue list
    if ($orderby == '') {
      $grouporderby = 'id';
      if ($is_pgsql) {
        $orderby = 'sortorder DESC,vw_Issues.id DESC';
      } else {
        $orderby = 'createdon DESC, sortorder DESC, tbl_Issues.id DESC';
      }
      $orderdir = '';
    } else {
      $grouporderby = $orderby;
    }

    // Parse the dates given - if any
    $validdate = true;
    if ($datefrom != '') {
      $pieces = explode("/", $datefrom);
      if (count($pieces) == 1) {
        // Parse a date without slashes DDMMYYYY
        if (!is_numeric($pieces[0])) {
          $validdate = false;
        } elseif (strlen($pieces[0]) != 8) {
          $validdate = false;
        } else {
          $day = substr($pieces[0], 0,2);
          $month = substr($pieces[0], 2, 2);
          $year = substr($pieces[0], 4, 4);
          if (checkdate($month, $day, $year)) {
            $datefrom = mktime(0,0,0, $month, $day, $year);
          } else {
            $validdate = false;
          }
        }
      } elseif (count($pieces) == 3) {
        // Parse a date with slashes (DD/MM/YYYY)
        $day = intval($pieces[0]);
        $month = intval($pieces[1]);
        $year = intval($pieces[2]);
        if (!checkdate($month, $day, $year)) {
          // Invalid date
          $validdate = false;
        } else {
          $datefrom = mktime(0,0,0,$month, $day, $year);
        }
      } else {
        // Invalid date
        $validdate = false;
      }
    }
    if ($dateto != '') {
      $pieces = explode("/", $dateto);
      if (count($pieces) == 1) {
        // Parse a date without slashes DDMMYYYY
        if (!is_numeric($pieces[0])) {
          $validdate = false;
        } elseif (strlen($pieces[0]) != 8) {
          $validdate = false;
        } else {
          $day = substr($pieces[0], 0,2);
          $month = substr($pieces[0], 2, 2);
          $year = substr($pieces[0], 4, 4);
          if (checkdate($month, $day, $year)) {
            $dateto = mktime(23,59,59, $month, $day, $year);
          } else {
            $validdate = false;
          }
        }
      } elseif (count($pieces) == 3) {
        // Parse a date with slashes (DD/MM/YYYY)
        $day = intval($pieces[0]);
        $month = intval($pieces[1]);
        $year = intval($pieces[2]);
        if (!checkdate($month, $day, $year)) {
          // Invalid date
          $validdate = false;
        } else {
          $dateto = mktime(23,59,59,$month, $day, $year);
        }
      } else {
        // Invalid date
        $validdate = false;
      }
    }
    if (($datefrom != '' && $dateto == '') ||
        ($datefrom == '' && $dateto != '')) {
      $act = '';
      $message = gettext("CORRECTION: When restricting results by date, please enter
        both a 'from' date and a 'to' date.");
    } elseif ($datefrom >= $dateto && $datefrom != '') {
      $act = '';
      $message = gettext("CORRECTION: The 'to' date needs to be later than the 'from'
        date");
    } elseif (!$validdate) {
      $act = '';
      $message = gettext('CORRECTION: Invalid date entered - Dates must be entered in
        the form DD/MM/YYYY (with or without slashes) or selected from the popup
        calendar.');
    } else {
      $act = 'dosearch';
    }
  }
  if ($act == 'dosearch') {
    // If the session does not remember a previous search, then create the sql from scratch
    if ($_SESSION['_searchsql'] == '') {
      // create sql statement using restictions
      $sql = '';
      if ($is_pgsql) {
        $sql = 'vw_Issues,tbl_UserSites';
      }
      if ($id != '') {
        if ($is_pgsql) {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND vw_Issues.site=tbl_UserSites.site AND vw_Issues.id=$id AND ";
        } else {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND
          tbl_Issues.site=tbl_UserSites.site AND tbl_Issues.id=$id AND ";
        }
      } else {
      ##  if (count($category) > 0) {
      ##    $sql .= ',tbl_ProblemDetails';
      ##  }
        if ($is_pgsql) {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND vw_Issues.site=tbl_UserSites.site AND ";
        } else {
          $sql .= " WHERE tbl_UserSites.userid=$_SESSION[_id] AND
          tbl_Issues.site=tbl_UserSites.site AND ";
        }
        if (count($site) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.site IN (';
          } else {
            $sql .= 'tbl_Issues.site IN (';
          }
          $flag = 0;
          foreach ($site as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($reportedby) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.reportedby IN (';
          } else {
            $sql .= 'tbl_Issues.reportedby IN (';
          }
          $flag = 0;
          foreach ($reportedby as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($createdby) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.createdby IN (';
          } else {
            $sql .= 'tbl_Issues.createdby IN (';
          }
          $flag = 0;
          foreach ($createdby as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if ($datefrom != '' && $dateto != '') {
          if ($is_pgsql) {
            $sql .= "vw_Issues.createdon > $datefrom " .
              " AND vw_Issues.createdon < $dateto AND ";
          } else {
            $sql .= "tbl_Issues.createdon > $datefrom " .
              " AND tbl_Issues.createdon < $dateto AND ";
          }
        }
        if (count($assignedto) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.assignedto IN (';
          } else {
            $sql .= 'tbl_Issues.assignedto IN (';
          }
          $flag = 0;
          foreach ($assignedto as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($level) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.level IN (';
          } else {
            $sql .= 'tbl_Issues.level IN (';
          }
          $flag = 0;
          foreach ($level as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($priority) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.priority IN (';
          } else {
            $sql .= 'tbl_Issues.priority IN (';
          }
          $flag = 0;
          foreach ($priority as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($status) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.status IN (';
          } else {
            $sql .= 'tbl_Issues.status IN (';
          }
          $flag = 0;
          foreach ($status as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($category) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.detail=tbl_ProblemDetails.id AND
              tbl_ProblemDetails.category IN (';
          } else {
            $sql .= 'tbl_Issues.detail=tbl_ProblemDetails.id AND
              tbl_ProblemDetails.category IN (';
          }
          $flag = 0;
          foreach ($category as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
        if (count($detail) > 0) {
          if ($is_pgsql) {
            $sql .= 'vw_Issues.detail IN (';
          } else {
            $sql .= 'tbl_Issues.detail IN (';
          }
          $flag = 0;
          foreach ($detail as $record) {
            if ($flag == 0) { $flag = 1; } else { $sql .= ','; }
            $sql .= $record;
          }
          $sql .= ') AND ';
        }
      }

      if ($is_pgsql) {
        $sql .= "vw_Issues.domain=$_SESSION[_domain]";
      } else {
        $sql .= "tbl_Issues.domain=$_SESSION[_domain]";
      }

      // tokenise searchstring allowing for quoted phrases
      $searchstringsquoted = array();
      $searchstrings = array();
      $tok = strtok($freetext,'\"');
      $flag = 0;
      if (strlen($tok) == 0) $flag = 1;
      while ($tok) {
        if (strlen($tok) > 0) $searchstringsquoted[] = $tok;
        $tok = strtok ('\"');
      }
      foreach ($searchstringsquoted as $substring) {
        if ($flag == 1) {
          $searchstrings[] = $substring;
          $flag = 0;
        } else {
          $tok = strtok($substring,' ');
          while ($tok) {
            $searchstrings[] = $tok;
            $tok = strtok (' ');
          }
          $flag = 1;
        }
      }

      // use $searchstrings to add a LIKE clause to the $sql
      if ($is_pgsql) {
        $field = "summary||' '||description||' '||solution||' '||reportedbyname";
        if ($freetextscope != '') $field = $freetextscope;
        foreach ($searchstrings as $searchstring) {
          $sql .= " AND $field ILIKE '%".addslashes($searchstring)."%'";
        }
      } else {
        $field = array("tbl_Issues.summary","tbl_Issues.description","tbl_Issues.solution","t2.name");
        if ($freetextscope != '') {$field = array($freetextscope);}
        foreach ($searchstrings as $searchstring) {
          $operator = 'AND';
          foreach ($field as $sfield) {
            $sql .= " $operator $sfield LIKE '%".addslashes($searchstring)."%'";
            $operator = 'OR';
          }
        }
      }
  
      // Set session to remember these restrictions
      $_SESSION['_searchsql'] = $sql;
    } else {
      // Retrieve the stored restrictions in sql form
      $sql = $_SESSION['_searchsql'];
    }

    if ($is_pgsql) {
      $issuesRS = db_recordset("SELECT count(vw_Issues.ID) AS num FROM $sql");
    } else {
      $issuesRS = db_recordset("SELECT DISTINCT $aselects FROM $afrom $sql");
    }
    // How many issues would be in this category
    if ($is_pgsql) {
      $num_issues = $issuesRS[0][num];
    } else {
      $num_issues = count($issuesRS);
    }
    // Set page size and limit issues to that number
    $pagesize = $global_prefs[pagesize];
    $num_pages = ceil($num_issues/$pagesize);
    if ($is_pgsql) {
      $sql = "SELECT vw_Issues.* FROM $sql ORDER BY $orderby $orderdir";
    } else {
      $sql = "SELECT DISTINCT $aselects FROM $afrom $sql ORDER BY $orderby $orderdir";
    }
    if ($page == '') $page = 0;
    if ($page <= 0) {
      $page = 0;
    } elseif ($page >= $num_pages) {
      $page = $num_pages - 1;
    }
    $sql .= " LIMIT $pagesize OFFSET " . ($page * $pagesize);
    // Retrieve issues (no more than $global_prefs[pagesize])
    $issuesRS = db_recordset($sql);
    //echo "<pre>$sql</pre>";

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

  <h1><?php echo gettext("Search Results")?></h1>
  <h2><?php echo gettext("Below are your search results")?>:</h2>
  
  <div class="block">

    <div class="buttonpanel">
      <?php
        // Make the back button work correctly for searches initiated from
        // an issue page (i.e. more issues like this links)
        $referer = $_SERVER['HTTP_REFERER'];
        if ($referer == '') $referer = 'find.php';
      ?>
      <input name="again" type="button" id="again" value="<?php echo gettext("Back to previous page")?>"
      onclick="document.location='<?php echo $referer?>'" />
    </div>
    <table width="100%" border="0" align="center" cellpadding="1" cellspacing="0" summary="<?php echo gettext("This table summarises the unresolved issues for this user's sitestes.")?>">
      <thead>
        <tr>
          <th align="left" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('id',$orderby,$orderdir)?>">#</a><?php echo makesymbol('id',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('createdon',$orderby,$orderdir)?>"><?php echo gettext("Reported")?></a><?php echo makesymbol('createdon',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('reportedbyname',$orderby,$orderdir)?>"><?php echo gettext("Reported By")?></a><?php echo makesymbol('reportedbyname',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('assignedtoname',$orderby,$orderdir)?>"><?php echo gettext("Assigned To")?></a><?php echo makesymbol('assignedtoname',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('sitename',$orderby,$orderdir)?>"><?php echo gettext("Site")?></a><?php echo makesymbol('sitename',$orderby,$orderdir)?></th>
          <th align="left" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('summary',$orderby,$orderdir)?>"><?php echo gettext("Summary")?></a><?php echo makesymbol('summary',$orderby,$orderdir)?></th>
          <th align="center" class="issueheader"><a href="find.php?page=<?php echo $page?>&amp;act=action&amp;<?php echo makeordering('sortorder',$orderby,$orderdir)?>"><?php echo gettext("Priority")?></a><?php echo makesymbol('sortorder',$orderby,$orderdir)?></th>
        </tr>
      </thead>
<?php
    if ($num_issues > 0) {
?>
      <tfoot>
        <tr>
<td align="right" colspan="7"><?php printf(gettext("Page %s of %s : %s record(s)"), $page+1, $num_pages, $num_issues); ?></td>
        </tr>
<?php
      if ($num_pages > 1) {
        // If there is more than one page then show links to the other pages
?>
        <tr>
          <td align="right" colspan="7">
<?php
        $paging = '            ';
        $begin = $page-4;
        $end = $page+5;
        if ($begin < 0) $end -= $begin;
        if ($end >= $num_pages) $begin -= ($end - $num_pages);
        if ($begin < 0) $begin = 0;
        if ($end >= $num_pages) $end = $num_pages;
        for ($i=$begin;$i<$end;$i++) {
          if ($i != $begin) $paging .= ' &bull; ';
          if ($i != $page) {
            $paging .= '<a href="find.php?act=action&amp;page=' . $i . '&amp;orderby=' . $orderby . '&amp;orderdir=' . $orderdir . '" title="'.gettext("Goto page"). ' ' . ($i+1) . '">';
          }
          $paging .= $i+1;
          if ($i != $page) {
            $paging .= '</a>';
          }
        }
        if ($page > 0) {
          $paging .= ' &nbsp; <a href="find.php?act=action&amp;page=0&amp;orderby=' . $orderby . '&amp;orderdir=' . $orderdir . '" title="'.gettext("First"). '">|&larr;</a>';
          $paging .= ' <a href="find.php?act=action&amp;page=' . ($page-1) . '&amp;orderby=' . $orderby . '&amp;orderdir=' . $orderdir . '" title="'.gettext("Previous"). '">&larr;</a>';
        } else {
          $paging .= ' &nbsp; |&larr; &larr;';
        }
        if ($page < ($num_pages-1)) {
          $paging .= ' <a href="find.php?act=action&amp;page=' . ($page+1) . '&amp;orderby=' . $orderby . '&amp;orderdir=' . $orderdir . '" title="'.gettext("Next"). '">&rarr;</a>';
          $paging .= ' <a href="find.php?act=action&amp;page=' . ($num_pages-1) . '&amp;orderby=' . $orderby . '&amp;orderdir=' . $orderdir . '" title="'.gettext("Last"). '">&rarr;|</a>';
        } else {
          $paging .= ' &rarr; &rarr;|';
        }
        print $paging;
?>
          </td>
        </tr>
<?php
      }
?>
      </tfoot>
<?php
    }
?>
      <tbody>
<?php
    if ($num_issues == 0) {
      // If there are no issues, then say as much...
      print "        <tr>\n";
      print "          <td colspan=\"7\" align=\"center\" class=\"issuecell\">".gettext("No Unresolved Issues.")."</td>\n";
      print "        </tr>\n";
    }

    // Alternately shade the rows on the sorted attribute by keeping track
    // of the previously shown value. If this value != last value then the
    // colour can be changed

    // flag shows whether to shade or not - starts being 'NO SHADING'
    $flag = 1;
    // Nullify the last value
    $lastvalue = "\0";
    foreach ($issuesRS as $record) {
      if ($lastvalue != $record[$grouporderby]) {
        // If different, toggle shading
        $flag = 1 - $flag;
        $lastvalue = $record[$grouporderby];
      }
      if ($flag == 0) {
        $class = 'issuecell';
      } else {
        $class = 'issuecelldark';
      }

      // For the priority column, choose the colouring
      if ($closedstatus == $record['status'] || $record['recalled'] == 1) {
        $priority='prioritydefunct';
      } else {
        switch ($record['class']) {
          case 0: $priority='prioritylow';
            break;
          case 1: $priority='prioritymedium';
            break;
          case 2: $priority='priorityhigh';
            break;
        }
      }

      // Show attributes
      print "        <tr valign=\"top\">\n";
      print "          <td class=\"$class\"><a href=\"issue.php?id=${record[id]}\">${record[id]}</a></td>\n";
      print "          <td class=\"$class\">";
      if (strftime('%d/%m/%y',$record[createdon]) == strftime('%d/%m/%y')) {
        print strftime('%H:%M',$record[createdon]);
      } else {
        print strftime('%d/%m/%y',$record[createdon]);
      }
      print "</td>\n";
      print "          <td class=\"$class\">${record[reportedbyname]}</td>\n";
      print "          <td class=\"$class\">";
      print $record[assignedtoname];
      print "</td>\n";
      print "          <td class=\"$class\">${record[sitename]}</td>\n";
      print "          <td class=\"$class\"><a href=\"issue.php?id=${record[id]}\">${record[summary]}</a></td>\n";
      print "          <td align=\"center\" class=\"$priority\">";
      if ($record['recalled'] == 1) {
        print 'Recalled';
      } else {
        print $record[priorityname];
      }
      print "</td>\n";
      print "        </tr>\n";

    }
?>
      </tbody>
    </table>

  </div>

<?php
  }

  // Default action: To ask for search terms and restrictions
  if ($act == '') {

    // Retrieve the values for restrictions from the actual set of issues
    $sitesRS = db_recordset("SELECT DISTINCT tbl_Sites.* FROM tbl_UserSites,tbl_Sites,tbl_Issues WHERE tbl_UserSites.userid=$_SESSION[_id] AND tbl_UserSites.site=tbl_Sites.id AND tbl_Sites.domain=$_SESSION[_domain] AND tbl_Issues.site=tbl_Sites.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Sites.site");
    $categoriesRS = db_recordset("SELECT DISTINCT tbl_ProblemCategories.* FROM tbl_ProblemCategories,tbl_ProblemDetails,tbl_Issues WHERE tbl_ProblemCategories.id=tbl_ProblemDetails.category AND tbl_ProblemDetails.id=tbl_Issues.detail AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_ProblemCategories.description");
    $num_categories = count($categoriesRS);
    if ($num_categories > 0)
      $detailsRS = db_recordset("SELECT DISTINCT tbl_ProblemDetails.* FROM tbl_ProblemDetails,tbl_Issues WHERE tbl_ProblemDetails.id=tbl_Issues.detail AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_ProblemDetails.description");
    $prioritiesRS = db_recordset("SELECT DISTINCT tbl_Priorities.* FROM tbl_Priorities,tbl_Issues WHERE tbl_Issues.priority=tbl_Priorities.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Priorities.sortorder");
    $levelsRS = db_recordset("SELECT DISTINCT tbl_Levels.* FROM tbl_Levels,tbl_Issues WHERE tbl_Issues.level=tbl_Levels.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Levels.sortorder");
    $statusesRS = db_recordset("SELECT DISTINCT tbl_Statuses.* FROM tbl_Statuses,tbl_Issues WHERE tbl_Issues.status=tbl_Statuses.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Statuses.sortorder");
    $usersRS = db_recordset("SELECT DISTINCT tbl_Users.* FROM tbl_Users,tbl_Issues WHERE tbl_Issues.reportedby=tbl_Users.id AND tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Users.name");
    $assignedtoRS = db_recordset("SELECT DISTINCT tbl_Users.* FROM
    tbl_Users,tbl_Issues WHERE tbl_Issues.assignedto=tbl_Users.id AND
    tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Users.name");
    $createdbyRS = db_recordset("SELECT DISTINCT tbl_Users.* FROM
    tbl_Users,tbl_Issues WHERE tbl_Issues.createdby=tbl_Users.id AND
    tbl_Issues.domain=$_SESSION[_domain] ORDER BY tbl_Users.name");
    // Reset remembered sql restrictions
    $_SESSION['_searchsql'] = '';

?>

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

  function mainSubmit() {
    focusElement(document.mainform.id);
    focusElement(document.mainform.freetext);
    if (document.mainform.id.value != '' && isNaN(parseInt(document.mainform.id.value))) {
      blurElement(document.mainform.id);
      blurElement(document.mainform.freetext);
      alert('<?php echo gettext("You must enter a valid positive integer as the issue number.")?>');
      return false;
    } else {
      if (document.mainform.id.value != '') {
        document.mainform.id.value = parseInt(document.mainform.id.value);
      }
      return true;
    }
  }

//-->
//]]>
</script>
    
  <?php display($message); ?>
    
  <h1><?php echo gettext("Find Issue")?></h1>
  <h2><?php echo gettext("Please enter as much of the following information as possible to best identify
      your issue")?>:</h2>
  
  <div class="block">
    
    <form name="mainform" id="mainform" method="get" onsubmit="return mainSubmit()" action="">
      <input type="hidden" name="act" value="action" />
      <div class="labelfieldpair">
        <div class="name"><label for="id"><?php echo gettext("Enter Issue")?> #</label></div>
        <div class="field"><input name="id" type="text" id="id" size="10" maxlength="10" value="[<?php echo gettext("Issue")?>#]" onfocus="focusElement(this)" onblur="blurElement(this)" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="freetext"><?php echo gettext("Free Text Search")?></label></div>
        <div class="field"><input name="freetext" type="text" id="freetext" size="60" maxlength="100" value="[<?php echo gettext("Please enter free text search")?>]" onfocus="focusElement(this)" onblur="blurElement(this)" /></div>
      </div>
      <div class="labelfieldpair">
        <div class="name"><label for="freetextscope"><?php echo gettext("Free Text Scope")?></label></div>
        <div class="field">
          <select name="freetextscope" id="freetextscope">
            <option value="" selected="selected">[<?php echo gettext("All Text Fields")?>]</option>
            <option value="tbl_Issues.summary"><?php echo gettext("Summary")?></option>
            <option value="tbl_Issues.description"><?php echo gettext("Description")?></option>
            <option value="tbl_Issues.solution"><?php echo gettext("Solution")?></option>
            <option value="reportedby"><?php echo gettext("Reported By")?></option>
          </select>
        </div>
      </div>
      <div class="buttonpanel">
        <input type="submit" value="<?php echo gettext("Find!")?>" />
        <input type="reset" value="<?php echo gettext("Reset")?>" />
      </div>

      <h3><?php echo gettext("Restrict Results")?>:</h3>

      <p><?php echo gettext("Optionally, you can restrict the results by selecting any number of fields below")?>:</p>

      <div class="columnleft">
        <div class="labelleft"><label for="site"><?php echo gettext("Site")?>:</label></div>
        <div class="columnleft">
          <select name="site[]" id="site" size="4" multiple="multiple">
<?php
    foreach ($sitesRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[site]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="reportedby"><?php echo gettext("Reported By")?>:</label></div>
        <div class="columnleft">
          <select name="reportedby[]" id="reportedby" size="4" multiple="multiple">
<?php
    foreach ($usersRS as $record) {
      print ("            <option value=\"{$record['id']}\">{$record['name']}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="createdby"><?php echo gettext("Created By")?>:</label></div>
        <div class="columnleft">
          <select name="createdby[]" id="createdby" size="4" multiple="multiple">
<?php
    foreach ($createdbyRS as $record) {
      print ("            <option value=\"{$record['id']}\">{$record['name']}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="assignedto"><?php echo gettext("Assigned To")?>:</label></div>
        <div class="columnleft">
          <select name="assignedto[]" id="assignedto" size="4" multiple="multiple">
<?php
    foreach ($assignedtoRS as $record) {
        if ($record['name'] == "* unassigned *")
        {
            print ("            <option value=\"{$record['id']}\">".gettext("* unassigned *")."</option>\n");
        } else {
            print ("            <option value=\"{$record['id']}\">{$record['name']}</option>\n");
        }
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="priority"><?php echo gettext("Priority")?>:</label></div>
        <div class="columnleft">
          <select name="priority[]" id="priority" size="4" multiple="multiple">
<?php
    foreach ($prioritiesRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[priority]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="level"><?php echo gettext("Level")?>:</label></div>
        <div class="columnleft">
          <select name="level[]" id="level" size="4" multiple="multiple">
<?php
    foreach ($levelsRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[level]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="status"><?php echo gettext("Status")?>:</label></div>
        <div class="columnleft">
          <select name="status[]" id="status" size="4" multiple="multiple">
<?php
    foreach ($statusesRS as $record) {
      print ("            <option value=\"${record[id]}\">${record[status]}</option>\n");
    }
?>
          </select>
        </div>
      </div>
<?php
    if ($num_categories > 0) {
?>
      <div class="columnleft">
        <div class="labelleft"><label for="category"><?php echo gettext("Problem Category")?>:</label></div>
        <div class="columnleft">
          <select name="category[]" id="category" size="4" multiple="multiple">
<?php
      foreach ($categoriesRS as $record) {
        print ("            <option value=\"${record[id]}\">${record[description]}</option>\n");
      }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labelleft"><label for="detail"><?php echo gettext("Problem Detail")?>:</label></div>
        <div class="columnleft">
          <select name="detail[]" id="detail" size="8" multiple="multiple">
<?php
      reset($categoriesRS);
      // Create a grouped <select> list, grouping details on categories
      foreach ($categoriesRS as $record) {
        print "            <optgroup label=\"${record[description]}\">\n";
        $current = filter_records($detailsRS,'category',$record[id]);
        foreach ($current as $recorddetail) {
          print "              <option value=\"${recorddetail[id]}\">${recorddetail[description]}</option>\n";
        }
        print "            </optgroup>\n";
      }
?>
          </select>
        </div>
      </div>
      <div class="columnleft">
        <div class="labeleft"><?php echo gettext("Creation date")?>:</div>
        <div class="columnleft">
            <label for="datefrom"><?php echo gettext("From")?>:</label>
            <div class="field"><input type="text" size="10" name="datefrom" 
            id="datefrom" />
            <a href="javascript:showCalendar('caldatefrom','datefrom')"
            >[ <?php echo gettext("calendar")?> ]</a></div>
            <div id="caldatefrom" class="calendar"></div>
            <label for="dateto"><?php echo gettext("To")?>:</label>
            <div class="field"><input type="text" size="10" name="dateto" 
            id="dateto" />
            <a href="javascript:showCalendar('caldateto','dateto')"
            >[ <?php echo gettext("calendar")?> ]</a></div>
            <div id="caldateto" class="calendar"></div>
        </div>
      </div>
<?php
    }
?>
      <hr class="hide" />
      <div class="buttonpanel">
        <input type="submit" value="<?php echo gettext("Find!")?>" />
        <input type="reset" value="<?php echo gettext("Reset")?>" />
      </div>
    </form>
  </div>

<script language="javascript" type="text/javascript">
//<![CDATA[
<!--

  document.mainform.id.focus();

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

<?php
  }

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