You are here

pdfthumb.module in PDFThumb 7

Give a way to create pdf thumbnails.

File

pdfthumb.module
View source
<?php

/**
 * @file
 * Give a way to create pdf thumbnails.
 */

/**
 * Implements hook_permission().
 */
function pdfthumb_permission() {
  return array(
    'administer PDFThumb' => array(
      'title' => t('Administer PDFThumb'),
      'description' => t('Perform administration tasks for PDFThumb.'),
      'restrict access' => TRUE,
    ),
  );
}

/**
 * Implements hook_menu().
 */
function pdfthumb_menu() {
  $items = array();
  $items['admin/config/media/pdfthumb'] = array(
    'title' => 'PDF Thumbnails',
    'description' => 'Configure PDF Thumbnails',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'pdfthumb_settings',
    ),
    'access callback' => 'user_access',
    'access arguments' => array(
      'administer PDFThumb',
    ),
  );
  return $items;
}

/**
 * Form constructor for the settings
 */
function pdfthumb_settings() {
  $form = array();
  $form['seetings'] = array(
    '#type' => 'fieldset',
    '#title' => t("settings"),
    '#description' => t('Warning: Currently this module only works for single valued fields.'),
  );
  $form['seetings']['pdfthumb_convertpath'] = array(
    '#type' => 'textfield',
    '#title' => t('Give the real path of convert tools'),
    '#description' => t('(Ex: /usr/bin/convert)'),
    '#default_value' => variable_get('pdfthumb_convertpath', NULL),
  );
  $form['seetings']['pdfthumb_link_files'] = array(
    '#type' => 'checkbox',
    '#title' => t('Link PDF with Image File. When you will delete the pdf file, the associated image file will be deleted.'),
    '#default_value' => variable_get('pdfthumb_link_files', NULL),
  );
  $form['entity_config'] = array(
    '#type' => 'fieldset',
    '#title' => t("Fields configuration"),
    '#description' => t('For each entity, match a PDF file field with an image field or the Media Library'),
  );

  // For each entity.
  foreach (entity_get_info() as $entity_name => $entity_values) {

    // Show only entity fieldable. User / Node / Taxonomy /etc.
    if ($entity_values['fieldable'] == TRUE) {
      $form['entity_config'][$entity_name] = array(
        '#type' => 'fieldset',
        '#title' => check_plain($entity_values['label']),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
      );

      // For each field in this entiy.
      foreach (field_info_instances($entity_name) as $type_name => $type_values) {
        $entity_infos = entity_get_info($entity_name);

        // Show a config field
        $form['entity_config'][$entity_name][$type_name] = array(
          '#type' => 'fieldset',
          '#title' => check_plain($entity_infos['bundles'][$type_name]['label']),
          '#collapsible' => TRUE,
          '#collapsed' => TRUE,
        );
        $form['entity_config'][$entity_name][$type_name]['no_field'] = array(
          '#markup' => "<i>" . t('There are no File Field to configure.') . "</i>",
        );
        foreach ($type_values as $key => $field) {
          $options = array();

          // If this field is a file field check to find Image field
          // in same content type.
          if ($field['widget']['type'] == 'file_generic') {
            unset($form['entity_config'][$entity_name][$type_name]['no_field']);
            $options = array(
              "none" => t("Do nothing"),
              "media" => t("Media Library"),
            );

            // Get only the images field.
            foreach (field_info_instances($entity_name, $type_name) as $field_img_key => $field_img) {
              if ($field_img['widget']['type'] == 'image_image') {
                $options[$field_img_key] = check_plain($field_img['label'] . " (" . $field_img_key . ")");
              }
            }

            // Finally complete the form. Sotre the config in variable table
            // with this template : pdfthumb_type-name_field-name
            $form['entity_config'][$entity_name][$type_name]["pdfthumb_" . $type_name . "_" . $key] = array(
              '#type' => 'select',
              '#title' => check_plain($field['label'] . " (" . $key . ")"),
              '#options' => $options,
              '#default_value' => variable_get("pdfthumb_" . $type_name . "_" . $key, NULL),
            );
          }
        }
      }
    }
  }
  return system_settings_form($form);
}

/**
 * Implements form validate.
 */
function pdfthumb_settings_validate($form, &$form_state) {
  $open_basedir = ini_get("open_basedir");
  if (!empty($open_basedir)) {
    drupal_set_message(t("open_base_dir restriction in effect. Can not check convert path."), "warning");
  }
  else {
    if (!file_exists($form_state['values']['pdfthumb_convertpath'])) {
      form_set_error('pdfthumb_convertpath', t('I can not find convert. Check the path and try again.'));
    }
  }
}

/**
 * Implements hook_entity_presave().
 */
function pdfthumb_entity_presave($entity, $type) {

  // Before saving an entity the module check for a pdf to process
  pdfthumb_process($entity, $type);
}

/**
 * Find a PDF field for generate a thumb after saving or updating a node
 *
 * @param object $entity
 *   The entity that is being inserted or updated.
 * @param string $type
 *   The entity name.
 */
