You are here

media_sitemap.module in Media Sitemap 7

Same filename and directory in other branches
  1. 8 media_sitemap.module

This module is used for creating XML sitemap of Image/Video for Google.

File

media_sitemap.module
View source
<?php

/**
 * @file
 * This module is used for creating XML sitemap of Image/Video for Google.
 */
define('MEDIA_SITEMAP_ADMIN_PATH', 'admin/config/media/media_sitemap');

/**
 * Implements hook_help().
 */
function media_sitemap_help($path, $arg) {
  $output = '';
  switch ($path) {
    case 'admin/help#media_sitemap':
      $output .= '<h3>' . t('About the Media Sitemap Module') . '</h3>';
      $output .= '<p>' . t('This module is used for creating the image sitemap for google. Actually this module uses the media module for generating the sitemap of all images. To list all of your image sitemap <a href="@media_sitemap">Click Here</a>', array(
        '@media_sitemap' => url(MEDIA_SITEMAP_ADMIN_PATH . '/list'),
      )) . '</p>';
      break;
  }
  return $output;
}

/**
 * Implements hook_permission().
 */
function media_sitemap_permission() {
  $permissions['administer media sitemap'] = array(
    'title' => t('Permissions for Media Sitemap Generation.'),
  );
  return $permissions;
}

/**
 * Implements hook_menu().
 *
 * Provides a page for configuring sitemap settings.
 */
function media_sitemap_menu() {
  $items[MEDIA_SITEMAP_ADMIN_PATH] = array(
    'title' => 'Media Sitemap',
    'description' => 'Create and configure google image sitemap.',
    'page callback' => '_media_sitemap_list',
    'access arguments' => array(
      'administer media sitemap',
    ),
  );
  $items[MEDIA_SITEMAP_ADMIN_PATH . '/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -5,
  );
  $items[MEDIA_SITEMAP_ADMIN_PATH . '/generate'] = array(
    'title' => 'Add new Google Image sitemap',
    'page callback' => '_media_sitemap_generate_sitemap',
    'access arguments' => array(
      'administer media sitemap',
    ),
  );
  return $items;
}

/**
 * Implements hook_cron().
 */
function media_sitemap_cron() {
  _media_sitemap_generate_sitemap();
}

/**
 * Custom function for generating the sitemap.
 */
function _media_sitemap_generate(&$context) {
  $query = db_select('file_usage', 'fu');
  $query
    ->fields('fu', array(
    'id',
  ));
  $query
    ->join('node', 'n', 'n.nid = fu.id');
  $nids = $query
    ->distinct()
    ->execute()
    ->fetchAll();
  $output = '';
  $total_urls = 0;
  if (count($nids) > 0) {
    $output = '<?xml version="1.0" encoding="UTF-8"?>';
    $output .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
    xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';
    foreach ($nids as $nid) {

      // fetch list of media files for each nid.
      $query = db_select('file_managed', 'fm');
      $query
        ->fields('fm', array(
        'fid',
        'filename',
        'uri',
      ));
      $query
        ->join('file_usage', 'fu', 'fu.fid = fm.fid');
      $query
        ->condition('fu.id', $nid->id);
      $query
        ->condition('fm.type', 'image');
      $files = $query
        ->execute()
        ->fetchAll();
      if (count($files) > 0) {
        $output .= '<url><loc>' . url('node/' . $nid->id, array(
          'absolute' => TRUE,
        )) . '</loc>';
        foreach ($files as $file) {
          $media_title = _media_sitemap_get_title($file->fid);
          if (!isset($media_title)) {
            $media_title = _media_sitemap_format_title($file->filename);
          }
          $output .= '<image:image><image:loc>' . file_create_url($file->uri) . '</image:loc><image:title>' . $media_title . '</image:title><image:caption>' . check_plain($media_title) . '</image:caption></image:image>';
        }
        $output .= '</url>';
        $total_urls++;
      }
    }
    $output .= '</urlset>';

    // File build path.
    $path = variable_get('file_public_path', 'sites/default/files') . '/media_sitemap';
    if (!is_dir($path)) {
      drupal_mkdir($path);
    }
  }
  $time = time();
  $filename = 'image_sitemap.xml';
  if ($file = file_unmanaged_save_data($output, $path . '/' . $filename, FILE_EXISTS_REPLACE)) {
    variable_set('image_sitemap_created', $time);
    variable_set('image_sitemap_number_of_urls', $total_urls);
  }
}

