<?php
/**
 * @author     Thomas Meyer
 * @licence    http://creativecommons.org/licenses/by-nc-sa/2.5/
 * @package    yana
 * @subpackage plugins
 */

/**
 * @access     public
 * @package    yana
 * @subpackage plugins
 */
class plugin_db_admin extends plugin
{

    /* private secureFileStream */ var $file;

    /**
     * Constructor
     *
     * @param string $name a name for this plugin
     * @access public
     */
    function plugin_db_admin($name)
    {
        settype($name,"string");
        $this->name = $name;
        global $YANA;
        $this->file = $YANA->plugins->get($this->name,"DBCONFIGFILE");
    }

    /**
     * Event handler
     *
     * parameters taken: none
     *
     * @access public
     * @param array $ARGS array of params passed to the function
     * @return boolean
     */
    function get_db_configuration($ARGS)
    {
        unset($ARGS);

        global $YANA;

        if (!class_exists("DB")) {
            $YANA->report( new error('PEARDB_FAILURE') );
            return false;
        }

        $YANA->setVar("DATABASE_ACTIVE",     YANA_DATABASE_ACTIVE);
        $YANA->setVar("DATABASE_DBMS",       YANA_DATABASE_DBMS);
        $YANA->setVar("DATABASE_HOST",       YANA_DATABASE_HOST);
        $YANA->setVar("DATABASE_PORT",       YANA_DATABASE_PORT);
        $YANA->setVar("DATABASE_USER",       YANA_DATABASE_USER);
        $YANA->setVar("DATABASE_PASSWORD",   YANA_DATABASE_PASSWORD);
        $YANA->setVar("DATABASE_PREFIX",     YANA_DATABASE_PREFIX);
        $YANA->setVar("DATABASE_NAME",       YANA_DATABASE_NAME);
        $YANA->setVar("YANA_DATABASE_ACTIVE",YANA_DATABASE_ACTIVE);
        $DATABASE_LIST = dirlist($YANA->getVar("DBDIR"), '*.config');
        foreach ($DATABASE_LIST as $key => $item)
        {
            $DATABASE_LIST[$key] = preg_replace("/\.\w*$/", "", $item);
        }
        $YANA->setVar("DATABASE_LIST", $DATABASE_LIST);
        return true;
    }

    /**
     * Event handler
     *
     * parameters taken:
     *
     * <ul>
     * <li> string database_dbms </li>
     * <li> array database_list  </li>
     * </ul>
     *
     * @access public
     * @param array $ARGS array of params passed to the function
     * @return boolean
     */
    function db_install($ARGS)
    {
        settype($ARGS, "array");
        global $YANA;

        if (!class_exists("DB")) {
            $YANA->report( new error('PEARDB_FAILURE') );
            return false;
        }

        if (!isset($ARGS['database_dbms']) || !isset($ARGS['database_list']) || !is_array($ARGS['database_list']) || count($ARGS['database_list']) === 0) {
            return false;
        }

        $install_dir = $YANA->getVar("DBDIR").'.install/';
        switch ($ARGS['database_dbms']) {
            case 'db2':
                $install_dir .= 'db2/';
            break;
            case 'dbase':
                $install_dir .= 'dbase/';
            break;
            case 'fbsql':
                $install_dir .= 'frontbase/';
            break;
            case 'ibase':
                $install_dir .= 'interbase/';
            break;
            case 'ifx':
                $install_dir .= 'informix/';
            break;
            case 'access':
                $install_dir .= 'msaccess/';
            break;
            case 'mssql':
                $install_dir .= 'mssql/';
            break;
            case 'mysql': case 'mysqli':
                $install_dir .= 'mysql/';
            break;
            case 'oci8':
                $install_dir .= 'oracle/';
            break;
            case 'pgsql':
                $install_dir .= 'postgresql/';
            break;
            case 'sybase':
                $install_dir .= 'sybase/';
            break;
            default:
                return false;
            break;
        }

        if (!is_dir($install_dir)) {
            $YANA->report( new error("There is no installation file for this dbms available.") );
            return false;
        }

        foreach ($ARGS['database_list'] as $item)
        {
            $install_file = $install_dir.$item.'.sql';
            if (!is_readable($install_file)) {
                $YANA->report( new error("Unable to install database $item. Cannot read sql file $install_file.") );
                return false;
            } else {
                $database = new bufferedDbStream($item);
                $database->read();
                if (!$database->importSQL($install_file)) {
                    $YANA->report(new error("SQL installation fault. Unable to install database $item."));
                    return false;
                } else {
                    $YANA->report(new log("SQL file $install_file has been imported."));
                }
            }
        }
        return true;
    }

