session.php 8.15 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
            'passwordchange' => false,
64
            'institution'    => 'mahara'
65 66 67 68 69 70 71 72 73 74 75 76 77 78
        );
        // 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,
79 80
     * 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.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
     */
    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);
        }
102
        if (!$_SESSION) {
103
            $this->create_session();
104
        }
105
        $_SESSION[$key] = $value;
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 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    /**
     * 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
153 154 155 156 157 158 159 160 161
    /**
     * Determines if the user is currently logged in
     *
     * @return boolean
     */
    public function is_logged_in() {
        return ($this->get('logout_time') > 0 ? true : false);
    }

162

163 164 165 166 167 168 169
    /**
     * 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) {
170 171 172
        if (empty($_SESSION)) {
            $this->create_session();
        }
173 174 175 176 177 178 179 180 181 182 183 184 185 186
        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) {
187 188 189
        if (empty($_SESSION)) {
            $this->create_session();
        }
190 191 192 193 194 195 196 197 198 199 200 201 202 203
        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) {
204 205 206
        if (empty($_SESSION)) {
            $this->create_session();
        }
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
        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() {
225
        $result = '<div id="messages">';
226 227 228 229 230 231
        if (isset($_SESSION['messages'])) {
            foreach ($_SESSION['messages'] as $data) {
                if ($data['type'] == 'ok') {
                    $color = 'green';
                }
                elseif ($data['type'] == 'info') {
232
                    $color = '#aa6';
233 234 235 236 237
                }
                else {
                    $color = 'red';
                }
                $result .= '<div style="color:' . $color . ';">' . $data['msg'] . '</div>';
238
            }
239
            $_SESSION['messages'] = array();
240
        }
241
        $result .= '</div>';
242 243 244
        return $result;
    }

245
    /**
246
     * Create a session, by initialising the $_SESSION array.
247 248
     */
    private function create_session() {
249 250 251
        if (!session_id()) {
            session_start();
        }
252 253 254 255
        $_SESSION = array(
            'messages' => array()
        );
    }
256

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
}

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

?>