<?php

/**
 * Test requirements for installation and running.
 */
function panels_requirements($phase) {
  $function = "panels_requirements_$phase";
  return function_exists($function) ? $function() : array();
}

/**
 * Check install-time requirements.
 */
function panels_requirements_install() {
  $requirements = array();
  $t = get_t();
  // Assume that if the user is running an installation profile that both
  // Panels and CTools are the same release.
  if (!(defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install')) {
    // apparently the install process doesn't include .module files,
    // so we need to force the issue in order for our versioning
    // check to work.
    if (!defined('PANELS_REQUIRED_CTOOLS_API')) {
      include_once drupal_get_path('module', 'panels') . '/panels.module';
    }

    // In theory we should check module_exists, but Drupal's gating should
    // actually prevent us from getting here otherwise.
    if (!defined('CTOOLS_API_VERSION')) {
      include_once drupal_get_path('module', 'ctools') . '/ctools.module';
    }
    if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
       $requirements['panels_ctools'] = array(
         'title' => $t('CTools API Version'),
         'value' => CTOOLS_API_VERSION,
         'severity' => REQUIREMENT_ERROR,
         'description' => t('The CTools API version is too old for Panels. Panels needs at least %version.', array('%version' => PANELS_REQUIRED_CTOOLS_API))
       );
    }
  }
  return $requirements;
}

/**
 * Check runtime requirements (status report).
 */
function panels_requirements_runtime() {
  $requirements = array();
  $legacy = panels_get_legacy_state();
  $t = get_t();
  $state = $legacy->getStatus();
  if (empty($state)) {
    $requirements['panels_legacy'] = array(
      'title' => $t('Panels operating normally'),
      'value' => NULL,
      'severity' => REQUIREMENT_OK,
      'description' => $t('Panels is operating normally - no out-of-date plugins or modules are forcing it into legacy mode'),
    );
  }
  else {
    $description = $t("Panels is operating in Legacy mode due to the following issues:\n");

    // Add the reasons why Panels is acting in legacy mode.
    $list = array();
    foreach ($state as $values) {
      $modules = array();
      foreach ($values['modules'] as $module => $type) {
        $modules[] = array('data' => check_plain($module) . ' - ' . $type);
      }

      $list[] = array('data' => $values['explanation'] ."\n" . theme('item_list', $modules));
    }

    $description .= theme('item_list', $list);

    $requirements['panels_legacy'] = array(
      'title' => $t('Panels operating in Legacy mode'),
      'value' => NULL,
      'severity' => REQUIREMENT_WARNING,
      'description' => $description,
    );
  }
  return $requirements;
}

/**
 * Implementation of hook_schema().
 */
function panels_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_schema_4();
}

/**
 * Schema that adds the 'storage_type' and 'storage_id' columns.
 */
function panels_schema_4() {
  $schema = panels_schema_3();

  // Add the storage type and id columns.
  $schema['panels_display']['fields']['storage_type'] = array(
    'type' => 'varchar',
    'length' => 255,
    'default' => '',
  );
  $schema['panels_display']['fields']['storage_id'] = array(
    'type' => 'varchar',
    'length' => 255,
    'default' => '',
  );

  return $schema;
}
 
/**
 * Schema that adds the panels_layout table.
 */
function panels_schema_3() {
  // Schema 3 is now locked. If you need to make changes, please create
  // schema 4 and add them.
  $schema = panels_schema_2();

  $schema['panels_renderer_pipeline'] = array(
    'description' => 'Contains renderer pipelines for Panels. Each pipeline contains one or more renderers and access rules to select which renderer gets used.',
    'export' => array(
      'identifier' => 'pipeline',
      'bulk export' => TRUE,
      'primary key' => 'rpid',
      'api' => array(
        'owner' => 'panels',
        'api' => 'pipelines',
        'minimum_version' => 1,
        'current_version' => 1,
      ),
    ),
    'fields' => array(
      'rpid' => array(
        'type' => 'serial',
        'description' => 'A database primary key to ensure uniqueness.',
        'not null' => TRUE,
        'no export' => TRUE,
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'Unique ID for this content. Used to identify it programmatically.',
      ),
      'admin_title' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'Administrative title for this pipeline.',
      ),
      'admin_description' => array(
        'type' => 'text',
        'size' => 'big',
        'description' => 'Administrative description for this pipeline.',
        'object default' => '',
      ),
      'weight' => array(
        'type' => 'int',
        'size' => 'small',
        'default' => 0,
      ),
      'settings' => array(
        'type' => 'text',
        'size' => 'big',
        'description' => 'Serialized settings for the actual pipeline. The contents of this field are up to the plugin that uses it.',
        'serialize' => TRUE,
        'object default' => array(),
      ),
    ),
    'primary key' => array('rpid'),
  );

  $schema['panels_layout'] = array(
    'description' => 'Contains exportable customized layouts for this site.',
    'export' => array(
      'identifier' => 'layout',
      'bulk export' => TRUE,
      'primary key' => 'lid',
      'api' => array(
        'owner' => 'panels',
        'api' => 'layouts',
        'minimum_version' => 1,
        'current_version' => 1,
      ),
    ),
    'fields' => array(
      'lid' => array(
        'type' => 'serial',
        'description' => 'A database primary key to ensure uniqueness.',
        'not null' => TRUE,
        'no export' => TRUE,
      ),
      'name' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'Unique ID for this content. Used to identify it programmatically.',
      ),
      'admin_title' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'Administrative title for this layout.',
      ),
      'admin_description' => array(
        'type' => 'text',
        'size' => 'big',
        'description' => 'Administrative description for this layout.',
        'object default' => '',
      ),
      'category' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'Administrative category for this layout.',
      ),
      'plugin' => array(
        'type' => 'varchar',
        'length' => '255',
        'description' => 'The layout plugin that owns this layout.',
      ),
      'settings' => array(
        'type' => 'text',
        'size' => 'big',
        'description' => 'Serialized settings for the actual layout. The contents of this field are up to the plugin that uses it.',
        'serialize' => TRUE,
        'object default' => array(),
      ),
    ),
    'primary key' => array('lid'),
  );

  $schema['cache_panels'] = drupal_get_schema_unprocessed('system', 'cache');

  return $schema;
}

