<?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 753 2006-10-25 21:52:28Z 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();

    $result = phpaga_config_get($config, $usr_id);

    if ($result != PHPAGA_ERR_NONE)
        return $result;

    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 PHPAGA_ERR_NONE;
}

/**
 * Gets all configuration settings from the database and places them
 * in an array.
 *
 * @param  array $config  Array containing the configuration settings
 * @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_get (&$config, $usr_id = null)
{

    $config = array();

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

    phpaga_db_connect($db);

    if ($usr_id == null)
        $query = "SELECT cfg_key, cfg_value ".
            "FROM config order by cfg_key";
    else
    {

        switch(PHPAGA_DB_SYSTEM)
        {

            case "mysql":
                /* MySQL 4.0 does not support subselects */

                $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 = ".$db->quoteSmart($usr_id).") ".
                    "UNION (SELECT null as usr_id, c1.cfg_key, c1.cfg_value ".
                    "FROM config c1 left join userconfig c2 ".
                    "on (c2.cfg_id = c1.cfg_id and usr_id = ".$db->quoteSmart($usr_id).") ".
                    "where c2.cfg_id is null)";

                break;

            default:
                $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 = ".$db->quoteSmart($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 = ".$db->quoteSmart($usr_id)."))";
                break;

        }
    }

    $result = $db->query($query);
    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    while ($qrow = $result->fetchRow())
        $config[$qrow["cfg_key"]] = $qrow["cfg_value"];

    $result->free();
    return PHPAGA_ERR_NONE;
}

/**
 * Updates a configuration item in the database.
 *
 * @param  string $key     Configuration key
 * @param  string $value   Configuration value
 *
 * @return int    $result  A result code.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @since phpaga 0.2
 */

function phpaga_config_updateitem ($key, $value)
{

    $db = "";
    $result = "";

    phpaga_db_connect($db);

    /* strings are escaped/quoted automatically by autoExecute */

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

    $result = $db->autoExecute("config", $fields, DB_AUTOQUERY_UPDATE,
                               "cfg_key = '".$db->escapeSimple($key)."'");

    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}


/**
 * 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 int    $result  A result code.
 *
 * @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 PHPAGA_ERR_USER_INVALIDID;

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

    $db = "";
    $result = "";

    phpaga_db_connect($db);

    /*
     * there are simpler ways of handling the following two queries in
     * one, but MySQL is not able to handle them
     */

    /* get internal item id */

    $cfg_id = $db->getOne("select cfg_id from config ".
                          "where cfg_key = ".$db->quoteSmart($key));

    if (DB::isError($cfg_id))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if (!strlen($cfg_id))
        return PHPAGA_ERR_CFG_INVALIDID;

    /* check whether user has this setting already */

    $num_sett = $db->getOne("select count(cfg_id) from userconfig ".
                            "where cfg_id = ".$db->quoteSmart($cfg_id).
                            " and usr_id = ".$db->quoteSmart($usr_id));


    if (DB::isError($num_sett))
        return PHPAGA_ERR_DB_EXEC_QUERY;

    if ($num_sett == 0)
    {
        $fields = array("cfg_id" => $cfg_id,
                        "usr_id" => $usr_id,
                        "cfg_value" => $value);

        $result = $db->autoExecute("userconfig", $fields, DB_AUTOQUERY_INSERT);
    }
    else
    {
        $fields = array("cfg_value" => $value);

        $result = $db->autoExecute("userconfig", $fields, DB_AUTOQUERY_UPDATE,
                                   "cfg_id = ".$db->quoteSmart($cfg_id)." ".
                                   "AND usr_id = ".$db->quoteSmart($usr_id));
    }


    if (DB::isError($result))
        return PHPAGA_ERR_DB_EXEC_QUERY;
    else
        return PHPAGA_ERR_NONE;
}

?>