<?php
// $Id: nodewords.install,v 1.10.2.154 2009/12/30 17:38:44 kiam Exp $

/**
 * @file
 * Installation file for Nodewords.
 */

/**
 * Implements hook_requirements().
 */
function nodewords_requirements($phase) {
  $requirements = array();

  if ($phase == 'runtime') {
    drupal_load('module', 'nodewords');

    if (!count(nodewords_get_possible_tags())) {
      $requirements['nodewords'] = array(
        'title' => t('Nodewords'),
        'description' => t('There are no modules that implement meta tags, or that support the current API version.'),
        'severity' => REQUIREMENT_ERROR,
        'value' => t('Check if there are enabled modules listed under the category <em>Meta tags</em> in the <a href="@modules-page">modules page</a>. If nodewords.module is not the only enabled module listed under the category <em>Meta tags</em>, then <a href="@bug-report">file an issue</a>.', array('@modules-page' => url('admin/build/modules'), '@bug-report' => 'http://drupal.org/node/add/project-issue/nodewords?title=There%20are%20no%20modules%20supporting%20the%20current%20API%20version&component=Code&categories=bug&version=212852')),
      );
    }
    elseif (module_exists('nodewords_bypath')) {
      $requirements['nodewords'] = array(
        'title' => t('Nodewords'),
        'description' => t('The feature implemented in <q>Meta Tags by Path</q> is now included in Nodewords; there is not need to use <q>Meta Tags by Path</q>, and the module should be disabled to avoid possible conflicts.'),
        'severity' => REQUIREMENT_ERROR,
        'value' => t('Disable the module in the<a href="@url">modules page</a>.', array('@url' => url('admin/build/modules'))),
      );
    }
  }

  return $requirements;
}

/**
 * Implements hook_schema().
 */
