<?php

/**
 * @file
 */

/**
 * Implementation of hook_schema().
 */
function panels_node_schema() {
  // This should always point to our 'current' schema. This makes it relatively easy
  // to keep a record of schema as we make changes to it.
  return panels_node_schema_1();
}

/**
 * Schema version 1 for Panels in D6.
 */
function panels_node_schema_1() {
  $schema = array();

  $schema['panels_node'] = array(
    'fields' => array(
      'nid' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
      ),
      'css_id' => array(
        'type' => 'varchar',
        'length' => '255',
      ),
      'did' => array(
        'type' => 'int',
        'not null' => TRUE,
      ),
      'pipeline' => array(
        'type' => 'varchar',
        'length' => '255',
      ),
    ),
    'primary key' => array('did'),
  );

  return $schema;
}

/**
 * Implementation of hook_install().
 */
function panels_node_install() {
  db_query("UPDATE {system} SET weight = 11 WHERE name = 'panels_node'");
}

/**
 * Implementation of hook_uninstall().
 */
function panels_node_uninstall() {
  db_query("DELETE FROM {node} WHERE type = 'panel'");
  drupal_uninstall_schema('panels_node');
}

/**
 * Implements hook_update_dependencies().
 */
function panels_node_update_dependencies() {
  // Update 7301 requires panels storage support.
  $dependencies['panels_node'][7301] = array(
    'panels' => 7305,
  );

  return $dependencies;
}

/**
 * Implementation of hook_update to handle adding a pipeline.
 */
function panels_node_update_6001() {
  $ret = array();
  $field = array(
    'type' => 'varchar',
    'length' => '255',
  );

  db_add_field('panels_node', 'pipeline', $field);
  return $ret;
}

/**
 * Migrate legacy Drupal 6 permissions to Drupal 7.
 */
function panels_node_update_7301() {
  $permissions = array(
    'create panel-nodes' => 'create panel content',
    'edit any panel-nodes' => 'edit any panel content',
    'edit own panel-nodes' => 'edit own panel content',
    'delete any panel-nodes' => 'delete any panel content',
    'delete own panel-nodes' => 'delete own panel content',
  );
  foreach ($permissions as $legacy_permission => $new_permission) {
    $query = db_select('role_permission', 'p')
      ->fields('p', array('rid'))
      ->condition('permission', $legacy_permission);
    $rids = $query->execute()->fetchCol();
    foreach ($rids as $rid) {
      // Insert the new permission if it doesn't already exist.
      db_merge('role_permission')
        ->key(array(
          'rid' => $rid,
          'permission' => $new_permission,
        ))
        ->insertFields(array(
          'rid' => $rid,
          'permission' => $new_permission,
          'module' => 'node',
        ))
        ->execute();
    }

    // Delete the legacy permission.
    db_delete('role_permission')
      ->condition('permission', $legacy_permission)
      ->execute();
  }
}

/**
 * Set the storage type and id on existing panels nodes.
 */
function panels_node_update_7302() {
  if (!isset($sandbox['progress'])) {
    // Initialize batch update information.
    $sandbox['progress'] = (float) 0;
    $sandbox['current_did'] = -1;
    $sandbox['max'] = db_query("SELECT COUNT(pd.did)
         FROM {panels_display} pd
           JOIN {panels_node} pn ON pn.did = pd.did
         WHERE pd.storage_type = ''")->fetchField();
  }

  // Set a limit of how many rows to process per batch.
  $limit = 1000;

  // Run the query.
  $result = db_query_range("SELECT pd.did, pn.nid
      FROM {panels_display} pd
        JOIN {panels_node} pn ON pn.did = pd.did
      WHERE pd.storage_type = '' AND pd.did > :current_did", 0, $limit, array(':current_did' => $sandbox['current_did']));

  foreach ($result as $row) {
    db_update('panels_display')
      ->fields(array(
        'storage_type' => 'panels_node',
        'storage_id' => $row->nid,
      ))
      ->condition('did', $row->did)
      ->execute();

    // Update our progress information.
    $sandbox['progress']++;
    $sandbox['current_did'] = $row->did;
  }

  // Set the "finished" status, to tell batch engine whether this function
  // needs to run again.
  $sandbox['#finished'] = ($sandbox['progress'] >= $sandbox['max']) ? TRUE : ($sandbox['progress'] / $sandbox['max']);

  if ($sandbox['#finished']) {
    return t('Added the storage type for panels_node to relevant panels displays');
  }
}