/**
 * Schema that adds the title_pane field.
 */
function panels_schema_2() {
  $schema = panels_schema_1();

  $schema['panels_display']['fields']['title_pane'] = array(
    'type' => 'int',
    'default' => 0,
    'no export' => TRUE,
  );

  return $schema;
}

/**
 * Schema version 1 for Panels in D6.
 *
 * Schema v1 is now LOCKED; any changes should be done via panels_schema_2.
 */
function panels_schema_1() {
  $schema = array();

  $schema['panels_display'] = array(
    'export' => array(
      'object' => 'panels_display',
      'bulk export' => FALSE,
      'export callback' => 'panels_export_display',
      'can disable' => FALSE,
      'identifier' => 'display',
    ),
    'fields' => array(
      'did' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'no export' => TRUE,
      ),
      'layout' => array(
        'type' => 'varchar',
        'length' => '255',
        'default' => '',
      ),
      'layout_settings' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'panel_settings' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'cache' => array(
        'type' => 'text',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'title' => array(
        'type' => 'varchar',
        'length' => '255',
        'default' => '',
      ),
      'hide_title' => array(
        'type' => 'int',
        'size' => 'tiny',
        'default' => 0,
        'no export' => TRUE,
      ),
    ),
    'primary key' => array('did'),
  );

  $schema['panels_pane'] = array(
    'export' => array(
      'can disable' => FALSE,
      'identifier' => 'pane',
      'bulk export' => FALSE,
    ),
    'fields' => array(
      'pid' => array(
        'type' => 'serial',
        'not null' => TRUE,
      ),
      'did' => array(
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'no export' => TRUE,
      ),
      'panel' => array(
        'type' => 'varchar',
        'length' => '32',
        'default' => '',
      ),
      'type' => array(
        'type' => 'varchar',
        'length' => '32',
        'default' => '',
      ),
      'subtype' => array(
        'type' => 'varchar',
        'length' => '64',
        'default' => '',
      ),
      'shown' => array(
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
      ),
      'access' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'configuration' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'cache' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'style' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'css' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'extras' => array(
        'type' => 'text',
        'size' => 'big',
        'serialize' => TRUE,
        'object default' => array(),
        'initial ' => array(),
      ),
      'position' => array(
        'type' => 'int',
        'size' => 'small',
        'default' => 0,
      ),
    ),
    'primary key' => array('pid'),
    'indexes' => array(
      'did_idx' => array('did')
    ),
  );

  return $schema;
}

/**
 * Implementation of hook_install().
 */
function panels_install() {
  drupal_install_schema('panels');
}

/**
 * Implementation of hook_uninstall().
 */
function panels_uninstall() {
  drupal_uninstall_schema('panels');
}

function panels_update_1000() {
  // Panels D6 2 had *no* update functions in it, so the schema version is
  // completely wrong. If we run this update with no schema version, we
  // were actually that version and we must therefore skip to the proper
  // update.
  if (db_table_exists('panels_pane')) {
    $GLOBALS['SKIP_PANELS_UPDATES'] = TRUE;
    return array();
  }
  $ret   = array();

  $ret[] = update_sql("ALTER TABLE {panels_info} RENAME {panels_page}");
  $ret[] = update_sql("ALTER TABLE {panels_page} CHANGE COLUMN did pid int(10) NOT NULL DEFAULT 0;");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN did int(10) NOT NULL DEFAULT 0 AFTER pid");
  $ret[] = update_sql("UPDATE {panels_page} SET did = pid");

  $max_pid = db_result(db_query("SELECT MAX(pid) FROM {panels_page}"));
  if ($max_pid) {
    $ret[] = update_sql("INSERT INTO {sequences} (name, id) VALUES ('{panels_page}_pid', $max_pid)");
  }

  $ret[]  = update_sql("ALTER TABLE {panels_area} RENAME {panels_pane}");
  $ret[]  = update_sql("ALTER TABLE {panels_pane} ADD COLUMN pid int(10) NOT NULL DEFAULT 0 FIRST");
  $ret[]  = update_sql("ALTER TABLE {panels_pane} CHANGE area panel varchar(32)");
  $result = db_query("SELECT * FROM {panels_pane}");
  while ($pane = db_fetch_object($result)) {
    $count++;
    $ret[] = update_sql("UPDATE {panels_pane} SET pid = $count WHERE did = $pane->did AND panel = '$pane->panel' AND position = $pane->position");
  }
  if ($count) {
    $ret[] = update_sql("INSERT INTO {sequences} (name, id) VALUES ('{panels_pane}_pid', $count)");
  }

  $ret[] = update_sql(<<<EOT
    CREATE TABLE {panels_display} (
      did INT(10) NOT NULL DEFAULT 0 PRIMARY KEY,
      layout VARCHAR(32)
    ) /*!40100 DEFAULT CHARACTER SET utf8 */
EOT
  );
  $result = db_query("SELECT did, layout FROM {panels_page}");
  $max_did = 0;
  while ($display = db_fetch_object($result)) {
    $ret[] = update_sql("INSERT INTO {panels_display} VALUES ($display->did, '$display->layout')");
    if ($display->did > $max_did) {
      $max_did = $display->did;
    }
  }
  $ret[] = update_sql("ALTER TABLE {panels_page} DROP COLUMN layout");
  if ($max_did) {
    $ret[] = update_sql("INSERT INTO {sequences} (name, id) VALUES ('{panels_display}_did', $max_did)");
  }
  return $ret;
}

