<?php
/**
 * phpaga
 *
 * Configuration system functionality.
 *
 * This file contains the necessary routines to manage phpaga's configuration.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: config.php 876 2007-10-24 16:05:55Z florian $
 *
 * 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)
{

    $key = '';
    $value = '';
    $config = array();

    $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.
 *
 * @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)
{

    $config = 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 ($usr_id == null)
        $r = $d->queryAll('SELECT cfg_key, cfg_value FROM config order by cfg_key');
    else {
        $query = '(SELECT usr_id, cfg_key, u.cfg_value FROM userconfig u
            LEFT JOIN config c ON c.cfg_id = u.cfg_id WHERE usr_id = ?)
            UNION (SELECT null as usr_id, cfg_key, cfg_value FROM config
            WHERE cfg_id NOT IN
            (SELECT cfg_id FROM userconfig WHERE usr_id = ?))';

        $r = $d->queryAll($query, array($usr_id, $usr_id));
    }

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

    foreach ($r as $qrow)
        $config[$qrow['cfg_key']] = $qrow['cfg_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->update('config', $fields, 'cfg_key = ?', $key);

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

    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)
{

    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'];

    $d = new PhPagaDbData;

    /* Get internal item id */

    $cfg_id = $d->queryOneVal('select cfg_id from config where cfg_key = ?', $key);

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

    if (!strlen($cfg_id))
        return PhPagaError::raiseErrorByCode(PHPAGA_ERR_CFG_INVALIDID);

    /* Check whether the user has this setting already */

    $num_sett = $d->queryOneVal('select count(cfg_id) from userconfig where cfg_id = ? and usr_id = ?',
                                array($cfg_id, $usr_id));

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

    if ($num_sett == 0) {

        $fields = array('cfg_id' => $cfg_id,
                        'usr_id' => $usr_id,
                        'cfg_value' => $value);

        $r = $d->insert('userconfig', $fields);

    } else {
        $fields = array('cfg_value' => $value);
        $r = $d->update('userconfig', $fields, 'cfg_id = ? AND usr_id = ?', array($cfg_id, $usr_id));
    }

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

    return true;
}

?>