<?php
/**
 * phpaga
 *
 * Configuration system functionality.
 *
 * This file contains the necessary routines to manage phpaga's configuration.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id$
 *
 * Copyright (c) 2003, Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * Reads all configuration settings from the database and defines the
 * necessary constants.
 *
 * @param  int   $usr_id  Read config for particular user (optional)
 *
 * @return int   $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.2
 */

function phpaga_config_read($usr_id = null)
{

    $config = phpaga_config_get($usr_id);

    if (PhPagaError::isError($config))
        return $config;

    foreach ($config as $key => $value) {

        switch($value) {

            case 'true': $value = true;
                break;

            case 'false': $value = false;
                break;

            default:
                break;
        }

        if (!defined("PHPAGA_$key"))
            define("PHPAGA_$key", $value);
    }

    return true;
}


/**
 * Returns all configuration settings from the database and places
 * them in an array. Adds any new default settings that are defined
 * in $phpaga_default_settings from etc/globals.php
 *
 * @param  int   $usr_id  Read config for particular user (optional)
 *
 * @return array $config  Array containing the configuration settings. A 
 * PhPagaError object on failure.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.2
 */

function phpaga_config_get($usr_id = null)
{

    global $phpaga_default_settings;

    $config = array();
    $settings = array();

    if (!is_numeric($usr_id))
        $usr_id = null;

    if (defined('PHPAGA_INSTALL') && PHPAGA_INSTALL && !defined('PHPAGA_ERRHANDLER_STANDARD'))
        define('PHPAGA_ERRHANDLER_NORECURSION', true);

    $d = new PhPagaDbData;

    if (is_numeric($usr_id)) {

        /* Fetch user settings */
        $usettings = $d->queryOneVal('SELECT usr_settings FROM users WHERE usr_id=?', $usr_id);
        if (PhPagaError::isError($usettings))
            return $usettings;

        $config = unserialize($usettings);
    }

    /* Add sitewide settings */
    $r = $d->queryAll('SELECT cfg_key, cfg_value FROM config order by cfg_key');
    if (PhPagaError::isError($r))
        return $r;

    foreach ($r as $qrow)
        if (!isset($config[$qrow['cfg_key']]))
            $config[$qrow['cfg_key']] = $qrow['cfg_value'];

    /* Add any new default settings that have not yet been stored with the sitewide settings */
    foreach ($phpaga_default_settings as $key => $value)
        if (!isset($config[$key]))
            $config[$key] = $value;
    
    return $config;
}


/**
 * Updates a configuration item in the database.
 *
 * @param  string $key     Configuration key
 * @param  string $value   Configuration value
 *
 * @return bool   $result  True, or PhPagaError
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.2
 */

function phpaga_config_updateitem($key, $value)
{

    $fields = array('cfg_value' => $value);

    $d = new PhPagaDbData;

    $r = $d->queryOneVal('SELECT COUNT(cfg_key) FROM config WHERE cfg_key=?', $key);

    if (PhPagaError::isError($r))
        return $r;

    if ($r==0) {
        $fields['cfg_key'] = $key;
        $r = $d->insert('config', $fields);
    } else
        $r = $d->update('config', $fields, 'cfg_key = ?', $key);

    if (PhPagaError::isError($r))
        return $v;

    return true;
}


/**
 * Sets/updates a configuration item for a particular user in the
 * database. If $usr_id is not set, the current user is assumed.
 *
 * @param  string $key     Configuration key
 * @param  string $value   Configuration value
 * @param  int    $usr_id  User ID
 *
 * @return bool   $result  True, or PhPagaError
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.2
 */

function phpaga_config_usersetitem($key, $value, $usr_id=null)
{

    global $phpaga_usersettings_keys;

    if (isset($usr_id) && !is_numeric($usr_id))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_USER_INVALIDID);

    if ($usr_id == null)
        $usr_id = $_SESSION['auth_user']['usr_id'];

    $settings = array();
    $sysconfig = phpaga_config_get();
    foreach ($phpaga_usersettings_keys as $gk) {
        if ($gk==$key)
            $settings[$gk] = $value;
        elseif (isset($sysconfig[$gk]))
            $settings[$gk] = $sysconfig[$gk];
    }

    $d = new PhPagaDbData;
    $r = $d->update('users', array('usr_settings' => serialize($settings)), 'usr_id=?', $usr_id);

    if (PhPagaError::isError($r))
        return $r;

    return true;
}

?>
