<?php
/**
 * Check if user is logged in, or perform authentication
 *
 * This file is part of Zoph.
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Zoph
 * @author Jason Geiger
 * @author Jeroen Roos
 */

namespace auth;

use conf\conf;
use web\session;
use web\request;
use settings;
use anonymousUser;
use user;
use language;
use log;
use userNotFoundException;

/**
 * Check if user is logged in, or perform authentication
 * for users logging in via the web interface
 * This class lets a user pass through if one of the following is true:
 * - a valid username/password was given
 * - a $user object was found in the session
 * - a default user has been defined in config.inc.php
 *
 */
class web implements auth {

    private $session;
    private $request;
    private $user;
    private $lang;

    /**
     * Create a new auth object for web authentication
     * @param web\session Session object
     * @param web\request HTTP request object
     */
    public function __construct(session $session, request $request) {
        $this->session=$session;
        $this->request=$request;
        $this->redirect="logon.php";
        $this->lang = new language(conf::get("interface.language"));

        if (conf::get("interface.user.remote") && $request->getServerVar("REMOTE_USER")) {
            $remote_user = $request->getServerVar("REMOTE_USER");
        } else {
            $remote_user = false;
        }
        if (isset($this->session['user'])) {
            $this->user = $this->session['user'];
        }

        if (empty($this->user)) {
            if (conf::get("interface.user.remote") && $request->getServerVar("REMOTE_USER")) {
                $username = $request->getServerVar("REMOTE_USER");
                try {
                    $user = user::getByName($username);
                    $this->user = $user;
                } catch (userNotFoundException $e) {
                    $this->loginUser();
                } 
            } else {
                $this->loginUser();
            }
        }

        if ($this->user instanceof anonymousUser) {
            if (!defined("IMAGE_PHP")) {
                $this->user=null;
            } else {
                user::setCurrent($this->user);
            }
            $this->redirect="";
            return;
        } else if ($this->user instanceof user) {
            $this->loadUser();
        }

        if (!empty($this->user)) {
            if (!empty($this->request["redirect"])) {
                $this->setRedirect();
            }
        } else if (!empty($this->request["uname"])) {
            /*  A username was given, but by now, no succesful logon has
                happened so, we'll redirect, with error set to PWDFAIL.
                This will show an error on the login screen.
                There is no indication what the exact problem was (unknown user,
                wrong password, etc.) as this might give an adversary more information
                than we want to give away */
            $this->setRedirectLogon("error=PWDFAIL&");
        } else {
            $this->setRedirectLogon();
        }
    }

    /**
     * Get URL to redirect to
     * string|null URL or null when no redirect required
     */
    public function getRedirect() {
        return $this->redirect;
    }

    /**
     * Get language
     * @return language Translation object
     */
    public function getLang() {
        return $this->lang;
    }

    /**
     * Get logged on user
     * @return null|user logged on user or null if nobody succesfully authenticated
     */
    public function getUser() {
        return $this->user;
    }

    /**
     * Logout
     * @codeCoverageIgnore
     */
    public function logout() {
        $this->session->logout();
        $this->redirect="logon.php";
    }

    /**
     * Logon user
     * Authenticate user or perform login for an anonymous user
     */
    private function loginUser() {
        $hash=$this->request["hash"];
        if (defined("IMAGE_PHP") && conf::get("share.enable") && !empty($hash)) {
            $user = new anonymousUser();
        } else if (defined("IMAGE_PHP") && defined("IMAGE_BG")) {
            $user = new anonymousUser();
        } else {
            $uname = $this->request["uname"];
            $pword = $this->request["pword"];
            if (!empty($uname)) {
                $validator = new validator($uname, $pword);
                $user = $validator->validate();
            }
        }
        if (isset($user)) {
            $this->user = $user;
            if (!($user instanceof anonymousUser)) {
                $this->session['user'] = $user;
            }
        }
    }

    /**
     * Load user
     * User has been authenticated and data for this user is loaded
     */
    private function loadUser() {
        $user=$this->user;
        $user->lookup();
        $user->lookupPerson();
        $user->lookupPrefs();

        $user->prefs->load();
        $this->lang=$user->loadLanguage(true);

        // Update Last Login Fields
        $user->set("lastlogin", "now()");
        $user->set("lastip", $this->request->getServerVar("REMOTE_ADDR"));
        $user->update();
        $user->lookup();
        $this->user=$user;
        $this->redirect="";
    }

    /**
     * Redirect to Logon screen
     * @param string error code to pass
     */
    private function setRedirectLogon($error = null) {
        $thisPage=urlencode(preg_replace("/^\//", "", $this->request->getServerVar("REQUEST_URI")));
        if (strstr($thisPage, "service%2F")) {
            $page = "../logon.php";
        } else {
            $page = "logon.php";
        }
        $this->redirect=$page . "?" . $error . "redirect=" . $thisPage;
    }

    /**
     * Redirect to Zoph page
     * Redirect to a Zoph page, making sure you are not tricked into opening a link
     * that would damage your database, for example deleting a photo by a url pointing
     * you to the "confirm" action. Just to be extra sure, any action, except "search" is
     * replaced by "display".
     */
    private function setRedirect() {
        $redirect="/" . urldecode($this->request["redirect"]);
        $this->redirect=preg_replace("/action=(?!search).[^&]+/", "action=display", $redirect);
    }

}
?>