/**
 * Custom function for getting the title of the Image.
 */
function _media_sitemap_get_title($fid = "") {
  $table_exits = db_query("SHOW TABLES LIKE '%field_data_media_title%'")
    ->fetchObject();
  if (isset($table_exits) && !empty($table_exits)) {
    $result = db_query('SELECT mt.media_title_value FROM {field_data_media_title} mt WHERE mt.entity_id = :fid', array(
      ':fid' => $fid,
    ));
    $record = $result
      ->fetchObject();
    if (isset($record->media_title_value)) {
      return $record->media_title_value;
    }
  }
}

/**
 * Custom function for getting the formated title of the Image.
 */
function _media_sitemap_format_title($filename = "") {
  $replacements = array(
    '/\\..*/' => '',
    '/[^a-zA-Z0-9]+/' => ' ',
    '/([a-z])([A-Z])/' => '\\1 \\2',
    '/([a-zA-Z])([0-9])/' => '\\1 \\2',
    '/([0-9])([a-zA-Z])/' => '\\1 \\2',
  );

  // In addition to above replacements, also capitalize the first letter of
  // each word, and remove leading and trailing spaces.
  $title = trim(ucwords(preg_replace(array_keys($replacements), array_values($replacements), $filename)));
  return $title;
}

/**
 * List the available sitemap.
 */
function _media_sitemap_list() {
  $output = '';
  $header = array(
    t('SITEMAP URL'),
    t('CREATED DATE'),
    t('TOTAL LINKS'),
    t('ACTIONS'),
  );
  $rows = array();
  $url = 'media_sitemap/image_sitemap.xml';
  $url = variable_get('file_public_path', 'sites/default/files') . '/' . $url;

  // Rows of table.
  $image_sitemap_created = variable_get('image_sitemap_created');
  $image_sitemap_number_of_urls = variable_get('image_sitemap_number_of_urls');
  if (isset($image_sitemap_created) && isset($image_sitemap_number_of_urls)) {
    $rows[] = array(
      $build_link = l($url, $url),
      date('d-M-Y ', variable_get('image_sitemap_created')),
      variable_get('image_sitemap_number_of_urls'),
      l(t('Re-Generate'), MEDIA_SITEMAP_ADMIN_PATH . '/generate'),
    );
  }
  $theme_args = array(
    'header' => $header,
    'rows' => $rows,
    'empty' => t('No sitemaps available.') . ' ' . l(t('Add a new media sitemap'), MEDIA_SITEMAP_ADMIN_PATH . '/generate'),
  );
  $output = theme('table', $theme_args);
  return $output;
}

/**
 * Creating batch for generating the sitemap.
 */
function _media_sitemap_generate_sitemap() {
  $operations[] = array(
    '_media_sitemap_generate',
    array(),
  );
  $batch = array(
    'operations' => $operations,
    'finished' => 'media_sitemap_finished',
    'title' => t('Processing Image Sitemap Creation'),
    'init_message' => t('Creating Image Sitemap.'),
    'progress_message' => t('Creating Image Sitemap.....'),
    'error_message' => t('Image Sitemap Creation has encountered an error.'),
  );
  batch_set($batch);
  batch_process('mybatch');
}

/**
 * Finish of batch.
 */
function media_sitemap_finished($success, $results, $operations) {
  if ($success) {
    drupal_set_message(t('Image Sitemap Generated Successfully.'));
  }
  else {
    $error_operation = reset($operations);
    drupal_set_message(t('An error occurred while processing @operation with arguments : @args', array(
      '@operation' => $error_operation[0],
      '@args' => print_r($error_operation[0], TRUE),
    )));
  }
  drupal_goto(MEDIA_SITEMAP_ADMIN_PATH . "/list");
  watchdog('import', 'import finished');
}

Functions

Namesort descending Description
media_sitemap_cron Implements hook_cron().
media_sitemap_finished Finish of batch.
media_sitemap_help Implements hook_help().
media_sitemap_menu Implements hook_menu().
media_sitemap_permission Implements hook_permission().
_media_sitemap_format_title Custom function for getting the formated title of the Image.
_media_sitemap_generate Custom function for generating the sitemap.
_media_sitemap_generate_sitemap Creating batch for generating the sitemap.
_media_sitemap_get_title Custom function for getting the title of the Image.
_media_sitemap_list List the available sitemap.

Constants

Namesort descending Description
MEDIA_SITEMAP_ADMIN_PATH @file This module is used for creating XML sitemap of Image/Video for Google.