You are here

media_watermark.module in Media watermark 7

Watermark media module.

File

media_watermark.module
View source
<?php

/**
 * @file
 * Watermark media module.
 */

/**
 * Implements hook_permission().
 */
function media_watermark_permission() {
  return array(
    'media watermark control' => array(
      'title' => t('Configure watermarks'),
      'description' => t('Configure watermarks, perform CRUD actions.'),
    ),
    'media watermark apply watermarks' => array(
      'title' => t('Add existing watermarks'),
      'description' => t('Checkbox appear for controlling watermarks on file entities.'),
    ),
  );
}

/**
 * Implements hook_menu().
 */
function media_watermark_menu() {
  $items = array();
  $items['admin/config/media/watermark'] = array(
    'title' => 'Media Watermark settings',
    'description' => 'Control how to apply watermark.',
    'page callback' => 'media_watermark_get_sort_table_watermarks',
    'access arguments' => array(
      'media watermark control',
    ),
    'file' => 'includes/media_watermark_edit.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/media/watermark/add'] = array(
    'title' => 'Add watermark',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'media_watermark_form',
    ),
    'access arguments' => array(
      'media watermark control',
    ),
    'file' => 'includes/media_watermark_add.admin.inc',
    'type' => MENU_LOCAL_ACTION,
  );
  $items['admin/config/media/watermark/edit/%'] = array(
    'title' => 'Edit watermark',
    'description' => 'Edit watermark.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'media_watermark_form',
    ),
    'access arguments' => array(
      'media watermark control',
    ),
    'file' => 'includes/media_watermark_add.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['admin/config/media/watermark/delete/%'] = array(
    'title' => 'Delete watermark',
    'description' => 'Delete watermark.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'media_watermark_delete_form',
    ),
    'access arguments' => array(
      'media watermark control',
    ),
    'file' => 'includes/media_watermark_delete.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Function to get all watermarks array stored in db.
 *
 * @return array|null
 *   all stored watermarks
 */
function media_watermark_get_watermarks() {
  $result = db_query("SELECT * FROM {media_watermark}");
  if (isset($result) && !empty($result)) {
    $watermarks = $result
      ->fetchAll(PDO::FETCH_ASSOC);

    // Clean values.
    foreach ($watermarks as &$watermark) {
      $watermark = array_map('check_plain', $watermark);
    }
    return $watermarks;
  }
}

/**
 * Function to get watermark name by id.
 *
 * @param string $id
 *   watermark id
 *
 * @return string
 *   watermark name
 */
function media_watermark_get_name($id) {
  $result = db_query('SELECT name FROM {media_watermark} WHERE wid = :wid', array(
    ':wid' => $id,
  ));
  $result = $result
    ->fetchObject();
  if (!empty($result)) {
    $result = $result->name;
    return $result;
  }
}

/**
 * Function to get watermark object by id.
 *
 * @param string $id
 *   watermark id
 *
 * @return object
 *   watermark object
 */
function media_watermark_get_watermark($id) {
  $result = db_query('SELECT * FROM {media_watermark} WHERE wid = :wid', array(
    ':wid' => $id,
  ));
  $result = $result
    ->fetchObject();
  if (!empty($result)) {
    return $result;
  }
}

/**
 * Implements hook_form_alter().
 */
function media_watermark_form_alter(&$form, &$form_state, $form_id) {
  if (user_access('media watermark apply watermarks')) {
    if (in_array($form_id, array(
      'file_entity_add_upload_multiple',
      'file_entity_add_upload',
      'media_add_upload',
      'media_tab_upload',
    ))) {
      if (empty($form['field_file_image_alt_text']) && empty($form['field_file_image_title_text'])) {
        $watermarks = media_watermark_get_watermarks();
        if (!empty($watermarks)) {
          $form['add_watermark'] = array(
            '#type' => 'checkbox',
            '#title' => t('Add watermark'),
            '#default_value' => FALSE,
            '#weight' => 20,
          );
          $names = media_watermark_prepare_names($watermarks);
          $form['watermarks_names'] = array(
            '#type' => 'select',
            '#options' => $names,
            '#description' => t('To edit watermark just click on its image'),
            '#weight' => 19,
          );

          // Hide select list if one watermark.
          if (count($watermarks) == 1) {
            $form['watermarks_names']['#prefix'] = '<div class="hide-select-list">';
            $form['watermarks_names']['#suffix'] = '</div>';
          }
          $form['watermarks_images'] = media_watermark_prepare_images($watermarks);
          $form['#attached']['js'] = array(
            drupal_get_path('module', 'media_watermark') . '/media_watermark.js',
          );

          // Add custom submit function.
          array_unshift($form['#submit'], 'media_watermark_add_watermark');
        }
      }
    }
  }
}

