You are here

asset_import.module in Asset 6

File

contrib/asset_import/asset_import.module
View source
<?php

/* This module is based largely on the image_import module that comes with the image module */

/**
 * Implementation of hook_help().
 */
function asset_import_help($section = '') {
  switch ($section) {
    case 'admin/content/asset_import':
      $output = '<p>' . t("Import multiple files and save them as assets. The files will be moved from their location into the chosen asset module's directory. ") . t("Searching for files in %dirpath.", array(
        '%dirpath' => realpath(variable_get('asset_import_path', '')),
      )) . '</p>';
      return $output;
    case 'admin/settings/asset_import':
      return t("Configure the Asset import module's settings.");
    default:
      return null;
  }
}

/**
 * Implementation of hook_perm().
 */
function asset_import_perm() {
  return array(
    'import asset images',
  );
}

/**
 * Implementation of hook_menu().
 */
function asset_import_menu($may_cache) {
  $items = array();
  if ($may_cache) {
    $items[] = array(
      'path' => 'admin/content/asset_import',
      'title' => t('Asset import'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array(
        'asset_import_form',
      ),
      'access' => user_access('import asset images'),
      'type' => MENU_NORMAL_ITEM,
      'description' => t('Import images from the filesystem.'),
    );
    $items[] = array(
      'path' => 'admin/settings/asset_import',
      'title' => t('Asset import'),
      'callback' => 'drupal_get_form',
      'callback arguments' => array(
        'asset_import_admin_settings',
      ),
      'access' => user_access('import asset images'),
      'type' => MENU_NORMAL_ITEM,
      'description' => t('Change settings for the Asset import module.'),
    );
  }
  return $items;
}
function asset_import_form() {
  $form = array();
  $dirpath = variable_get('asset_import_path', '');
  if (!file_check_directory($dirpath)) {
    drupal_set_message(t("You need to configure the import directory on the Asset import module's <a href='!admin-settings-asset_import'>settings page</a>.", array(
      '!admin-settings-asset_import' => url('admin/settings/asset_import'),
    )), 'error');
    return $form;
  }
  $files = file_scan_directory($dirpath, '.*');
  ksort($files);
  if ($files) {

    // Display a list of asset directories
    include_once drupal_get_path('module', 'asset') . '/asset_wizard.inc';
    $list = asset_wizard_directory_options();
    $form['parent'] = array(
      '#type' => 'select',
      '#title' => t('Parent Directory'),
      '#default_value' => $form_values['parent'] ? $form_values['parent'] : $_GET['dir'],
      '#options' => asset_wizard_directory_options(),
    );

    // Offer to create a subdirectory in the chosen asset directory
    $form['subdirectory'] = array(
      '#type' => 'textfield',
      '#title' => t('Create subdirectory'),
      '#size' => 13,
      '#description' => t('Enter the name of the subdirectory to be created in the chose Parent Directory. Don\'t add a leading or trailing slash. Leave blank to import all files in the Parent Directory.'),
    );

    // Copy or move the files? Is useful when importing files from other file modules to make a comparison
    $form['copy'] = array(
      '#type' => 'checkbox',
      '#title' => t('Copy the files instead of moving them'),
      '#description' => t('Default behavior is to move the selected files. Check this options if you wish to copy the files instead of moving them. This could be useful for testing the asset module in comparision with the file handling module(s) you are currently using.'),
    );

    // Put the files into an array for the checkboxes and gather
    // additional information like the filesizes. Make sure that
    // there's no 0th element, because a checkbox with a zero value is seen as
    // unchecked and won't be imported.
    // $fields = array('filesize', 'dimensions', 'title', 'body');
    $fields = array(
      'filesize',
      'title',
      'body',
    );
    foreach ($fields as $field) {
      $form['files'][$field][0] = NULL;
    }
    $filelist = array(
      0 => NULL,
    );
    foreach ($files as $file) {
      $info = pathinfo($file->filename);
      if ($info && isset($info['extension'])) {
        $filelist[] = substr($file->filename, strlen($dirpath) + 1);
        $form['files']['filesize'][] = array(
          '#type' => 'item',
          '#value' => format_size(filesize($file->filename)),
        );

        /*
        $form['files']['dimensions'][] = array(
          '#type' => 'item',
          '#value' => $info['width'] .'x'. $info['height'],
        );
        */
        $form['files']['title'][] = array(
          '#type' => 'textfield',
          '#size' => 20,
          '#default_value' => basename($file->name),
        );
        $form['files']['body'][] = array(
          '#type' => 'textfield',
          '#size' => 20,
        );
      }
    }

    // Remove our 0 elements.
    unset($filelist[0]);
    foreach ($fields as $field) {
      $form['files'][$field][0] = NULL;
    }

    // Put the titles into an array.
    $form['files']['title']['#tree'] = TRUE;
    $form['files']['body']['#tree'] = TRUE;

    // Store a copy of the list into a form value so we can compare it to what
    // they submit and not have to worry about files being added or removed from
    // the filesystem.
    $form['file_list'] = array(
      '#type' => 'value',
      '#value' => $filelist,
    );
    $form['import_file'] = array(
      '#type' => 'checkboxes',
      '#options' => $filelist,
    );
    $form['buttons']['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Import'),
    );
  }
  else {
    $form['import_file'] = array(
      '#type' => 'item',
      '#value' => t('No files were found'),
    );
  }
  return $form;
}
function theme_asset_import_form($form) {
  $output = drupal_render($form['parent']);
  $output .= drupal_render($form['subdirectory']);
  $output .= drupal_render($form['copy']);
  if (isset($form['import_file']) && $form['import_file']['#type'] == 'checkboxes') {

    // $header = array(theme('table_select_header_cell'), t('Name'), t('Size'), t('Dimensions'), t('Caption'), t('Copyright'));
    $header = array(
      theme('table_select_header_cell'),
      t('Name'),
      t('Size'),
      t('Caption'),
      t('Copyright'),
    );
    $rows = array();
    foreach (element_children($form['import_file']) as $key) {
      $filename = $form['import_file'][$key]['#title'];
      unset($form['import_file'][$key]['#title']);
      $rows[] = array(
        drupal_render($form['import_file'][$key]),
        $filename,
        drupal_render($form['files']['filesize'][$key]),
        // drupal_render($form['files']['dimensions'][$key]),
        drupal_render($form['files']['title'][$key]),
        drupal_render($form['files']['body'][$key]),
      );
    }
    $output .= theme('table', $header, $rows);
  }
  return $output . drupal_render($form);
}
function asset_import_form_submit($form_id, $form_values) {
  $nodes = array();

  // We will save the results in this array
  $op = isset($form_values['op']) ? $form_values['op'] : '';
  if ($op == t('Import')) {
    $method = $form_values['copy'] ? 'copy' : 'rename';
    $dirpath = variable_get('asset_import_path', '');
    if ($form_values['subdirectory']) {
      $options = array();
      $dirpath_new = file_create_path($form_values['parent'] . '/' . $form_values['subdirectory']);
      if (!asset_check_directory($dirpath_new, FILE_CREATE_DIRECTORY, 'folder', $options)) {
        form_set_error('folder', t('Error creating %dir.', array(
          '%dir' => $dir,
        )));
        return;
      }
    }
    if (file_check_directory($dirpath)) {
      $nodes = array();
      $files = array();
      foreach (array_filter($form_values['import_file']) as $index) {

        // try to avoid php's script timeout with a bunch of large files or a slow machine
        if (!ini_get('safe_mode')) {
          set_time_limit(0);
        }
        $origname = $form_values['file_list'][$index];
        $filename = file_check_location($dirpath . '/' . $origname, $dirpath);
        if (!$form_values['subdirectory']) {
          $target = file_directory_path() . '/' . $form_values['parent'] . '/' . $origname;
        }
        else {
          $target = file_directory_path() . '/' . $form_values['parent'] . '/' . $form_values['subdirectory'] . '/' . $origname;
        }
        if ($filename && $method($filename, $target)) {
          $options = array(
            'title' => $form_values['title'][$index],
            'author' => $form_values['body'][$index],
            'status' => 1,
          );
          $asset = new StdClass();
          $asset->filepath = $target;
          $asset->filesize = filesize($target);
          asset_save($asset, $options);
          $nodes[] = t('%filename', array(
            '%filename' => $origname,
          ));
        }
      }

      // report back on our progress
      if (!empty($nodes)) {
        drupal_set_message(t('Successfully imported: ') . theme('item_list', $nodes));
      }
      else {
        drupal_set_message(t('No image files were imported.'));
      }
    }
  }
}
function asset_import_admin_settings() {
  $form['asset_import_path'] = array(
    '#type' => 'textfield',
    '#title' => t('Import path'),
    '#default_value' => variable_get('asset_import_path', file_directory_path() . '/images/import'),
    '#after_build' => array(
      '_asset_import_settings_check_directory',
    ),
    '#description' => t("The directory to import assets from. Drupal will need to have write access to this directory so we can move the file.") . '<br />' . t("<strong>Note:</strong> a path begining with a <kbd>/</kbd> indicates the path is relative to the server's root, not the website's root. One starting without a <kbd>/</kbd> specifies a path relative to Drupal's root. For example: <kbd>/tmp/image</kbd> would be the temp directory off the root while <kbd>tmp/image</kbd> would be inside Drupal's directory."),
    '#required' => TRUE,
  );
  return system_settings_form($form);
}

/**
 * Checks the existence of the directory specified in $form_element.
 *
 * @param $form_element
 *   The form element containing the name of the directory to check.
 * @see system_check_directory()
 */
function _asset_import_settings_check_directory($form_element) {
  $import_dir = $form_element['#value'];
  file_check_directory($import_dir, 0, $form_element['#parents'][0]);
  $image_dir = file_create_path(variable_get('image_default_path', 'images'));
  if (realpath($import_dir) == realpath($image_dir)) {
    form_set_error($form_element['#parents'][0], t("You can't import from the image module's directory. The import deletes the original files so you would just be asking for trouble."));
  }
  return $form_element;
}

Functions

Namesort descending Description
asset_import_admin_settings
asset_import_form
asset_import_form_submit
asset_import_help Implementation of hook_help().
asset_import_menu Implementation of hook_menu().
asset_import_perm Implementation of hook_perm().
theme_asset_import_form
_asset_import_settings_check_directory Checks the existence of the directory specified in $form_element.