function panels_update_1001() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret   = array();
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN no_blocks int(1)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu int(1) DEFAULT 0");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_tab int(1)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_tab_weight int(4)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_title varchar(255)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_tab_default int(1)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_tab_default_parent_type varchar(10)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_parent_title varchar(255)");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN menu_parent_tab_weight int(4)");
  return $ret;
}

// Create a field for the layout settings
function panels_update_1002() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret   = array();
  $ret[] = update_sql("ALTER TABLE {panels_display} ADD COLUMN layout_settings longtext");
  $ret[] = update_sql("ALTER TABLE {panels_pane} ADD COLUMN access varchar(128) AFTER type");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN css longtext AFTER css_id");
  return $ret;
}

// Create a field for the panel settings.
function panels_update_1003() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  $ret[] = update_sql("ALTER TABLE {panels_display} ADD COLUMN panel_settings longtext");
  return $ret;
}

// Kept up updates from older versions of Panels 2 for D5 to smooth updates.
// Create a field for the panel settings.
// Renumbering to proper numbering scheme.
function panels_update_5204() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret   = array();
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN name varchar(255) UNIQUE");
  $ret[] = update_sql("ALTER TABLE {panels_display} ADD COLUMN name varchar(255) UNIQUE");
  // Give all our panels a name.
  $ret[] = update_sql("UPDATE {panels_page} SET name = CONCAT('panel_page_', pid)");
  $ret[] = update_sql("UPDATE {panels_display} SET name = CONCAT('display_', did)");
  return $ret;
}

// Add the arguments field
function panels_update_5205() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN arguments longtext");
  return $ret;
}

// Add a field so that panes can remember their subtype so we can retrieve
// context information about it.
function panels_update_5206() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  $ret[] = update_sql("ALTER TABLE {panels_pane} ADD COLUMN subtype varchar(64)");
  return $ret;
}

// Add fields for displays and extra contexts
function panels_update_5207() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret   = array();
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN displays longtext");
  $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN contexts longtext");
  return $ret;
}

// Correct the mistaken {panels_display}_id when it should be {panels_display}_did
function panels_update_5208() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret   = array();
  $count = db_result(db_query("SELECT MAX(did) FROM {panels_display}"));
  $ret[] = update_sql("DELETE FROM {sequences} WHERE name = '{panels_display}_did'");
  $ret[] = update_sql("DELETE FROM {sequences} WHERE name = '{panels_display}_id'");
  if ($count) {
    $ret[] = update_sql("INSERT INTO {sequences} (name, id) VALUES ('{panels_display}_did',
    $count)");
  }

  return $ret;
}

// Update argument, relationship and context code to be more correct.
function panels_update_5209() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret    = array();
  $ret[]  = update_sql("ALTER TABLE {panels_page} ADD COLUMN relationships longtext");
  $result = db_query("SELECT * FROM {panels_page}");

  // This code removed due to call to panels_get_argument(). People with
  // older versions will just have to suffer.
  return $ret;
  ctools_include('plugins', 'panels');

  while ($page = db_fetch_object($result)) {
    $args = unserialize($page->arguments);
    $arguments = $ids = $keywords = array();
    if (!empty($args)) {
      // Update each argument
      foreach ($args as $id => $argument) {
        $name = $argument['name'];
        $info = panels_get_argument($name);
        if (!$info) {
          continue;
        }
        // Make sure the id is valid
        if (empty($argument['id'])) {
          if (empty($ids[$name])) {
            $ids[$name] = 1;
          }
          else {
            $ids[$name]++;
          }

          $argument['id'] = $ids[$name];
        }

        // Give it an identifier if it doesn't already have one
        if (empty($argument['identifier'])) {
          $argument['identifier'] = $info['title'] . ($id > 1 ? ' ' . $id : '');
        }

        // Give it a unique keyword if it doesn't already have one
        if (empty($argument['keyword'])) {
          $keyword = $base = $info['keyword'];
          $count = 0;
          while (!empty($keywords[$keyword])) {
            $keyword = $base . '_' . ++$count;
          }
          $keywords[$keyword] = TRUE;
          $argument['keyword'] = $keyword;
        }
        $arguments[$id] = $argument;
      }
    }
    // Move old relationships (stored as contexts) to relationships, where
    // the belong
    $rels = unserialize($page->contexts);
    // Not resetting $keywords!
    $relationships = $ids = array();
    if (!empty($rels)) {
      foreach ($rels as $id => $relationship) {
        $name = $relationship['name'];
        $info = panels_get_relationship($name);
        if (!$info) {
          continue;
        }
        // Make sure the id is valid
        if (empty($relationship['id'])) {
          if (empty($ids[$name])) {
            $ids[$name] = 1;
          }
          else {
            $ids[$name]++;
          }

          $relationship['id'] = $ids[$name];
        }

        // Give it an identifier if it doesn't already have one
        if (empty($relationship['identifier'])) {
          $relationship['identifier'] = $info['title'] . ($id > 1 ? ' ' . $id : '');
        }

        // Give it a unique keyword if it doesn't already have one
        if (empty($relationship['keyword'])) {
          $keyword = $base = $info['keyword'];
          $count = 0;
          while (!empty($keywords[$keyword])) {
            $keyword = $base . '_' . ++$count;
          }
          $keywords[$keyword] = TRUE;
          $relationship['keyword'] = $keyword;
        }
        $relationships[$id] = $relationship;
      }
    }
    db_query("UPDATE {panels_page} " .
      "SET arguments = '%s', " .
      "relationships = '%s', " .
      "contexts = '%s' " .
      "WHERE pid = $page->pid", serialize($arguments), serialize($relationships), serialize(array()), $page->pid
    );
  }
  return $ret;
}

