You are here

ml_flickr.module in Media Library 6

This module aims to provide some basic sources for images to use with Media Library, such as navigating on existing files and uploading new images

File

ml_image/ml_flickr/ml_flickr.module
View source
<?php

/**
 * @file
 * This module aims to provide some basic sources for images to use with
 * Media Library, such as navigating on existing files and uploading new images
 */

/**
 * Default images dir
 */
define('ML_FLICKR_DIR', 'images/flickr');

/**
 * ML Image Hooks
 */

/**
 * Implementation of hook_ml_image_source()
 */
function ml_flickr_ml_image_source() {
  return array(
    'flickr' => array(
      'label' => t('Flickr'),
      'module' => 'ml_flickr',
      'settings' => 'ml_flickr_settings',
    ),
  );
}

/**
 * Forms
 */

/**
 * Form for checking flickr images.
 */
function ml_flickr_flickr_source_form($form_state) {
  $form = array();
  $form['#description'] = t('Type in desired filter for showing results');
  $metadata = ml_image_get_metadata();
  foreach ($metadata as $field => $data) {
    switch ($data['type']) {
      case 'term':
        $vocabulary = $data['vocabulary'];
        if ($vocabulary->tags) {
          $form[$field] = array(
            '#type' => 'textfield',
            '#title' => $data['label'],
            '#description' => $data['description'],
            '#autocomplete_path' => 'taxonomy/autocomplete/' . $vocabulary->vid,
            '#maxlength' => 1024,
          );
        }
        else {

          // Extract terms belonging to the vocabulary in question.
          $form[$field] = taxonomy_form($vocabulary->vid, array(), $data['description']);
          $form[$field]['#title'] = $data['title'];
        }
        break;
    }
  }
  return $form;
}

/**
 * Validate callback for ml_flickr_flickr_source_form()
 */
function ml_flickr_flickr_source_form_validate($form, &$form_state) {
  $values = $form_state['values'];
}

/**
 * Submit callback for ml_flickr_flickr_source_form()
 */
function ml_flickr_flickr_source_form_submit($form, &$form_state) {
}

/**
 * Image selection stage
 */
function ml_flickr_flickr_options_form($form_state) {
  $form_values = $form_state['values']['flickr'];

  // Get the search results
  $result = ml_flickr_search();

  // Build base form
  $form = media_library_modal_browse_form($form_state, $result['total']);

  // Build form elements
  $images = array();
  foreach ($result['photo'] as $image) {

    // TODO: copy form structer from ml_image_basic_existing_options_form
    if ($url = ml_flickr_build_url($image, 'thumbnail')) {
      $image = ml_flickr_image_info($image['id']);
      $img_tag = theme('image', $url, $image['title'], $image['title'], NULL, FALSE);
      $form[] = array(
        '#tree' => FALSE,
        'choice' => array(
          '#type' => 'radio',
          '#title' => $image['title'],
          '#return_value' => $image['id'],
          '#prefix' => '<div class="ml-image-list-item">',
          '#suffix' => $img_tag . '</div>',
        ),
      );
      $form['images'][$image['id']] = array(
        '#type' => 'value',
        '#value' => $image,
      );
    }
  }
  return $form;
}

/**
 * Submit of image selection stage
 */
function ml_flickr_flickr_options_form_validate($form, &$form_state) {
  $image_id = current(array_filter($form_state['values']['choice']));
  $image = $form_state['values']['images'][$image_id];

  // TODO: validate choice?
  // First we need to check for the available sizes;
  $sizes = ml_flickr_get_sizes($image['id']);
  foreach ($sizes as $size) {

    // TODO: configurable max width/height
    if ($size['width'] > 1000 || $size['height'] > 800) {
      break;
    }
    $url = $size['source'];
  }

  // Could not find usable size
  if (!$url) {
    form_set_error('choice', t('Could not find usable source image for option'));
  }
}

/**
 * Submit of image selection stage
 */
function ml_flickr_flickr_options_form_submit($form, &$form_state) {
  $image_id = current(array_filter($form_state['values']['choice']));
  $image = $form_state['values']['images'][$image_id];

  // Save image
  // First we need to check for the available sizes;
  $sizes = ml_flickr_get_sizes($image['id']);
  foreach ($sizes as $size) {

    // TODO: configurable max width/height
    if ($size['width'] > 1000 || $size['height'] > 800) {
      break;
    }
    $url = $size['source'];
  }
  if ($file = ml_flickr_save_image($url)) {
    $form_state['media_obj']->filepath = $file->filepath;
    $form_state['media_obj']->fid = $file->fid;
    $form_state['media_obj']->filename = $file->filename;
    $form_state['media_obj']->metatags = array(
      'title' => $image['title'],
      'author' => empty($image['owner']['realname']) ? $image['owner']['username'] : $image['owner']['realname'],
      'copyright' => $image['license']['name'],
    );
    $metatags = (object) $form_state['media_obj']->metatags;
    $metatags->fid = $file->fid;
    $metatags->source = 'flickr';
    ml_image_save_metatags($metatags);
  }
}

