<?php

/**
 * @file
 * Install, update, and uninstall functions for Pathauto.
 *
 * @ingroup pathauto
 */

/**
 * Implements hook_schema().
 */
function pathauto_schema() {
  $schema['pathauto_state'] = array(
    'description' => 'The status of each entity alias (whether it was automatically generated or not).',
    'fields' => array(
      'entity_type' => array(
        'type' => 'varchar',
        'length' => 32,
        'not null' => TRUE,
        'description' => 'An entity type.',
      ),
      'entity_id' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'description' => 'An entity ID.',
      ),
      'pathauto' => array(
        'type' => 'int',
        'size' => 'tiny',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The automatic alias status of the entity.',
      ),
    ),
    'primary key' => array('entity_type', 'entity_id'),
  );

  return $schema;
}


/**
 * Implements hook_install().
 */
function pathauto_install() {
  // Set some default variables necessary for the module to perform.
  variable_set('pathauto_node_pattern', 'content/[node:title]');
  variable_set('pathauto_taxonomy_term_pattern', '[term:vocabulary]/[term:name]');
  variable_set('pathauto_forum_pattern', '[term:vocabulary]/[term:name]');
  variable_set('pathauto_user_pattern', 'users/[user:name]');
  variable_set('pathauto_blog_pattern', 'blogs/[user:name]');

  // Set the default separator character to replace instead of remove (default).
  variable_set('pathauto_punctuation_hyphen', 1);

  // Set the weight to 1
  db_update('system')
    ->fields(array('weight' => 1))
    ->condition('type', 'module')
    ->condition('name', 'pathauto')
    ->execute();
}

/**
 * Implements hook_uninstall().
 */
function pathauto_uninstall() {
  // Delete all the pathauto variables and then clear the variable cache.
  db_query("DELETE FROM {variable} WHERE name LIKE 'pathauto_%'");
  cache_clear_all('variables', 'cache');
}

/**
 * Implements hook_requirements().
 */
function pathauto_requirements($phase) {
  $requirements = array();
  $t = get_t();
  if ($phase == 'runtime' && module_exists('pathauto_persist')) {
    $requirements['pathauto'] = array(
      'title' => $t('Pathauto Persist'),
      'value' => $t('Enabled'),
      'description' => $t('Pathauto Persist is installed and enabled. As Pathauto Persist has been merged into Pathauto, the Pathauto Persist module can be safely disabled and removed. All Pathauto Persist settings have been migrated to the Pathauto implementation.'),
      'severity' => REQUIREMENT_INFO,
    );
  }
  return $requirements;
}

/**
 * Remove the unsupported user/%/contact and user/%/tracker pattern variables.
 */
function pathauto_update_6200() {
  variable_del('pathauto_contact_bulkupdate');
  variable_del('pathauto_contact_pattern');
  variable_del('pathauto_contact_supportsfeeds');
  variable_del('pathauto_contact_applytofeeds');
  variable_del('pathauto_tracker_bulkupdate');
  variable_del('pathauto_tracker_pattern');
  variable_del('pathauto_tracker_supportsfeeds');
  variable_del('pathauto_tracker_applytofeeds');
}

/**
 * Empty update since it is handled by pathauto_update_7000().
 */
function pathauto_update_6201() {
}

/**
 * Empty update since it is handled by pathauto_update_7004().
 */
function pathauto_update_6202() {
}

/**
 * Remove obsolete variables since batch API is now used.
 */
function pathauto_update_7000() {
  variable_del('pathauto_max_bulk_update');
  variable_del('pathauto_node_bulkupdate');
  variable_del('pathauto_taxonomy_bulkupdate');
  variable_del('pathauto_forum_bulkupdate');
  variable_del('pathauto_user_bulkupdate');
  variable_del('pathauto_blog_bulkupdate');
  variable_del('pathauto_modulelist');
  variable_del('pathauto_indexaliases');
  variable_del('pathauto_indexaliases_bulkupdate');
}

/**
 * Empty update since feed paths are no longer supported.
 */
function pathauto_update_7001() {
}

/**
 * Update pathauto_taxonomy_[vid]_pattern variables to pathauto_taxonomy_[machinename]_pattern.
 */
function pathauto_update_7002() {
  if (module_exists('taxonomy')) {
    $vocabularies = taxonomy_get_vocabularies();
    foreach ($vocabularies as $vid => $vocabulary) {
      if ($vid == variable_get('forum_nav_vocabulary', '')) {
        // Skip the forum vocabulary.
        continue;
      }
      if ($pattern = variable_get('pathauto_taxonomy_' . $vid . '_pattern', '')) {
        variable_set('pathauto_taxonomy_' . $vocabulary->machine_name . '_pattern', $pattern);
      }
      variable_del('pathauto_taxonomy_' . $vid . '_pattern');
    }
  }
}

/**
 * Rename 'taxonomy' variables to use the entity type 'taxonomy_term'.
 */