function panels_update_5210() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  $ret[] = update_sql("UPDATE {system} SET weight = 10 WHERE name = 'panels'");
  return $ret;
}

/**
 * Force a menu update
 */
function panels_update_5211() {
//  menu_rebuild();
  return array();
}

/**
 * Add a field to store pane caching information.
 */
function panels_update_5213() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("ALTER TABLE {panels_pane} ADD COLUMN cache longtext AFTER configuration");
      $ret[] = update_sql("ALTER TABLE {panels_display} ADD COLUMN cache longtext AFTER panel_settings");
      break;

    case 'pgsql':
      db_add_column($ret, 'panels_pane', 'cache', 'text');
      db_add_column($ret, 'panels_display', 'cache', 'text');
  }
  return $ret;
}

/**
 * Create a new table for object caching. This isn't part of the cache
 * system.
 */
function panels_update_5214() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  return $ret;
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql(<<<EOT
        CREATE TABLE {panels_object_cache} (
          sid varchar(64),
          did integer,
          obj varchar(255),
          timestamp integer,
          data text,
          KEY (sid, obj, did),
          KEY (timestamp)
        ) /*!40100 DEFAULT CHARACTER SET utf8 */
EOT
      );
    case 'pgsql':
  }
  return !empty($ret) ? $ret : $ret;
}

/**
 * Increase the size of the data column in the {panels_object_cache} table
 * on MySQL.
 *
 * Also gets rid of some duplicate indexes resulting the CREATE TABLE queries
 * in the install() of schema 5214
 */
function panels_update_5215() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("ALTER TABLE {panels_pane} ADD PRIMARY KEY (pid)");
      break;

    case 'pgsql':
      $ret[] = update_sql("ALTER TABLE {panels_pane} ADD PRIMARY KEY (pid)");
  }
  return $ret;
}

/**
 * Adds the 'shown' field to the panels_pane table in order to accomodate
 * the new show/hide panes feature.
 */
function panels_update_5216() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("ALTER TABLE {panels_pane} ADD COLUMN shown int(1) DEFAULT 1 AFTER subtype");
      $ret[] = update_sql("ALTER TABLE {panels_display} ADD COLUMN title varchar(128) AFTER cache");
      $ret[] = update_sql("ALTER TABLE {panels_display} ADD COLUMN hide_title int(1) AFTER title");
      $ret[] = update_sql("ALTER TABLE {panels_display} DROP COLUMN name");
      $ret[] = update_sql("ALTER TABLE {panels_pane} ADD COLUMN visibility text AFTER access");
      break;

    case 'pgsql':
      db_add_column($ret, 'panels_pane', 'shown', 'tinyint', array('default' => 1));
      db_add_column($ret, 'panels_display', 'title', 'varchar(128)');
      db_add_column($ret, 'panels_display', 'hide_title', 'tinyint', array('default' => 0));
      $ret = update_sql("ALTER TABLE {panels_display} DROP name");
      db_add_column($ret, 'panels_pane', 'visibility', 'text');
  }
  return $ret;
}

/**
 * Add the switcher fields to the database
 */
function panels_update_5217() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN switcher_type varchar(128) AFTER no_blocks");
      $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN switcher_name varchar(128) AFTER no_blocks");
      $ret[] = update_sql("ALTER TABLE {panels_page} ADD COLUMN switcher_options longtext AFTER switcher_type");
      break;

    case 'pgsql':
      db_add_column($ret, 'panels_page', 'switcher_type', 'varchar(128)');
      db_add_column($ret, 'panels_page', 'switcher_name', 'varchar(128)');
      db_add_column($ret, 'panels_page', 'switcher_options', 'text');
  }
  return $ret;
}


/**
 * Oversight in 5216: 'tinyint' is not a field type in pgsql; the type we wanted
 * was 'smallint.'
 */
function panels_update_5218() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = array('success' => TRUE, 'query' => t('Update #5218 only has changes for PostgreSQL. There are no updates for MySQL databases - since you\'re running MySQL, you should consider this update successful.'));
      break;

    case 'pgsql':
      db_add_column($ret, 'panels_pane', 'shown', 'smallint', array('default' => 1));
      db_add_column($ret, 'panels_display', 'hide_title', 'smallint', array('default' => 0));
      $ret[] = array('success' => TRUE, 'query' => t('You can disregard failed attempts to add new columns in update #5216 as long as the two queries preceding this text were successful.'));
  }
  return $ret;
}

/**
 * Update from 5.x v2
 */
function panels_update_5299() {
  if (!empty($GLOBALS['SKIP_PANELS_UPDATES'])) {
    return array();
  }
  $ret = array();
  // Fetch schema version 1.
  $schema = panels_schema_1();

  // Certain really old versions of Panels had errors that would cause invalid
  // panes to be written. This wipes them so that the conversion won't fail:
  $ret[] = update_sql("DELETE FROM {panels_pane} WHERE pid = 0");

  // update pid and did to be serial
  db_drop_primary_key($ret, 'panels_pane');
  db_change_field($ret, 'panels_pane', 'pid', 'pid', $schema['panels_pane']['fields']['pid'], array('primary key' => array('pid')));
  db_drop_primary_key($ret, 'panels_display');
  db_change_field($ret, 'panels_display', 'did', 'did', $schema['panels_display']['fields']['did'], array('primary key' => array('did')));

  drupal_set_message(t('Please note that the Panels upgrade from Drupal 5 to Drupal 6 is far from perfect, especially where Views and CCK are involved. Please check all your panels carefully and compare them against the originals. You may need to do some rework to regain your original functionality.'));

  return $ret;
}

