session.php 8.48 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php
/**
 * This program is part of Mahara
 *
 *  This program 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.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    mahara
Nigel McNie's avatar
Nigel McNie committed
20
 * @subpackage core
21 22 23 24 25 26 27 28 29 30 31 32
 * @author     Nigel McNie <nigel@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006,2007 Catalyst IT Ltd http://catalyst.net.nz
 *
 */

defined('INTERNAL') || die();


/**
 * The session class handles user sessions and session messages.
 *
33 34 35 36 37 38
 * This class stores information about the user across page loads,
 * so it only needs to be requested once when a user logs in.
 *
 * This class also is smart about giving out sessions - if a visitor
 * has not logged in (e.g. they are a guest, searchbot or a simple
 * 'curl' request), a session will not be created for them.
39
 *
40 41
 * Messages are stored in the session and are displayed the next time
 * a page is displayed to a user, even over multiple requests.
42 43 44
 */
class Session {

45 46
    /**
     * Defaults for user information.
47 48
     *
     * @var array
49 50 51 52 53 54 55 56 57 58
     */
    private $defaults;

    /**
     * Sets defaults for the session object (only because PHP5 does not appear
     * to support private static const arrays), and resumes a session only if
     * a session already exists.
     */
    public function __construct() {
        $this->defaults = array(
59
            'logout_time'    => 0,
60
            'id'             => 0,
61
            'username'       => '',
62
            'password'       => '',
63
            'institution'    => 'mahara',
64
            'passwordchange' => false,
65 66 67 68 69 70 71 72 73
            'deleted'        => false,
            'expiry'         => 0,
            'lastlogin'      => 0,
            'staff'          => false,
            'admin'          => false,
            'firstname'      => '',
            'lastname'       => '',
            'prefname'       => '',
            'email'          => ''
74 75 76 77 78 79 80 81 82 83 84 85 86 87
        );
        // Resume an existing session if required
        if (isset($_COOKIE['PHPSESSID'])) {
            session_start();
        }
    }

    /**
     * Gets the session property keyed by $key.
     *
     * @param string $key The key to get the value of
     * @return mixed
     * @throws KeyInvalidException
     * @todo<nigel>: Given that KeyInvalidException doesn't actually exist,
88 89
     * referring to an incorrect key will be fatal. I'm not going to do anything
     * about this until more is known about what will be stored in the session.
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
     */
    public function get($key) {
        if (!isset($this->defaults[$key])) {
            throw new KeyInvalidException($key);
        }
        if (isset($_SESSION[$key])) {
            return $_SESSION[$key];
        }
        return $this->defaults[$key];
    }

    /**
     * Sets the session property keyed by $key.
     *
     * @param string $key   The key to set.
     * @param string $value The value to set for the key
     */
    public function set($key, $value) {
        if (!isset($this->defaults[$key])) {
            throw new KeyInvalidException($key);
        }
111
        if (!$_SESSION) {
112
            $this->create_session();
113
        }
114
        $_SESSION[$key] = $value;
115 116
    }

117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    /**
     * Logs in the given user.
     *
     * The passed object should contain the basic information to persist across
     * page loads.
     *
     * @param object $USER  The user object with properties to persist already
     *                      set
     */
    public function login($USER) {
        if (empty($_SESSION)) {
            $this->create_session();
        }
        foreach (array_keys($this->defaults) as $key) {
            $this->set($key, (isset($USER->{$key})) ? $USER->{$key} : $this->defaults[$key]);
        }
        $this->set('logout_time', time() + get_config('session_timeout'));
    }

    /**
     * Assuming that a session is already active for a user, this method
     * retrieves the information from the session and creates a user object
     * that the script can use
     *
     * @return object
     */
    public function renew() {
        $this->set('logout_time', time() + get_config('session_timeout'));
        $USER = new StdClass;
        foreach (array_keys($this->defaults) as $key) {
            $USER->{$key} = $this->get($key);
        }
        return $USER;
    }

    /**
     * Logs the current user out
     */
    public function logout () {
        $_SESSION = array(
            'logout_time' => 0,
            'messages'    => array()
        );
    }

Martyn Smith's avatar
Martyn Smith committed
162 163 164 165 166 167 168 169 170
    /**
     * Determines if the user is currently logged in
     *
     * @return boolean
     */
    public function is_logged_in() {
        return ($this->get('logout_time') > 0 ? true : false);
    }

171

172 173 174 175 176 177 178
    /**
     * Adds a message that indicates something was successful
     *
     * @param string $message The message to add
     * @param boolean $escape Whether to HTML escape the message
     */
    public function add_ok_msg($message, $escape=true) {
179 180 181
        if (empty($_SESSION)) {
            $this->create_session();
        }
182 183 184 185 186 187 188 189 190 191 192 193 194 195
        if ($escape) {
            $message = htmlspecialchars($message, ENT_COMPAT, 'UTF-8');
            $message = str_replace('  ', '&nbsp; ', $message);
        }
        $_SESSION['messages'][] = array('type' => 'ok', 'msg' => $message);
    }

    /**
     * Adds a message that indicates an informational message
     *
     * @param string $message The message to add
     * @param boolean $escape Whether to HTML escape the message
     */
    public function add_info_msg($message, $escape=true) {
196 197 198
        if (empty($_SESSION)) {
            $this->create_session();
        }
199 200 201 202 203 204 205 206 207 208 209 210 211 212
        if ($escape) {
            $message = htmlspecialchars($message, ENT_COMPAT, 'UTF-8');
            $message = str_replace('  ', '&nbsp; ', $message);
        }
        $_SESSION['messages'][] = array('type' => 'info', 'msg' => $message);
    }

    /**
     * Adds a message that indicates a failure to do something
     *
     * @param string $message The message to add
     * @param boolean $escape Whether to HTML escape the message
     */
    public function add_err_msg($message, $escape=true) {
213 214 215
        if (empty($_SESSION)) {
            $this->create_session();
        }
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        if ($escape) {
            $message = htmlspecialchars($message, ENT_COMPAT, 'UTF-8');
            $message = str_replace('  ', '&nbsp; ', $message);
        }
        $_SESSION['messages'][] = array('type' => 'err', 'msg' => $message);
    }

    /**
     * Builds HTML that represents all of the messages and returns it.
     *
     * This is designed to let smarty templates hook in any session messages.
     *
     * Calling this function will destroy the session messages that were
     * rendered, so they do not inadvertently get displayed again.
     *
     * @return string The HTML representing all of the session messages.
     */
    public function render_messages() {
234
        $result = '<div id="messages">';
235 236 237 238 239 240
        if (isset($_SESSION['messages'])) {
            foreach ($_SESSION['messages'] as $data) {
                if ($data['type'] == 'ok') {
                    $color = 'green';
                }
                elseif ($data['type'] == 'info') {
241
                    $color = '#aa6';
242 243 244 245 246
                }
                else {
                    $color = 'red';
                }
                $result .= '<div style="color:' . $color . ';">' . $data['msg'] . '</div>';
247
            }
248
            $_SESSION['messages'] = array();
249
        }
250
        $result .= '</div>';
251 252 253
        return $result;
    }

254
    /**
255
     * Create a session, by initialising the $_SESSION array.
256 257
     */
    private function create_session() {
258 259 260
        if (!session_id()) {
            session_start();
        }
261 262 263 264
        $_SESSION = array(
            'messages' => array()
        );
    }
265

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
}

/**
 * A smarty callback to insert page messages
 *
 * @return string The HTML represening all of the session messages.
 */
function insert_messages() {
    global $SESSION;
    return $SESSION->render_messages();
}

$SESSION =& new Session;

?>