function pdfthumb_process($entity, $type) {
  global $user;

  // When we save bundles check for a configured file field.
  if (is_object($entity)) {

    // Get the current bundle name Ex: User / News / Page
    $current_bundle = pdfthumb_entity_get_bundle($entity, $type);
    foreach (field_info_instances($type, $current_bundle) as $key => $value) {

      // If this file has been configured.
      if (variable_get("pdfthumb_" . $current_bundle . "_" . $key, NULL)) {
        $img_dest = variable_get("pdfthumb_" . $current_bundle . "_" . $key);
        $pdf_field = field_get_items($type, $entity, $key);

        // If the pdf file exist
        if (isset($pdf_field[0]['fid'])) {

          // Check convert path is configured
          if (variable_get('pdfthumb_convertpath', NULL)) {

            // If the option media library is selected for this file.
            if ($img_dest == "media") {
              pdfthumb_create_thumb($pdf_field[0]['fid']);
            }
            elseif ($img_dest != "none") {

              // Create a thumb file and link it with the specified field.
              $field_lg = field_language($type, $entity, $img_dest);
              $file = pdfthumb_create_thumb($pdf_field[0]['fid']);

              // If the file has been created
              if ($file) {
                $entity->{$img_dest} = array(
                  $field_lg => array(
                    0 => array(
                      'fid' => $file->fid,
                      'filename' => $file->filename,
                      'filemime' => $file->filemime,
                      'uid' => $user->uid,
                      'uri' => $file->uri,
                      'status' => 1,
                    ),
                  ),
                );
              }
            }
          }
          else {
            watchdog("pdfthumb", "Convert path not found. No PDF thumbnails generate", array(), WATCHDOG_WARNING);
          }
        }
      }
    }
  }
}

/**
 * Return the current bundle name.
 *
 * @param object $entity
 *   The entity object
 * @param string $entity_type
 *   The entity type
 *
 * @return string
 *   Current bundle name
 */
function pdfthumb_entity_get_bundle($entity, $entity_type) {
  $info = entity_get_info($entity_type);
  if (empty($info['entity keys']['bundle'])) {
    return $entity_type;
  }
  else {
    return $entity->{$info['entity keys']['bundle']};
  }
}

/**
 * Create the PDF Covers. And insert the generated image to the media librarie.
 *
 * @param object $fid
 *   The file_id from file to convert
 *
 * @return object
 *   Drupal file object or NULL.
 */
function pdfthumb_create_thumb($fid) {
  $file = file_load($fid);

  /*$file_directory_temp = file_directory_temp();
    $lastCharacterTempPath = substr(file_directory_temp(), -1);

    if ($lastCharacterTempPath == "/") {
      $file_directory_temp = substr(file_directory_temp(), 0, -1);
    }
    */
  if ($file->filemime == "application/pdf") {
    $src = drupal_realpath($file->uri) . "[0]";
    $dest = file_directory_temp() . "/" . $file->filename . ".png";
    if (file_exists($dest)) {
      unlink($dest);
    }

    //$exec = variable_get('pdfthumb_convertpath', NULL) . " " . escapeshellarg($src) . " " . escapeshellarg($dest);
    $exec = escapeshellcmd(variable_get('pdfthumb_convertpath', NULL)) . " " . escapeshellarg($src) . " " . escapeshellarg($dest);
    if (function_exists("exec")) {
      exec($exec, $array, $status);
    }
    elseif (function_exists("system")) {
      system($exec, $status);
    }
    elseif (function_exists("passthru")) {
      passthru($exec, $status);
    }
    if ($status == 0) {
      global $user;
      $file_uri = file_unmanaged_move($dest);
      $file = new stdClass();
      $file->uid = $user->uid;
      $file->status = 1;
      $file->filename = drupal_basename($dest);
      $file->uri = $file_uri;
      $file->filemime = file_get_mimetype($dest);
      $pdf_thumb = file_save($file);
      if (variable_get('pdfthumb_link_files', NULL)) {
        $fields = array(
          'pdffid' => $pdf_thumb->fid,
          'fid' => $fid,
        );
        drupal_write_record('pdfthumb', $fields);
      }
      return $pdf_thumb;
    }
    else {
      drupal_set_message(t("Error while creating PDF Thumbnails."), "error");
      watchdog("pdfthumb", "Error during the converstion from the file @src to @dest with the command @exec", array(
        '@src' => $src,
        '@dest' => $dest,
        '@exec' => $exec,
      ), WATCHDOG_WARNING);
      return NULL;
    }
  }
  else {
    return NULL;
  }
}

/**
 * Implements hook_file_delete().
 */
function pdfthumb_file_delete($file) {
  $result = db_query("SELECT p.pdffid FROM {pdfthumb} p WHERE p.fid=:fid", array(
    ':fid' => $file->fid,
  ));
  $data = $result
    ->fetchField(0);
  if (is_numeric($data)) {
    $file_to_delete = file_load($data);
    if ($file_to_delete) {
      file_delete(file_load($data));
    }
    db_delete('pdfthumb')
      ->condition('fid', $file->fid)
      ->execute();
  }
}

Functions

Namesort descending Description
pdfthumb_create_thumb Create the PDF Covers. And insert the generated image to the media librarie.
pdfthumb_entity_get_bundle Return the current bundle name.
pdfthumb_entity_presave Implements hook_entity_presave().
pdfthumb_file_delete Implements hook_file_delete().
pdfthumb_menu Implements hook_menu().
pdfthumb_permission Implements hook_permission().
pdfthumb_process Find a PDF field for generate a thumb after saving or updating a node
pdfthumb_settings Form constructor for the settings
pdfthumb_settings_validate Implements form validate.