/**
 * Update from 6.x v2.
 */
function panels_update_6290() {
  $ret = array();
  if (!module_exists('panels')) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('The Panels module cannot be updated while disabled. If you wish to update Panels, please enable it. If you do not wish to update Panels, please uninstall it.'));
    return $ret;
  }

  // Fetch schema version 1.
  $schema = panels_schema_1();

  // Update size of pane 'access' field.
  db_change_field($ret, 'panels_pane', 'access', 'access', $schema['panels_pane']['fields']['access']);

  // Remove the no longer used visibility field
  if (db_column_exists('panels_pane', 'visibility')) {
    db_drop_field($ret, 'panels_pane', 'visibility');
  }

  // Remove panels_object_cache table
  if (db_table_exists('panels_object_cache')) {
    db_drop_table($ret, 'panels_object_cache');
  }

  // Doublecheck that ctools is enabled. If not, automatically disable the module.
  if (!module_exists('ctools')) {
    // Try to enable it:
    drupal_install_modules(array('ctools'));

    // If that fails, shut off all Panels.
    if (!module_exists('ctools')) {
      drupal_set_message(t('Panels now requires the Chaos Tool Suite (ctools) module to function. Panels has been disabled until you can add this module.'));
      module_disable(array('panels', 'panels_mini', 'panels_export', 'panels_node', 'panels_simple_cache'));
    }
  }

  if (!module_exists('page_manager') && db_table_exists('panels_page')) {
    drupal_set_message('Page manager module has been automatically enabled to replace the Panels pages module.');
    drupal_install_modules(array('page_manager'));
  }

  $ret[] = update_sql("DELETE FROM {system} WHERE name IN ('panels_page', 'panels_views')");

  return $ret;
}

/**
 * Special update function for the alpha2 to alpha3 transition after
 * I messed it up.
 */
function panels_update_6291() {
  $ret = array();
  if (!module_exists('panels')) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('The Panels module cannot be updated while disabled. If you wish to update Panels, please enable it. If you do not wish to update Panels, please uninstall it.'));
    return $ret;
  }

  // Fetch schema version 1.
  $schema = panels_schema_1();


  // Add some new fields
  db_add_field($ret, 'panels_pane', 'style', $schema['panels_pane']['fields']['style']);
  db_add_field($ret, 'panels_pane', 'css', $schema['panels_pane']['fields']['css']);
  db_add_field($ret, 'panels_pane', 'extras', $schema['panels_pane']['fields']['extras']);

  return $ret;
}

/**
 * Update panels pane fields using batch API.
 */
function panels_update_6292(&$sandbox) {
  $ret = array();
  if (!module_exists('panels')) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('The Panels module cannot be updated while disabled. If you wish to update Panels, please enable it. If you do not wish to update Panels, please uninstall it.'));
    return $ret;
  }

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    // We'll -1 to disregard the uid 0...
    $sandbox['max'] = db_result(db_query('SELECT COUNT(*) FROM {panels_pane}'));
  }

  // configuration
  $result = db_query_range("SELECT pid, access, configuration FROM {panels_pane} ORDER BY pid ASC", $sandbox['progress'], 20);
  while ($pane = db_fetch_object($result)) {
    // access
    if (!empty($pane->access)) {
      $rids = explode(', ', $pane->access);
      // For safety, eliminate any non-numeric rids, as we occasionally had
      // problems with nulls and such getting in here:
      foreach ($rids as $id => $rid) {
        if (!is_numeric($rid)) {
          unset($rids[$id]);
        }
      }

      if (empty($rids)) {
        $pane->access = array();
      }
      else {
        // The old access style was just a role based system, so let's convert
        // it to that.
        $pane->access = array(
          'plugins' => array(
            array(
              'name' => 'role',
              'context' => 'logged-in-user',
              'settings' => array(
                'rids' => array_values($rids),
              )
            ),
          ),
        );
      }
    }
    else {
      $pane->access = array();
    }

    // Move style from configuration.
    $pane->configuration = unserialize($pane->configuration);
    $pane->style = array();
    if (!empty($pane->configuration['style'])) {
      $pane->style['style'] = $pane->configuration['style'];
      unset($pane->configuration['style']);
    }

    $pane->css = array();
    // Move css configuration from configuration
    if (isset($pane->configuration['css_id'])) {
      $pane->css['css_id'] = $pane->configuration['css_id'];
      unset($pane->configuration['css_id']);
    }

    if (isset($pane->configuration['css_class'])) {
      $pane->css['css_class'] = $pane->configuration['css_class'];
      unset($pane->configuration['css_class']);
    }

    // Make sure extras is an array. This isn't used by anything in Panels
    // yet, so an empty array is just fine.
    $pane->extras = array();
    db_query("UPDATE {panels_pane} SET " .
      "access = '%s', css = '%s', style = '%s', configuration = '%s', extras = '%s'" .
      " WHERE pid = %d",
      serialize($pane->access),
      serialize($pane->css),
      serialize($pane->style),
      serialize($pane->configuration),
      serialize($pane->extras),
      $pane->pid);

    $sandbox['progress']++;
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
  if ($ret['#finished'] === 1) {
    $ret[] = array('success' => TRUE, 'query' => t('Panel panes were updated'));
  }
  return $ret;
}

/**
 * Update panels display fields using batch API.
 */
