You are here

google_image_sitemap.module in Google Image Sitemap 6

Same filename and directory in other branches
  1. 7 google_image_sitemap.module

A module gives to Google information about images on your site.

File

google_image_sitemap.module
View source
<?php

/**
 * @file
 * A module gives to Google information about images on your site.
 */
define('GOOGLE_IMAGE_SITEMAP_ADMIN_PATH', 'admin/settings/google_image_sitemap');

/**
 * Implements hook_perm().
 */
function google_image_sitemap_perm() {
  $permissions = array(
    'administer google image sitemap',
  );
  return $permissions;
}

/**
 * Implements hook_menu().
 *
 * Provides a page for configuring sitemap settings.
 */
function google_image_sitemap_menu() {
  $items = array();
  $items[GOOGLE_IMAGE_SITEMAP_ADMIN_PATH] = array(
    'title' => 'Google Image Sitemap',
    'description' => 'Create and configure google image sitemap.',
    'page callback' => '_google_image_sitemap_list',
    'access arguments' => array(
      'administer google image sitemap',
    ),
  );
  $items[GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -5,
  );
  $items[GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/add'] = array(
    'title' => 'Add new Google Image sitemap',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      '_google_image_sitemap_create_form',
    ),
    'access arguments' => array(
      'administer google image sitemap',
    ),
    'type' => MENU_LOCAL_ACTION,
  );
  $items[GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/edit/%'] = array(
    'title' => 'Edit google image sitemap',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      '_google_image_sitemap_create_form',
      4,
    ),
    'access arguments' => array(
      'administer google image sitemap',
    ),
    'modal' => TRUE,
  );
  $items[GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/delete/%'] = array(
    'title' => 'Delete google image sitemap',
    'page callback' => '_google_image_sitemap_delete_form',
    'page arguments' => array(
      4,
    ),
    'access arguments' => array(
      'administer google image sitemap',
    ),
  );
  $items[GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/build/%'] = array(
    'title' => 'Build google image sitemap',
    'description' => 'Build google image sitemap.',
    'page callback' => '_google_image_sitemap_build',
    'page arguments' => array(
      4,
    ),
    'access arguments' => array(
      'administer google image sitemap',
    ),
  );
  return $items;
}

/**
 * Menu callback: Displays a list of available sitemaps.
 *
 * @return string
 *   Theme table data.
 */