function nodewords_schema() {
  $schema = array();

  $schema['nodewords'] = array(
    'description' => 'The table containing the meta tag values for all the pages.',
    'fields' => array(
      'mtid' => array(
        'description' => 'The primary key.',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'type' => array(
        'description' => 'The type of object to which the meta tag refers (node, user, page, etc...).',
        'type' => 'int',
        'size' => 'small',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'id' => array(
        'description' => 'The object ID.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
      'name' => array(
        'description' => 'The meta tag name.',
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'default' => '',
      ),
      'content' => array(
        'description' => 'The content of the meta tag.',
        'type' => 'text',
        'size' => 'big',
        'not null' => TRUE,
      ),
    ),
    'indexes' => array(
      'nodewords_name' => array(array('name', 6)),
      'nodewords_type_id' => array('type', 'id'),
    ),
    'unique keys' => array(
      'nodewords_type_id_name' => array('type', 'id', 'name'),
    ),
    'primary key' => array('mtid'),
  );

  $schema['nodewords_custom'] = array(
    'description' => 'The table containing data for custom pages.',
    'fields' => array(
      'pid' => array(
        'description' => 'The primary key.',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'name' => array(
        'description' => 'The page name as shown in the list of custom pages.',
        'type' => 'varchar',
        'length' => 60,
        'not null' => TRUE,
        'default' => '',
      ),
      'path' => array(
        'description' => 'The page path.',
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE,
      ),
      'weight' => array(
        'description' => 'The weight of the page.',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
      ),
      'enabled' => array(
        'description' => 'A flag set when the page is enabled.',
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 1,
      ),
    ),
    'primary key' => array('pid'),
  );

  return $schema;
}

/**
 * Implements hook_install().
 */
function nodewords_install() {
  drupal_install_schema('nodewords');
  db_query("UPDATE {system} SET weight = 10 WHERE name = 'nodewords' AND type = 'module'");
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6100() {
  $tags = array(
    'abstract' => 'abstract',
    'copyright' => 'copyright',
    'description' => 'description',
    'geourl' => 'location',
    'keywords' => 'keywords',
    'Revisit-After' => 'revisit-after',
    'robots' => 'robots',
  );
  $ret = array();

  db_change_field($ret, 'nodewords', 'content', 'content',
    array(
      'type' => 'text',
      'size' => 'big',
      'not null' => TRUE,
    )
  );

  $settings = variable_get('nodewords', array());

  // Create the new Drupal variables used for the settings.
  if (isset($settings['global'])) {
    variable_set('nodewords_global', $settings['global']);
  }

  if (!empty($settings['use_teaser'])) {
    variable_set('nodewords_basic_use_teaser', $settings['use_teaser']);
  }

  if (isset($settings['taxonomy']['keyword_vids'])) {
    variable_set('nodewords_keyword_vids', $settings['taxonomy']['keyword_vids']);
  }

  if (isset($settings['edit'])) {
    $new_tags = array();

    foreach ($tags as $old_tag => $new_tag) {
      if (!empty($settings['edit'][$old_tag])) {
        $new_tags[$new_tag] = $new_tag;
      }
    }

    variable_set('nodewords_edit', $new_tags);
  }

  if (isset($settings['head'])) {
    $new_tags = array();

    foreach ($tags as $old_tag => $new_tag) {
      if (!empty($settings['head'][$old_tag])) {
        $new_tags[$new_tag] = $new_tag;
      }
    }

    variable_set('nodewords_head', $new_tags);
  }

  if (!empty($settings['advanced']['enable_user_metatags'])) {
    variable_set('nodewords_enable_user_metatags', $settings['advanced']['enable_user_metatags']);
  }

  if (!empty($settings['advanced']['repeat'])) {
    variable_set('nodewords_list_repeat', $settings['advanced']['repeat']);
  }

  if (!empty($settings['advanced']['use_front_page_tags'])) {
    variable_set('nodewords_use_frontpage_tags', $settings['advanced']['use_front_page_tags']);
  }

  if (!empty($settings['advanced']['max_size'])) {
    variable_set('nodewords_max_size', $settings['advanced']['max_size']);
  }

  if (!empty($settings['advanced']['use_alt_tags'])) {
    variable_set('nodewords_use_alt_attribute', $settings['advanced']['use_alt_tags']);
  }

  // Delete the old Drupal variable used.

  $ret[] = array(
    'success' => TRUE,
    'query' => 'Created new setting variables',
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6102() {
  $metatags = array();
  $ret = array();
  $settings = variable_get('nodewords_global', array());

  drupal_load('module', 'nodewords');
  if (empty($settings['geourl'])) {
    $coordinates = array(0, 0);
  }
  else {
    $coordinates = array_map('trim', explode(',', $settings['geourl']));
    $coordinates[] = 0;
    $coordinates[] = 0;
    $coordinates = array_splice($coordinates, 0, 2);
  }

  $metatags['copyright'] = empty($settings['copyright']) ? '' : $settings['copyright'];
  $metatags['geourl'] = $coordinates[0] . ',' . $coordinates[1];
  $metatags['keywords'] = empty($settings['keywords']) ? '' : nodewords_unique($settings['keywords']);
  $metatags['robots'] = empty($settings['robots']) ? '' : $settings['robots'];

  foreach ($metatags as $name => $content) {
    $result = db_result(
      db_query(
        "SELECT 1 FROM {nodewords} WHERE type = 'default' AND id = '' AND name = '%s'",
        $name
      )
    );

    if ($result) {
      $ret[] = update_sql(
        "UPDATE {nodewords} SET content = '" . db_escape_string($content) .
        "' WHERE type = 'default' AND id = '' AND name = '" .
        db_escape_string($name) . "'"
      );
    }
    else {
      $ret[] = update_sql(
        "INSERT INTO {nodewords} (type, id, name, content) VALUES ('default', '', '" .
        db_escape_string($name) . "', '" .
        db_escape_string($content) ."')"
      );
    }
  }

  $ret[] = array(
    'success' => TRUE,
    'query' => check_plain('The default meta tags values have been updated; verify they have the correct values at ' . url('admin/content/nodewords/meta-tags/default', array('absolute' => TRUE))),
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6103() {
  $ret = array();

  $ret[] = update_sql("UPDATE {nodewords} SET name = 'revisit-after' WHERE name = 'Revisit-After'");
  $ret[] = update_sql("UPDATE {nodewords} SET name = 'dc.title' WHERE name = 'DC.Title'");
  $ret[] = update_sql("UPDATE {nodewords} SET type = 'frontpage' WHERE type = 'page' AND id = ''");

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6104() {
  $ret = array();

  $head_tags = variable_get('nodewords_head', array());
  array_change_key_case($head_tags);

  if (isset($head_tags['geourl'])) {
    $head_tags['location'] = $head_tags['geourl'];
    unset($head_tags['geourl']);
  }

  variable_set('nodewords_head', $head_tags);

  $edit_tags = variable_get('nodewords_edit', array());

  if (isset($edit_tags['geourl'])) {
    $edit_tags['location'] = $edit_tags['geourl'];
    unset($edit_tags['geourl']);
    variable_set('nodewords_edit', $edit_tags);
  }

  $ret[] = array(
    'success' => TRUE,
    'query' => 'Updated the module settings',
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6106() {
  $ret = array();

  $ret[] = update_sql("UPDATE {nodewords} SET name = 'location' WHERE name = 'geourl'");

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6113(&$sandbox) {
  $ret = array();

  if (!isset($sandbox['progress'])) {
    if (db_table_exists('nodewords_tmp')) {
      db_drop_table($ret, 'nodewords_tmp');
    }

    db_rename_table($ret, 'nodewords', 'nodewords_tmp');

    $sandbox['progress'] = 0;
    $sandbox['max'] = db_result(db_query("SELECT COUNT(*) FROM {nodewords_tmp}"));

    $schema['nodewords'] = array(
      'fields' => array(
        'mtid' => array(
          'type' => 'serial',
          'not null' => TRUE,
        ),
        'type' => array(
          'type' => 'varchar',
          'length' => 16,
          'not null' => TRUE,
          'default' => '',
        ),
        'id' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'default' => '',
        ),
        'name' => array(
          'type' => 'varchar',
          'length' => 32,
          'not null' => TRUE,
          'default' => '',
        ),
        'content' => array(
          'type' => 'text',
          'size' => 'big',
          'not null' => TRUE,
        ),
      ),
      'indexes' => array(
        'nodewords_id' => array(array('id', 6)),
        'nodewords_type' => array(array('type', 6)),
      ),
      'unique keys' => array(
        'tin' => array('type', 'id', 'name'),
      ),
      'primary key' => array('mtid'),
    );

    db_create_table($ret, 'nodewords', $schema['nodewords']);
  }

  if ($sandbox['max']) {
    $metatags = db_query_range("SELECT * FROM {nodewords_tmp}", $sandbox['progress'], 10);

    while ($metatag = db_fetch_object($metatags)) {
      switch ($metatag->name) {
        case 'location':
          if (empty($metatag->content)) {
            $metatag->content = serialize(
              array(
                'latitude' => 0,
                'longitude' => 0,
              )
            );
          }
          else {
            $coordinates = array_map('trim', explode(',', $metatag->content));
            $coordinates[] = 0;
            $coordinates[] = 0;
            $coordinates = array_splice($coordinates, 0, 2);

            $metatag->content = serialize(
              array(
                'latitude' => $coordinates[0],
                'longitude' => $coordinates[1],
              )
            );
          }
          break;

        case 'robots':
          if (empty($metatag->content)) {
            $metatag->content = serialize(
              array(
                'value' => array(),
              )
            );
          }
          else {
            $content = array_map('trim', explode(',', $metatag->content));
            $new_content = array(
             'noarchive' => 0,
             'nofollow' => in_array('nofollow', $content) ? 'nofollow' : 0,
             'noindex' => in_array('noindex', $content) ? 'noindex' : 0,
             'noodp' => 0,
             'nosnippet' => 0,
             'noydir' => 0,
            );

            $metatag->content = serialize($new_content);
          }
          break;
      }

      db_query(
        "INSERT INTO {nodewords} (type, id, name, content) VALUES ('%s', '%s', '%s', '%s')",
        $metatag->type,
        $metatag->id,
        $metatag->name,
        $metatag->content
      );

      $sandbox['progress']++;
    }
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  if ($ret['#finished'] == 1) {
    db_drop_table($ret, 'nodewords_tmp');

    variable_set('nodewords_update_6113', TRUE);
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6115() {
  $ret = array();

  if (db_column_exists('nodewords', 'weight')) {
    db_drop_field($ret, 'nodewords', 'weight');
  }

  if (!db_table_exists('nodewords_custom')) {
    db_create_table($ret, 'nodewords_custom',
      array(
        'fields' => array(
          'pid' => array(
            'type' => 'serial',
            'not null' => TRUE,
          ),
          'path' => array(
            'type' => 'varchar',
            'length' => 255,
            'not null' => TRUE,
            'default' => '',
          ),
          'weight' => array(
            'type' => 'int',
            'size' => 'tiny',
            'not null' => TRUE,
            'default' => 0,
          ),
          'enabled' => array(
            'type' => 'int',
            'size' => 'tiny',
            'not null' => TRUE,
            'default' => 1,
          ),
        ),
        'primary key' => array('pid'),
        'unique keys' => array(
          'path' => array('path'),
        ),
      )
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6117() {
  $ret[] = update_sql("DELETE FROM {nodewords} WHERE type IN ('views', 'panels')");

  if (db_affected_rows()) {
    $ret[] = array(
      'success' => TRUE,
      'query' => check_plain('The support for Views, and Panels have been changed; visit '. url('admin/content/nodewords/meta-tags/other', array('absolute' => TRUE)) . ' to edit the meta tags for those pages'),
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6120() {
  $ret = array();

  db_drop_unique_key($ret, 'nodewords', 'tin');

  db_change_field($ret, 'nodewords', 'type', 'type',
    array(
      'type' => 'varchar',
      'length' => 16,
      'not null' => TRUE,
      'default' => '',
    )
  );

  db_change_field($ret, 'nodewords', 'id', 'id',
    array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => '',
    )
  );

  db_change_field($ret, 'nodewords', 'name', 'name',
    array(
      'type' => 'varchar',
      'length' => 32,
      'not null' => TRUE,
      'default' => '',
    )
  );

  db_add_unique_key($ret, 'nodewords', 'tin', array('type', 'id', 'name'));

  db_drop_unique_key($ret, 'nodewords_custom', 'path');

  db_change_field($ret, 'nodewords_custom', 'path', 'path',
    array(
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => '',
    )
  );

  db_add_unique_key($ret, 'nodewords_custom', 'path', array('path'));

  db_change_field($ret, 'nodewords_custom', 'weight', 'weight',
    array(
      'type' => 'int',
      'size' => 'tiny',
      'not null' => TRUE,
      'default' => 0,
    )
  );

  if (!db_column_exists('nodewords_custom', 'enabled')) {
    db_add_field($ret, 'nodewords_custom', 'enabled',
      array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 1,
      )
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6122() {
  $ret = array();
  $ret[] = update_sql("UPDATE {nodewords_custom} SET weight = 10 WHERE weight > 10");
  $ret[] = update_sql("UPDATE {nodewords_custom} SET weight = -10 WHERE weight < -10");

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6128() {
  $ret = array();
  $ret[] = update_sql("DELETE FROM {nodewords} WHERE type = 'offline'");

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6131() {
  $result = db_query("SELECT name FROM {variable} WHERE name LIKE 'basic\_metatags\_%'");
  $ret = array();

  while ($row = db_fetch_object($result)) {
    $value = variable_get($row->name, NULL);

    if (isset($value)) {
      variable_set(
        str_replace('basic_metatags_', 'nodewords_basic', $row->name),
        $value
      );
      variable_del($row->name);
    }
  }

  $ret[] = array(
    'success' => TRUE,
    'query' => 'Updated the module settings',
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6135() {
  $ret = array();

  if (db_table_exists('cache_nodewords')) {
    db_drop_table($ret, 'cache_nodewords');
  }

  return $ret;
}


/**
 * Implements hook_update_N().
 */
function nodewords_update_6136() {
  $ret = array();

  if (module_exists('nodewords')) {
    $tags = array(
      'nodewords_basic' => array(
        'abstract',
        'canonical',
        'copyright',
        'description',
        'keywords',
        'revisit-after',
        'robots'
      ),
      'nodewords_extra' => array(
        'dc.contributor',
        'dc.creator',
        'dc.date',
        'dc.publisher',
        'dc.title',
        'geourl',
        'location',
        'pics-label',
      ),
      'nodewords_verification_tags' => array(
        'bing_webmaster_center',
        'google_webmaster_tools',
        'yahoo_site_explorer',
      ),
    );

    foreach ($tags as $module => $module_tags) {
      $bool = (
        db_result(
          db_query(
            "SELECT COUNT(1) FROM {nodewords} WHERE name IN (" . db_placeholders($module_tags, 'varchar') . ")",
            $module_tags
          )
        )
      );

      if ($bool) {
        module_enable(array($module));
        $ret[] = array(
          'success' => TRUE,
          'query' => "UPDATE {system} SET status = 1 WHERE type = 'module' AND name = '$module'",
        );
      }
    }
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6137() {
  $ret = array();

  if (!variable_get('nodewords_update_6113', FALSE)) {
    db_add_index($ret, 'nodewords', 'nodewords_id', array(array('id', 6)));
    db_add_index($ret, 'nodewords', 'nodewords_type', array(array('type', 6)));
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6140() {
  $node_types = array_keys(node_get_types('names'));
  $ret = array();

  foreach ($node_types as $node_type) {
    $value = variable_get('nodewords_basic_user_teaser_' . $node_type, NULL);
    if (isset($value)) {
      variable_set('nodewords_basic_use_teaser_' . $node_type, $value);
    }
  }

  $ret[] = array(
    'success' => TRUE,
    'query' => 'Updated the module settings',
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6141() {
  $ret = array();

  if (db_table_exists('nodewords_10')) {
    db_drop_table($ret, 'nodewords_10');
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6143() {
  $ret = array();

  // Only update if the setting have the default value, and if it has been
  // previously set.
  $value = variable_get('nodewords_max_size', NULL);

  if (isset($value) && $value == 255) {
    variable_set('nodewords_max_size', 350);

    $ret[] = array(
      'success' => TRUE,
      'query' => check_plain('The default maximum meta tags length has been extended to 350 characters to improve Google results pages. See http://googleblog.blogspot.com/2009/03/two-new-improvements-to-google-results.html for more information'),
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6144() {
  $ret = array();

  if (!variable_get('menu_rebuild_needed', FALSE)) {
    variable_set('menu_rebuild_needed', TRUE);

    $ret[] = array(
      'success' => TRUE,
      'query' => 'Updated the menu callback definitions',
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6145() {
  $ret = array();

  db_drop_unique_key($ret, 'nodewords', 'tin');
  db_drop_index($ret, 'nodewords', 'nodewords_id');
  db_drop_index($ret, 'nodewords', 'nodewords_type');

  db_add_field($ret, 'nodewords', 'language',
    array(
      'type' => 'varchar',
      'length' => 12,
      'not null' => TRUE,
      'default' => '',
    )
  );

  db_add_index($ret, 'nodewords', 'nodewords_lang', array(array('language', 6)));
  db_add_index($ret, 'nodewords', 'nodewords_name', array(array('name', 6)));
  db_add_index($ret, 'nodewords', 'nodewords_type_id',
    array(
      array('type', 6),
      array('id', 6),
    )
  );

  db_add_unique_key($ret, 'nodewords', 'nodewords_type_id_name_lang',
    array(
      'type',
      'id',
      'name',
      'language'
    )
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6146() {
  $ret = array();

  drupal_load('module', 'nodewords');

  $content = db_result(
    db_query(
      "SELECT content FROM {nodewords} WHERE type = '%s' AND id = '' AND name = 'robots'",
      NODEWORDS_TYPE_PAGER
    )
  );

  if ($content !== FALSE) {
    variable_set('nodewords_list_robots', unserialize($content));

    $ret[] = array(
      'success' => TRUE,
      'query' => 'The previous value for the meta tag ROBOTS used in list pages has been restored; check if it is the desired value',
    );
  }

  $ret[] = update_sql("DELETE FROM {nodewords} WHERE type = '" . NODEWORDS_TYPE_PAGER . "'");

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6147() {
  $ret = array();

  if (db_column_exists('nodewords', 'language')) {
    db_drop_unique_key($ret, 'nodewords', 'nodewords_type_id_name_lang');
    db_drop_index($ret, 'nodewords', 'nodewords_lang');

    db_drop_field($ret, 'nodewords', 'language');
  }

  db_add_unique_key($ret, 'nodewords', 'nodewords_type_id_name',
    array(
      'type',
      'id',
      'name',
    )
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6149() {
  $ret = array();

  $value = variable_get('nodewords_basic_use_alt_attribute', NULL);
  if (isset($value)) {
    variable_set('nodewords_use_alt_attribute', $value);
    variable_del('nodewords_basic_use_alt_attribute');
  }

  $ret[] = array(
    'success' => TRUE,
    'query' => 'Updated the module settings',
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6150() {
  $ret = array();

  if (!db_column_exists('nodewords_custom', 'name')) {
    db_add_field($ret, 'nodewords_custom', 'name',
      array(
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE,
      )
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6151(&$sandbox) {
  $ret = array();

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['max'] = db_result(db_query("SELECT COUNT(*) FROM {nodewords_custom} WHERE name = ''"));
  }

  if ($sandbox['max']) {
    $pages = db_query_range("SELECT * FROM {nodewords_custom} WHERE name = '' ORDER BY pid ASC", $sandbox['progress'], 10);

    while ($page = db_fetch_object($pages)) {
      db_query(
        "UPDATE {nodewords_custom} SET name = '%s' WHERE pid = %d",
        "Custom page #{$sandbox['progress']}", $page->pid
      );

      $sandbox['progress']++;
    }
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6153() {
  $ret = array();

  $schema['nodewords_custom'] = array(
    'fields' => array(
      'pid' => array(
        'description' => 'The primary key.',
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
      ),
      'path' => array(
        'type' => 'text',
        'size' => 'medium',
        'not null' => TRUE,
      ),
      'weight' => array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
      ),
      'enabled' => array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 1,
      ),
    ),
    'primary key' => array('pid'),
  );

  if (db_table_exists('nodewords_custom')) {
    db_drop_unique_key($ret, 'nodewords_custom', 'path');
  }
  else {
    db_create_table($ret, 'nodewords_custom', $schema['nodewords_custom']);
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6154() {
  $ret = array();

  db_change_field($ret, 'nodewords_custom', 'name', 'name',
    array(
      'type' => 'varchar',
      'length' => 60,
      'not null' => TRUE,
      'default' => '',
    )
  );

  db_change_field($ret, 'nodewords_custom', 'path', 'path',
    array(
      'type' => 'text',
      'size' => 'medium',
      'not null' => TRUE,
    )
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6158(&$sandbox) {
  $names = array('dc.date', 'location', 'robots');
  $ret = array();

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['max'] = (int) db_result(db_query("SELECT COUNT(*) FROM {nodewords}"));
    $sandbox['current_mtid'] = 0;
  }

  if ($sandbox['max']) {
    $metatags = db_query_range("SELECT * FROM {nodewords} WHERE mtid > %d ORDER BY mtid ASC", $sandbox['current_mtid'], 0, 20);

    while ($metatag = db_fetch_object($metatags)) {
      if (!in_array($metatag->name, $names)) {
        // Verify if the meta tag content has been already serialized, and
        // serialize it if it is not.
        // The error is being suppressed because if unserialize() returns an error,
        // then the passed value has not been serialiazed.
        if (@unserialize($metatag->content) === FALSE) {
          $content = serialize(array('value' => $metatag->content));

          db_query(
            "UPDATE {nodewords} SET content = '%s' WHERE mtid = %d",
            $content, $metatag->mtid
          );
        }
      }

      $sandbox['current_mtid'] = $metatag->mtid;
      $sandbox['progress']++;
    }
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  if ($ret['#finished'] == 1) {
    variable_set('nodewords_update_6156', TRUE);
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6159(&$sandbox) {
  $ret = array();

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['max'] = (int) db_result(db_query("SELECT COUNT(*) FROM {nodewords} WHERE name = 'robots'"));
    $sandbox['current_mtid'] = 0;
  }

  if ($sandbox['max']) {
    $metatags = db_query_range("SELECT * FROM {nodewords} WHERE name = 'robots' AND mtid > %d ORDER BY mtid ASC", $sandbox['current_mtid'], 0, 20);

    while ($metatag = db_fetch_object($metatags)) {
      // The errors are suppressed to allow the update function to fix as
      // much rows as possible; if the call to unserialize returns an error,
      // then the content of that row is possibly corrupted.
      if (($content = @unserialize($metatag->content)) !== FALSE) {
        if (isset($content['value'])) {
          if (($value = @unserialize($content['value'])) !== FALSE) {
            db_query(
              "UPDATE {nodewords} SET content = '%s' WHERE mtid = %d",
              serialize($value), $metatag->mtid
            );
          }
        }
      }

      $sandbox['current_mtid'] = $metatag->mtid;
      $sandbox['progress']++;
    }
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  if ($ret['#finished'] == 1) {
    variable_set('nodewords_update_6159', TRUE);

    $ret[] = array(
      'success' => TRUE,
      'query' => 'Corrected the values saved in the database',
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6160(&$sandbox) {
  $ret = array();

  drupal_load('module', 'nodewords');

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
  }

  $old_types = array(
    'default',
    'errorpage',
    'frontpage',
    'node',
    'page',
    'pager',
    'term',
    'tracker',
    'user',
    'vocabulary',
  );

  $new_types = array(
    NODEWORDS_TYPE_DEFAULT,
    NODEWORDS_TYPE_ERRORPAGE,
    NODEWORDS_TYPE_FRONTPAGE,
    NODEWORDS_TYPE_NODE,
    NODEWORDS_TYPE_PAGE,
    NODEWORDS_TYPE_PAGER,
    NODEWORDS_TYPE_TERM,
    NODEWORDS_TYPE_TRACKER,
    NODEWORDS_TYPE_USER,
    NODEWORDS_TYPE_VOCABULARY,
  );

  $ret[] = update_sql(
    "UPDATE {nodewords} SET type = " . $new_types[$sandbox['progress']] . " WHERE type = '" . $old_types[$sandbox['progress']++] . "'"
  );

  $ret['#finished'] = ($sandbox['progress'] / 10);

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6161(&$sandbox) {
  $ret = array();

  drupal_load('module', 'nodewords');

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    $sandbox['max'] = db_result(
      db_query("SELECT COUNT(*) FROM {nodewords_custom}")
    );
    $sandbox['current_pid'] = 0;
  }

  if ($sandbox['max']) {
    $metatags = db_query_range(
      "SELECT * FROM {nodewords_custom} WHERE pid > %d",
      $sandbox['current_pid'], 0, 10
    );

    while ($metatag = db_fetch_object($metatags)) {
      $ret[] = update_sql("UPDATE {nodewords} SET id = " . $metatag->pid . " WHERE id = '" . db_escape_string(drupal_truncate_bytes($metatag->path, 255)) . "'");
      $sandbox['current_pid'] = $metatag->pid;
      $sandbox['progress']++;
    }
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);

  if ($ret['#finished'] == 1) {
    $ret[] = array(
      'success' => TRUE,
      'query' => 'Corrected the values saved in the database',
    );
  }

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6162() {
  $ret = array();

  db_drop_index($ret, 'nodewords', 'nodewords_type_id');
  db_drop_unique_key($ret, 'nodewords', 'nodewords_type_id_name');

  db_change_field($ret, 'nodewords', 'type', 'type',
    array(
      'type' => 'int',
      'size' => 'small',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
    )
  );

  db_change_field($ret, 'nodewords', 'id', 'id',
    array(
      'type' => 'int',
      'size' => 'small',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
    )
  );

  db_add_index($ret, 'nodewords', 'nodewords_type_id',
    array('type', 'id')
  );
  db_add_unique_key($ret, 'nodewords', 'nodewords_type_id_name',
    array('type', 'id', 'name')
  );

  variable_set('nodewords_update_6162', TRUE);

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6164() {
  $node_types = array_keys(node_get_types('names'));
  $ret = array();

  $value = variable_get('nodewords_basic_use_teaser', NULL);
  if (isset($value)) {
    variable_set('nodewords_use_teaser', $value);
  }

  $value = variable_get('nodewords_basic_user_teaser', NULL);
  if (isset($value)) {
    variable_set('nodewords_user_teaser', $value);
  }

  foreach ($node_types as $node_type) {
    $value = variable_get('nodewords_basic_use_teaser_' . $node_type, NULL);
    if (isset($value)) {
      variable_set('nodewords_use_teaser_' . $node_type, $value);
      variable_del('nodewords_basic_use_teaser_' . $node_type);
    }

    $value = variable_get('nodewords_basic_user_teaser_' . $node_type, NULL);
    if (isset($value)) {
      variable_del('nodewords_basic_user_teaser_' . $node_type);
    }
  }

  $value = variable_get('nodewords_use_teaser', NULL);
  if (isset($value) && $value) {
    variable_set('metatags_generation_method', 2);
  }

  variable_set('nodewords_6164', TRUE);

  $ret[] = array(
    'success' => TRUE,
    'query' => 'Updated the module settings',
  );

  return $ret;
}

/**
 * Implements hook_update_N().
 */
function nodewords_update_6167() {
  $ret = array();

  $ret[] = update_sql('DELETE FROM {nodewords} WHERE type = 0');
  variable_set('nodewords_update_6166', TRUE);

  return $ret;
}

/**
 * Implements hook_uninstall().
 */
function nodewords_uninstall() {
  drupal_uninstall_schema('nodewords');

  variable_del('nodewords');
  variable_del('nodewords-repeat');
  variable_del('nodewords-use_front');
  variable_del('nodewords_base_url');
  variable_del('nodewords_metatags_generation_method');
  variable_del('nodewords_metatags_generation_source');
  variable_del('nodewords_collapse_fieldset');
  variable_del('nodewords_edit');
  variable_del('nodewords_enable_user_metatags');
  variable_del('nodewords_global');
  variable_del('nodewords_global_keywords');
  variable_del('nodewords_head');
  variable_del('nodewords_icra_validation_content');
  variable_del('nodewords_keyword_vids');
  variable_del('nodewords_list_repeat');
  variable_del('nodewords_list_robots');
  variable_del('nodewords_max_size');
  variable_del('nodewords_update_6113');
  variable_del('nodewords_update_6139');
  variable_del('nodewords_update_6145');
  variable_del('nodewords_update_6147');
  variable_del('nodewords_update_6156');
  variable_del('nodewords_update_6159');
  variable_del('nodewords_update_6162');
  variable_del('nodewords_update_6163');
  variable_del('nodewords_update_6164');
  variable_del('nodewords_update_6166');
  variable_del('nodewords_use_alt_attribute');
  variable_del('nodewords_use_frontpage_tags');
  variable_del('nodewords_use_teaser');

  $node_types = array_keys(node_get_types('names'));
  $variables = array(
    'nodewords_metatags_generation_method_',
    'nodewords_metatags_generation_source_',
    'nodewords_edit_metatags_',
    'nodewords_filter_modules_output_',
    'nodewords_filter_regexp_',
    'nodewords_use_teaser_',
  );

  foreach ($node_types as $node_type) {
    foreach ($variables as $variable) {
      variable_del($variable . $node_type);
    }
  }
}
