Showing posts with label stream wrapper. Show all posts
Showing posts with label stream wrapper. Show all posts

Wednesday, 30 March 2011

Using stream wrappers

Sorry I haven't uploaded my two new modules to d.o yet - just not had time.

In my current contract the client wanted the option of either downloading a PDF or opening it in the browser (assuming the browser could handle it - but that's not my problem). These PDFs being stored in the Private file space.

The first question they had was: can it be done? They'd been told it couldn't. But I assured them with naive certainty that it probably could. I had already sorted out the ability to auto-create and download archives and I was pretty sure it was merely a matter of the correct HTTP headers.

But how to do it? What I needed was a different path to the same file, one path would download it, the other path would display it in the browser.

If you're using Private files the URL you get is 'system/files/filename.pdf' which goes through various checks to ensure the download is permitted, and gets the HTTP headers at the same time, using hook_file_download(). The path fragment "system/files" is what invokes the file_download() function. If you create a different stream wrapper, such as my archive stream, this is replaced with "system/archive" - or whatever you want really.

So I thought, okay, how about I create a new stream wrapper based on a "system/views" path which invokes file_download() but extracts the Content-Disposition header before sending it.

The trick here is to make the new stream wrapper point to the same location as the Private stream - so it can access the same files - and then, when I'm building the download link, I get the file's URL (e.g. "system/files/filename.pdf") and simply do a string replace, changing "files" to "views".

So the user clicks on my modified URL, it goes through my routines which get the headers but strip out the Content-Disposition header and, as a result, instead of downloading the file, it opens in the browser. I have two links to the same file, each one does something different with the file.

In retrospect using the word "Views" may be a little confusing, obviously it's nothing to do with the Views module - sorry about that.

You need the stream wrapper class...


class ViewsStreamWrapper extends DrupalLocalStreamWrapper {
  /**
   * Implements abstract public function getDirectoryPath()
   *
   * This is identical to the private stream wrapper which means
   * we can just replace 'files' with 'views' the path and get the same file
   */
  public function getDirectoryPath() {
    return variable_get('file_private_path', '');
  }


  /**
   * Overrides getExternalUrl().
   */
  public function getExternalUrl() {
    $path = str_replace('\\', '/', $this->getTarget());
    return url('system/views/' . $path, array('absolute' => TRUE));
  }
}

You need to tell Drupal about the class...


/**
 * Implements hook_stream_wrappers().
 */
function views_stream_stream_wrappers() {
  return array(
    'views' => array(
      'name' => t('Views'),
      'class' => 'ViewsStreamWrapper',
      'description' => t('Stream wrapper for viewing files in a browser'),
      'type' => STREAM_WRAPPERS_READ,
    ),
  );
}



And then the hook_menu() and hook_file_download() support, note this code assumes a PDF.


/**
 * Implements hook_menu().
 */
function views_stream_menu() {
  $items = array();


  $items['system/views'] = array(
    'title' => 'View files',
    'page callback' => 'file_download',
    'page arguments' => array('views'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );


  return $items;
}


/**
 * Implements hook_file_download().
 *
 * Construct the headers to ensure the file gets downloaded
 */
function views_stream_file_download($uri) {
  list($scheme, $path) = explode('://', $uri, 2);
  if ($scheme=='views') {
    $file = (object) array(
      'filename' => basename($path),
      'filemime' => 'application/pdf',
      'filesize' => filesize(drupal_realpath($uri)),
    );
    $headers = file_get_content_headers($file);
    unset($headers['Content-Disposition']);
    return $headers;
  }
}


And then as an example of modifying a private file. The $uri variable contains the file's internal path which you can get from a file entity, or file field.


$href = file_create_url($uri);
$href = str_replace('/files/', '/views/', $href);


$link = array(
  '#type' => 'link',
  '#title' => t('View'),
  '#href' => $href,
  '#attributes' => array('target' => '_blank'),
  '#weight' => 0,
);


And that's all there is to it.

Monday, 21 March 2011

Coming to a website near you

Now I don't want you to get too excited but I have recently completed two little Drupal 7 modules designed to make my life easier - so may well help other developers:

field_extract
This takes the little function I built to extract values from fields to the extreme by attaching "extractors" to the cached field type data, and then using the appropriate extractor to extract the data from a field. So there's one extractor that gets nodes, another that gets terms, another for fields, for body, for text, for integers and so on. It follows proper Drupal guidelines and is completely extensible.

archive_stream
Makes it easy to build a downloadable Zip archive using stream_wrappers. You give it a temporary filename and an array of file info arrays (or file entities) and it gives you a file path you can use for downloading. The module also handles the downloading part when a user accesses the link.

Simples.

It may take a few days to get them on to drupal.org but I'll let you know.