function panels_update_6293(&$sandbox) {
  $ret = array();
  if (!module_exists('panels')) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('The Panels module cannot be updated while disabled. If you wish to update Panels, please enable it. If you do not wish to update Panels, please uninstall it.'));
    return $ret;
  }

  if (!isset($sandbox['progress'])) {
    $sandbox['progress'] = 0;
    // We'll -1 to disregard the uid 0...
    $sandbox['max'] = db_result(db_query('SELECT COUNT(*) FROM {panels_display}'));
  }

  // configuration
  $result = db_query_range("SELECT did, panel_settings FROM {panels_display} ORDER BY did ASC", $sandbox['progress'], 20);
  while ($display = db_fetch_object($result)) {
    if (empty($display->panel_settings)) {
      $display->panel_settings = array();
    }
    else {
      $display->panel_settings = unserialize($display->panel_settings);
      if (!is_array($display->panel_settings)) {
        $display->panel_settings = array();
      }
    }

    if (isset($display->panel_settings['panel'])) {
      foreach ($display->panel_settings['panel'] as $key => $settings) {
        $display->panel_settings[$key] = $settings;
      }
      unset($display->panel_settings['panel']);
    }

    if (isset($display->panel_settings['individual'])) {
      unset($display->panel_settings['individual']);
    }

    db_query("UPDATE {panels_display} SET " .
      "panel_settings = '%s'" .
      " WHERE did = %d",
      serialize($display->panel_settings),
      $display->did);

     $sandbox['progress']++;
  }

  $ret['#finished'] = empty($sandbox['max']) ? 1 : ($sandbox['progress'] / $sandbox['max']);
  if ($ret['#finished'] === 1) {
    $ret[] = array('success' => TRUE, 'query' => t('Panel displays were updated'));
  }
  return $ret;
}

/**
 * Establish a baseline schema version for 6.x-3.x
 */
function panels_update_6300() {
  return array();
}

function panels_update_6302() {
  $ret = array();
  if (!module_exists('panels')) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('The Panels module cannot be updated while disabled. If you wish to update Panels, please enable it. If you do not wish to update Panels, please uninstall it.'));
    return $ret;
  }

  if (!module_exists('page_manager') && db_table_exists('panels_page')) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('Conversion of panels pages cannot be completed without page manager module from CTools installed. Please install CTools, activate page manager, and attempt the update again.'));
    return $ret;
  }

  if (!db_table_exists('panels_page')) {
    return $ret;
  }

  // Store the node edit handlers because we merged the edit/add path and we
  // need to be able to keep these together to make sure the names work ok.
  $node_edit_handlers = array();
  page_manager_get_task('page');
  $result = db_query("SELECT * FROM {panels_page}");
  while ($p = db_fetch_object($result)) {
    $page = page_manager_page_new();
    $page->default_handlers = array();
    // Should we check for uniqueness here? It doesn't seem really
    // plausible that there could be page manager pages already.
    $page->name = $p->name;
    $page->task = 'page'; // could become custom later.
    $page->subtask = $p->name;
    $page->admin_title = $p->name;
    $page->path = $p->path;
    // convert access
    if (!empty($p->access)) {
      $rids = explode(', ', $p->access);
      // For safety, eliminate any non-numeric rids, as we occasionally had
      // problems with nulls and such getting in here:
      foreach ($rids as $id => $rid) {
        if (!is_numeric($rid)) {
          unset($rids[$id]);
        }
      }

      if (empty($rids)) {
        $page->access = array();
      }
      else {
        // The old access style was just a role based system, so let's convert
        // it to that.
        $page->access = array(
          'plugins' => array(
            array(
              'name' => 'role',
              'context' => 'logged-in-user',
              'settings' => array(
                'rids' => array_values($rids),
              )
            ),
          ),
        );
      }
    }

    // Convert menu stuff.
    $page->menu = array(
      'type' => 'none',
      'title' => '',
      'weight' => 0,
      'name' => 'navigation',
      'parent' => array(
        'type' => 'none',
        'title' => '',
        'weight' => 0,
        'name' => 'navigation',
      ),
    );

    if ($p->menu) {
      if ($p->menu_tab) {
        if ($p->menu_tab_default) {
          $page->menu['type'] = 'default tab';
          $page->menu['parent']['type'] = $p->menu_tab_default_parent_type;
          $page->menu['parent']['title'] = $p->menu_parent_title;
          $page->menu['parent']['weight'] = $p->menu_parent_tab_weight;
        }
        else {
          $page->menu['type'] = 'tab';
        }
      }
      else {
        $page->menu['type'] = 'normal';
      }

      $page->menu['title'] = $p->menu_title;
      $page->menu['weight'] = $p->menu_tab_weight;
    }

    $page->conf = array();
    $displays = unserialize($p->displays);
    $arguments = unserialize($p->arguments);

    foreach ($arguments as $id => $argument) {
      $page->arguments[$argument['keyword']] = array(
        'name' => $argument['name'],
        'identifier' => $argument['identifier'],
        'title' => $argument['title'],
        'id' => $argument['id'],
        'settings' => isset($argument['argument_settings']) ? $argument['argument_settings'] : array(),
      );

      $match = FALSE;
      $bits = explode('/', $page->path);
      foreach ($bits as $pos => $bit) {
        if ($bit == '%') {
          $bits[$pos] = '%' . $argument['keyword'];
          $match = TRUE;
          $page->path = implode('/', $bits);
          break;
        }
      }

      if (!$match) {
        if ($argument['default'] == '404') {
          $page->path .= '/%' . $argument['keyword'];
        }
        else {
          $page->path .= '/!' . $argument['keyword'];
        }
      }

      // save this for later use.
      $arguments[$id]['context'] = 'argument_' . $argument['name'] . '_' . $argument['id'];
    }

    // Reset the task type here if it's one of our overrides. This ensures
    // that we get the right names.
    switch ($p->path) {
      case 'node/%':
        $page->task = 'node_view';
        $page->subtask = '';
        variable_set('page_manager_node_view_disabled', FALSE);
        break;
      case 'node/add/%':
        // It seems nearly impossible to actually upgrade this properly.
        continue;
      case 'node/%/edit':
        // Could we get conflicts here if they had both?
        $page->task = 'node_edit';
        $page->subtask = '';
        variable_set('page_manager_node_edit_disabled', FALSE);
        break;
      case 'taxonomy/term':
      case 'taxonomy/term/%':
        $page->task = 'term_view';
        $page->subtask = '';
        if ($arguments[0]['name'] == 'term') {
          variable_set('page_manager_term_view_type', 'single');
        }
        variable_set('page_manager_term_view_disabled', FALSE);
        break;
      case 'user/%':
        $page->task = 'user_view';
        $page->subtask = '';
        variable_set('page_manager_user_view_disabled', FALSE);
        break;
      // There is no default here.
    }

    if (empty($displays)) {
      // only one display on this panel, mak
      $cache = new stdClass();
      if ($page->task != 'node_edit') {
        $cache->handlers = array();
      }
      else {
        $cache->handlers = $node_edit_handlers;
      }
      _panels_update_create_handler($page, $p, NULL, array('did' => $p->did, 'title' => t('Panel')), $arguments, 0, $cache);
      $page->default_handlers = $cache->handlers;
    }
    else {
      // for each display we need to create a new handler.
      $weight = 0;
      $cache = new stdClass();
      if ($page->task != 'node_edit') {
        $cache->handlers = array();
      }
      else {
        $cache->handlers = $node_edit_handlers;
        $weight = count($cache->handlers) + 1;
      }
      foreach ($displays as $origin => $info) {
        if (!isset($info['argument_id'])) {
          $info['argument_id'] = 0;
        }

        _panels_update_create_handler($page, $p, $origin, $info, $arguments, $weight++, $cache);
      }

      // Also add the primary display as a default with no selector.
//      _panels_update_create_handler($page, $p, NULL, array('did' => $p->did, 'title' => t('Default')), $arguments, $weight++, $cache);
      $page->default_handlers = $cache->handlers;
    }

    if ($page->task != 'page') {
      // just save the handlers.
      foreach ($cache->handlers as $name => $handler) {
        page_manager_save_task_handler($handler);

        // Keep all node edit handlers for later use.
        if ($page->task == 'node_edit') {
          $node_edit_handlers[$name] = $handler;
        }
      }
    }
    else {
      page_manager_page_save($page);
    }
  }

  $ret[] = update_sql("DROP TABLE {panels_page}");

  // Update a couple of pane types that changed and are easily moved:
  switch ($GLOBALS['db_type']) {
    case 'mysql':
    case 'mysqli':
      $ret[] = update_sql("UPDATE {panels_pane} SET type = CONCAT(type, '_', subtype) WHERE type = 'node_form'");
      break;

    case 'pgsql':
      $ret[] = update_sql("UPDATE {panels_pane} SET type = type || '_' || subtype WHERE type = 'node_form'");
  }
  $ret[] = update_sql("UPDATE {panels_pane} SET type = 'node_form_path' WHERE type = 'node_form_url_path'");

  if (module_exists('ctools') && !module_exists('views_content') && db_result(db_query("SELECT pid FROM {panels_pane} WHERE type = 'views'"))) {
    drupal_install_modules(array('views_content'));
  }

  return $ret;
}