/**
 * Callback to add watermark.
 */
function media_watermark_add_watermark(&$form, &$form_state) {
  if ($form_state['values']['add_watermark']) {

    // Uploaded file.
    if (is_object($form_state['values']['upload'])) {
      $file_path = drupal_realpath($form_state['values']['upload']->uri);
      media_watermark_create_image($file_path, $form_state);
    }
    elseif (is_int($form_state['values']['upload']) || is_string($form_state['values']['upload'])) {
      $uploaded = file_load($form_state['values']['upload']);
      $file_path = drupal_realpath($uploaded->uri);
      media_watermark_create_image($file_path, $form_state);
    }
    else {
      media_watermark_add_upload_multiple_submit($form, $form_state);
    }
  }
}

/**
 * Function to create image (.jpg, .jpeg, .png, .gif) file.
 *
 * @param string $file_path
 *   temporary path of uploaded file
 *
 * @param array $form_state
 *   array of form state
 */
function media_watermark_create_image($file_path, $form_state) {
  $watermark_obj = db_query("SELECT * FROM {media_watermark} WHERE fid = :fid", array(
    ':fid' => $form_state['values']['watermarks_names'],
  ));
  $watermark_obj = $watermark_obj
    ->fetchObject();
  $watermark_file = file_load($watermark_obj->fid);
  $watermark_filepath = drupal_realpath($watermark_file->uri);
  $watermark_extension = pathinfo($watermark_filepath, PATHINFO_EXTENSION);

  // Check uploaded image extension.
  $ext = pathinfo($file_path, PATHINFO_EXTENSION);
  if ($ext == 'jpg' || $ext == 'jpeg') {
    $img = imagecreatefromjpeg($file_path);
  }
  elseif ($ext == 'png') {
    $img = imagecreatefrompng($file_path);
  }
  elseif ($ext == 'gif') {
    $img = imagecreatefromgif($file_path);
  }
  if (!empty($img)) {
    ob_start();
    if ($watermark_extension == 'png') {
      $watermark_img = imagecreatefrompng($watermark_filepath);
    }
    elseif ($watermark_extension == 'gif') {
      $watermark_img = imagecreatefromgif($watermark_filepath);
    }
    module_load_include('inc', 'media_watermark', 'includes/media_watermark');
    $watermark = new MediaWatermark();
    $im = $watermark
      ->addWatermark($img, $watermark_img, $watermark_obj, $ext);
    imagepng($im, $file_path);
    imagedestroy($im);
    ob_end_clean();
  }
}

/**
 * Function to return watermark names array.
 *
 * @param array $results
 *   watermarks array
 *
 * @return array
 *   names array
 */
function media_watermark_prepare_names($results) {
  $names = array();
  foreach ($results as $value) {
    $names[$value['fid']] = $value['name'];
  }
  return $names;
}

/**
 * Function to prepare watermark images html.
 *
 * @todo move into theme function.
 *
 * @param array $results
 *   watermark images file id array
 *
 * @return string
 *   html of watermark images
 */
function media_watermark_prepare_images($results) {
  $output = array();

  // Build render array.
  $output['images'] = array(
    '#type' => 'container',
    '#prefix' => '<div id="edit-watermarks-images">',
    '#suffix' => '</div>',
    '#weight' => 18,
  );
  foreach ($results as $value) {
    $file = file_load($value['fid']);
    $output['images']['image-' . $value['fid']] = array(
      '#theme' => 'image_formatter',
      '#item' => array(
        'uri' => $file->uri,
        'alt' => t('Edit'),
        'title' => t('Edit'),
      ),
      '#path' => array(
        'path' => 'admin/config/media/watermark/edit/' . $value['wid'],
        'options' => array(
          'html' => TRUE,
        ),
      ),
      '#image_style' => 'media_watermark',
      '#prefix' => '<div class="image-hidden" id="image-' . $value['fid'] . '">',
      '#suffix' => '</div>',
    );
  }
  return $output;
}

/**
 * Batch operation: prepare batch to add watermarks to images.
 *
 * @param array $form_state
 *   form state array
 *
 * @return array
 *   batch operations array
 */
