session.php 10.3 KB
Newer Older
1 2 3 4
<?php
/**
 *
 * @package    mahara
Nigel McNie's avatar
Nigel McNie committed
5
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9 10 11 12 13
 *
 */

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

14 15 16
//
// Set session settings
//
17
session_name(get_config('cookieprefix') . 'mahara');
18 19
ini_set('session.save_path', '3;' . get_config('dataroot') . 'sessions');
ini_set('session.gc_divisor', 1000);
20
ini_set('session.gc_maxlifetime', get_config('session_timeout'));
21
ini_set('session.use_only_cookies', true);
22 23 24
if ($domain = get_config('cookiedomain')) {
    ini_set('session.cookie_domain', $domain);
}
25 26
ini_set('session.cookie_path', get_mahara_install_subdirectory());
ini_set('session.cookie_httponly', 1);
27
ini_set('session.hash_bits_per_character', 4);
28
ini_set('session.hash_function', 0);
29 30 31
if (is_https()) {
    ini_set('session.cookie_secure', true);
}
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
// Attempt to create session directories
$sessionpath = get_config('dataroot') . 'sessions';
if (!is_dir("$sessionpath/0")) {
    // Create three levels of directories, named 0-9, a-f
    $characters = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    foreach ($characters as $c1) {
        check_dir_exists("$sessionpath/$c1");
        foreach ($characters as $c2) {
            check_dir_exists("$sessionpath/$c1/$c2");
            foreach ($characters as $c3) {
                check_dir_exists("$sessionpath/$c1/$c2/$c3");
            }
        }
    }
}

49
/**
50
 * The session class handles session data and messages.
51
 *
52 53 54 55
 * This class stores information across page loads, using only a cookie to
 * remember the info. User information is stored in the session so it does
 * not have to be requested each time the page is loaded, however any other
 * information can also be stored using this class.
56 57 58 59
 *
 * 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.
60
 *
61 62
 * Messages are stored in the session and are displayed the next time
 * a page is displayed to a user, even over multiple requests.
63 64 65
 */
class Session {

66
    /**
67
     * Resumes an existing session, only if there is one
68
     */
69
    private function __construct() {
70
        // Resume an existing session if required
71
        if (isset($_COOKIE[session_name()])) {
72
            @session_start();
73 74 75
        }
    }

76 77 78 79 80 81 82 83 84 85 86 87
    /**
     * Singelton function keeps us from generating multiple instances of this
     * class
     *
     * @return object   The class instance
     * @access public
     */
    public static function singleton() {
        //single instance
        static $instance;

        //if we don't have the single instance, create one
88
        if (!isset($instance)) {
89 90 91 92 93
            $instance = new Session();
        }
        return($instance);
    }

94 95 96 97 98 99 100 101 102 103
    /**
     * Gets the session property keyed by $key.
     *
     * @param string $key The key to get the value of
     * @return mixed
     */
    public function get($key) {
        if (isset($_SESSION[$key])) {
            return $_SESSION[$key];
        }
Penny Leach's avatar
Penny Leach committed
104 105 106
        return null;
    }

107 108 109 110 111 112 113
    /**
     * 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) {
114
        $this->ensure_session();
115
        $_SESSION[$key] = $value;
116 117
    }

Martyn Smith's avatar
Martyn Smith committed
118 119 120 121 122
    /**
     * Clears the session property keyed by $key (by setting it to null).
     *
     * @param string $key   The key to set.
     */
Martyn Smith's avatar
Martyn Smith committed
123
    public function clear($key) {
Martyn Smith's avatar
Martyn Smith committed
124 125 126 127
        $this->ensure_session();
        $_SESSION[$key] = null;
    }

128 129 130 131 132
    /**
     * Adds a message that indicates something was successful
     *
     * @param string $message The message to add
     * @param boolean $escape Whether to HTML escape the message
133
     * @param string $placement Place for messages to appear on page
134
     */
135
    public function add_ok_msg($message, $escape=true, $placement='messages') {
136
        $this->ensure_session();
137
        if ($escape) {
138
            $message = self::escape_message($message);
139
        }
140
        $_SESSION['messages'][] = array('type' => 'ok', 'msg' => $message, 'placement' => $placement);
141 142 143 144 145 146 147
    }

    /**
     * Adds a message that indicates an informational message
     *
     * @param string $message The message to add
     * @param boolean $escape Whether to HTML escape the message
148
     * @param string $placement Place for messages to appear on page
149
     */
150
    public function add_info_msg($message, $escape=true, $placement='messages') {
151
        $this->ensure_session();
152
        if ($escape) {
153
            $message = self::escape_message($message);
154
        }
155
        $_SESSION['messages'][] = array('type' => 'info', 'msg' => $message, 'placement' => $placement);
156 157 158 159 160 161 162
    }