function _panels_update_create_handler($page, $p, $origin, $info, $arguments, $weight, &$cache) {
  $task = page_manager_get_task($page->task);
  $task_name = 'page-' . $page->name;
  $plugin = page_manager_get_task_handler('panel_context');
  $handler = page_manager_new_task_handler($plugin);

  $handler->weight = $weight;
  $handler->task = $page->task;
  if ($page->task == 'page') {
    $handler->subtask = $page->name;
  }
  $handler->export_type = EXPORT_IN_DATABASE;
  $handler->type = t('Normal');

  $handler->name = page_manager_handler_get_name($task_name, $cache->handlers, $handler);

  $handler->conf['css'] = $p->css;
  $handler->conf['css_id'] = $p->css_id;
  $handler->conf['no_blocks'] = $p->no_blocks;
  if (!empty($info['did']) && is_numeric($info['did'])) {
    $handler->conf['did'] = $info['did'];
  }
  else {
    $d = panels_load_display($p->did);
    if ($d) {
      $display_code = panels_export_display($d);
      eval($display_code);

      $handler->conf['did'] = 'new';
      $handler->conf['display'] = $display;
    }
  }
  $handler->conf['title'] = !empty($info['title']) ? $info['title'] : '';
  $handler->conf['contexts'] = unserialize($p->contexts);
  $handler->conf['relationships'] = unserialize($p->relationships);

  if ($origin && strpos($origin, '-')) {
    $handler->conf['access'] = array(
      'logic' => 'and',
      'plugins' => array(),
    );

    // Only 4 types of arguments supported having their own displays:
    // nid, node_add_form, node_edit_form and term. 3 of those simply used
    // node type and the last simply used vocabulary.
    list($junk, $key) = explode('-', $origin);
    if ($key && $key != 'default') {
      if ($arguments[$info['argument_id']]['name'] == 'term') {
        $handler->conf['access']['plugins'][] = array(
          'name' => 'term_vocabulary',
          'context' => $arguments[$info['argument_id']]['context'],
          'settings' => array(
            'vids' => array($key),
           ),
         );
      }
      else {
        $handler->conf['access']['plugins'][] = array(
          'name' => 'node_type',
          'context' => $arguments[$info['argument_id']]['context'],
          'settings' => array(
            'type' => array($key),
           ),
         );
      }
    }
    else {
      // make sure defaults float to the bottom:
      $handler->weight += 100;
    }
  }
  $cache->handlers[$handler->name] = $handler;

  return $handler;
}

/**
 * Ensure the panels_simple_cache module does not exist.
 */
