<?php

/**
 * @file
 * Set up the Oracle migration example module.
 */

/**
 * Implements hook_install().
 */
function migrate_example_oracle_install() {
  global $conf;

  // Should never fail - we can't get here unless hook_requirements passed, right?
  $connection = @oci_connect($conf['oracle_db']['username'], $conf['oracle_db']['password'],
    $conf['oracle_db']['connection_string'], 'UTF8');
  if (!$connection) {
    $e = oci_error();
    throw new Exception($e['message']);
  }

  // Create a table to hold test data
  $query = "CREATE TABLE ORACLE_CONTENT
            (OID     NUMBER NOT NULL,
             TITLE   VARCHAR2(255) NOT NULL,
             BODY    CLOB NOT NULL,
             MAINIMAGE   BLOB NOT NULL,
             CREATED DATE NOT NULL,
             UPDATED DATE NOT NULL,
             CONSTRAINT ORACLE_CONTENT_PK PRIMARY KEY (OID)
            )";
  $result = oci_parse($connection, $query);
  if (!$result) {
    $e = oci_error($connection);
    throw new Exception($e['message'] . "\n" . $e['sqltext']);
  }
  $status = oci_execute($result);
  if (!$status) {
    $e = oci_error($result);
    throw new Exception($e['message'] . "\n" . $e['sqltext']);
  }

  // Insert a test row or three
  $query = "INSERT INTO ORACLE_CONTENT
            (OID, TITLE, BODY, MAINIMAGE, CREATED, UPDATED)
            VALUES(:oid, :title, EMPTY_CLOB(), EMPTY_BLOB(),
              TO_DATE(:created, 'yyyy/mm/dd hh24:mi:ss'),
              TO_DATE(:updated, 'yyyy/mm/dd hh24:mi:ss'))
            RETURNING body, mainimage INTO :body, :mainimage";
  $result = oci_parse($connection, $query);
  if (!$result) {
    $e = oci_error($connection);
    throw new Exception($e['message'] . "\n" . $e['sqltext']);
  }

  $data = migrate_example_oracle_sample_data();

  oci_bind_by_name($result, ':oid', $oid, 1, SQLT_INT);
  oci_bind_by_name($result, ':title', $title, 255, SQLT_CHR);
  $body_clob = oci_new_descriptor($connection, OCI_D_LOB);
  $image_blob = oci_new_descriptor($connection, OCI_D_LOB);
  oci_bind_by_name($result, ':body', $body_clob, -1, SQLT_CLOB);
  oci_bind_by_name($result, ':mainimage', $image_blob, -1, SQLT_BLOB);
  oci_bind_by_name($result, ':created', $created, 9, SQLT_CHR);
  oci_bind_by_name($result, ':updated', $updated, 9, SQLT_CHR);
  foreach ($data as $row) {
    extract($row);
    $status = oci_execute($result, OCI_DEFAULT);
    if (!$status) {
      $e = oci_error($result);
      throw new Exception($e['message'] . "\n" . $e['sqltext']);
    }
    $body_clob->save($body);
    $image_blob->save($mainimage);
  }
  oci_commit($connection);
}

/**
 * Implements hook_uninstall().
 */
function migrate_example_oracle_uninstall() {
  global $conf;

  $connection = @oci_connect($conf['oracle_db']['username'], $conf['oracle_db']['password'],
    $conf['oracle_db']['connection_string'], 'UTF8');
  if (!$connection) {
    $e = oci_error();
    throw new Exception($e['message']);
  }

  // Get rid of the test data
  // This SQL from http://dbaforums.org/oracle/index.php?showtopic=4990.
  $query = "begin execute immediate 'drop table ORACLE_CONTENT'; exception when others then null; end;";
  $result = oci_parse($connection, $query);
  if (!$result) {
    $e = oci_error($connection);
    throw new Exception($e['message'] . "\n" . $e['sqltext']);
  }
  $status = oci_execute($result);
  if (!$status) {
    $e = oci_error($result);
    throw new Exception($e['message'] . "\n" . $e['sqltext']);
  }
}

/**
 * Implements hook_requirements().
 */
function migrate_example_oracle_requirements($phase) {
  $requirements = array();
  $t = get_t();
  switch ($phase) {
    case 'install':
      // Check that the OCI8 extension is loaded
      $requirements['oci8'] = array('title' => $t('Oracle extension'));
      if (!extension_loaded('oci8')) {
        $requirements['oci8']['description'] = $t('Migrating from an Oracle
          database requires that you have the !link extension loaded in PHP.',
          array('!link' => l('oci8', 'http://us.php.net/manual/en/book.oci8.php')));
        $requirements['oci8']['severity'] = REQUIREMENT_ERROR;
        break;
      }

      $sample_setting =
        '<pre>
$conf[\'oracle_db\'] = array(
  \'username\' => \'Oracle_username\',
  \'password\' => \'Oracle_password\',
  \'connection_string\' => \'//Oracle_host/SID\',
);
</pre>';
      // Check that there is an Oracle database configured for use
      $requirements['oracle_db'] = array('title' => $t('Oracle configuration'));
      global $conf;
      if (empty($conf['oracle_db']) || empty($conf['oracle_db']['username']) ||
        empty($conf['oracle_db']['password']) || empty($conf['oracle_db']['connection_string'])) {
        $requirements['oracle_db']['description'] = $t('You must define $conf[\'oracle_db\']
          (in your site\'s settings.php file) to point to the Oracle database where
          you want test data to be stored: ' . $sample_setting);
        $requirements['oracle_db']['severity'] = REQUIREMENT_ERROR;
        break;
      }

      // Check that we can connect to the Oracle db.
      $requirements['oracle_connect'] = array('title' => $t('Oracle connection available'));
      $connection = oci_connect($conf['oracle_db']['username'], $conf['oracle_db']['password'],
        $conf['oracle_db']['connection_string'], 'UTF8');
      if (!$connection) {
        $e = oci_error();
        $requirements['oracle_connect']['description'] = $t('Could not connect to configured
          Oracle database at !conn_string. Oracle error message: !message',
          array(
            '!conn_string' => $conf['oracle_db']['connection_string'],
            '!message' => $e['message'],
          ));
        $requirements['oracle_connect']['severity'] = REQUIREMENT_ERROR;
        break;
      }

      // Check for necessary privileges
      $requirements['oracle_privs'] = array('title' => $t('Necessary Oracle privileges are assigned'));
      $statement = oci_parse($connection, 'SELECT * FROM SESSION_PRIVS');
      if (!$statement) {
        $e = oci_error($connection);
        $requirements['oracle_connect']['description'] = $e['message'];
        $requirements['oracle_connect']['severity'] = REQUIREMENT_ERROR;
        break;
      }
      $result = oci_execute($statement);
      if (!$result) {
        $e = oci_error($statement);
        $requirements['oracle_connect']['description'] = $e['message'];
        $requirements['oracle_connect']['severity'] = REQUIREMENT_ERROR;
        break;
      }
      $ok = FALSE;
      while ($row = oci_fetch_object($statement)) {
        if ($row->PRIVILEGE == 'CREATE TABLE') {
          $ok = TRUE;
          break;
        }
      }

      if (!$ok) {
        $requirements['oracle_privs']['description'] = $t('The specified
            username !username does not have the CREATE TABLE privilege. This privilege
            is necessary to create test tables in the Oracle database.',
          array('!username' => $conf['oracle_db']['username']));
        $requirements['oracle_privs']['severity'] = REQUIREMENT_ERROR;
        break;
      }
      break;
    case 'update':
      break;
    case 'runtime':
      break;
  }
  return $requirements;
}