function media_watermark_prepare_batch($form_state) {
  drupal_set_message(t('Adding watermarks.'));
  foreach ($form_state['files'] as $value) {
    $file_path = drupal_realpath($value->uri);
    $operations[] = array(
      'media_watermark_process_multiple_images',
      array(
        $file_path,
        $form_state,
      ),
    );
  }
  $batch = array(
    'operations' => $operations,
    'finished' => 'media_watermark_batch_finished',
    'init_message' => 'Prepare data.',
    'progress_message' => 'Executed @current from @total.',
    'error_message' => 'An error has occurred.',
  );
  return $batch;
}

/**
 * Batch worker function.
 *
 * Callback for batch_set().
 *
 * @param string $file_path
 *   path to image file
 * @param array $form_state
 *   array of form state
 * @param array $context
 *   batch helper array
 *
 * @ingroup callbacks
 */
function media_watermark_process_multiple_images($file_path, $form_state, &$context) {
  $context['results'][] = $file_path;

  // Optional message displayed under the progressbar.
  $context['message'] = t('Processing images "@title"', array(
    '@title' => $file_path,
  ));
  media_watermark_create_image($file_path, $form_state);
}

/**
 * Perform tasks when a batch is complete.
 *
 * Callback for batch_set().
 *
 * @param bool $success
 *   A boolean indicating whether the batch operation successfully concluded.
 * @param int $results
 *   The results from the batch process.
 * @param array $operations
 *   The batch operations that remained unprocessed. Only relevant if $success
 *   is FALSE.
 *
 * @ingroup callbacks
 */
function media_watermark_batch_finished($success, $results, $operations) {
  if ($success) {
    $count = count($results);
    drupal_set_message(t('Added watermarks to @count images', array(
      '@count' => $count,
    )));
  }
  else {
    drupal_set_message(t('Finished with errors.'), 'error');
  }
}

/**
 * Function which make same things as file_entity__add_upload_multiple_submit().
 */
function media_watermark_add_upload_multiple_submit($form, &$form_state) {
  $scheme = variable_get('file_default_scheme', 'public') . '://';
  foreach ($form_state['values']['upload'] as $uploaded_file) {
    if ($uploaded_file['status'] == 'done') {
      $source = $uploaded_file['tmppath'];
      $destination = file_stream_wrapper_uri_normalize($scheme . $uploaded_file['name']);

      // Rename it to its original name, and put it in its final home.
      // Note - not using file_move here because if we call file_get_mime
      // (in file_uri_to_object) while it has a .tmp extension, it horks.
      $destination = file_unmanaged_move($source, $destination, FILE_EXISTS_RENAME);
      $file = file_uri_to_object($destination);
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      $form_state['files'][$file->fid] = $file;
    }
    else {

      // @todo: move this to element validate or something.
      form_set_error('pud', t('The specified file %name could not be uploaded.', array(
        '%name' => $uploaded_file['name'],
      )));
    }
  }
  $batch = media_watermark_prepare_batch($form_state);
  batch_set($batch);

  // Redirect to the file edit page.
  if (file_entity_access('edit') && module_exists('multiform')) {
    $destination = array(
      'destination' => 'admin/content/file',
    );
    if (isset($_GET['destination'])) {
      $destination = drupal_get_destination();
      unset($_GET['destination']);
    }
    $form_state['redirect'] = array(
      'admin/content/file/edit-multiple/' . implode(' ', array_keys($form_state['files'])),
      array(
        'query' => $destination,
      ),
    );
  }
  else {
    $form_state['redirect'] = 'admin/content/file';
  }
}

Functions

Namesort descending Description
media_watermark_add_upload_multiple_submit Function which make same things as file_entity__add_upload_multiple_submit().
media_watermark_add_watermark Callback to add watermark.
media_watermark_batch_finished Perform tasks when a batch is complete.
media_watermark_create_image Function to create image (.jpg, .jpeg, .png, .gif) file.
media_watermark_form_alter Implements hook_form_alter().
media_watermark_get_name Function to get watermark name by id.
media_watermark_get_watermark Function to get watermark object by id.
media_watermark_get_watermarks Function to get all watermarks array stored in db.
media_watermark_menu Implements hook_menu().
media_watermark_permission Implements hook_permission().
media_watermark_prepare_batch Batch operation: prepare batch to add watermarks to images.
media_watermark_prepare_images Function to prepare watermark images html.
media_watermark_prepare_names Function to return watermark names array.
media_watermark_process_multiple_images Batch worker function.