<?php

/**
 * @file
 * Install, update and uninstall functions for the nodequeue module.
 */

/**
 * Implements hook_schema().
 */
function nodequeue_schema() {
  $schema['nodequeue_queue'] = array(
    'description' => 'Base table for queues, storing global information for each queue',
    'fields' => array(
      'qid' => array(
        'description' => 'The primary identifier for a queue.',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'name' => array(
        'description' => 'The machine name for the queue.',
        'type' => 'varchar',
        'length' => 128,
      ),
      'title' => array(
        'description' => 'Title of a queue.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'subqueue_title' => array(
        'description' => 'Title of a subqueue.',
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
      ),
      'size' => array(
        'description' => 'How many nodes this queue will hold',
        'type' => 'int',
        'default' => 0,
      ),
      'link' => array(
        'description' => 'The link text to show under a node to add it to the queue.',
        'type' => 'varchar',
        'length' => 40,
      ),
      'link_remove' => array(
        'description' => 'The link text to show under a node to remove it from the queue.',
        'type' => 'varchar',
        'length' => 40,
      ),
      'owner' => array(
        'description' => '',
        'type' => 'varchar',
        'length' => 255,
      ),
      'show_in_ui' => array(
        'description' => '',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
      ),
      'show_in_tab' => array(
        'description' => '',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
      ),
      'show_in_links' => array(
        'description' => '',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
      ),
      'reference' => array(
        'description' => '',
        'type' => 'varchar',
        'length' => 255,
        'default' => '0',
      ),
      'reverse' => array(
        'description' => '',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 0,
      ),
      'insert_at_front' => array(
        'description' => '',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 0,
      ),
      'i18n' => array(
        'description' => '',
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
      ),
    ), // fields
    'primary key' => array('qid'),
    'unique keys' => array(
      'name' => array('name'),
    ),
  ); // nodequeue_queue.
  $schema['nodequeue_roles'] = array(
    'description' => 'Defines the roles which are allowed to use a particular nodequeue.',
    'fields' => array(
      'qid' => array(
        'description' => 'Primary key for {nodequeue_queue}',
        'type' => 'int',
        'size' => 'big',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'rid' => array(
        'description' => 'Primary key for roles',
        'type' => 'int',
        'size' => 'big',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
    ), // fields
    'indexes' => array(
      'qid' => array('qid'),
      'rid' => array('rid'),
    ), // indexes
  ); // nodequeue_roles
  $schema['nodequeue_types'] = array(
    'description' => 'Defines the node types which are allowed in each queue',
    'fields' => array(
      'qid' => array(
        'description' => 'Primary key for {nodequeue_queue}',
        'type' => 'int',
        'size' => 'big',
        'unsigned' => TRUE,
        'not null' => TRUE
      ),
      'type' => array(
        'description' => 'Node Type',
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE
      ),
    ), // fields
    'indexes' => array(
      'qid' => array('qid'),
      'type' => array('type'),
    ), // indexes
  ); // nodequeue_types

  // Subqueues are minor queues that inherit all of the properties of
  // the parent queue. A parent queue must have at least 1 subqueue
  // to do anything. Reference is for the use of whatever is creating
  // the subqueues in order to link it to some other ID easily.
  $schema['nodequeue_subqueue'] = array(
    'description' => 'Subqueues are minor queues that inherit all of the properties of the parent queue. A parent queue must have at least 1 subqueue to do anything. Reference is for the use of whatever is creating the subqueues in order to link it to some other ID easily.',
    'fields' => array(
      'sqid' => array(
        'description' => 'Subqueue identifier',
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'qid' => array(
        'description' => 'Queue identifier.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'reference' => array(
        'description' => '',
        'type' => 'varchar',
        'length' => 255,
        'default' => '0',
        'not null' => FALSE
      ),
      'title' => array(
        'description' => '',
        'type' => 'varchar',
        'length' => 255,
        'default' => '',
        'not null' => FALSE
      ),
    ), // fields
    'primary key' => array('sqid'),
    'indexes' => array(
      'qid' => array('qid'),
      'reference' => array('reference'),
      'title' => array('title'),
    ), // indexes
  ); // nodequeue_subqueue

  $schema['nodequeue_nodes'] = array(
    'description' => 'Indicates which nodes are in which queues/subqueues.',
    'fields' => array(
      'qid' => array(
        'description' => 'Queue id',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'sqid' => array(
        'description' => 'Subqueue this node is in',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
      ),
      'nid' => array(
        'description' => 'Node id in this subqueue',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE
      ),
      'position' => array(
        'description' => 'The position of the node in this subqueue.',
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => FALSE
      ),
      'timestamp' => array(
        'description' => "The time that the item's position in the subqueue was updated.",
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
      ),
    ), // fields
    'indexes' => array(
      'sqid' => array('sqid', 'position'),
      'nid' => array('nid'),
      'qid_nid' => array('qid', 'nid'),
    ), // indexes
  ); // nodequeue_nodes

  return $schema;
}

/**
 * Implements hook_uninstall().
 */
function nodequeue_uninstall() {
  // Remove our variables.
  $variables = array(
    'nodequeue_use_tab',
    'nodequeue_tab_display_max',
    'nodequeue_tab_name',
    'nodequeue_autocomplete_limit',
    'nodequeue_view_per_queue',
  );
  foreach ($variables as $variable) {
    variable_del($variable);
  }
}

/**
 * There was a discrepancy between the link/link_remove fields created with
 * node_install/node_schema, and the ones created with nodequeue_update_5000.
 * This forces everyone to 40 characters.
 */
function nodequeue_update_6000() {
  $ret = array();
  db_change_field('nodequeue_queue', 'link', 'link', array('type' => 'varchar', 'length' => 40));
  db_change_field('nodequeue_queue', 'link_remove', 'link_remove', array('type' => 'varchar', 'length' => 40));
  return $ret;
}

/**
 * @todo Please insert a Doxygen style comment for this hook_update_N.
 */
function nodequeue_update_6001() {
  $ret = array();
  db_add_field('nodequeue_queue', 'i18n', array('description' => '', 'type' => 'int', 'size' => 'tiny', 'default' => 1));
  return $ret;
}

// The previous 6002 update has been moved to 5205.

/**
 * Remove invalid entries from the nodequeue_nodes table created as a result of
 * bugs like http://drupal.org/node/593858.
 */
function nodequeue_update_6003() {
  $ret = array();
  $invalid = db_query("SELECT count(nid) FROM {nodequeue_nodes} WHERE nid = 0")->fetchField();
  if (!empty($invalid)) {
    db_delete('nodequeue_nodes')
    ->condition('nid', 0)
    ->execute();
    $t = get_t();
    $ret[] = array('success' => TRUE, 'query' => $t("Deleted @invalid invalid entries from the {nodequeue_nodes} table.", array('@invalid' => $invalid)));
  }
  else {
    $ret[] = array('success' => TRUE, 'query' => "No invalid entries found in the {nodequeue_nodes} table.");
  }
  return $ret;
}

/**
 * Add a new index to {nodequeue_nodes}
 */
function nodequeue_update_6004() {
  $ret = array();
  db_add_index('nodequeue_nodes', '{nodequeue_nodes}_qid_nid_idx', array('qid', 'nid'));
  return $ret;
}

/**
 * Rename the 'nodequeue_automatic_views_generation'
 * to 'nodequeue_view_per_queue'.
 */
function nodequeue_update_6005() {
  $ret = array();
  $ret[] = update_sql("UPDATE {system} set name = 'nodequeue_view_per_queue' where name = 'nodequeue_automatic_views_generation'");
  return $ret;
}

/**
 * Renaming indices so that they're consistent with what Schema module would
 * expect.
 */
function nodequeue_update_7200() {
  // Check if the indices weren't already renamed by a 6.x-2.x-dev version
  // prior to 6.x-2.10.
  if (!db_index_exists('nodequeue_nodes', 'sqid')) {
    // Delete existing indexes
    $del_indices = array(
      'nodequeue_roles' => array('qid', 'rid'),
      'nodequeue_types' => array('qid', 'type'),
      'nodequeue_subqueue' => array('qid', 'reference', 'title'),
      'nodequeue_nodes' => array('sqid', 'qid_nid'),
    );
    foreach ($del_indices as $table => $indices) {
      foreach ($indices as $k => $index) {
        db_drop_index($table, $table . "_" . $index . "_idx");
      }
    }
    // Naming convention incorrect for this one
    db_drop_index("nodequeue_nodes", "nodequeue_subqueue_nid_idx");

    // Create new indexes
    $add_indexes = array(
       'nodequeue_roles' => array(
         'qid' => array('qid'),
         'rid' => array('rid'),
       ),
       'nodequeue_types' => array(
         'qid' => array('qid'),
         'type' => array('type'),
       ),
       'nodequeue_subqueue' => array(
         'qid' => array('qid'),
         'reference' => array('reference'),
         'title' => array('title'),
       ),
       'nodequeue_nodes' => array(
         'sqid' => array('sqid', 'position'),
         'qid_nid' => array('qid', 'nid'),
         'nid' => array('nid'),
       ),
    );
    foreach ($add_indexes as $table => $indices) {
      foreach ($indices as $name => $columns) {
        db_add_index($table, $name, $columns);
      }
    }
  }
}

/**
 * Provide machine names and auto-generation of machine names for existing
 * queues.
 */
function nodequeue_update_7201() {
  // Check that the name field hasn't been created by a 6.x-2.x-dev version
  // prior to 6.x-2.10.
  if (!db_field_exists('nodequeue_queue', 'name')) {
    $name_field = array(
      'description' => 'The machine name for the queue.',
      'type' => 'varchar',
      'length' => 128,
    );
    db_add_field('nodequeue_queue', 'name', $name_field);
    db_add_unique_key('nodequeue_queue', 'name', array('name'));

    // Auto-generate machine names for existing queues and subqueues. Existing
    // queues will be given the first 128 characters of the title, with all
    // spaces replaced with underline characters, made lowercase and trimmed
    // of excess whitespace. Nodequeues with empty titles will receive a name
    // like 'queue_$qid'.
    $result = db_query("SELECT qid, title FROM {nodequeue_queue}");
    foreach ($result as $queue) {
      if (!empty($queue->title)) {
        // Basic formatting.
        $new_name = strtolower(trim(substr($queue->title, 0, 128)));
        // Regex to strip out all unwanted characters.
        $new_name = preg_replace('/[^a-z0-9_]+/', '_', $new_name);

        // Check if this queue name already exists.
        if (nodequeue_machine_name_exists($new_name)) {
          $tmp_name = $new_name;
          $i = 0;
          do {
            // Append an incrementing numeric suffix until we find a unique name.
            $unique_suffix = '_' . $i;
            $new_name = truncate_utf8($tmp_name, 128 - drupal_strlen($unique_suffix, TRUE)) . $unique_suffix;
            $i++;
          } while (nodequeue_machine_name_exists($new_name));
        }
      }
      else {
        // Default to a name like 'queue_$qid' for queues that don't have a title.
        $new_name = 'queue_' . $queue->qid;
      }

      db_update('nodequeue_queue')
        ->fields(array('name' => $new_name))
        ->condition('qid', $queue->qid)
        ->execute();
    }
  }
}

/**
 * Add new field 'insert_at_front'.
 */
function nodequeue_update_7202() {
  $field = array(
    'description' => '',
    'type' => 'int',
    'size' => 'tiny',
    'default' => 0,
  );
  db_add_field('nodequeue_queue', 'insert_at_front', $field);
}

/**
 * Rebuild the menu cache so that contextual links in views appear.
 */
function nodequeue_update_7203() {
  variable_set('menu_rebuild_needed', TRUE);
  drupal_set_message(t('The menus will now be rebuilt.'));
}