function panels_update_6303() {
  $ret = array();
  if (module_exists('panels_simple_cache')) {
    drupal_set_message(t('Your installation contains a module that no longer exists. When updating modules, you should always remove the module directory first, then replace it with the new code. The "Panels Simple Cache" module is being automatically disabled for you. Please do not re-enable it as it will cause your system to crash.'));
    $ret[] = update_sql("DELETE FROM {system} WHERE name = 'panels_simple_cache'");
  }

  return $ret;
}

/**
 * Ensure that users are informed about the page manager module.
 */
function panels_update_6304() {
  if (!module_exists('page_manager')) {
    drupal_set_message(t('The delegator module has been replaced by the Page Manager module. You should enable the page manager module to ensure that any panel pages you have will not be lost.'));
  }

  return array();
}

/**
 * Add the title_pane field.
 */
function panels_update_6305() {
  $ret = array();

  // Fetch schema version 2.
  $schema = panels_schema_2();

  // Add new field
  db_add_field($ret, 'panels_display', 'title_pane', $schema['panels_display']['fields']['title_pane']);

  return $ret;
}

/**
 * Drop a table that should have been gone long ago.
 */
function panels_update_6306() {
  $ret = array();

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

  return $ret;
}

/**
 * This update function does nothing, it was committed in error and is
 * left in to prevent update problems.
 */
function panels_update_6307() {
  return array();
}

/**
 * Add the panels_layout table
 */
function panels_update_6308() {
  $ret = array();

  // Schema 3 is locked and should not be changed.
  $schema = panels_schema_3();

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

/**
 * Add the panels_renderer_pipeline table
 */
function panels_update_6309() {
  $ret = array();

  // Schema 3 is locked and should not be changed.
  $schema = panels_schema_3();

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

/**
 * Move stylizer data from Panels to CTools.
 */
function panels_update_6310() {
  $ret = array();
  // load the module files, if possible
  if (!defined('PANELS_REQUIRED_CTOOLS_API')) {
    include_once drupal_get_path('module', 'panels') . '/panels.module';
  }
  if (!defined('CTOOLS_API_VERSION')) {
    include_once drupal_get_path('module', 'ctools') . '/ctools.module';
  }
  // Safety: go away if CTools is not at an appropriate version.
  if (!module_invoke('ctools', 'api_version', PANELS_REQUIRED_CTOOLS_API)) {
    $ret['#abort'] = array('success' => FALSE, 'query' => t('Panels cannot be updated because CTools 1.7 (API v1.7.2) is required. Please update CTools and then try update.php again.'));
    return $ret;
  }

  // Enable the stylizer module to make everything as seamless as possible.
  drupal_install_modules(array('stylizer'));
  return $ret;
}

/**
 * Change panels_display.layout to match the size of panels_layout.name.
 */
function panels_update_6311() {
  $ret = array();

  // Clear the schema cache so the change is picked up.
  cache_clear_all('schema', 'cache');

  // Load the schema.
  $schema = panels_schema();
  $table = 'panels_display';
  $field = 'layout';
  $spec = $schema[$table]['fields'][$field];

  // Re-define the column.
  db_change_field($ret, $table, $field, $field, $spec);

  $ret[] = array('success' => TRUE, 'query' => t('Changed the panels_display.layout field to the correct size.'));

  return $ret;
}

/**
 * Add a custom cache table for Panels.
 */
function panels_update_6312() {
  $ret = array();

  $table_name = 'cache_panels';
  if (!db_table_exists($table_name)) {
    $ret = array();
    $schema = drupal_get_schema_unprocessed('system', 'cache');
    db_create_table($ret, $table_name, $schema);
  }

  $ret[] = array('success' => TRUE, 'query' => t('Added a cache panels table.'));

  return $ret;
}

/**
 * Add the "storage_type" and "storage_id" columns to "panels_display".
 */
function panels_update_6313() {
  $schema = panels_schema_4();

  $new_fields = array(
    'panels_display' => array('storage_type', 'storage_id'),
  );

  $ret = array();

  foreach ($new_fields as $table => $fields) {
    foreach ($fields as $field_name) {
      db_add_field($ret, $table, $field_name, $schema[$table]['fields'][$field_name]);
    }
  }

  $ret[] = array('success' => TRUE, 'query' => t('Added the storage_type and storage_id columns.'));

  return $ret;
}

/**
 * Set the storage type and id on existing page manager panels displays.
 */
function panels_update_6314() {
  $ret = array();

  if (!db_table_exists('page_manager_handlers')) {
    $ret[] = array('success' => TRUE, 'query' => t('Skipping update - page_manager is not installed.'));
    return $ret;
  }

  // Get all page_manager_handlers that have a panels context.
  $result = db_query("SELECT pm.name, pm.conf FROM {page_manager_handlers} pm WHERE pm.handler = 'panel_context'");
  $page_manager_panels = array();
  while ($row = db_fetch_object($result)) {
    $conf = unserialize($row->conf);
    if (isset($conf['did'])) {
      $page_manager_panels[$conf['did']] = $row->name;
    }
  }
  $dids = array_keys($page_manager_panels);

  if (!empty($dids)) {
    // Check panels displays that only have empty storage types
    $result = db_query("SELECT pd.did FROM {panels_display} pd WHERE pd.did IN (" . db_placeholders($dids, 'int') . ") AND storage_type = ''", $dids);
    while ($row = db_fetch_object($result)) {
      db_query("UPDATE {panels_display} SET storage_type = '%s', storage_id = '%s' WHERE did = %d",
        'page_manager', $page_manager_panels[$row->did], $row->did);
    }
  }

  $ret[] = array('success' => TRUE, 'query' => t('Set storage_type and storage_id on existing page manager panels displays.'));

  return $ret;
}
