<?php


/**
 *
 *		sabreTools Module for plugin to Drupal 7 Framework
 *    --> used by QMS and Scheduler
 *
 *	 	Generic file handling functions
 *
*/

//-------------------------- FILE DOWNLOADS - Headers and Content Types --------------


/*
 *	_st_add_http_content_type()
 *
 *	Sets the appropriate HTTP headers and returns the requested file for download
 */

function _st_add_http_content_type($ext) {

  $content_type = '';

  if (isset($ext)) {
    $ext = strtolower($ext);
    switch ($ext) {

      case 'avi':
      case 'mp4':
      case 'mpg':
      case 'mpeg':
      case 'mpeg2':
        $content_type = 'video/' . $ext;
        break;
      case 'csv':
        $content_type = 'text/' . $ext;
        break;
      case 'doc':
        $content_type = 'application/msword';
        break;
      case 'docm':
        $content_type = 'application/vnd.ms-word.document.macroEnabled.12';
        break;
      case 'docx':
        $content_type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
        break;
      case 'eml':
        $content_type = 'message/rfc822';
        break;
      case 'flv':
        $content_type = 'video/x-flv';
        break;
      case 'gif':
      case 'jpeg':
      case 'jpg':
      case 'png':
        $content_type = 'image/' . $ext;
        break;
      case 'mov':
        $content_type = 'video/quicktime';
        break;
      case 'msg':
        $content_type = 'application/msoutlook';
        break;
      case 'odp':
        $content_type = 'application/vnd.oasis.opendocument.presentation';
        break;
      case 'ods':
        $content_type = 'application/vnd.oasis.opendocument.spreadsheet';
        break;
      case 'odt':
        $content_type = 'application/vnd.oasis.opendocument.text';
        break;
      case 'cap':
      case 'pcap':
        $content_type = 'application/vnd.tcpdump.pcap';
        break;
      case 'pdf':
        $content_type = 'application/' . $ext;
        break;
      case 'ppt':
      case 'pps':
        $content_type = 'application/vnd.ms-powerpoint';
        break;
      case 'ppam':
        $content_type = 'application/vnd.ms-powerpoint.addin.macroEnabled.12';
        break;
      case 'ppsm':
        $content_type = 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12';
        break;
      case 'ppsx':
        $content_type = 'application/vnd.openxmlformats-officedocument.presentationml.slideshow';
        break;
      case 'pptm':
        $content_type = 'application/vnd.ms-powerpoint.presentation.macroEnabled.12';
        break;
      case 'pptx':
        $content_type = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
        break;
      case 'psd':
        $content_type = 'application/photoshop';
        break;
      case 'txt':
        $content_type = 'text/plain';
        break;
      case 'wav':
        $content_type = 'audio/' . $ext;
        break;
      case 'wmv':
        $content_type = 'video/x-ms-wmv';
        break;
      case 'xls':
        $content_type = 'application/vnd.ms-excel';
        break;
      case 'xlsm':
        $content_type = 'application/vnd.ms-excel.sheet.macroEnabled.12';
        break;
      case 'xlsx':
        $content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        break;
      case 'rar':
      case 'zip':
      default:
        $content_type = 'application/octet-stream';
    }
  }
  else {
    // unknown file extension, force download
    $content_type = 'application/octet-stream';
  }


  // append flag is set to FALSE.  We want to replace (not append) the content type otherwise some browsers will
  // get confused and default to 'text/html'  (Safari, I'm referring to you.)
  drupal_add_http_header('Content-Type', $content_type, False);

}


/*
 *	_st_return_requested_file()
 *
 *	Sets the appropriate HTTP headers and returns the requested file for download
 */

function _st_return_requested_file($file_path) {
  
  try{

  //$size = filesize($file_path);
  $isReadable = is_readable($file_path);
  $path_parts = pathinfo($file_path);

  if ( !$isReadable ) {
    drupal_set_message(t($path_parts['basename'] . ' is not readable.  Incorrect file permissions.'));
    return False;
  }

  _st_add_http_content_type($path_parts['extension']);
  set_time_limit(0);

  // REVISED after file downloads began failing under php70
//  drupal_add_http_header('Content-Disposition', 'attachment; filename=' . $path_parts['basename']);
//  drupal_add_http_header('Content-Length', $size, True);

  // this handles an issue with SSL file downloads attempting to cache content
  // triggers errors in IE browsers
//  if ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ||
//      (!empty($_SERVER['HTTP_X_REMOTE_SCHEME']) && ($_SERVER['HTTP_X_REMOTE_SCHEME'] == 'https') )) {
//    drupal_add_http_header('Cache-Control', 'private', True);
//    drupal_add_http_header('Pragma', 'private', True);
//  }
  
    if (in_array(strtolower($path_parts['extension']), array('jpg', 'jpeg', 'png', 'gif')) ) {
            //preg_match("/jpg|gif|png|jpeg/i", $path_parts['basename'])){
        $mime = getimagesize($file_path);
        if(!empty($mime)) {
          header("Content-type: {$mime['mime']}");
          header('Content-Type: application/force-download');
          header('Content-Disposition: inline; filename="' . $path_parts['basename'] . '"');
        }
    } else if (strtolower($path_parts['extension']) == 'pdf') {
        //header("Content-Type: application/force-download");
        header("Content-type: application/pdf");
        header('Content-Disposition: inline; filename="'.$path_parts['basename'].'";');
        header('Accept-Ranges: bytes');
        
    } else {
        header("Content-type: application/octet-stream");
        header('Content-Type: application/force-download');
        header('Content-Description: File Transfer');
        header("Content-Disposition: attachment; filename=\"".$path_parts['basename']."\";");
        header('Content-Length: ' . filesize($file_path));
    }
  
    
    header('Content-Transfer-Encoding: binary');
    header('Connection: Keep-Alive');
    header('Expires: 0');
    
    if ((isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ||
      (!empty($_SERVER['HTTP_X_REMOTE_SCHEME']) && ($_SERVER['HTTP_X_REMOTE_SCHEME'] == 'https') )) {
      header('Cache-Control: private, must-revalidate');
      header('Pragma: private');
    } else {
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
    }
    
    ob_clean();
    flush();
    $result = readfile($file_path);
//    if ($result) {
//        error_log('download complete');
//     }
//     else {
//        error_log('unable to download');
//     }

    //return True;
    die;
  } catch(Exception $e) {
    watchdog('sabreTools.files', $e->getMessage());
  }
}
