<?php

/**
 * @file
 * Module for exporting LOM-CH descriptions for import in other applications.
 *
 * The Archibald Export module allows admins to export LOM-CH description data
 * along with revision information and other meta-data. This data can be used to
 * port this data into other applications.
 */

/**
 * Implements hook_action_info().
 */
function archibald_export_action_info() {
  // This is a little trick to put the action implementations in their own file.
  // Because the result of this hook is not cached, it is called every time an
  // action is to be performed. This allows us to load our action definitions
  // only when they might be needed.
  module_load_include('inc', 'archibald_export', 'includes/archibald_export.actions');

  return array(
    'archibald_export_export_node_action' => array(
      'type' => 'node',
      'label' => t("Export JSON"),
      'configurable' => TRUE,
      // This is a hack we need to put in place to prevent VBO to trigger a save
      // at the end of our execution. It's not a valid behavior, but it prevents
      // a default one to be added.
      'behavior' => array('none'),
    ),
  );
}

/**
 * Implements hook_views_pre_view().
 */
function archibald_export_views_pre_view(&$view, &$display_id, &$args) {
  // Must we display a 'Export JSON' action?
  if ($view->name == 'archibald_lomch_descriptions' && in_array($display_id, array('pending', 'published'))) {

    // Fetch the display handler.
    $handler = &$view->display[$display_id]->handler;

    // Add our custom action.
    $handler->options['fields']['views_bulk_operations']['vbo_operations']['action::archibald_export_export_node_action'] = array(
      'selected' => 1,
      'postpone_processing' => 0,
      'skip_confirmation' => 1,
      'override_label' => 0,
      'label' => '',
    );
  }
}

/**
 * Implements hook_file_download().
 */
function archibald_export_file_download($uri) {
  // If this is one of our archives, grant access if the user is the one that
  // generated the file, or if the current user is User-1.
  $match = array();
  if (preg_match('/.+:\/\/archibald_export--u(\d)+.+\.zip$/', $uri, $match)) {
    global $user;
    if ($user->uid === 1 || $user->uid === $match[1]) {
      // Fetch the file.
      $files = file_load_multiple(array(), array('uri' => $uri));
      $file = reset($files);
      return file_get_content_headers($file);
    }
    else {
      // Deny access.
      return -1;
    }
  }
}
