<?php
// $Id: webform.install,v 1.14 2006/09/17 23:45:34 quicksketch Exp $

function webform_install() {
  drupal_set_message('Installing webform');

  switch ($GLOBALS['db_type']) {
    case 'mysqli':
    case 'mysql':
      db_query("CREATE TABLE if not exists {webform} (
        nid int(10) unsigned NOT NULL default '0',
        confirmation text,
        redirect_post int(1) unsigned not null default '0',
        submit_limit int(2)  not null default '-1',
        submit_interval int(10) not null default '157784630',
        email varchar(255) default NULL,
        email_from varchar(255) default NULL,
        email_subject varchar(255) default NULL,
        additional_validate text default NULL,
        additional_submit text default NULL,
        PRIMARY KEY  (nid)
        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
      );

      db_query("CREATE TABLE if not exists {webform_component} (
        nid int(10) unsigned NOT NULL default '0',
        cid int(10) unsigned NOT NULL default '0',
        pid int(10) unsigned NOT NULL default '0',
        name varchar(128) default NULL,
        type varchar(16) default NULL,
        value text default NULL,
        extra text,
        mandatory int(2) unsigned default NULL,
        weight int(2) default NULL,
        PRIMARY KEY  (nid,cid)
        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
      );

      db_query("CREATE TABLE if not exists {webform_submissions} (
        nid int(10) unsigned NOT NULL default '0',
        sid int(10) unsigned NOT NULL default '0',
        submitted int(11) NOT NULL default '0',
        user varchar(128),
        remote_addr varchar(128),
        PRIMARY KEY  (nid,sid)
        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
      );

      db_query("CREATE TABLE if not exists {webform_submitted_data} (
        nid int(10) unsigned NOT NULL default '0',
        sid int(10) unsigned NOT NULL default '0',
        cid int(10) unsigned NOT NULL default '0',
        no int(10) unsigned NOT NULL default '0',
        data longtext,
        PRIMARY KEY  (nid,sid,cid,no)
        ) TYPE=MyISAM /*!40100 DEFAULT CHARACTER SET utf8 */"
      );
      break;

  case 'pgsql':
      db_query("CREATE TABLE {webform} (
        nid integer NOT NULL default '0',
        confirmation text NOT NULL default '',
        redirect_post smallint NOT NULL default '0',
        submit_limit smallint NOT NULL default '-1',
        submit_interval integer NOT NULL default '157784630',
        email varchar(255) NOT NULL default '',
        email_from varchar(255) NOT NULL default '',
        email_subject varchar(255) NOT NULL default '',
        additional_validate text default NULL,
        additional_submit text default NULL,
        PRIMARY KEY (nid)
        )"
      );
  
      db_query("CREATE TABLE {webform_component} (
        nid integer NOT NULL default '0',
        cid integer NOT NULL default '0',
        pid integer NOT NULL default '0',
        name varchar(128) NOT NULL default '',
        type varchar(16) NOT NULL default '',
        value text NOT NULL default '',
        extra text NOT NULL default '',
        mandatory smallint NOT NULL default '0',
        weight smallint NOT NULL default '0',
        PRIMARY KEY (nid,cid)
        )"
      );
  
      db_query("CREATE TABLE {webform_submissions} (
        nid integer NOT NULL default '0',
        sid serial,
        submitted integer NOT NULL default '0',
        \"user\" varchar(128),
        remote_addr varchar(128) NOT NULL default '',
        PRIMARY KEY (nid,sid)
        )"
      );
    
      db_query("CREATE TABLE {webform_submitted_data} (
        nid integer NOT NULL default '0',
        sid integer NOT NULL default '0',
        cid integer NOT NULL default '0',
        no integer NOT NULL default '0',
        data text NOT NULL default '',
        PRIMARY KEY (nid,sid,cid,no)
        )"
      );
    break;
  }
  
  variable_set('webform_version',array('text'=>'4.7.1', 'build' => '471'));

  $success = TRUE;

  if ($success) {
    drupal_set_message(t('Webform module installed module tables successfully.'));
  }
  else {
    drupal_set_message(t('The installation of webform module was unsuccessful.'), 'error');
  }
}

/*
 * Schema changes include component id's (cid) keys in the webform_component
 * and webform_submitted_data tables
 */
