source: trunk/lib/Auth_SQL.inc.php @ 111

Last change on this file since 111 was 111, checked in by scdev, 18 years ago

Q - Finished depreciating addslashes. array_map instances need to use array('DB', 'escapeString') as first argument.

File size: 39.0 KB
Line 
1<?php
2/**
3 * The Auth_SQL:: class provides a SQL implementation for authentication.
4 *
5 * @author  Quinn Comendant <quinn@strangecode.com>
6 * @version 2.0
7 */
8
9// Available encryption types for class Auth_SQL.
10define('AUTH_ENCRYPT_MD5', 'md5');
11define('AUTH_ENCRYPT_CRYPT', 'crypt');
12define('AUTH_ENCRYPT_SHA1', 'sha1');
13define('AUTH_ENCRYPT_PLAINTEXT', 'plaintext');
14
15require_once dirname(__FILE__) . '/Email.inc.php';
16
17class Auth_SQL {
18
19    var $_auth = '';
20    var $_sess = '_auth_';
21    var $_authentication_tested;
22    var $_params = array();
23
24    // Default param values.
25    var $_default_params = array(
26
27        // Automatically create table and verify columns. Better set to false after site launch.
28        'create_table' => true,
29
30        // The database table containing users to authenticate.
31        'db_table' => 'user_tbl',
32
33        // The name of the primary key for the db_table.
34        'db_primary_key' => 'user_id',
35
36        // The name of the username key for the db_table.
37        'db_username_column' => 'username',
38
39        // If using the db_login_table feature, specify the db_login_table. The primary key must match the primary key for the db_table.
40        'db_login_table' => 'user_login_tbl',
41
42        // The type of encryption to use for passwords stored in the db_table. Use one of the AUTH_ENCRYPT_* types specified above.
43        'encryption_type' => AUTH_ENCRYPT_MD5,
44
45        // The URL to the login script.
46        'login_url' => '/',
47
48        // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
49        // This applies to admins and users. In seconds. 21600 seconds = 6 hours.
50        'login_timeout' => 21600,
51
52        // The maximum amount of time a user is allowed to be idle before their session expires. They will be forced to login again if they expire.
53        // This applies to admins and users. In seconds. 3600 seconds = 1 hour.
54        'idle_timeout' => 3600,
55
56        // The period of time to compare login abuse attempts. If a threshold of logins is reached in this amount of time the account is blocked.
57        // Days and hours, like this: 'DD:HH'
58        'login_abuse_timeframe' => '04:00',
59
60        // The number of warnings a user will receive (and their password reset each time) before their account is completely blocked.
61        'login_abuse_warnings' => 3,
62
63        // The maximum number of IP addresses a user can login with over the timeout period before their account is blocked.
64        'login_abuse_max_ips' => 5,
65
66        // The IP address subnet size threshold. Uses a CIDR notation network mask (see CIDR cheatsheet at bottom).
67        // Any integar between 0 and 32 is permitted. Setting this to '24' permits any address in a
68        // class C network (255.255.255.0) to be considered the same. Setting to '32' compares each IP absolutely.
69        // Setting to '0' ignores all IPs, thus disabling login_abuse checking.
70        'login_abuse_ip_bitmask' => 32,
71
72        // Specify usernames to exclude from the account abuse detection system. This is specified as a hardcoded array provided at
73        // class instantiation time, or can be saved in the db_table under the login_abuse_exempt field.
74        'login_abuse_exempt_usernames' => array(),
75
76        // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
77        'trusted_networks' => array(),
78
79        // Allow user accounts to be blocked? Requires the user table to have the columns 'blocked' and 'blocked_reason'
80        'blocking' => false,
81
82        // Use a db_login_table to detect excessive logins. This requires blocking to be enabled.
83        'abuse_detection' => false,
84    );
85
86    /**
87     * Constructs a new authentication object.
88     *
89     * @access public
90     * @param optional array $params  A hash containing parameters.
91     */
92    function Auth_SQL($auth_name=null)
93    {
94        if (isset($auth_name)) {
95            $this->_auth = $auth_name;
96            $this->_sess .= $auth_name;
97        }
98
99        // Initialize default parameters.
100        $this->setParam($this->_default_params);
101
102        // Get create tables config from global context.
103        if (!is_null(App::getParam('db_create_tables'))) {
104            $this->setParam(array('create_table' => App::getParam('db_create_tables')));
105        }
106    }
107
108    /**
109     * Setup the database tables for this class.
110     *
111     * @access  public
112     * @author  Quinn Comendant <quinn@strangecode.com>
113     * @since   26 Aug 2005 17:09:36
114     */
115    function initDB($recreate_db=false)
116    {
117        static $_db_tested = false;
118
119        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
120
121            // User table.
122            if ($recreate_db) {
123                DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
124                App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_DEBUG, __FILE__, __LINE__);
125            }
126
127            // The minimal columns for a table compatable with the Auth_SQL class.
128            DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_table') . " (
129                " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL auto_increment,
130                " . $this->getParam('db_username_column') . " varchar(255) NOT NULL default '',
131                userpass varchar(255) NOT NULL default '',
132                first_name varchar(255) NOT NULL default '',
133                last_name varchar(255) NOT NULL default '',
134                email varchar(255) NOT NULL default '',
135                user_type enum('public', 'editor', 'admin', 'root') default NULL,
136                login_abuse_exempt enum('true') default NULL,
137                blocked enum('true') default NULL,
138                blocked_reason varchar(255) NOT NULL default '',
139                abuse_warning_level tinyint(4) NOT NULL default '0',
140                seconds_online int(11) NOT NULL default '0',
141                last_login_datetime datetime NOT NULL default '0000-00-00 00:00:00',
142                last_access_datetime datetime NOT NULL default '0000-00-00 00:00:00',
143                last_login_ip varchar(255) NOT NULL default '0.0.0.0',
144                added_by_user_id smallint(11) default NULL,
145                modified_by_user_id smallint(11) default NULL,
146                added_datetime datetime NOT NULL default '0000-00-00 00:00:00',
147                modified_datetime datetime NOT NULL default '0000-00-00 00:00:00',
148                PRIMARY KEY (" . $this->getParam('db_primary_key') . "),
149                KEY " . $this->getParam('db_username_column') . " (" . $this->getParam('db_username_column') . "),
150                KEY userpass (userpass),
151                KEY email (email)
152            )");
153
154            if (!DB::columnExists($this->getParam('db_table'), array(
155                $this->getParam('db_primary_key'),
156                $this->getParam('db_username_column'),
157                'userpass',
158                'first_name',
159                'last_name',
160                'email',
161                'user_type',
162                'login_abuse_exempt',
163                'blocked',
164                'blocked_reason',
165                'abuse_warning_level',
166                'seconds_online',
167                'last_login_datetime',
168                'last_access_datetime',
169                'last_login_ip',
170                'added_by_user_id',
171                'modified_by_user_id',
172                'added_datetime',
173                'modified_datetime',
174            ), false, false)) {
175                App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
176                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
177            }
178
179            // Login table is used for abuse_detection features.
180            if ($this->getParam('abuse_detection')) {
181                if ($recreate_db) {
182                    DB::query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
183                    App::logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_DEBUG, __FILE__, __LINE__);
184                }
185                DB::query("CREATE TABLE IF NOT EXISTS " . $this->getParam('db_login_table') . " (
186                    " . $this->getParam('db_primary_key') . " smallint(11) NOT NULL default '0',
187                    login_datetime datetime NOT NULL default '0000-00-00 00:00:00',
188                    remote_ip_binary char(32) NOT NULL default '',
189                    KEY " . $this->getParam('db_primary_key') . " (" . $this->getParam('db_primary_key') . "),
190                    KEY login_datetime (login_datetime),
191                    KEY remote_ip_binary (remote_ip_binary)
192                )");
193
194                if (!DB::columnExists($this->getParam('db_login_table'), array(
195                    $this->getParam('db_primary_key'),
196                    'login_datetime',
197                    'remote_ip_binary',
198                ), false, false)) {
199                    App::logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
200                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
201                }
202            }
203        }
204        $_db_tested = true;
205    }
206
207    /**
208     * Set the params of an auth object.
209     *
210     * @param  array $params   Array of parameter keys and value to set.
211     * @return bool true on success, false on failure
212     */
213    function setParam($params)
214    {
215        if (isset($params) && is_array($params)) {
216            // Merge new parameters with old overriding only those passed.
217            $this->_params = array_merge($this->_params, $params);
218        }
219    }
220
221    /**
222     * Return the value of a parameter, if it exists.
223     *
224     * @access public
225     * @param string $param        Which parameter to return.
226     * @return mixed               Configured parameter value.
227     */
228    function getParam($param)
229    {
230        if (isset($this->_params[$param])) {
231            return $this->_params[$param];
232        } else {
233            App::logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
234            return null;
235        }
236    }
237
238    /**
239     * Clear any authentication tokens in the current session. A.K.A. logout.
240     *
241     * @access public
242     */
243    function clearAuth()
244    {
245        $this->initDB();
246
247        DB::query("
248            UPDATE " . $this->_params['db_table'] . " SET
249            seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
250            last_login_datetime = '0000-00-00 00:00:00'
251            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
252        ");
253        $_SESSION['_auth_file'] = array('authenticated' => false);
254    }
255
256    /**
257     * Sets a variable into a registered auth session.
258     *
259     * @access public
260     * @param mixed $key      Which value to set.
261     * @param mixed $val      Value to set variable to.
262     */
263    function setVal($key, $val)
264    {
265        if (!isset($_SESSION[$this->_sess]['user_data'])) {
266            $_SESSION[$this->_sess]['user_data'] = array();
267        }
268        $_SESSION[$this->_sess]['user_data'][$key] = $val;
269    }
270
271    /**
272     * Returns a specified value from a registered auth session.
273     *
274     * @access public
275     * @param mixed $key      Which value to return.
276     * @param mixed $default  Value to return if key not found in user_data.
277     * @return mixed          Value stored in session.
278     */
279    function getVal($key, $default='')
280    {
281        if (isset($_SESSION[$this->_sess][$key])) {
282            return $_SESSION[$this->_sess][$key];
283        } else if (isset($_SESSION[$this->_sess]['user_data'][$key])) {
284            return $_SESSION[$this->_sess]['user_data'][$key];
285        } else {
286            return $default;
287        }
288    }
289
290    /**
291     * Find out if a set of login credentials are valid.
292     *
293     * @access private
294     * @param string $username      The username to check.
295     * @param string $password      The password to compare to username.
296     * @return mixed  False if credentials not found in DB, or returns DB row matching credentials.
297     */
298    function authenticate($username, $password)
299    {
300        $this->initDB();
301
302        // Query DB for user matching credentials.
303        // FIXME: Cannot compare crypt style passwords this way.
304        $qid = DB::query("
305            SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
306            FROM " . $this->_params['db_table'] . "
307            WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
308            AND BINARY userpass = '" . DB::escapeString($this->encryptPassword($password)) . "'
309        ");
310
311        // Return user data if found.
312        if ($user_data = mysql_fetch_assoc($qid)) {
313            App::logMsg(sprintf('Authentication successful for %s %s (%s)', $this->_auth, $user_data['user_id'], $username), LOG_INFO, __FILE__, __LINE__);
314            return $user_data;
315        } else {
316            App::logMsg(sprintf('Authentication failed for %s %s (encrypted attempted password: %s)', $this->_auth, $username, $this->encryptPassword($password)), LOG_NOTICE, __FILE__, __LINE__);
317            return false;
318        }
319    }
320
321    /**
322     * If user authenticated, register login into session.
323     *
324     * @access private
325     * @param string $username     The username to check.
326     * @param string $password     The password to compare to username.
327     * @return boolean  Whether or not the credentials are valid.
328     */
329    function login($username, $password)
330    {
331        $this->initDB();
332
333        $this->clearAuth();
334
335        if (!$user_data = $this->authenticate($username, $password)) {
336            // No login: failed authentication!
337            return false;
338        }
339
340        // Register authenticated session.
341        $_SESSION[$this->_sess] = array(
342            'authenticated'         => true,
343            'user_id'               => $user_data['user_id'],
344            'auth_name'             => $this->_auth,
345            'username'              => $username,
346            'login_datetime'        => date('Y-m-d H:i:s'),
347            'last_access_datetime'  => date('Y-m-d H:i:s'),
348            'remote_ip'             => getRemoteAddr(),
349            'login_abuse_exempt'    => isset($user_data['login_abuse_exempt']) ? !empty($user_data['login_abuse_exempt']) : in_array($username, $this->_params['login_abuse_exempt_usernames']),
350            'user_data'             => $user_data
351        );
352
353        /**
354         * Check if the account is blocked, respond in context to reason. Cancel the login if blocked.
355         */
356        if ($this->getParam('blocking')) {
357            if (!empty($user_data['blocked'])) {
358
359                App::logMsg(sprintf('%s %s (%s) login failed due to blocked account: %s', ucfirst($this->_auth), $this->getVal('user_id'), $this->getVal('username'), $this->getVal('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
360
361                switch ($user_data['blocked_reason']) {
362                    case 'account abuse' :
363                        App::raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact us to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
364                        break;
365                    default :
366                        App::raiseMsg(sprintf(_("This account is currently not active. %s"), $user_data['blocked_reason']), MSG_WARNING, __FILE__, __LINE__);
367                        break;
368                }
369
370                // No login: user is blocked!
371                $this->clearAuth();
372                return false;
373            }
374        }
375
376        /**
377         * Check the db_login_table for too many logins under this account.
378         * (1) Count the number of unique IP addresses that logged in under this user within the login_abuse_timeframe
379         * (2) If this number exceeds the login_abuse_max_ips, assume multiple people are logging in under the same account.
380        **/
381        if ($this->getParam('abuse_detection') && !$this->getVal('login_abuse_exempt')) {
382            $qid = DB::query("
383                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
384                FROM " . $this->_params['db_login_table'] . "
385                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
386                AND DATE_ADD(login_datetime, INTERVAL '" . $this->_params['login_abuse_timeframe'] . "' DAY_HOUR) > NOW()
387            ");
388            list($distinct_ips) = mysql_fetch_row($qid);
389            if ($distinct_ips > $this->_params['login_abuse_max_ips']) {
390                if ($this->getVal('abuse_warning_level') < $this->_params['login_abuse_warnings']) {
391                    // Warn the user with a password reset.
392                    $this->resetPassword(null, _("This is a security precaution. We have detected this account has been accessed from multiple computers simultaneously. It is against policy to share login information with others. If further account abuse is detected this account will be blocked."));
393                    App::raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
394                    App::logMsg(sprintf('Account abuse detected for %s %s (%s) from IP %s', $this->_auth, $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
395                } else {
396                    // Block the account with the reason of account abuse.
397                    $this->blockAccount(null, 'account abuse');
398                    App::raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
399                    App::logMsg(sprintf('Account blocked for %s %s (%s) from IP %s', $this->_auth, $this->getVal('user_id'), $this->getVal('username'), $this->getVal('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
400                }
401                // Increment user's warning level.
402                DB::query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
403                // Reset the login counter for this user.
404                DB::query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'");
405                // No login: reset password because of account abuse!
406                $this->clearAuth();
407                return false;
408            }
409
410            // Update the login counter table with this login access. Convert IP to binary.
411            DB::query("
412                INSERT INTO " . $this->_params['db_login_table'] . " (
413                    " . $this->_params['db_primary_key'] . ",
414                    login_datetime,
415                    remote_ip_binary
416                ) VALUES (
417                    '" . $this->getVal('user_id') . "',
418                    '" . $this->getVal('login_datetime') . "',
419                    '" . sprintf('%032b', ip2long($this->getVal('remote_ip'))) . "'
420                )
421            ");
422        }
423
424        // Update user table with this login.
425        DB::query("
426            UPDATE " . $this->_params['db_table'] . " SET
427                last_login_datetime = '" . $this->getVal('login_datetime') . "',
428                last_access_datetime = '" . $this->getVal('login_datetime') . "',
429                last_login_ip = '" . $this->getVal('remote_ip') . "'
430            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
431        ");
432
433        // We're logged-in!
434        return true;
435    }
436
437    /**
438     * Test if user has a currently logged-in session.
439     *  - authentication flag set to true
440     *  - username not empty
441     *  - total logged-in time is not greater than login_timeout
442     *  - idle time is not greater than idle_timeout
443     *  - remote address is the same as the login remote address (aol users excluded).
444     *
445     * @access public
446     */
447    function isLoggedIn($user_id=null)
448    {
449        $this->initDB();
450
451        if (isset($user_id)) {
452            // Check the login status of a specific user.
453            $qid = DB::query("
454                SELECT 1 FROM " . $this->_params['db_table'] . "
455                WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
456                AND DATE_ADD(last_login_datetime, INTERVAL '" . $this->_params['login_timeout'] . "' SECOND) > NOW()
457                AND DATE_ADD(last_access_datetime, INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND) > NOW()
458            ");
459            return (mysql_num_rows($qid) > 0);
460        }
461
462        // User login test need only be run once per script execution. We cache the result in the session.
463        if ($this->_authentication_tested && isset($_SESSION[$this->_sess]['authenticated'])) {
464            return $_SESSION[$this->_sess]['authenticated'];
465        }
466
467        // Tesing login should occur once. This is the first time. Set flag.
468        $this->_authentication_tested = true;
469
470        // Some users will access from networks with a changing IP number (i.e. behind a proxy server). These users must be allowed entry by adding their IP to the list of trusted_networks.
471        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
472            $user_in_trusted_network = true;
473            App::logMsg(sprintf('%s%s accessing from trusted network %s',
474                ucfirst($this->_auth),
475                ($this->getVal('user_id') ? ' ' . $this->getVal('user_id') . ' (' .  $this->getVal('username') . ')' : ''),
476                $trusted_net
477            ), LOG_DEBUG, __FILE__, __LINE__);
478        } else if (preg_match('/proxy.aol.com$/i', getRemoteAddr(true))) {
479            $user_in_trusted_network = true;
480            App::logMsg(sprintf('%s%s accessing from trusted network proxy.aol.com',
481                ucfirst($this->_auth),
482                ($this->getVal('user_id') ? ' ' . $this->getVal('user_id') . ' (' .  $this->getVal('username') . ')' : '')
483            ), LOG_DEBUG, __FILE__, __LINE__);
484        } else {
485            $user_in_trusted_network = false;
486        }
487
488        // Test login with information stored in session. Skip IP matching for users from trusted networks.
489        if (isset($_SESSION[$this->_sess])
490            && true === $_SESSION[$this->_sess]['authenticated']
491            && !empty($_SESSION[$this->_sess]['username'])
492            && strtotime($_SESSION[$this->_sess]['login_datetime']) > time() - $this->_params['login_timeout']
493            && strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - $this->_params['idle_timeout']
494            && ($_SESSION[$this->_sess]['remote_ip'] == getRemoteAddr() || $user_in_trusted_network)
495        ) {
496            // User is authenticated!
497            $_SESSION[$this->_sess]['last_access_datetime'] = date('Y-m-d H:i:s');
498
499            // Update the DB with the last_access_datetime and increment the seconds_online.
500            DB::query("
501                UPDATE " . $this->_params['db_table'] . " SET
502                seconds_online = seconds_online + (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
503                last_access_datetime = '" . $this->getVal('last_access_datetime') . "'
504                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->getVal('user_id') . "'
505            ");
506            if (mysql_affected_rows(DB::getDBH()) > 0) {
507                // User record still exists in DB. Do this to ensure user was not delete from DB between accesses. Notice "+ 1" in SQL above to ensure record is modified.
508                return true;
509            } else {
510                App::logMsg(sprintf('User update failed. Record not found for %s %s (%s).', $this->_auth, $this->getVal('user_id'), $this->getVal('username')), LOG_NOTICE, __FILE__, __LINE__);
511            }
512        } else if (isset($_SESSION[$this->_sess]) && true === $_SESSION[$this->_sess]['authenticated']) {
513            // User is authenticated, but login has expired.
514            if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) > time() - 43200) {
515                // Only raise message if last session is less than 12 hours old.
516                App::raiseMsg(sprintf(_("Your %s session has closed. You need to log-in again."), strtolower($this->_auth)), MSG_NOTICE, __FILE__, __LINE__);
517            }
518
519            // Log the reason for login expiration.
520            $expire_reasons = array();
521            if (empty($_SESSION[$this->_sess]['username'])) {
522                $expire_reasons[] = 'username not found';
523            }
524            if (strtotime($_SESSION[$this->_sess]['login_datetime']) <= time() - $this->_params['login_timeout']) {
525                $expire_reasons[] = 'login_timeout expired';
526            }
527            if (strtotime($_SESSION[$this->_sess]['last_access_datetime']) <= time() - $this->_params['idle_timeout']) {
528                $expire_reasons[] = 'idle_timeout expired';
529            }
530            if ($_SESSION['_auth_file']['remote_ip'] != getRemoteAddr() && !$user_in_trusted_network) {
531                $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION[$this->_sess]['remote_ip'], getRemoteAddr());
532            }
533            App::logMsg(sprintf('%s %s (%s) session expired: %s', ucfirst($this->_auth), $this->getVal('user_id'), $this->getVal('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
534        }
535
536        // User is not authenticated.
537        $this->clearAuth();
538        return false;
539    }
540
541    /**
542     * Redirect user to login page if they are not logged in.
543     *
544     * @param string $message The text description of a message to raise.
545     * @param int    $type    The type of message: MSG_NOTICE,
546     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
547     * @param string $file    __FILE__.
548     * @param string $line    __LINE__.
549     * @access public
550     */
551    function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
552    {
553        if (!$this->isLoggedIn()) {
554            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
555            App::raiseMsg($message, $type, $file, $line);
556
557            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
558            App::setBoomerangURL(absoluteMe(), 'login');
559            App::dieURL($this->_params['login_url']);
560        }
561    }
562
563    /**
564     * This sets the 'blocked' field for a user in the db_table, and also
565     * adds an optional reason
566     *
567     * @param  string   $reason      The reason for blocking the account.
568     */
569    function blockAccount($user_id=null, $reason='')
570    {
571        $this->initDB();
572
573        if ($this->getParam('blocking')) {
574            if (strlen(DB::escapeString($reason)) > 255) {
575                // blocked_reason field is varchar(255).
576                App::logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
577            }
578
579            // Get user_id if specified.
580            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
581            DB::query("
582                UPDATE " . $this->_params['db_table'] . " SET
583                blocked = 'true',
584                blocked_reason = '" . DB::escapeString($reason) . "'
585                WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
586            ");
587        }
588    }
589
590    /**
591     * Unblocks a user in the db_table, and clears any blocked_reason.
592     */
593    function unblockAccount($user_id=null)
594    {
595        $this->initDB();
596
597        if ($this->getParam('blocking')) {
598            // Get user_id if specified.
599            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
600            DB::query("
601                UPDATE " . $this->_params['db_table'] . " SET
602                blocked = '',
603                blocked_reason = ''
604                WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
605            ");
606        }
607    }
608
609    /**
610     * Returns true if username already exists in database.
611     *
612     * @param  string  $username    Username to look for.
613     * @return bool                 True if username exists.
614     */
615    function usernameExists($username)
616    {
617        $this->initDB();
618
619        $qid = DB::query("
620            SELECT 1
621            FROM " . $this->_params['db_table'] . "
622            WHERE " . $this->_params['db_username_column'] . " = '" . DB::escapeString($username) . "'
623        ");
624        return (mysql_num_rows($qid) > 0);
625    }
626
627    /**
628     * Returns a username for a specified user id.
629     *
630     * @param  string  $user_id     User id to look for.
631     * @return string               Username, or false if none found.
632     */
633    function getUsername($user_id)
634    {
635        $this->initDB();
636
637        $qid = DB::query("
638            SELECT " . $this->_params['db_username_column'] . "
639            FROM " . $this->_params['db_table'] . "
640            WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
641        ");
642        if (list($username) = mysql_fetch_row($qid)) {
643            return $username;
644        } else {
645            return false;
646        }
647    }
648
649    /**
650     * Returns a randomly generated password based on $pattern. The pattern is any
651     * sequence of 'x', 'V', 'C', 'v', 'c', or 'd' and if it is something like 'cvccv' this
652     * function will generate a pronouncable password. Recommend using more complex
653     * patterns, at minimum the US State Department standard: cvcddcvc.
654     *
655     * - x    a random upper or lower alpha character or digit
656     * - C    a random upper or lower consanant
657     * - V    a random upper or lower vowel
658     * - c    a random lowercase consanant
659     * - v    a random lowercase vowel
660     * - d    a random digit
661     *
662     * @param  string $pattern  a sequence of character types, above.
663     * @return string           a password
664     */
665    function generatePassword($pattern='CvccvCdd')
666    {
667        mt_srand((double) microtime() * 10000000);
668        $str = '';
669        for ($i=0; $i<strlen($pattern); $i++) {
670            $x = substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZaeiouyAEIOUY0123456789', (mt_rand() % 60), 1);
671            $c = substr('bcdfghjklmnprstvwxz', (mt_rand() % 19), 1);
672            $C = substr('bcdfghjklmnprstvwxzBCDFGHJKLMNPRSTVWXZ', (mt_rand() % 38), 1);
673            $v = substr('aeiouy', (mt_rand() % 6), 1);
674            $V = substr('aeiouyAEIOUY', (mt_rand() % 12), 1);
675            $d = substr('0123456789', (mt_rand() % 10), 1);
676            $str .= $$pattern{$i};
677        }
678        return $str;
679    }
680
681    /**
682     *
683     */
684    function encryptPassword($password)
685    {
686        switch ($this->_params['encryption_type']) {
687        case AUTH_ENCRYPT_PLAINTEXT :
688            return $password;
689            break;
690
691        case AUTH_ENCRYPT_CRYPT :
692            return crypt($password);
693            break;
694
695        case AUTH_ENCRYPT_SHA1 :
696            return sha1($password);
697            break;
698
699        case AUTH_ENCRYPT_MD5 :
700        default :
701            return md5($password);
702            break;
703        }
704    }
705
706    /**
707     *
708     */
709    function setPassword($user_id=null, $password)
710    {
711        $this->initDB();
712
713        // Get user_id if specified.
714        $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
715
716        // Issue the password change query.
717        DB::query("
718            UPDATE " . $this->_params['db_table'] . "
719            SET userpass = '" . DB::escapeString($this->encryptPassword($password)) . "'
720            WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
721        ");
722    }
723
724    /**
725     * Resets the password for the user with the specified id.
726     *
727     * @param  string $user_id   The id of the user to reset.
728     * @param  string $reason    Additional message to add to the reset email.
729     * @return string            The user's new password.
730     */
731    function resetPassword($user_id=null, $reason='')
732    {
733        $this->initDB();
734
735        // Get user_id if specified.
736        $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
737
738        // Reset password of a specific user.
739        $qid = DB::query("
740            SELECT * FROM " . $this->_params['db_table'] . "
741            WHERE " . $this->_params['db_primary_key'] . " = '" . DB::escapeString($user_id) . "'
742        ");
743        if (!$user_data = mysql_fetch_assoc($qid)) {
744            App::logMsg(sprintf('Reset password failed. %s %s not found.', ucfirst($this->_auth), $user_id), LOG_NOTICE, __FILE__, __LINE__);
745            return false;
746        }
747
748        // Get new password.
749        $password = $this->generatePassword();
750
751        // Update password query.
752        $this->setPassword($user_id, $password);
753
754        // Make sure user has an email on record before continuing.
755        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
756            App::logMsg(sprintf('Password reset but notification failed, no email address for %s %s (%s).', $this->_auth, $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
757        } else {
758            // Body for email.
759            $email_body = <<<EOF
760Hello {NAME},
761
762Your password at {SITE_NAME} has been reset. {REASON}
763Your new login information is:
764
765USERNAME: {USERNAME}
766PASSWORD: {PASSWORD}
767
768If you have any questions or concerns please reply to this email or visit the website below.
769
770Thank you,
771{SITE_NAME}
772{SITE_URL}/
773
774EOF;
775            $email = new Email(array(
776                'to' => $user_data['email'],
777                'from' => sprintf('%s <%s>', App::getParam('site_name'), App::getParam('site_email')),
778                'subject' => sprintf('%s password change', App::getParam('site_name'))
779            ));
780            $email->setString($email_body);
781            $email->replace(array(
782                'site_name' => App::getParam('site_name'),
783                'site_url' => App::getParam('site_url'),
784                'name' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
785                'username' => $user_data[$this->_params['db_username_column']],
786                'password' => $password,
787                'reason' => $reason,
788            ));
789            $email->send();
790        }
791
792        return array(
793            'username' => $user_data[$this->_params['db_username_column']],
794            'userpass' => $password
795        );
796    }
797
798    /**
799     * If the current user has access to the specified $security_zone, return true.
800     * If the optional $priv is supplied, test that against the zone.
801     *
802     * @param  constant $security_zone   string of comma delimited priviliges for the zone
803     * @param  string   $priv            a privilege that might be found in a zone
804     * @return bool     true if user is a member of security zone, false otherwise
805     */
806    function inClearanceZone($security_zone, $priv='')
807    {
808        return true;
809        $zone_members = preg_split('/,\s*/', $security_zone);
810        $priv = empty($priv) ? $this->getVal('priv') : $priv;
811
812        // If the current user's privilege level is NOT in that array or if the
813        // user has no privilege, return false. Otherwise the user is clear.
814        if (!in_array($priv, $zone_members) || empty($priv)) {
815            return false;
816        } else {
817            return true;
818        }
819    }
820
821    /**
822     * This function tests a list of arguments $security_zone against the priv that the current user has.
823     * If the user doesn't have one of the supplied privs, die.
824     *
825     * @param  constant $security_zone   string of comma delimited priviliges for the zone
826     */
827    function requireAccessClearance($security_zone, $message='')
828    {
829        return true;
830        $zone_members = preg_split('/,\s*/', $security_zone);
831
832        /* If the current user's privilege level is NOT in that array or if the
833         * user has no privilege, DIE with a message. */
834        if (!in_array($this->getVal('priv'), $zone_members) || !$this->getVal('priv')) {
835            $message = empty($message) ? _("You have insufficient privileges to view that page.") : $message;
836            App::raiseMsg($message, MSG_NOTICE, __FILE__, __LINE__);
837            App::dieBoomerangURL();
838        }
839    }
840
841} // end class
842
843// CIDR cheat-sheet
844//
845// Netmask              Netmask (binary)                 CIDR     Notes
846// _____________________________________________________________________________
847// 255.255.255.255  11111111.11111111.11111111.11111111  /32  Host (single addr)
848// 255.255.255.254  11111111.11111111.11111111.11111110  /31  Unusable
849// 255.255.255.252  11111111.11111111.11111111.11111100  /30    2  useable
850// 255.255.255.248  11111111.11111111.11111111.11111000  /29    6  useable
851// 255.255.255.240  11111111.11111111.11111111.11110000  /28   14  useable
852// 255.255.255.224  11111111.11111111.11111111.11100000  /27   30  useable
853// 255.255.255.192  11111111.11111111.11111111.11000000  /26   62  useable
854// 255.255.255.128  11111111.11111111.11111111.10000000  /25  126  useable
855// 255.255.255.0    11111111.11111111.11111111.00000000  /24 "Class C" 254 useable
856//
857// 255.255.254.0    11111111.11111111.11111110.00000000  /23    2  Class C's
858// 255.255.252.0    11111111.11111111.11111100.00000000  /22    4  Class C's
859// 255.255.248.0    11111111.11111111.11111000.00000000  /21    8  Class C's
860// 255.255.240.0    11111111.11111111.11110000.00000000  /20   16  Class C's
861// 255.255.224.0    11111111.11111111.11100000.00000000  /19   32  Class C's
862// 255.255.192.0    11111111.11111111.11000000.00000000  /18   64  Class C's
863// 255.255.128.0    11111111.11111111.10000000.00000000  /17  128  Class C's
864// 255.255.0.0      11111111.11111111.00000000.00000000  /16  "Class B"
865//
866// 255.254.0.0      11111111.11111110.00000000.00000000  /15    2  Class B's
867// 255.252.0.0      11111111.11111100.00000000.00000000  /14    4  Class B's
868// 255.248.0.0      11111111.11111000.00000000.00000000  /13    8  Class B's
869// 255.240.0.0      11111111.11110000.00000000.00000000  /12   16  Class B's
870// 255.224.0.0      11111111.11100000.00000000.00000000  /11   32  Class B's
871// 255.192.0.0      11111111.11000000.00000000.00000000  /10   64  Class B's
872// 255.128.0.0      11111111.10000000.00000000.00000000  /9   128  Class B's
873// 255.0.0.0        11111111.00000000.00000000.00000000  /8   "Class A"
874//
875// 254.0.0.0        11111110.00000000.00000000.00000000  /7
876// 252.0.0.0        11111100.00000000.00000000.00000000  /6
877// 248.0.0.0        11111000.00000000.00000000.00000000  /5
878// 240.0.0.0        11110000.00000000.00000000.00000000  /4
879// 224.0.0.0        11100000.00000000.00000000.00000000  /3
880// 192.0.0.0        11000000.00000000.00000000.00000000  /2
881// 128.0.0.0        10000000.00000000.00000000.00000000  /1
882// 0.0.0.0          00000000.00000000.00000000.00000000  /0   IP space
883?>
Note: See TracBrowser for help on using the repository browser.