<?php

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

/**
 * Implements hook_uninstall().
 */
function comment_uninstall() {
  // Delete comment_body field.
  field_delete_field('comment_body');

  // Remove variables.
  variable_del('comment_block_count');
  $node_types = array_keys(node_type_get_types());
  foreach ($node_types as $node_type) {
    field_attach_delete_bundle('comment', 'comment_node_' . $node_type);
    variable_del('comment_' . $node_type);
    variable_del('comment_anonymous_' . $node_type);
    variable_del('comment_controls_' . $node_type);
    variable_del('comment_default_mode_' . $node_type);
    variable_del('comment_default_order_' . $node_type);
    variable_del('comment_default_per_page_' . $node_type);
    variable_del('comment_form_location_' . $node_type);
    variable_del('comment_preview_' . $node_type);
    variable_del('comment_subject_field_' . $node_type);
  }
}

/**
 * Implements hook_enable().
 */
function comment_enable() {
  // Insert records into the node_comment_statistics for nodes that are missing.
  $query = db_select('node', 'n');
  $query->leftJoin('node_comment_statistics', 'ncs', 'ncs.nid = n.nid');
  $query->addField('n', 'created', 'last_comment_timestamp');
  $query->addField('n', 'uid', 'last_comment_uid');
  $query->addField('n', 'nid');
  $query->addExpression('0', 'comment_count');
  $query->addExpression('NULL', 'last_comment_name');
  $query->isNull('ncs.comment_count');

  db_insert('node_comment_statistics')
    ->from($query)
    ->execute();
}

/**
 * Implements hook_modules_enabled().
 *
 * Creates comment body fields for node types existing before the comment module
 * is enabled. We use hook_modules_enabled() rather than hook_enable() so we can
 * react to node types of existing modules, and those of modules being enabled
 * both before and after comment module in the loop of module_enable().
 *
 * There is a separate comment bundle for each node type to allow for
 * per-node-type customization of comment fields. Each one of these bundles
 * needs a comment body field instance. A comment bundle is needed even for
 * node types whose comments are disabled by default, because individual nodes
 * may override that default.
 *
 * @see comment_node_type_insert()
 */
function comment_modules_enabled($modules) {
  // Only react if comment module is one of the modules being enabled.
  // hook_node_type_insert() is used to create body fields while the comment
  // module is enabled.
  if (in_array('comment', $modules)) {
    // Ensure that the list of node types reflects newly enabled modules.
    node_types_rebuild();

    // Create comment body fields for each node type, if needed.
    foreach (node_type_get_types() as $type => $info) {
      _comment_body_field_create($info);
    }
  }
}

/**
 * Implements hook_update_dependencies().
 */
function comment_update_dependencies() {
  // comment_update_7005() creates the comment body field and therefore must
  // run after all Field modules have been enabled, which happens in
  // system_update_7027().
  $dependencies['comment'][7005] = array(
    'system' => 7027,
  );

  // comment_update_7006() needs to query the {filter_format} table to get a
  // list of existing text formats, so it must run after filter_update_7000(),
  // which creates that table.
  $dependencies['comment'][7006] = array(
    'filter' => 7000,
  );

  return $dependencies;
}

/**
 * @addtogroup updates-6.x-to-7.x
 * @{
 */

/**
 * Rename comment display setting variables.
 */