function webform_update_1() {
  
  $ret = array();
  
  // Update pre-4.7 tables to the 463 build schema
  $installed_version = variable_get("webform_version",0);
  $current_version = array('text'=>'4.6.3', 'build' => '463');
  if ($installed_version > 0) {
    $ret = _webform_legacy_update($installed_version,$current_version);
  }
  
  // Start the normal update
  $ret[] = update_sql("CREATE TABLE {webform_tmp} ( ".
                      "  nid int(10) unsigned NOT NULL default '0', ".
                      "  sid int(10) unsigned NOT NULL default '0', ".
                      "  cid int(10) unsigned NOT NULL default '0', ".
                      "  no int(10) unsigned NOT NULL default '0', ".
                      "  data longtext, ".
                      " PRIMARY KEY  (nid,sid,cid,no) ".
                      " ) ");
  $result = db_query("SELECT ws.nid, ws.sid, wc.cid, ws.name, ws.data ".
                     " FROM {webform_submitted_data} ws, {webform_component} wc ".
                     " WHERE ws.nid = wc.nid ".
                     " AND ws.name = wc.name ");
  
  while ($row = db_fetch_object($result)) {    
    $data = unserialize($row->data);
    if ( is_array($data) ) {
      foreach($data as $k => $v) {
        db_query("INSERT INTO {webform_tmp} (nid, sid, cid, no, data) VALUES (%d, %d, %d, %d, '%s')",
                 $row->nid, $row->sid, $row->cid, $k, $v);
      }
    }
    else {
      db_query("INSERT INTO {webform_tmp} (nid, sid, cid, no, data) VALUES (%d, %d, %d, %d, '%s')",
               $row->nid, $row->sid, $row->cid, 0, $row->data);
    }
  }
  
  $ret[] = update_sql("DROP TABLE {webform_submitted_data}");
  $ret[] = update_sql("ALTER TABLE {webform_tmp} RENAME TO {webform_submitted_data}");

  $ret[] = update_sql("CREATE TABLE {webform_submissions} ( ".
                      " nid int(10) unsigned NOT NULL default '0', ".
                      " sid int(10) unsigned NOT NULL default '0', ".
                      " submitted int(11)  NOT NULL default '0', ".
                      " PRIMARY KEY  (nid, sid) ".
                      ")" );
  
  variable_set('webform_version',array('text'=>'4.7.1', 'build' => '471'));
  
  return $ret;
}

/*
 * Schema changes 2: Added redirect_post column in webform table
 */
function webform_update_2() {
  
  $ret = array();
  
  $ret[] = update_sql("ALTER TABLE {webform} ADD redirect_post int(1) UNSIGNED NOT NULL DEFAULT '0' AFTER confirmation");
  
  return $ret;
}


/*
 * Schema change 3: Update to UTF8
 */
function webform_update_3() {
  return _system_update_utf8(array('webform', 'webform_component', 'webform_role_node', 'webform_submissions', 'webform_submitted_data'));
}

/*
 * Schema change 4: Remove the webform_role_node table, node access can be handled by other modules made for this purpose.
 * Add additional columns to webform_submissions for recording of repeated submissions (IP Address, Browser, etc).
 * Add additional columns to webform for setting submission limitations
 * Change 'maintain webforms' permission into two seperate perms: 'edit webforms', 'access webform results'
 */
function webform_update_4() {
  $ret[] = update_sql("DROP TABLE if exists {webform_role_node}");
  $ret[] = update_sql("ALTER TABLE {webform_submissions} ADD user varchar(128) AFTER submitted");
  $ret[] = update_sql("ALTER TABLE {webform_submissions} ADD remote_addr varchar(128) AFTER user");
  $ret[] = update_sql("ALTER TABLE {webform} ADD submit_limit int(2) NOT NULL DEFAULT '-1' AFTER redirect_post");
  $ret[] = update_sql("ALTER TABLE {webform} ADD submit_interval int(10) NOT NULL DEFAULT '157784630' AFTER submit_limit"); // 5 years in seconds
  
  // Split 'maintain webforms' permissions into both 'edit webforms' and 'access webform results'
  $result = db_query("SELECT rid,perm FROM {permission}");
  while ($row = db_fetch_object($result)) {
    if (strpos($row->perm,"maintain webforms") !== false) {
      $updatedPerm = str_replace("maintain webforms", "edit webforms, access webform results", $row->perm);
      db_query("UPDATE {permission} SET perm='%s' WHERE rid = %d", $updatedPerm, $row->rid);
    }
  }
  return $ret;
}

/*
 * Update MySQL sequence name to be cross-database compatible
 */
function webform_update_5() {
  $ret = array();
  
  switch ($GLOBALS['db_type']) {
    case 'mysqli':
    case 'mysql':
      db_query('LOCK TABLES {sequences} WRITE');
      $ret[] = update_sql(sprintf("UPDATE {sequences} SET name = '%s' WHERE name = '%s'", db_prefix_tables('{webform_submissions}_sid'), db_prefix_tables('{webform_submissions}_id')));
      db_query('UNLOCK TABLES'); 
      break;
  }
  
  return $ret;
}

/*
 * Add a parent ID to all components, allowing nested fieldsets
 */