/**
 * Settings form
 */
function ml_flickr_settings($form_state) {
  $form = array();
  $form['ml_flickr_destination'] = array(
    '#type' => 'textfield',
    '#title' => t('Flickr Images Destination'),
    '#description' => t('Directory to save images, relative to files dir. Defaults to "' . ML_FLICKR_DIR . '".'),
    '#size' => 40,
    '#maxlength' => 255,
    '#default_value' => variable_get('ml_flickr_destination', ML_FLICKR_DIR),
  );
  return $form;
}

/**
 * Helpers and callbacks
 */

/**
 * Builds an image url 
 */
function ml_flickr_build_url($image, $size) {
  $size = strtolower($size);
  if (ml_flickr_build_url_validate($image)) {
    $flickr_obj = ml_flickr_get_obj();
    return $flickr_obj
      ->buildPhotoURL($image, $size);
  }
}

/**
 * Validates if image url can be built
 */
function ml_flickr_build_url_validate($image) {
  if (!empty($image['id']) && !empty($image['secret']) && !empty($image['server']) && !empty($image['farm'])) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Returns an object of flickr for the operations.
 * To reduce memory footprint, we statically cache it
 */
function ml_flickr_get_obj() {
  static $flickr_obj;
  if (!is_object($flickr_obj)) {
    $flickr_obj = flickrapi_phpFlickr();
  }
  return $flickr_obj;
}

/**
 * Function that searches flickr
 * TODO: Add arguments
 */
function ml_flickr_search() {

  // Get variables
  $limit = variable_get('media_library_limit', MEDIA_LIBRARY_LIMIT);
  $page = isset($_GET['page']) ? $_GET['page'] : 0;

  // Call flickr search
  $flickr_obj = ml_flickr_get_obj();
  return $flickr_obj
    ->photos_search(array(
    'tags' => 'cow',
    'tag_mode' => 'all',
    //'license' => 'something',
    'media' => 'photos',
    'per_page' => $limit,
    'page' => $page + 1,
  ));
}

/**
 * Loads image info
 */
function ml_flickr_image_info($image_id) {
  $flickr_obj = ml_flickr_get_obj();
  $image = $flickr_obj
    ->photos_getInfo($image_id);
  $license_info = $flickr_obj
    ->photos_licenses_getInfo();
  $image['license'] = $license_info[$image['license']];
  return $image;
}

/**
 * Loads image sizes
 */
function ml_flickr_get_sizes($image_id) {
  $flickr_obj = ml_flickr_get_obj();
  $sizes = $flickr_obj
    ->photos_getSizes($image_id);
  return $sizes;
}

/**
 * Saves a Flickr picture from an URL
 * @param
 *  url - url of image
 * @return
 *  file object
 */
function ml_flickr_save_image($url) {
  global $user;

  // URL fopen
  $fd = fopen($url, 'rb');
  if (!$fd) {

    // TODO: issue error
    return;
  }
  $dir = variable_get('ml_flickr_destination', ML_FLICKR_DIR);
  $dest = file_create_path($dir);
  if (!file_check_directory($dest, TRUE)) {

    // TODO: issue error
    return;
  }
  $filename = basename($url);

  // Begin building file object.
  $file = new stdClass();
  $file->filename = $filename;

  //$file->filepath = $_FILES['files']['tmp_name'][$source];
  $file->filemime = file_get_mimetype($file->filename);

  //$file->source = $source;
  $file->destination = file_destination(file_create_path($dest . '/' . $file->filename), FILE_EXISTS_REPLACE);

  // Copy file
  $file->filepath = $file->destination;
  if ($fd_dest = fopen($file->filepath, 'w+')) {
    stream_copy_to_stream($fd, $fd_dest);
    fclose($fd);
    fclose($fd_dest);
  }

  // If we made it this far it's safe to record this file in the database.
  $file->uid = $user->uid;
  $file->status = 1;
  $file->timestamp = time();
  $file->filesize = filesize($file->filepath);
  drupal_write_record('files', $file);
  return $file;
}

Functions

Namesort descending Description
ml_flickr_build_url Builds an image url
ml_flickr_build_url_validate Validates if image url can be built
ml_flickr_flickr_options_form Image selection stage
ml_flickr_flickr_options_form_submit Submit of image selection stage
ml_flickr_flickr_options_form_validate Submit of image selection stage
ml_flickr_flickr_source_form Form for checking flickr images.
ml_flickr_flickr_source_form_submit Submit callback for ml_flickr_flickr_source_form()
ml_flickr_flickr_source_form_validate Validate callback for ml_flickr_flickr_source_form()
ml_flickr_get_obj Returns an object of flickr for the operations. To reduce memory footprint, we statically cache it
ml_flickr_get_sizes Loads image sizes
ml_flickr_image_info Loads image info
ml_flickr_ml_image_source Implementation of hook_ml_image_source()
ml_flickr_save_image Saves a Flickr picture from an URL
ml_flickr_search Function that searches flickr TODO: Add arguments
ml_flickr_settings Settings form

Constants

Namesort descending Description
ML_FLICKR_DIR Default images dir