function comment_update_7000() {
  $types = _update_7000_node_get_types();
  foreach ($types as $type => $type_object) {
    variable_del('comment_default_order' . $type);

    // Drupal 6 had four display modes:
    // - COMMENT_MODE_FLAT_COLLAPSED = 1
    // - COMMENT_MODE_FLAT_EXPANDED = 2
    // - COMMENT_MODE_THREADED_COLLAPSED = 3
    // - COMMENT_MODE_THREADED_EXPANDED = 4
    //
    // Drupal 7 doesn't support collapsed/expanded modes anymore, so we
    // migrate all the flat modes to COMMENT_MODE_FLAT (0) and all the threaded
    // modes to COMMENT_MODE_THREADED (1).
    $setting = variable_get('comment_default_mode_' . $type, 4);
    if ($setting == 3 || $setting == 4) {
      variable_set('comment_default_mode_' . $type, 1);
    }
    else {
      variable_set('comment_default_mode_' . $type, 0);
    }

    // There were only two comment modes in the past:
    // - 1 was 'required' previously, convert into DRUPAL_REQUIRED (2).
    // - 0 was 'optional' previously, convert into DRUPAL_OPTIONAL (1).
    $preview = variable_get('comment_preview_' . $type, 1) ? 2 : 1;
    variable_set('comment_preview_' . $type, $preview);
  }
}

/**
 * Change comment status from published being 0 to being 1
 */
function comment_update_7001() {
  // Choose a temporary status value different from the existing status values.
  $tmp_status = db_query('SELECT MAX(status) FROM {comments}')->fetchField() + 1;

  $changes = array(
    0 => $tmp_status,
    1 => 0,
    $tmp_status => 1,
  );

  foreach ($changes as $old => $new) {
    db_update('comments')
      ->fields(array('status' => $new))
      ->condition('status', $old)
      ->execute();
  }
}

/**
 * Rename {comments} table to {comment} and upgrade it.
 */
function comment_update_7002() {
  db_rename_table('comments', 'comment');

  // Add user-related indexes. These may already exist from Drupal 6.
  if (!db_index_exists('comment', 'comment_uid')) {
    db_add_index('comment', 'comment_uid', array('uid'));
    db_add_index('node_comment_statistics', 'last_comment_uid', array('last_comment_uid'));
  }

  // Create a language column.
  db_add_field('comment', 'language', array(
    'type' => 'varchar',
    'length' => 12,
    'not null' => TRUE,
    'default' => '',
  ));
  db_add_index('comment', 'comment_nid_language', array('nid', 'language'));
}

/**
 * Split {comment}.timestamp into 'created' and 'changed', improve indexing on {comment}.
 */
function comment_update_7003() {
  // Drop the old indexes.
  db_drop_index('comment', 'status');
  db_drop_index('comment', 'pid');

  // Create a created column.
  db_add_field('comment', 'created', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ));

  // Rename the timestamp column to changed.
  db_change_field('comment', 'timestamp', 'changed', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
  ));

  // Migrate the data.
  // @todo db_update() should support this.
  db_query('UPDATE {comment} SET created = changed');

  // Recreate the indexes.
  // The 'comment_num_new' index is optimized for comment_num_new()
  // and comment_new_page_count().
  db_add_index('comment', 'comment_num_new', array('nid', 'status', 'created', 'cid', 'thread'));
  db_add_index('comment', 'comment_pid_status', array('pid', 'status'));
}

/**
 * Upgrade the {node_comment_statistics} table.
 */
function comment_update_7004() {
  db_add_field('node_comment_statistics', 'cid', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The {comment}.cid of the last comment.',
  ));
  db_add_index('node_comment_statistics', 'cid', array('cid'));

  // The comment_count index may have been added in Drupal 6.
  if (!db_index_exists('node_comment_statistics', 'comment_count')) {
    // Add an index on the comment_count.
    db_add_index('node_comment_statistics', 'comment_count', array('comment_count'));
  }
}

/**
 * Create the comment_body field.
 */
function comment_update_7005() {
  // Create comment body field.
  $field = array(
    'field_name' => 'comment_body',
    'type' => 'text_long',
    'module' => 'text',
    'entity_types' => array(
      'comment',
    ),
    'settings' => array(),
    'cardinality' => 1,
  );
  _update_7000_field_create_field($field);

  // Add the field to comments for all existing bundles.
  $generic_instance = array(
    'entity_type' => 'comment',
    'label' => t('Comment'),
    'settings' => array(
      'text_processing' => 1,
    ),
    'required' => TRUE,
    'display' => array(
      'default' => array(
        'label' => 'hidden',
        'type' => 'text_default',
        'weight' => 0,
        'settings' => array(),
        'module' => 'text',
      ),
    ),
    'widget' => array(
      'type' => 'text_textarea',
      'settings' => array(
        'rows' => 5,
      ),
      'weight' => 0,
      'module' => 'text',
    ),
    'description' => '',
  );

  $types = _update_7000_node_get_types();
  foreach ($types as $type => $type_object) {
    $instance = $generic_instance;
    $instance['bundle'] = 'comment_node_' . $type;
    _update_7000_field_create_instance($field, $instance);
  }
}