function _google_image_sitemap_list() {
  $output = '';
  $header = array(
    t('S.NO.'),
    t('SITEMAP URL'),
    t('RANGE'),
    t('CONTENT TYPE'),
    t('LAST UPDATED'),
    t('ACTIONS'),
  );
  $result = db_query('SELECT * FROM {google_image_sitemap}');
  $counter = 0;
  $rows = array();
  while ($gis_obj = db_fetch_object($result)) {
    $url = 'google_image_sitemap/sitemap_' . $gis_obj->created . '.xml';

    // $url = file_create_url($url);
    $url = variable_get('file_directory_path', conf_path() . '/files') . '/' . $url;

    // Build links.
    $link_attributs = array(
      'attributes' => array(
        'title' => $gis_obj->range_start . " to " . $gis_obj->range_end,
      ),
    );
    if (empty($gis_obj->last_updated)) {
      $rebuild_link = '';
      $build_link = l(t('Generate Sitemap'), GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/build/' . $gis_obj->sid, $link_attributs);
    }
    else {
      $rebuild_link = l(t('RE-GENERATE'), GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/build/' . $gis_obj->sid) . " | ";

      // $build_link = l($url, $url, $link_attributs);
      // l() was adding ?q= in the url and user wasn't able to download file.
      $build_link = "<a href='{$url}'>{$url}</a>";
    }

    // Rows of table.
    $rows[] = array(
      ++$counter,
      $build_link,
      $gis_obj->range_start . " - " . $gis_obj->range_end,
      $gis_obj->node_type,
      empty($gis_obj->last_updated) ? '-' : date('d-M-Y ', $gis_obj->last_updated),
      $rebuild_link . l(t('EDIT'), GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/edit/' . $gis_obj->sid) . " | " . l(t('DELETE'), GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/delete/' . $gis_obj->sid),
    );
  }
  $output = '<p>' . l(t('Add new Google Image Sitemap'), GOOGLE_IMAGE_SITEMAP_ADMIN_PATH . '/add') . '</p>';
  if (!empty($counter)) {
    $output .= theme('table', $header, $rows);
  }
  return $output;
}

/**
 * Form builder: Generate a form to add/edit sitemaps.
 */
function _google_image_sitemap_create_form($form, $sitemap_id = NULL) {
  $form = array();

  // Get all node types.
  $node_types = node_get_types('names');

  // Count the all records from every content types.
  foreach ($node_types as $node_type_key => $node_type_val) {
    $cnt = db_result(db_query("SELECT COUNT(*) AS cnt FROM {node} WHERE type = '%s'", $node_type_key));
    $node_types[$node_type_key] = $node_type_val . " ( " . $cnt . " )";
  }
  $form['node_type'] = array(
    '#type' => 'select',
    '#title' => t('Select Content Type'),
    '#description' => t('Select the content type for which you want to generate image sitemap.'),
    '#options' => $node_types,
    '#required' => TRUE,
  );
  $form['range_start'] = array(
    '#type' => 'textfield',
    '#title' => t('Range Start'),
    '#description' => t('Starting Node ID.'),
    '#default_value' => '',
    '#required' => TRUE,
  );
  $form['range_end'] = array(
    '#type' => 'textfield',
    '#title' => t('Range End'),
    '#description' => t('Ending Node ID.'),
    '#default_value' => '',
    '#required' => TRUE,
  );
  $form['license'] = array(
    '#type' => 'textfield',
    '#title' => t('License url'),
    '#description' => t('An absolute url to the license agreement of the image.'),
  );
  $form['buttons']['save'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );
  $form['buttons']['cancel'] = array(
    '#type' => 'link',
    '#href' => isset($_GET['destination']) ? $_GET['destination'] : GOOGLE_IMAGE_SITEMAP_ADMIN_PATH,
    '#title' => t('Cancel'),
  );
  if (!empty($sitemap_id) && ($sitemap_obj = _google_image_sitemap_valid_sitemap_id($sitemap_id))) {
    $form['storage_sitemap_id'] = array(
      '#type' => 'hidden',
      '#value' => $sitemap_id,
    );

    // Set default value of form elements.
    $form['node_type']['#default_value'] = $sitemap_obj->node_type;
    $form['license']['#default_value'] = $sitemap_obj->license;
    $form['range_end']['#default_value'] = $sitemap_obj->range_end;
    $form['range_start']['#default_value'] = $sitemap_obj->range_start;
  }
  return $form;
}

/**
 * Form validation handler for _google_image_sitemap_create_form().
 */
function _google_image_sitemap_create_form_validate($form, &$form_state) {

  // Check for valid url.
  if (!empty($form_state['values']['license']) && !valid_url($form_state['values']['license'], TRUE)) {
    form_set_error('license', t('Lincese should be a valid url.'));
  }

  // Validate range start for integer.
  if (empty($form_state['values']['range_start'])) {
    form_set_error('range_start', t('Range start should be an integer and greater than 0 value.'));
  }

  // Validate range start for integer.
  if (!preg_match("/^([0-9]+)\$/", $form_state['values']['range_start'])) {
    form_set_error('range_start', t('Range start should be an integer.'));
  }

  // Validate range end for integer.
  if (!preg_match("/^([0-9]+)\$/", $form_state['values']['range_end'])) {
    form_set_error('range_end', t('Range end should be an integer value.'));
  }

  // Validate range start and end.
  if ($form_state['values']['range_start'] > $form_state['values']['range_end']) {
    form_set_error('range_start', t('Range start should be less than to Range end.'));
  }

  // Validate range end with datbase.
  $max_nid = db_result(db_query("SELECT MAX(nid) AS max_nid FROM {node} WHERE type = '%s' AND status = %d", $form_state['values']['node_type'], 1));

  // Validate range start and end.
  if ($form_state['values']['range_start'] > $max_nid) {
    form_set_error('range_start', t('Range Start should not be greater than @max_nid (Node ID).', array(
      '@max_nid' => $max_nid,
    )));
  }
  if ($form_state['values']['range_end'] > $max_nid) {
    form_set_error('range_end', t('Range End should not be greater than @max_nid (Node ID).', array(
      '@max_nid' => $max_nid,
    )));
  }
}

/**
 * Form submission handler for _google_image_sitemap_create_form().
 */
function _google_image_sitemap_create_form_submit($form, &$form_state) {
  $sitemap_obj = (object) $form_state['values'];

  // Check for sitemap_id sign.
  if (isset($form_state['values']['storage_sitemap_id']) && is_numeric($form_state['values']['storage_sitemap_id'])) {

    // Update if set.
    $sitemap_obj->sid = $form_state['values']['storage_sitemap_id'];
    drupal_write_record('google_image_sitemap', $sitemap_obj, 'sid');
  }
  else {

    // Insert if not set.
    $sitemap_obj->created = time();
    drupal_write_record('google_image_sitemap', $sitemap_obj);
  }

  // Redirect to main page of sitemap.
  $form_state['redirect'] = isset($_GET['destination']) ? $_GET['destination'] : GOOGLE_IMAGE_SITEMAP_ADMIN_PATH;
}

/**
 * This will delete a sitemap of user.
 */
function _google_image_sitemap_delete_form($sitemap_id) {

  // Validate sitemap_id string.
  if (!empty($sitemap_id) && ($sitemap_obj = _google_image_sitemap_valid_sitemap_id($sitemap_id))) {
    $uri = variable_get('file_directory_path', conf_path() . '/files') . '/google_image_sitemap/sitemap_' . $sitemap_obj->created . '.xml';
    if (file_exists($uri)) {
      file_delete($uri);
    }
    db_query('DELETE FROM {google_image_sitemap} WHERE sid = %d', $sitemap_id);
    drupal_set_message(t("Sitemap deleted successfully!"));
  }
  drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : GOOGLE_IMAGE_SITEMAP_ADMIN_PATH);
}

/**
 * Menu callback for sitemap generate.
 */
function _google_image_sitemap_build($sitemap_id) {
  if (!empty($sitemap_id) && ($sitemap_obj = _google_image_sitemap_valid_sitemap_id($sitemap_id))) {

    // Get records.
    $limit_start = $sitemap_obj->range_start - 1;
    $limit_end = $sitemap_obj->range_end;
    $result = db_query(db_rewrite_sql("SELECT n.nid, n.created, n.title, f.filepath FROM {node} n\n      INNER JOIN {upload} u ON n.nid = u.nid\n      INNER JOIN {files} f ON u.fid = f.fid\n      WHERE n.type = '%s' AND n.status = 1 AND f.filemime IN ('image/png', 'image/jpg', 'image/gif', 'image/jpeg')\n      ORDER BY n.created DESC, f.timestamp DESC LIMIT %d, %d", 'n', 'nid'), $sitemap_obj->node_type, $limit_start, $limit_end);
    while ($row = db_fetch_object($result)) {
      $nodes[] = $row;
    }

    // Create only if images are found.
    if (count($nodes) > 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 ($nodes as $node) {
        $output .= '<url><loc>' . url('node/' . $node->nid, array(
          'absolute' => TRUE,
        )) . '</loc>
                    <image:image>
                      <image:loc>' . file_create_url($node->filepath) . '</image:loc>
                      <image:title>' . check_plain($node->title) . '</image:title>
                      <image:caption>' . check_plain($node->title) . '</image:caption>
                      <image:license>' . check_url($sitemap_obj->license) . '</image:license>
                    </image:image></url>';
      }
      $output .= '</urlset>';

      // File build path.
      $path = file_create_path('google_image_sitemap');
      if (!is_dir($path)) {
        drupal_mkdir($path);
      }
      $filename = 'sitemap_' . $sitemap_obj->created . '.xml';
      if ($file = file_save_data($output, $path . '/' . $filename, FILE_EXISTS_REPLACE)) {
        db_query("UPDATE {google_image_sitemap} SET last_updated = %d WHERE sid = %d", time(), $sitemap_obj->sid);
        drupal_set_message(t("Sitemap created successfully!"));
      }
    }
    else {
      drupal_set_message(t("No Images found!"));
    }
  }
  drupal_goto(isset($_GET['destination']) ? $_GET['destination'] : GOOGLE_IMAGE_SITEMAP_ADMIN_PATH);
}

/**
 * This will check a valid sitemap_id with database table.
 */
function _google_image_sitemap_valid_sitemap_id($sitemap_id) {
  $row = db_fetch_object(db_query("SELECT * FROM {google_image_sitemap} WHERE sid = %d", $sitemap_id));
  if (!empty($row->sid)) {
    return $row;
  }
  else {
    return FALSE;
  }
}

/**
 * Implements hook_node_type_update().
 */
function google_image_sitemap_node_type_update($info) {
  if (!empty($info->old_type) && $info->old_type != $info->type) {
    db_query("UPDATE {google_image_sitemap} SET node_type = '%s' WHERE node_type = '%s'", $info->type, $info->old_type);
  }
}

/**
 * Implements hook_node_type_delete().
 */
function google_image_sitemap_node_type_delete($info) {

  // Node type is being deleted, delete its preferences.
  db_query("DELETE FROM {google_image_sitemap} WHERE node_type = '%s'", $info->type);
}
if (!function_exists('drupal_mkdir')) {

  /**
   * Drupal 7 function drupal_mkdir() ported to drupal 6.
   */
  function drupal_mkdir($uri, $mode = NULL, $recursive = FALSE, $context = NULL) {
    if (!isset($mode)) {
      $mode = variable_get('file_chmod_directory', 0775);
    }
    if (!isset($context)) {
      return mkdir($uri, $mode, $recursive);
    }
    else {
      return mkdir($uri, $mode, $recursive, $context);
    }
  }
}

Functions

Namesort descending Description
google_image_sitemap_menu Implements hook_menu().
google_image_sitemap_node_type_delete Implements hook_node_type_delete().
google_image_sitemap_node_type_update Implements hook_node_type_update().
google_image_sitemap_perm Implements hook_perm().
_google_image_sitemap_build Menu callback for sitemap generate.
_google_image_sitemap_create_form Form builder: Generate a form to add/edit sitemaps.
_google_image_sitemap_create_form_submit Form submission handler for _google_image_sitemap_create_form().
_google_image_sitemap_create_form_validate Form validation handler for _google_image_sitemap_create_form().
_google_image_sitemap_delete_form This will delete a sitemap of user.
_google_image_sitemap_list Menu callback: Displays a list of available sitemaps.
_google_image_sitemap_valid_sitemap_id This will check a valid sitemap_id with database table.

Constants

Namesort descending Description
GOOGLE_IMAGE_SITEMAP_ADMIN_PATH @file A module gives to Google information about images on your site.