<?php
/**
 * phpaga
 *
 * Installation wizard
 *
 * This is the first-time installation wizard that helps creating the
 * first user.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: install.php 878 2007-10-31 22:11:00Z florian $
 *
 * Copyright (c) 2004, 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.
 */


define("PHPAGA_INSTALL", true);

include_once("./config.php");
require_once(PHPAGA_LIBPATH.'dbtools.php');

$errmsg = "";
$struct = false;
$structsuccess = false;
$errormessage = null;
$select_pecat = array();

if (isset ($_REQUEST["action"]) && ($_REQUEST["action"] == "dbinst"))
{

    if ((PHPAGA_DB_SYSTEM == 'mysql') && !defined("PHPAGA_MYSQLBIN")) {
        phpaga_error(_("Please set PHPAGA_MYSQLBIN in etc/config.local.php to the full path to mysql (the client binary)."));
        exit;
    }

    if ((PHPAGA_DB_SYSTEM == 'mysql') && defined("PHPAGA_MYSQLBIN") && (!is_file(PHPAGA_MYSQLBIN) || !is_readable(PHPAGA_MYSQLBIN))) {
        phpaga_error(sprintf(_("Wrong setting for PHPAGA_MYSQLBIN in etc/config.local.php: Can't open %s"), PHPAGA_MYSQLBIN));
        exit;
    }

    $instres = phpaga_db_install($errormessage);

    if (PhPagaError::isError($instres)) {
        $instres->printMessage();
        phpaga_error($errormessage);
        exit;
    } else
        header('Location: install.php');
}

$struct = phpaga_db_checkstructure();

if (PhPagaError::isError($struct)) {
    $struct->printMessage();
    exit;
}

if (!$struct) {
    $tpl = new psmarty;
    $tpl->display("install_dbstructmiss.tpl.html");
    exit;
}

define('PHPAGA_ERRHANDLER_STANDARD', true);

$numusers = 0;
$numusers = phpaga_user_getNumUsers();

if (PhPagaError::isError($numusers)) {
    $numusers->printMessage();
    exit;
}

if ($numusers > 0)
{
    $tpl = new psmarty;
    $tpl->display("install_complete.tpl.html");
    exit;
}

$user = array("usr_login" => null,
              "usr_passwd" => null,
              "usr_skin" => defined('PHPAGA_DEFAULT_SKIN') ? PHPAGA_DEFAULT_SKIN : 'phpaga',
              "lng_id" => defined('PHPAGA_DEFAULTLANGUAGE') ? PHPAGA_DEFAULTLANGUAGE : 'en',
              "pe_id" => 0);

$person = array("pe_firstname" => null,
                "pe_lastname" => null,
                "ctr_id" => defined('PHPAGA_DEFAULTCOUNTRY') ? PHPAGA_DEFAULTCOUNTRY : null);

$company = array("cpn_name" => null,
                 "ccat_id" => null);

$skins = array();
$languages = array();
$error = array();

$pe_id = null;
$cpn_id = null;