    /**
     * Event handler
     *
     * parameters taken:
     *
     * <ul>
     * <li> string database_dbms </li>
     * <li> array database_list  </li>
     * </ul>
     *
     * @access public
     * @param array $ARGS array of params passed to the function
     * @return boolean
     */
    function db_sync($ARGS)
    {
        settype($ARGS, "array");
        global $YANA;

        if (!class_exists("DB")) {
            $YANA->report( new error('PEARDB_FAILURE') );
            return false;
        }

        if (!isset($ARGS['database_dbms']) || !isset($ARGS['database_list']) || !is_array($ARGS['database_list']) || count($ARGS['database_list']) === 0) {
            return false;
        }

        foreach ($ARGS['database_list'] as $item)
        {
            /* read database content */
            $database = new bufferedDbStream($item);
            $database->read();
            $file_database = new filedb($item);
            $file_database->read();
            $structure        = array();
            $database_content = array();
            $file_content     = array();
            $structure = getConfigFile($file_database->getFilename());

            foreach ($structure['TABLES'] as $table => $content)
            {

                $primary_key = $content['PRIMARY_KEY'];

                if ($database->exists($table)) {
                    $database_keys = $database->get("$table.*.$primary_key");
                } else {
                    $database_keys = array();
                }
                if ($file_database->exists($table)) {
                    $file_keys     = $file_database->get("$table.*.$primary_key");
                } else {
                    $file_keys     = array();
                }

                $difference = array_diff($database_keys,$file_keys);
                $i = 0;
                /* synchronize: database -> file */
                foreach ($difference as $key)
                {
                    if (!$file_database->insert("$table.$key", $database->get("$table.$key"))) {
                        return false;
                    } else if ($i>20) {
                        if ($file_database->write()) {
                            $i = 0;
                        } else {
                            return false;
                        }
                    } else {
                        $i++;
                    }
                }

                if ($i>0 && !$file_database->write()) {
                    return false;
                }

                $difference = array_diff($file_keys,$database_keys);
                $i = 0;
                /* synchronize: file -> database */
                foreach ($difference as $key)
                {
                    if (!$database->insert("$table.$key", $file_database->get("$table.$key"))) {
                        return false;
                    } else if ($i>20) {
                        if ($database->write()) {
                            $i = 0;
                        } else {
                            return false;
                        }
                    } else {
                        $i++;
                    }
                }
                if ($i>0 && !$database->write()) {    
                    return false;
                }

            }

            unset($structure);
        }

        return true;
    }

    /**
     * Event handler
     *
     * parameters taken:
     *
     * <ul>
     * <li> string database_active   </li>
     * <li> string database_dbms     </li>
     * <li> string database_host     </li>
     * <li> string database_port     </li>
     * <li> string database_password </li>
     * <li> string database_name     </li>
     * <li> string database_prefix   </li>
     * </ul>
     *
     * @access public
     * @param array $ARGS array of params passed to the function
     * @return boolean
     */
    function set_db_configuration($ARGS)
    {
        settype($ARGS, "array");
        global $YANA;

        /* update database settings */
        if (isset($ARGS['database_dbms'])) {

            if ($ARGS['database_active'] === 'true') {
                /* check input data */
                $dsn = array('DBMS'     => $ARGS['database_dbms'],
                             'HOST'     => stripslashes($ARGS['database_host']),
                             'PORT'     => $ARGS['database_port'],
                             'USERNAME' => stripslashes($ARGS['database_user']),
                             'PASSWORD' => stripslashes($ARGS['database_password']),
                             'DATABASE' => stripslashes($ARGS['database_name']));
                $test = dbServer::test($dsn);
                if ($test !== true) {
                    return false;
                }
            }

            if (isset($ARGS['database_active']) && $ARGS['database_active'] === 'true' && $YANA->getVar('INSTALLED_PLUGINS.USER')) {
                $args = array('database_dbms' => $ARGS['database_active'], 'database_list' => array('user'));
                if (!$this->db_install($args) && !$this->db_sync($args)) {
                    $YANA->report(new error(500));
                    $YANA->report(new log('Unable to install tables of plugin "user" with the choosen dbms. Operation aborted.'));
                    return false;
                }
            }

            $text = "<?php

if (!defined('YANA_DATABASE_ACTIVE'))   define('YANA_DATABASE_ACTIVE', ".    ( (isset($ARGS['database_active']))   ? $ARGS['database_active']   : YANA_DATABASE_ACTIVE )   .");
if (!defined('YANA_DATABASE_DBMS'))     define('YANA_DATABASE_DBMS', \"".    ( (isset($ARGS['database_dbms']))     ? $ARGS['database_dbms']     : YANA_DATABASE_DBMS )     ."\");
if (!defined('YANA_DATABASE_HOST'))     define('YANA_DATABASE_HOST', \"".    ( (isset($ARGS['database_host']))     ? $ARGS['database_host']     : YANA_DATABASE_HOST )     ."\");
if (!defined('YANA_DATABASE_PORT'))     define('YANA_DATABASE_PORT',\"".     ( (isset($ARGS['database_port']))     ? $ARGS['database_port']     : YANA_DATABASE_PORT )     ."\");
if (!defined('YANA_DATABASE_USER'))     define('YANA_DATABASE_USER',\"".     ( (isset($ARGS['database_user']))     ? $ARGS['database_user']     : YANA_DATABASE_USER )     ."\");
if (!defined('YANA_DATABASE_PASSWORD')) define('YANA_DATABASE_PASSWORD',\"". ( (isset($ARGS['database_password'])) ? $ARGS['database_password'] : YANA_DATABASE_PASSWORD ) ."\");
if (!defined('YANA_DATABASE_PREFIX'))   define('YANA_DATABASE_PREFIX',\"".   ( (isset($ARGS['database_prefix']))   ? $ARGS['database_prefix']   : YANA_DATABASE_PREFIX )   ."\");
if (!defined('YANA_DATABASE_NAME'))     define('YANA_DATABASE_NAME',\"".     ( (isset($ARGS['database_name']))     ? $ARGS['database_name']     : YANA_DATABASE_NAME )     ."\");

?>";
            if (!$this->file->exists()) {
                $this->file->create();
            }
            $this->file->read();
            $this->file->remove();
            $this->file->insert($text);
            $this->file->failSafeWrite();

        }

        return true;
    }

}

// © 2006, Thomas Meyer www.All-Community.de
// Copyright Hinweis nicht entfernen!
?>