session.php 9.98 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
            'salt'           => '',
64
            'institution'    => 'mahara',
65
            'passwordchange' => false,
66 67 68 69 70 71 72
            'deleted'        => false,
            'expiry'         => 0,
            'lastlogin'      => 0,
            'staff'          => false,
            'admin'          => false,
            'firstname'      => '',
            'lastname'       => '',
73
            'preferredname'  => '',
Penny Leach's avatar
Penny Leach committed
74 75 76
            'email'          => '',
            'accountprefs'   => array(),
            'activityprefs'  => array(),
77
            'sesskey'        => ''
78 79 80 81 82 83 84 85 86 87 88 89 90 91
        );
        // 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,
92 93
     * 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.
94 95 96 97 98 99 100 101 102 103 104
     */
    public function get($key) {
        if (!isset($this->defaults[$key])) {
            throw new KeyInvalidException($key);
        }
        if (isset($_SESSION[$key])) {
            return $_SESSION[$key];
        }
        return $this->defaults[$key];
    }

Penny Leach's avatar
Penny Leach committed
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    /** 
     * This function returns a method for a particular
     * activity type.
     * or null if it's not set.
     * 
     * @param string $key the activity type
     */
    public function get_activity_preference($key) {
        if (isset($_SESSION['activityprefs'][$key])) {
            return $_SESSION['activityprefs'][$key];
        }
        return null;
    }

    /** 
     * This function returns a value for a particular
     * account preference, or null if it's not set.
     * 
     * @param string $key the field name
     */
    public function get_account_preference($key) {
        if (isset($_SESSION['accountprefs'][$key])) {
            return $_SESSION['accountprefs'][$key];
        }
        return null;
    }

132 133 134 135 136 137 138 139 140 141
    /**
     * 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);
        }
142
        if (!$_SESSION) {
143
            $this->create_session();
144
        }
145
        $_SESSION[$key] = $value;
146 147
    }

148 149
    /** @todo document these next two methods */
    public function set_account_preference($field, $value) {
Penny Leach's avatar
Penny Leach committed
150 151 152 153
        set_account_preference($this->get('id'), $field, $value);
        $_SESSION['accountprefs'][$field] = $value;
    }

154
    public function set_activity_preference($activity, $method) {
Penny Leach's avatar
Penny Leach committed
155 156 157 158
        set_activity_preference($this->get('id'), $activity, $method);
        $_SESSION['activityprefs'][$activity] = $method;
    }

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    /**
     * 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'));
176
        $this->set('sesskey', get_random_key());
Penny Leach's avatar
Penny Leach committed
177 178
        $_SESSION['activityprefs'] = load_activity_preferences($this->get('id'));
        $_SESSION['accountprefs'] = load_account_preferences($this->get('id'));
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    }

    /**
     * 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
207 208 209 210 211 212 213 214 215
    /**
     * Determines if the user is currently logged in
     *
     * @return boolean
     */
    public function is_logged_in() {
        return ($this->get('logout_time') > 0 ? true : false);
    }

216

217 218 219 220 221 222 223
    /**
     * 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) {
224 225 226
        if (empty($_SESSION)) {
            $this->create_session();
        }
227 228 229 230 231 232 233 234 235 236 237 238 239 240
        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) {
241 242 243
        if (empty($_SESSION)) {
            $this->create_session();
        }
244 245 246 247 248 249 250 251 252 253 254 255 256 257
        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) {
258 259 260
        if (empty($_SESSION)) {
            $this->create_session();
        }
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
        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() {
279
        $result = '<div id="messages">';
280 281 282 283 284 285
        if (isset($_SESSION['messages'])) {
            foreach ($_SESSION['messages'] as $data) {
                if ($data['type'] == 'ok') {
                    $color = 'green';
                }
                elseif ($data['type'] == 'info') {
286
                    $color = '#aa6';
287 288 289 290 291
                }
                else {
                    $color = 'red';
                }
                $result .= '<div style="color:' . $color . ';">' . $data['msg'] . '</div>';
292
            }
293
            $_SESSION['messages'] = array();
294
        }
295
        $result .= '</div>';
296 297 298
        return $result;
    }

299
    /**
300
     * Create a session, by initialising the $_SESSION array.
301 302
     */
    private function create_session() {
303 304 305
        if (!session_id()) {
            session_start();
        }
306 307 308 309
        $_SESSION = array(
            'messages' => array()
        );
    }
310

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
}

/**
 * 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;

?>