<?php

  /*

      attachments.php

      Attachment related functions can be found in this file.

      ----

      Copyright (C) 2006  Central Manchester CLC
      Copyright (C) 2006  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.

   */

  // Pull in required config and preferences
  require_once 'config/global.conf.php';

  /*
   * function get_attachment_dir()
   *
   * Parameter $issue_id is the id of the issue for which you want the
   *   attachment directory path.
   * Parameter $create decides whether the outcome of this call should create
   *   the appropriate directory if it does not already exist.
   *
   * In normal operation, this function returns the path of the attachment
   * directory for the given issue id.
   */
  function get_attachment_dir($issue_id, $create = false)
  {
    // Ensure access to configuration
    global $conf;

    // What the path should be
    $attachment_path = $conf['attachment_dir']."/".$issue_id;
    
    // Create directory if required
    if ($create && !file_exists($attachment_path)) {
      $cwd = getcwd();
      chdir($conf['attachment_dir']);
      mkdir($issue_id);
      chdir($cwd);
    }
    
    return $attachment_path;
  }

  /*
   * function get_attachments()
   *
   * Parameter $issue_id is the id of the issue for which you want the
   *   attachment list.
   *
   * In normal operation, this function returns an array of .
   */
  function get_attachments($issue_id)
  {
    // Ensure access to configuration
    global $conf;

    // Get attachment path
    $attachment_path = get_attachment_dir($issue_id);
    $attachments = Array();
    
    // Compile the list
    if (file_exists($attachment_path) && is_dir($attachment_path) && $dh = opendir($attachment_path)) {
      while (($file = readdir($dh)) !== false) {
        if (!is_dir($file)) {
          $attachments[] = $file;
        }
      }
      closedir($dh);
    }

    return $attachments;
  }
  
?>