function webform_update_6() {
  $ret = array();
  
  switch ($GLOBALS['db_type']) {
    case 'pgsql':
      $ret[] = update_sql("ALTER TABLE {webform_component} ADD pid integer NOT NULL DEFAULT '0' AFTER cid");
      break;
    case 'mysqli':
    case 'mysql':
      $ret[] = update_sql("ALTER TABLE {webform_component} ADD pid int(10) NOT NULL DEFAULT 0 AFTER cid");
      break;
  }
  
  return $ret;
}

/*
 * Allow much larger default values for components
 */
function webform_update_7() {
  $ret = array();
  
  switch ($GLOBALS['db_type']) {
    case 'pgsql':
      db_change_column($ret, 'webform_component', 'value', 'value', 'TEXT', array('not null' => FALSE, 'default' => "NULL"));
      break;
    case 'mysqli':
    case 'mysql':
      $ret[] = update_sql("ALTER TABLE {webform_component} CHANGE value value TEXT NULL DEFAULT NULL");
      break;
  }
  
  return $ret;
}

/*
 * Add additional validate and submit processing columns
 */
function webform_update_8() {
  $ret = array();
  
  switch ($GLOBALS['db_type']) {
    case 'pgsql':
    case 'mysqli':
    case 'mysql':
      $ret[] = update_sql("ALTER TABLE {webform} ADD additional_validate text DEFAULT NULL AFTER email_subject");
      $ret[] = update_sql("ALTER TABLE {webform} ADD additional_submit text DEFAULT NULL AFTER additional_validate");
      break;
  }
  
  return $ret;
}

/**
 * Makes updates to the database structure (Pre-4.7 versions of Drupal).
 **/
function _webform_legacy_update($installed_version, $current_version) {
    $ret = array();
    // Check to see if we should do a update.

    // Upgrading from original version    
    if ( $installed_version['build'] <= 1 ) {
      $ret[] = array(1 => "<strong>Build 1</strong><br />\n", 2 => "");
      // Add the table webform_submitted_data
      $ret[] = update_sql("CREATE TABLE {webform_submited_data} ".
                          "( nid int(10) unsigned not null, ".
                          "sid int(10) unsigned not null, ".
                          "name varchar(255) not null, ".
                          "data blob, ".
                          "PRIMARY KEY(nid, sid, name))");
 
      // Converting data from old submission table.
      //$ret[] = _webform_convert_old_submissions();
    }
    if ( $installed_version['build'] <= 1 ) {
      //$ret[] = array(1 => "<strong>Build 4.5.0</strong><br />\n", 2 => "");
      // Change webform_component.extra from varchar(128) -> text
      $ret[] = update_sql("ALTER TABLE {webform_component} MODIFY extra TEXT");
      // Change webform_submited_data.data blob -> longtext
      $ret[] = update_sql("ALTER TABLE {webform_submited_data} MODIFY data LONGTEXT");
    }
    if ( $installed_version['build'] < 460 ) {
     // $ret[] = array(1 => "<strong>Build 4.6.0</strong><br />\n", 2 => "");
      // Update webform_submited_data to webform_submitted_data
      $ret[] = update_sql("ALTER TABLE {webform_submited_data} RENAME TO {webform_submitted_data}");
    }
    if ( $installed_version['build'] < 461 ) {
      //$ret[] = array(1 => "<strong>Build 4.6.1</strong><br />\n", 2 => "");
      // Update webform.email varchar(50) -> varchar(255)
      $ret[] = update_sql(" ALTER TABLE {webform} MODIFY email varchar(255)");
      // Update from lable to label in webform_component
      $ret[] = update_sql(" UPDATE {webform_component} SET type = 'label' WHERE type = 'lable'");
    }
    if ( $installed_version['build'] < 462 ) {
      //$ret[] = array(1 => "<strong>Build 4.6.2</strong><br />\n", 2 => "");
      // Update webform.confirm varchar(255) -> text and change name to "confirmation"
      $ret[] = update_sql(" ALTER TABLE {webform} CHANGE confirm confirmation text");
    }
    if ( $installed_version['build'] < 463 ) {
      //$ret[] = array(1 => "<strong>Build 4.6.3</strong><br />\n", 2 => "");
      // No more lazy update ...
      // Check if the lazy update has already been performed
      $result = db_query("SHOW COLUMNS FROM {webform} LIKE 'email_subject'");  		
      if (db_num_rows($result) == 0) {  
        // The email_subject column is needed
        $ret[] = update_sql("ALTER TABLE {webform} ADD COLUMN email_subject varchar(255)");
      }
      $result = db_query("SHOW COLUMNS FROM {webform} LIKE 'email_from'");      
      if (db_num_rows($result) == 0) {  
        // The email_subject column is needed
        $ret[] = update_sql("ALTER TABLE {webform} ADD COLUMN email_from varchar(255)");
      }
    }
        
    // Set the $current_version
    variable_set("webform_version", $current_version);
    
    return $ret;
}