if (isset ($_REQUEST["action"]) && ($_REQUEST["action"] == ACTION_ADD))
{

    if (isset($_REQUEST["pe_lastname"]) && strlen($_REQUEST["pe_lastname"]))
        $person["pe_lastname"] = $_REQUEST["pe_lastname"];
    else
        $error[] = _("Insert your last name.");

    if (isset($_REQUEST["pe_firstname"]) && strlen($_REQUEST["pe_firstname"]))
        $person["pe_firstname"] = $_REQUEST["pe_firstname"];


    if (isset($_REQUEST["ctr_id"]) && is_numeric($_REQUEST["ctr_id"]))
    {
        $person["ctr_id"] = $_REQUEST["ctr_id"];
        $company["ctr_id"] = $_REQUEST["ctr_id"];
    }

    if (isset($_REQUEST["cpn_name"]) && strlen($_REQUEST["cpn_name"]))
        $company["cpn_name"] = $_REQUEST["cpn_name"];
    else
        $company["cpn_name"] = phpaga_persons_formatname($person["pe_lastname"], $person["pe_firstname"]);

    if (isset($_REQUEST["ccat_id"]) && is_numeric($_REQUEST["ccat_id"]))
        $company["ccat_id"] = $_REQUEST["ccat_id"];
    else
        $error[] = _("Select a category for your company.");

    if (isset($_REQUEST["usr_login"]) && strlen($_REQUEST["usr_login"]))
        $user["usr_login"] = $_REQUEST["usr_login"];
    else
        $error[] = PHPAGA_ERR_AUTH_LOGINLENGTH;

    if (isset($_REQUEST["lng_id"]) && is_numeric($_REQUEST["lng_id"]))
        $user["lng_id"] = $_REQUEST["lng_id"];

    if (!isset($_REQUEST["usr_pwd_new"]) || !strlen($_REQUEST["usr_pwd_new"]))
        $error[] = PHPAGA_ERR_AUTH_PASSWDLENGTH;

    else if (!isset($_REQUEST["usr_pwd_confirm"]) || !strlen($_REQUEST["usr_pwd_confirm"])
             || ($_REQUEST["usr_pwd_new"] != $_REQUEST["usr_pwd_confirm"]))
    {
        $error[] = _("The password and its confirmation do not match.");
    }
    else
        $user["usr_passwd"] = $_REQUEST["usr_pwd_new"];


    if (count($error) == 0)
    {

        $pe_id = phpaga_persons_add($person);

        if (PhPagaError::isError($pe_id))
            $error[] = $pe_id->getMessage();
        else
        {
            $person["pe_id"] = $pe_id;
            $person["pe_pe_id"] = $pe_id;
            $company["pe_id"] = $pe_id;
            $user["pe_id"] = $pe_id;

            $cpn_id = phpaga_companies_add($company);

            if (PhPagaError::isError($cpn_id))
                $error[] = $cpn_id->getMessage();
            else
            {
                $person["cpn_id"] = $cpn_id;

                $result = phpaga_persons_update($person);

                if (PhPagaError::isError($result))
                    $error[] = $result->getMessage();
                else
                {
                    if (isset($phpaga_perm) && is_array($phpaga_perm))
                        $user["perm"] = array_keys($phpaga_perm);

                    $result = phpaga_user_add($user);

                    if (PhPagaError::isError($result))
                        $error[] = $result->getCode();

                    if (count($error) == 0)
                    {
                        header("Location: ".basename($_SERVER["PHP_SELF"]));
                        exit;
                    }
                }
            }
        }
    }
}

$userdata = array("usr_login" => $user["usr_login"],
                  "usr_passwd" => $user["usr_passwd"],
                  "lng_id" => $user["lng_id"],
                  "pe_firstname" => $person["pe_firstname"],
                  "pe_lastname" => $person["pe_lastname"],
                  "ctr_id" => $person["ctr_id"],
                  "cpn_name" => $company["cpn_name"],
                  "ccat_id" => $company["ccat_id"]
    );

$skins = phpaga_getSkinNames();
$languages = phpaga_getLanguages();

$select_ctr = phpaga_countries_getCountryList();
$jobcategories = phpaga_jobcat_getList();
$select_pecat = phpaga_persons_getCategoryList();
$select_ccat = phpaga_companies_getCategories();

$tpl = new psmarty;

$tpl->assign("SELF", basename($_SERVER["PHP_SELF"]));

if (count($error) > 0)
    $tpl->assign("errmsg", phpaga_returnerror($error));
else
    $tpl->assign("errmsg", false);

$tpl->assign("userdata", $userdata);
$tpl->assign("select_ctr", $select_ctr);
$tpl->assign("select_pecat", $select_pecat);
$tpl->assign("select_ccat", $select_ccat);
$tpl->assign("jobcategories", $jobcategories);
$tpl->assign("skins", $skins);
$tpl->assign("languages", $languages);

$tpl->display("install.tpl.html");

?>