/**
 * Migrate data from the comment field to field storage.
 */
function comment_update_7006(&$sandbox) {
  // This is a multipass update. First set up some comment variables.
  if (empty($sandbox['total'])) {
    $comments = (bool) db_query_range('SELECT 1 FROM {comment}', 0, 1)->fetchField();
    $sandbox['types'] = array();
    if ($comments) {
      $sandbox['types'] = array_keys(_update_7000_node_get_types());
    }
    $sandbox['total'] = count($sandbox['types']);
  }

  if (!empty($sandbox['types'])) {
    $type = array_shift($sandbox['types']);

    $query = db_select('comment', 'c');
    $query->innerJoin('node', 'n', 'c.nid = n.nid AND n.type = :type', array(':type' => $type));
    $query->addField('c', 'cid', 'entity_id');
    $query->addExpression("'comment_node_$type'", 'bundle');
    $query->addExpression("'comment'", 'entity_type');
    $query->addExpression('0', 'deleted');
    $query->addExpression("'" . LANGUAGE_NONE . "'", 'language');
    $query->addExpression('0', 'delta');
    $query->addField('c', 'comment', 'comment_body_value');
    $query->addField('c', 'format', 'comment_body_format');

    db_insert('field_data_comment_body')
      ->from($query)
      ->execute();

    $sandbox['#finished'] = 1 - count($sandbox['types']) / $sandbox['total'];
  }

  // On the last pass of the update, $sandbox['types'] will be empty.
  if (empty($sandbox['types'])) {
    // Update the comment body text formats. For an explanation of these
    // updates, see the code comments in user_update_7010().
    db_update('field_data_comment_body')
      ->fields(array('comment_body_format' => NULL))
      ->condition('comment_body_value', '')
      ->condition('comment_body_format', 0)
      ->execute();
    $existing_formats = db_query("SELECT format FROM {filter_format}")->fetchCol();
    $default_format = variable_get('filter_default_format', 1);
    db_update('field_data_comment_body')
      ->fields(array('comment_body_format' => $default_format))
      ->isNotNull('comment_body_format')
      ->condition('comment_body_format', $existing_formats, 'NOT IN')
      ->execute();

    // Finally, remove the old comment data.
    db_drop_field('comment', 'comment');
    db_drop_field('comment', 'format');
  }
}

/**
 * @} End of "addtogroup updates-6.x-to-7.x".
 */

/**
 * @addtogroup updates-7.x-extra
 * @{
 */

/**
 * Add an index to the created column.
 */
function comment_update_7007() {
  db_add_index('comment', 'comment_created', array('created'));
}

/**
 * Update database to match Drupal 7 schema.
 */
function comment_update_7008() {
  // Update default status to 1.
  db_change_field('comment', 'status', 'status', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 1,
    'size' => 'tiny',
  ));

  // Realign indexes.
  db_drop_index('comment', 'comment_status_pid');
  db_add_index('comment', 'comment_status_pid', array('pid', 'status'));
  db_drop_index('comment', 'comment_pid_status');
  db_drop_index('comment', 'nid');
}

/**
 * Change the last_comment_timestamp column description.
 */
function comment_update_7009() {
  db_change_field('node_comment_statistics', 'last_comment_timestamp', 'last_comment_timestamp', array(
    'type' => 'int',
    'not null' => TRUE,
    'default' => 0,
    'description' => 'The Unix timestamp of the last comment that was posted within this node, from {comment}.changed.',
  ));
}