    /**
     * 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
163
     * @param string $placement Place for messages to appear on page
164
     */
165
    public function add_error_msg($message, $escape=true, $placement='messages') {
166
        $this->ensure_session();
167
        if ($escape) {
168
            $message = self::escape_message($message);
169
        }
170
        $_SESSION['messages'][] = array('type' => 'error', 'msg' => $message, 'placement' => $placement);
171 172 173 174 175 176 177 178
    }

    /**
     * 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
179 180 181
     * assigned to the $placement, so they do not inadvertently get
     * displayed again.
     * @param string  $placement Render only messages for this placement
182
     *
183 184
     * @return string The HTML representing all of the session messages assigned
     * to $placement.
185
     */
186
    public function render_messages($placement) {
187
        global $THEME;
188
        $result = '<div id="' . $placement . '">';
189
        if (isset($_SESSION['messages'])) {
190 191 192 193 194 195
            foreach ($_SESSION['messages'] as $key => $data) {
                if ($data['placement'] == $placement) {
                    $result .= '<div class="' . $data['type'] . '"><div>';
                    $result .= $data['msg'] . '</div></div>';
                    unset($_SESSION['messages'][$key]);
                }
196 197
            }
        }
198
        $result .= '</div>';
199 200 201
        return $result;
    }

202
    /**
203
     * Create a session, by initialising the $_SESSION array.
204
     */
205 206 207
    private function ensure_session() {
        if (empty($_SESSION)) {
            if (!session_id()) {
208
                @session_start();
209 210 211 212
            }
            $_SESSION = array(
                'messages' => array()
            );
213
        }
214 215
    }

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
    /**
     * Destroy a session
     */
    public function destroy_session() {
        if ($this->is_live()) {
            $_SESSION = array();
            if (isset($_COOKIE[session_name()])) {
                setcookie(session_name(), '', time() - 65536,
                    ini_get('session.cookie_path'),
                    ini_get('session.cookie_domain'),
                    ini_get('session.cookie_secure'),
                    ini_get('session.cookie_httponly')
                );
            }
            session_destroy();
        }
    }

234 235 236 237 238 239 240 241 242 243
    /**
     * Find out if the session has been started yet
     */
    public function is_live() {
        if ("" == session_id()) {
            return false;
        }
        return true;
    }

244 245
    /**
     * Escape a message for HTML output
246
     *
247 248 249 250 251 252 253
     * @param string $message The message to escape
     * @return string         The message, escaped for output as HTML
     */
    private static function escape_message($message) {
        $message = hsc($message);
        $message = str_replace('  ', '&nbsp; ', $message);
        return $message;
254
    }
255

256 257 258 259 260 261 262
}

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

268

269 270 271 272
/**
 * Delete all sessions belonging to a given user except for the current one
 */
function remove_user_sessions($userid) {
273
    global $sessionpath, $USER, $SESSION;
274

275
    $sessionids = get_column('usr_session', 'session', 'usr', (int) $userid);
276 277

    if (empty($sessionids)) {
278 279 280 281 282
        return;
    }

    $alive = array();
    $dead = array();
283 284 285 286 287 288 289 290 291 292

    // Keep track of the current session id so we can return to it at the end
    if ($SESSION->is_live()) {
        $sid = $USER->get('sessionid');
    }
    else {
        // The user has no session (this function is being called by a CLI script)
        $sid = false;
    }

293
    foreach ($sessionids as $sessionid) {
294 295 296
        if ($sessionid == $sid) {
            continue;
        }
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
        $file = $sessionpath;
        for ($i = 0; $i < 3; $i++) {
            $file .= '/' . substr($sessionid, $i, 1);
        }
        $file .= '/sess_' . $sessionid;
        if (file_exists($file)) {
            $alive[] = $sessionid;
        }
        else {
            $dead[] = $sessionid;
        }
    }

    if (!empty($dead)) {
        delete_records_select('usr_session', 'session IN (' . join(',', array_map('db_quote', $dead)) . ')');
    }

    if (empty($alive)) {
        return;
    }

    session_commit();

    foreach ($alive as $sessionid) {
        session_id($sessionid);
        if (session_start()) {
            session_destroy();
            session_commit();
        }
    }

328 329 330 331
    if ($sid !== false) {
        session_id($sid);
        session_start();
    }
332 333 334 335

    delete_records_select('usr_session', 'session IN (' . join(',', array_map('db_quote', $alive)) . ')');
}

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
/**
 * Delete all session files except for the current one
 */
function remove_all_sessions() {
    global $sessionpath, $USER;

    $sid = $USER->get('sessionid');

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($sessionpath));
    foreach ($iterator as $path) {
        if ($path->isFile() && $path->getFilename() !== ('sess_' . $sid)) {
            @unlink($path->getPathname());
        }
    }
    clearstatcache();

    delete_records_select('usr_session', 'session != ?', array($sid));
}