<?php
/**
 * Phoebe pedagogic planner
 *
 * PHP version 5
 *
 * LICENSE: The GNU General Public License (GPL), version 2. See LICENSE.txt
 *
 * Copyright (c) 2006-2008 JISC/HEFCE/University of Oxford
 *
 * @author      David Balch <david.balch@conted.ox.ac.uk>
 * @license     http://opensource.org/licenses/gpl-license.php GPL2
 * @link        http://phoebe-project.conted.ox.ac.uk/
 */

include_once($_SERVER['DOCUMENT_ROOT'].'/inc/core.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/utils.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/session.php');

// Construct page
$content['windowTitle'] = 'Install' . ' | ' . $CNF->appName;
$content['settings'] = '';
$content['main'] = "<h1>Phoebe installation</h1>\n";

if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/installed.txt')) {
    // Check requirements
    $content['main'] .= "<h2>Dependency check</h2>\n";
    $missingDependencies = false;
    // MDB2
    if(!require_once('MDB2.php')) {
        // Missing PEAR MDB2
        $missingDependencies['MDB2'] = '<p>The database abstraction layer, <a href="http://pear.php.net/">PEAR</a> <a href="http://pear.php.net/package/MDB2">MDB2</a>, is required.'.
        ' Remember to <a href="http://pear.php.net/manual/en/package.database.mdb2.intro.php#AEN39000">install the appropriate database driver</a> with it.</p>';
    }

    // MDB2_Schema
    if(!require_once('MDB2/Schema.php')) {
        // Missing PEAR MDB2_Schema
        $missingDependencies['MDB2_Schema'] = '<p>The database abstraction layer schema tools, <a href="http://pear.php.net/">PEAR</a> <a href="http://pear.php.net/package/MDB2_Schema">MDB2_Schema</a>, are required.';
    }

    // XML_Serializer 
    if(!require_once 'XML/Serializer.php') {
        // Missing PEAR XML_Serializer 
        $missingDependencies['XML_Serializer'] = '<p><a href="http://pear.php.net/">PEAR</a> <a href="http://pear.php.net/package/XML_Serializer/">XML_Serializer</a> required.';
    }

    // XSLT
    if(!extension_loaded('xsl')) {
        // Missing XSL
        $missingDependencies['XSL'] = '<p>The <a href="http://www.php.net/xsl">PHP XSL</a> extension is required.';
    }
    // Need others?...

    if($missingDependencies) {
        // List missing requirements
        $content['main'] .= "<p>The following dependencies need to be met before installation can continue:</p>\n";
        $content['main'] .= '<ul>';
        foreach ($missingDependencies as $key => $req) {
            $content['main'] .= "<li id=\"$key\">$req</li>\n";
        }
        $content['main'] .= '</ul>';
    } else {
        // We have the requirements, lets set up the database
        $content['main'] .= "The system dependencies are satisfied, database setup will now proceed...";
        $content['main'] .= "<h2>Database setup</h2>\n";
        $mdb2->loadModule('Manager');

        // Check we can connect to the database
        $tableList = $mdb2->listTables();
        print_r($tableList);

        if(PEAR::isError($tableList)) {
            // Problem listing tables - probably no database, or permissions.
            $content['main'] .= "<p>Connected to database server, but could not connect to database.</p>\n";
            $content['main'] .= "<p>Please set up your DSN in <code>/inc/config.php</code>, ensuring the database user has modification permissions on the database (GRANT is not required).</p>\n";
        } else if(sizeof($tableList) > 0) {
            // Already got the db
            $content['main'] .= '<p>Database already set up, please <a href="/">continue</a>.</p>';
        } else {
            // Have database, without tables - so set them up.
            $content['main'] .= "<p>Found empty database, setting up tables.</p>\n";

            // Set up tables
            createDB();

            // Insert some designs to get started.
            insertDefaults();
        }
    }
}

/* Database handling functions */
function createDB() {
    global $mdb2, $content;

    $dbSchemaFile = $_SERVER['DOCUMENT_ROOT'].'/db/schema.xml';

    $options = array(
        'log_line_break' => '<br>',
        'idxname_format' => '%s',
        'debug' => true,
        'quote_identifier' => true,
        'force_defaults' => false,
        'portability' => false
    );

    $schema =& MDB2_Schema::factory($mdb2, $options);

    if (PEAR::isError($schema)) {
        $error = "Could not init MDB2_Schema::factory: ".$schema->getMessage();
    } else {
        // first run with queries disabled to make sure everything is alright
        $disable_query = true;

        $definition = $schema->parseDatabaseDefinitionFile($dbSchemaFile);
        if (PEAR::isError($definition)) {
            $error = "Could not parse database schema: ".$definition->getMessage();
        } else {
            $content['main'] .= '<p>Creating tables...</p>';
            $op = $schema->createDatabase($definition, array(), $disable_query);

            if (PEAR::isError($op)) {
                $error = "Could not create database tables: ".$op->getMessage();
            }
        }
    }

    if (isset($error)) {
        die($error);
    } else {
        $content['main'] .= '<p>Done.</p>';
    }

    $schema->disconnect();
}

function insertDefaults() {
    /* Insert field defenitions and default data from (localised) files */
    global $CNF, $content;
    include($CNF->root.'lang/'.$CNF->lang.'/definitions.php');
    include($CNF->root.'lang/'.$CNF->lang.'/data.php');
    //$content['main'] .= tableFromArray($defaultFields);
    //$content['main'] .= tableFromArray($defaultData);

    $allDefaults = array_merge_recursive($defaultFields, $defaultData);
    //$content['main'] .= tableFromArray($allDefaults);

    $content['main'] .= '<ul>';
    foreach($allDefaults as $tableName=>$tableData) {
        echo $tableName;
        $content['main'] .= "<li>Inserting data into table $tableName...";
        insertToTable($tableName, $tableData);
        $content['main'] .= ' Done.</li>';
    }
    $content['main'] .= '</ul>';
}

function insertToTable($tableName, $tableData) {
    global $mdb2;

    foreach($tableData as $row) {
        // Build query
        $keys = '';
        $values = '';
        foreach($row as $key=>$value) {
            $keys .= $key.', ';
            $values .= $mdb2->quote($value).', ';
        }

        // Trim redundant "comma-space"
        $keys = substr($keys, 0, -2);
        $values = substr($values, 0, -2);

        $sql = 'INSERT INTO '.$tableName.' ('.$keys.') VALUES ('.$values.')';
        //echo $sql.'<br><br>';

        // Insert data
        $affected = $mdb2->exec($sql);

        // Always check that result is not an error
        if (PEAR::isError($affected)) {
            die($affected->getMessage());
        }
    }
}

// Write via template
include_once($CNF->template);
?>