/**
 * @} End of "addtogroup updates-7.x-extra".
 */

/**
 * Implements hook_schema().
 */
function comment_schema() {
  $schema['comment'] = array(
    'description' => 'Stores comments and associated data.',
    'fields' => array(
      'cid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique comment ID.',
      ),
      'pid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {comment}.cid to which this comment is a reply. If set to 0, this comment is not a reply to an existing comment.',
      ),
      'nid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {node}.nid to which this comment is a reply.',
      ),
      'uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {users}.uid who authored the comment. If set to 0, this comment was created by an anonymous user.',
      ),
      'subject' => array(
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
        'description' => 'The comment title.',
      ),
      'hostname' => array(
        'type' => 'varchar',
        'length' => 128,
        'not null' => TRUE,
        'default' => '',
        'description' => "The author's host name.",
      ),
      'created' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The time that the comment was created, as a Unix timestamp.',
      ),
      'changed' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The time that the comment was last edited, as a Unix timestamp.',
      ),
      'status' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 1,
        'size' => 'tiny',
        'description' => 'The published status of a comment. (0 = Not Published, 1 = Published)',
      ),
      'thread' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'description' => "The vancode representation of the comment's place in a thread.",
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => 60,
        'not null' => FALSE,
        'description' => "The comment author's name. Uses {users}.name if the user is logged in, otherwise uses the value typed into the comment form.",
      ),
      'mail' => array(
        'type' => 'varchar',
        'length' => 64,
        'not null' => FALSE,
        'description' => "The comment author's e-mail address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on.",
      ),
      'homepage' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => FALSE,
        'description' => "The comment author's home page address from the comment form, if user is anonymous, and the 'Anonymous users may/must leave their contact information' setting is turned on.",
      ),
      'language' => array(
        'description' => 'The {languages}.language of this comment.',
        'type' => 'varchar',
        'length' => 12,
        'not null' => TRUE,
        'default' => '',
      ),
    ),
    'indexes' => array(
      'comment_status_pid' => array('pid', 'status'),
      'comment_num_new' => array('nid', 'status', 'created', 'cid', 'thread'),
      'comment_uid' => array('uid'),
      'comment_nid_language' => array('nid', 'language'),
      'comment_created' => array('created'),
    ),
    'primary key' => array('cid'),
    'foreign keys' => array(
      'comment_node' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'comment_author' => array(
        'table' => 'users',
        'columns' => array('uid' => 'uid'),
      ),
    ),
  );

  $schema['node_comment_statistics'] = array(
    'description' => 'Maintains statistics of node and comments posts to show "new" and "updated" flags.',
    'fields' => array(
      'nid' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {node}.nid for which the statistics are compiled.',
      ),
      'cid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The {comment}.cid of the last comment.',
      ),
      'last_comment_timestamp' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The Unix timestamp of the last comment that was posted within this node, from {comment}.changed.',
      ),
      'last_comment_name' => array(
        'type' => 'varchar',
        'length' => 60,
        'not null' => FALSE,
        'description' => 'The name of the latest author to post a comment on this node, from {comment}.name.',
      ),
      'last_comment_uid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The user ID of the latest author to post a comment on this node, from {comment}.uid.',
      ),
      'comment_count' => array(
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'default' => 0,
        'description' => 'The total number of comments on this node.',
      ),
    ),
    'primary key' => array('nid'),
    'indexes' => array(
      'node_comment_timestamp' => array('last_comment_timestamp'),
      'comment_count' => array('comment_count'),
      'last_comment_uid' => array('last_comment_uid'),
    ),
    'foreign keys' => array(
      'statistics_node' => array(
        'table' => 'node',
        'columns' => array('nid' => 'nid'),
      ),
      'last_comment_author' => array(
        'table' => 'users',
        'columns' => array(
          'last_comment_uid' => 'uid',
        ),
      ),
    ),
  );

  return $schema;
}