function pathauto_update_7003() {
  $variables = db_select('variable', 'v')
    ->fields('v', array('name'))
    ->condition(db_and()
      ->condition('name', db_like("pathauto_taxonomy_") . '%', 'LIKE')
      ->condition('name', db_like("pathauto_taxonomy_term_") . '%', 'NOT LIKE')
    )
    ->execute()
    ->fetchCol();
  foreach ($variables as $variable) {
    $value = variable_get($variable);
    variable_del($variable);
    $variable = strtr($variable, array('pathauto_taxonomy_' => 'pathauto_taxonomy_term_'));
    variable_set($variable, $value);
  }
}

/**
 * Remove obsolete variables for removed feed handling.
 */
function pathauto_update_7004() {
  variable_del('pathauto_node_supportsfeeds');
  variable_del('pathauto_node_applytofeeds');
  variable_del('pathauto_taxonomy_supportsfeeds');
  variable_del('pathauto_taxonomy_applytofeeds');
  variable_del('pathauto_forum_supportsfeeds');
  variable_del('pathauto_forum_applytofeeds');
  variable_del('pathauto_user_supportsfeeds');
  variable_del('pathauto_user_applytofeeds');
  variable_del('pathauto_blog_supportsfeeds');
  variable_del('pathauto_blog_applytofeeds');
}

/**
 * Fix original incorrect tokens in taxonomy and forum patterns.
 */
function pathauto_update_7005() {
  $replacements = array(
    '[vocabulary:name]' => '[term:vocabulary]',
    '[vocabulary:' => '[term:vocabulary:',
    '[term:catpath]' => '[term:name]',
    '[term:path]' => '[term:name]',
  );
  $variables = db_select('variable', 'v')
    ->fields('v', array('name'))
    ->condition(db_or()
      ->condition('name', db_like("pathauto_taxonomy_term_") . '%' . db_like('pattern'), 'LIKE')
      ->condition('name', db_like("pathauto_forum_") . '%' . db_like('pattern'), 'LIKE')
    )
    ->execute()
    ->fetchCol();
  foreach ($variables as $variable) {
    if ($pattern = variable_get($variable)) {
      $pattern = strtr($pattern, $replacements);
      variable_set($variable, $pattern);
    }
  }

  return 'Your Pathauto taxonomy and forum patterns have been corrected. You may wish to regenerate your taxonomy and forum term URL aliases.';
}

/**
 * Create pathauto table, copying data from pathauto_persist if it exists
 */
function pathauto_update_7006() {
  if (!db_table_exists('pathauto_state')) {

    $schema['pathauto_state'] = array(
      'description' => 'The status of each entity alias (whether it was automatically generated or not).',
      'fields' => array(
        'entity_type' => array(
          'type' => 'varchar',
          'length' => 32,
          'not null' => TRUE,
          'description' => 'An entity type.',
        ),
        'entity_id' => array(
          'type' => 'varchar',
          'length' => 255,
          'not null' => TRUE,
          'description' => 'An entity ID.',
        ),
        'pathauto' => array(
          'type' => 'int',
          'size' => 'tiny',
          'not null' => TRUE,
          'default' => 0,
          'description' => 'The automatic alias status of the entity.',
        ),
      ),
      'primary key' => array('entity_type', 'entity_id'),
    );

    if (db_table_exists('pathauto_persist')) {
      // Rename pathauto_persist's table, then create a new empty one just so
      // that we can cleanly disable that module.
      db_rename_table('pathauto_persist', 'pathauto_state');
      db_create_table('pathauto_persist', $schema['pathauto_state']);
      // Change the entity_id column to varchar because the entity system does
      // not assume serial or integer IDs (see [#1823494]).
      db_drop_primary_key('pathauto_state');
      db_change_field('pathauto_state', 'entity_id', 'entity_id',
            array('type' => 'varchar', 'length' => 255, 'not null' => TRUE, 'description' => 'An entity ID.'));
      db_add_primary_key('pathauto_state', array('entity_type', 'entity_id'));
      // Disable the module and inform the user.
      if (module_exists('pathauto_persist')) {
        module_disable(array('pathauto_persist'));
      }
      return t('This version of Pathauto includes the functionality of Pathauto Persist, which has been disabled and can be safely removed. All settings have been copied.');
    }
    else {
      db_create_table('pathauto_state', $schema['pathauto_state']);
    }
  }
}

/**
 * Build a list of Drupal 6 tokens and their Drupal 7 token names.
 */
function _pathauto_upgrade_token_list() {
  $tokens = array(
    //'catpath' => 'node:term-lowest:parent:path][node:term-lowest',
    //'catalias' => 'node:term-lowest:path',
    //'termpath' => 'term:parent:path][term:name',
    //'termalias' => 'term:url:alias',
    //'bookpathalias' => 'node:book:parent:path',
  );
}
