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

Last change on this file since 619 was 619, checked in by anonymous, 7 years ago

Update messages

File size: 50.9 KB
Line 
1<?php
2/**
3 * The Strangecode Codebase - a general application development framework for PHP
4 * For details visit the project site: <http://trac.strangecode.com/codebase/>
5 * Copyright 2001-2012 Strangecode, LLC
6 *
7 * This file is part of The Strangecode Codebase.
8 *
9 * The Strangecode Codebase is free software: you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * The Strangecode Codebase is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17 * details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * The Strangecode Codebase. If not, see <http://www.gnu.org/licenses/>.
21 */
22
23/*
24* The Auth_SQL class provides a SQL implementation for authentication.
25*
26* @author  Quinn Comendant <quinn@strangecode.com>
27* @version 2.1
28*/
29
30require_once dirname(__FILE__) . '/Email.inc.php';
31
32class Auth_SQL
33{
34    // Available hash types for class Auth_SQL.
35    const ENCRYPT_PLAINTEXT = 1;
36    const ENCRYPT_CRYPT = 2;
37    const ENCRYPT_SHA1 = 3;
38    const ENCRYPT_SHA1_HARDENED = 4;
39    const ENCRYPT_MD5 = 5;
40    const ENCRYPT_MD5_HARDENED = 6;
41    const ENCRYPT_PASSWORD_BCRYPT = 7;
42    const ENCRYPT_PASSWORD_DEFAULT = 8;
43
44    // Namespace of this auth object.
45    protected $_ns;
46
47    // Static var for test.
48    protected $_authentication_tested;
49
50    // Parameters to be configured by setParam.
51    protected $_params = array();
52    protected $_default_params = array(
53
54        // Automatically create table and verify columns. Better set to false after site launch.
55        // This value is overwritten by the $app->getParam('db_create_tables') setting if it is available.
56        'create_table' => true,
57
58        // The database table containing users to authenticate.
59        'db_table' => 'user_tbl',
60
61        // The name of the primary key for the db_table.
62        'db_primary_key' => 'user_id',
63
64        // The name of the username key for the db_table.
65        'db_username_column' => 'username',
66
67        // If using the db_login_table feature, specify the db_login_table. The primary key must match the primary key for the db_table.
68        'db_login_table' => 'user_login_tbl',
69
70        // The type of hash to use for passwords stored in the db_table. Use one of the Auth_SQL::ENCRYPT_* types specified above.
71        // Hardened password hashes rely on the same key/salt being used to compare hashes.
72        // Be aware that when using one of the hardened types the App signing_key or $more_salt below cannot change!
73        'hash_type' => self::ENCRYPT_MD5,
74        'encryption_type' => null, // Backwards misnomer compatibility.
75
76        // Automatically update stored user hashes when the user next authenticates if the hash type changes (requires user_tbl with populated userpass_hashtype column).
77        'hash_type_autoupdate' => true,
78
79        // The URL to the login script.
80        'login_url' => '/',
81
82        // The maximum amount of time a user is allowed to be logged in. They will be forced to login again if they expire.
83        // In seconds. 21600 seconds = 6 hours.
84        'login_timeout' => 21600,
85
86        // 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.
87        // In seconds. 3600 seconds = 1 hour.
88        'idle_timeout' => 3600,
89
90        // 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.
91        // Days and hours, like this: 'DD:HH'
92        'login_abuse_timeframe' => '04:00',
93
94        // The number of warnings a user will receive (and their password reset each time) before their account is completely blocked.
95        'login_abuse_warnings' => 3,
96
97        // The maximum number of IP addresses a user can login with over the timeout period before their account is blocked.
98        'login_abuse_max_ips' => 5,
99
100        // The IP address subnet size threshold. Uses a CIDR notation network mask (see CIDR cheat-sheet at bottom).
101        // Any integer between 0 and 32 is permitted. Setting this to '24' permits any address in a
102        // class C network (255.255.255.0) to be considered the same. Setting to '32' compares each IP absolutely.
103        // Setting to '0' ignores all IPs, thus disabling login_abuse checking.
104        'login_abuse_ip_bitmask' => 32,
105
106        // Specify usernames to exclude from the account abuse detection system. This is specified as a hardcoded array provided at
107        // class instantiation time, or can be saved in the db_table under the login_abuse_exempt field.
108        'login_abuse_exempt_usernames' => array(),
109
110        // Specify usernames to exclude from remote_ip matching. Users behind proxy servers should be appended to this array so their shifting remote IP will not log them out.
111        'match_remote_ip_exempt_usernames' => array(),
112
113        // Match the user's current remote IP against the one they logged in with.
114        'match_remote_ip' => true,
115
116        // An array of IP blocks that are bypass the remote_ip comparison check. Useful for dynamic IPs or those behind proxy servers.
117        'trusted_networks' => array(),
118
119        // Allow user accounts to be blocked? Requires the user table to have the columns 'blocked' and 'blocked_reason'
120        'blocking' => false,
121
122        // Use a db_login_table to detect excessive logins. This requires blocking to be enabled.
123        'abuse_detection' => false,
124
125        // Allow users to save login form passwords in their browser? Setting to 'true' may pose a potential security risk.
126        'login_form_allow_autocomplete' => false,
127    );
128
129    /**
130     * Constructs a new authentication object.
131     *
132     * @access public
133     * @param optional array $params  A hash containing parameters.
134     */
135    public function __construct($namespace='')
136    {
137        $app =& App::getInstance();
138
139        $this->_ns = $namespace;
140
141        // Initialize default parameters.
142        $this->setParam($this->_default_params);
143
144        // Get create tables config from global context.
145        if (!is_null($app->getParam('db_create_tables'))) {
146            $this->setParam(array('create_table' => $app->getParam('db_create_tables')));
147        }
148
149        if (!isset($_SESSION['_auth_sql'][$this->_ns])) {
150            $this->clear();
151        }
152    }
153
154    /**
155     * Setup the database tables for this class.
156     *
157     * @access  public
158     * @author  Quinn Comendant <quinn@strangecode.com>
159     * @since   26 Aug 2005 17:09:36
160     */
161    public function initDB($recreate_db=false)
162    {
163        $app =& App::getInstance();
164        $db =& DB::getInstance();
165
166        static $_db_tested = false;
167
168        if ($recreate_db || !$_db_tested && $this->getParam('create_table')) {
169
170            // User table.
171            if ($recreate_db) {
172                $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_table'));
173                $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_table')), LOG_INFO, __FILE__, __LINE__);
174            }
175
176            // The minimal columns for a table compatible with the Auth_SQL class.
177            $db->query(sprintf(
178                "CREATE TABLE IF NOT EXISTS %1\$s (
179                    %2\$s MEDIUMINT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
180                    %3\$s varchar(255) NOT NULL default '',
181                    userpass VARCHAR(255) NOT NULL DEFAULT '',
182                    userpass_hashtype TINYINT UNSIGNED NOT NULL DEFAULT '0',
183                    first_name VARCHAR(50) NOT NULL DEFAULT '',
184                    last_name VARCHAR(50) NOT NULL DEFAULT '',
185                    email VARCHAR(255) NOT NULL DEFAULT '',
186                    login_abuse_exempt ENUM('true') DEFAULT NULL,
187                    blocked ENUM('true') DEFAULT NULL,
188                    blocked_reason VARCHAR(255) NOT NULL DEFAULT '',
189                    abuse_warning_level TINYINT NOT NULL DEFAULT '0',
190                    seconds_online INT NOT NULL DEFAULT '0',
191                    last_login_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
192                    last_access_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
193                    last_login_ip VARCHAR(45) NOT NULL DEFAULT '0.0.0.0',
194                    added_by_user_id SMALLINT DEFAULT NULL,
195                    modified_by_user_id SMALLINT DEFAULT NULL,
196                    added_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
197                    modified_datetime DATETIME NOT NULL DEFAULT '%4\$s 00:00:00',
198                    KEY %5\$s (%5\$s),
199                    KEY userpass (userpass),
200                    KEY email (email),
201                    KEY last_login_datetime (last_login_datetime),
202                    KEY last_access_datetime (last_access_datetime)
203                )",
204                $db->escapeString($this->getParam('db_table')),
205                $this->getParam('db_primary_key'),
206                $this->getParam('db_username_column'),
207                $db->getParam('zero_date'),
208                $this->getParam('db_username_column')
209            ));
210
211            if (!$db->columnExists($this->getParam('db_table'), array(
212                $this->getParam('db_primary_key'),
213                $this->getParam('db_username_column'),
214                'userpass',
215                'first_name',
216                'last_name',
217                'email',
218                'login_abuse_exempt',
219                'blocked',
220                'blocked_reason',
221                'abuse_warning_level',
222                'seconds_online',
223                'last_login_datetime',
224                'last_access_datetime',
225                'last_login_ip',
226                'added_by_user_id',
227                'modified_by_user_id',
228                'added_datetime',
229                'modified_datetime',
230            ), false, false)) {
231                $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), LOG_ALERT, __FILE__, __LINE__);
232                trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_table')), E_USER_ERROR);
233            }
234
235            // Login table is used for abuse_detection features.
236            if ($this->getParam('abuse_detection')) {
237                if ($recreate_db) {
238                    $db->query("DROP TABLE IF EXISTS " . $this->getParam('db_login_table'));
239                    $app->logMsg(sprintf('Dropping and recreating table %s.', $this->getParam('db_login_table')), LOG_INFO, __FILE__, __LINE__);
240                }
241                $db->query(sprintf(
242                    "CREATE TABLE IF NOT EXISTS %1\$s (
243                        %2\$s MEDIUMINT UNSIGNED NOT NULL DEFAULT '0',
244                        login_datetime DATETIME NOT NULL DEFAULT '%3\$s 00:00:00',
245                        remote_ip_binary CHAR(32) NOT NULL DEFAULT '',
246                        KEY %4\$s (%4\$s),
247                        KEY login_datetime (login_datetime),
248                        KEY remote_ip_binary (remote_ip_binary)
249                    )",
250                    $this->getParam('db_login_table'),
251                    $this->getParam('db_primary_key'),
252                    $db->getParam('zero_date'),
253                    $this->getParam('db_primary_key')
254                ));
255
256                if (!$db->columnExists($this->getParam('db_login_table'), array(
257                    $this->getParam('db_primary_key'),
258                    'login_datetime',
259                    'remote_ip_binary',
260                ), false, false)) {
261                    $app->logMsg(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), LOG_ALERT, __FILE__, __LINE__);
262                    trigger_error(sprintf('Database table %s has invalid columns. Please update this table manually.', $this->getParam('db_login_table')), E_USER_ERROR);
263                }
264            }
265        }
266        $_db_tested = true;
267    }
268
269    /**
270     * Set the params of an auth object.
271     *
272     * @param  array $params   Array of parameter keys and value to set.
273     * @return bool true on success, false on failure
274     */
275    public function setParam($params)
276    {
277        $app =& App::getInstance();
278
279        if (isset($params['match_remote_ip_exempt_usernames'])) {
280            $params['match_remote_ip_exempt_usernames'] = array_map('strtolower', $params['match_remote_ip_exempt_usernames']);
281        }
282        if (isset($params['login_abuse_exempt_usernames'])) {
283            $params['login_abuse_exempt_usernames'] = array_map('strtolower', $params['login_abuse_exempt_usernames']);
284        }
285        if (isset($params['encryption_type'])) {
286            // Backwards misnomer compatibility.
287            $params['hash_type'] = $params['encryption_type'];
288        }
289        if (isset($params['hash_type']) && version_compare(PHP_VERSION, '5.5.0', '<') && in_array($params['hash_type'], array(self::ENCRYPT_PASSWORD_BCRYPT, self::ENCRYPT_PASSWORD_DEFAULT))) {
290            // These hash types require the password_* userland lib in PHP < 5.5.0
291            $pw_compat_lib = 'vendor/ircmaxell/password-compat/lib/password.php';
292            if (false !== stream_resolve_include_path($pw_compat_lib)) {
293                include_once $pw_compat_lib;
294            } else {
295                $app->logMsg(sprintf('Hash type %s requires password-compat lib in PHP < 5.5.0; falling back to ENCRYPT_SHA1_HARDENED', $params['hash_type']), LOG_ERR, __FILE__, __LINE__);
296                $params['hash_type'] = self::ENCRYPT_SHA1_HARDENED;
297            }
298        }
299        if (isset($params['hash_type']) && !in_array($params['hash_type'], array(self::ENCRYPT_PLAINTEXT, self::ENCRYPT_CRYPT, self::ENCRYPT_SHA1, self::ENCRYPT_SHA1_HARDENED, self::ENCRYPT_MD5, self::ENCRYPT_MD5_HARDENED, self::ENCRYPT_PASSWORD_BCRYPT, self::ENCRYPT_PASSWORD_DEFAULT))) {
300            $app->logMsg(sprintf('Invalid hash type %s; falling back to ENCRYPT_SHA1_HARDENED', $params['hash_type']), LOG_ERR, __FILE__, __LINE__);
301            $params['hash_type'] = self::ENCRYPT_SHA1_HARDENED;
302        }
303        if (isset($params) && is_array($params)) {
304            // Merge new parameters with old overriding only those passed.
305            $this->_params = array_merge($this->_params, $params);
306        }
307    }
308
309    /**
310     * Return the value of a parameter, if it exists.
311     *
312     * @access public
313     * @param string $param        Which parameter to return.
314     * @return mixed               Configured parameter value.
315     */
316    public function getParam($param)
317    {
318        $app =& App::getInstance();
319
320        if (array_key_exists($param, $this->_params)) {
321            return $this->_params[$param];
322        } else {
323            $app->logMsg(sprintf('Parameter is not set: %s', $param), LOG_DEBUG, __FILE__, __LINE__);
324            return null;
325        }
326    }
327
328    /**
329     * Clear any authentication tokens in the current session. A.K.A. logout.
330     *
331     * @access public
332     */
333    public function clear()
334    {
335        $app =& App::getInstance();
336        $db =& DB::getInstance();
337
338        if ($this->get('user_id', false)) {
339
340            $this->initDB();
341
342            // FIX ME: Should we check if the session is active?
343            $db->query(sprintf(
344                "UPDATE %s SET
345                    seconds_online = seconds_online + ABS(UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)),
346                    last_login_datetime = '%s 00:00:00'
347                    WHERE %s = '%s'
348                ",
349                $this->_params['db_table'],
350                $db->getParam('zero_date'),
351                $this->_params['db_primary_key'],
352                $this->get('user_id')
353            ));
354        }
355        $_SESSION['_auth_sql'][$this->_ns] = array(
356            'authenticated'         => false,
357            'user_id'               => null,
358            'username'              => null,
359            'login_datetime'        => null,
360            'last_access_datetime'  => null,
361            'remote_ip'             => getRemoteAddr(),
362            'login_abuse_exempt'    => null,
363            'match_remote_ip_exempt'=> null,
364            'user_data'             => null,
365        );
366
367        $app->logMsg(sprintf('Cleared %s auth', $this->_ns), LOG_DEBUG, __FILE__, __LINE__);
368    }
369
370    /**
371     * Sets a variable into a registered auth session.
372     *
373     * @access public
374     * @param mixed $key      Which value to set.
375     * @param mixed $val      Value to set variable to.
376     */
377    public function set($key, $val)
378    {
379        if (!isset($_SESSION['_auth_sql'][$this->_ns]['user_data'])) {
380            $_SESSION['_auth_sql'][$this->_ns]['user_data'] = array();
381        }
382        $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key] = $val;
383    }
384
385    /**
386     * Returns a specified value from a registered auth session.
387     *
388     * @access public
389     * @param mixed $key      Which value to return.
390     * @param mixed $default  Value to return if key not found in user_data.
391     * @return mixed          Value stored in session.
392     */
393    public function get($key, $default='')
394    {
395        if (isset($_SESSION['_auth_sql'][$this->_ns][$key])) {
396            return $_SESSION['_auth_sql'][$this->_ns][$key];
397        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['user_data'][$key])) {
398            return $_SESSION['_auth_sql'][$this->_ns]['user_data'][$key];
399        } else {
400            return $default;
401        }
402    }
403
404    /**
405     * Retrieve and verify the given username and password against a matching user record in the database.
406     *
407     * @access private
408     * @param string $username      The username to check.
409     * @param string $password      The password to compare to username.
410     * @return mixed  False if credentials not found in DB, or returns DB row matching credentials.
411     */
412    public function authenticate($username, $password)
413    {
414        $app =& App::getInstance();
415        $db =& DB::getInstance();
416
417        $this->initDB();
418
419        // Get user data for specified username.
420        $qid = $db->query("
421            SELECT *, " . $this->_params['db_primary_key'] . " AS user_id
422            FROM " . $this->_params['db_table'] . "
423            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
424        ");
425        if (!$user_data = mysql_fetch_assoc($qid)) {
426            $app->logMsg(sprintf('Username %s not found for authentication', $username), LOG_NOTICE, __FILE__, __LINE__);
427            return false;
428        }
429
430        // Check given password against hashed DB password.
431        $old_hash_type = isset($user_data['userpass_hashtype']) && !empty($user_data['userpass_hashtype']) ? $user_data['userpass_hashtype'] : $this->getParam('hash_type');
432        if ($this->verifyPassword($password, $user_data['userpass'], $old_hash_type)) {
433            $app->logMsg(sprintf('Authentication successful for %s (user_id=%s)', $username, $user_data['user_id']), LOG_INFO, __FILE__, __LINE__);
434            unset($user_data['userpass']); // Avoid revealing the encrypted password in the $user_data.
435            if ($this->getParam('hash_type_autoupdate') && $old_hash_type != $this->getParam('hash_type')) {
436                // Let's update user's password hash to new type (just run setPassword with this authenticated password
).
437                $this->setPassword($user_data['user_id'], $password);
438                $app->logMsg(sprintf('User %s password hash type updated from %s to %s', $username, $old_hash_type, $this->getParam('hash_type')), LOG_INFO, __FILE__, __LINE__);
439            }
440            return $user_data;
441        }
442
443        $app->logMsg(sprintf('Authentication failed for %s (user_id=%s)', $username, $user_data['user_id']), LOG_NOTICE, __FILE__, __LINE__);
444        return false;
445    }
446
447    /**
448     * Check username and password, and create new session if authenticated.
449     *
450     * @access private
451     * @param string $username     The username to check.
452     * @param string $password     The password to compare for username.
453     * @return boolean  Whether or not the credentials are valid.
454     */
455    public function login($username, $password)
456    {
457        $app =& App::getInstance();
458        $db =& DB::getInstance();
459
460        if ($user_data = $this->authenticate($username, $password)) {
461            // The credentials match. Now setup the session.
462            return $this->createSession($user_data);
463        }
464        // No login: failed authentication!
465        return false;
466    }
467
468    /**
469     * Create new login session for given user.
470     *
471     * @access private
472     * @param string $user_data User data that is normally returned from this->authenticate(). If provided manually:
473     *                          Required array values:
474     *                              'user_id' => '1'
475     *                              'username' => 'name'
476     *                          Optional array values:
477     *                              'match_remote_ip_exempt' => true
478     *                              'login_abuse_exempt' => true
479     *                              'abuse_warning_level' => true
480     *                              'blocked' => true
481     *                              'blocked_reason' => ''
482     *                              '
' => '
' (any other values that should be retrievable via this->get())
483     * @return boolean          Whether or not the session was created. It will return true unless abuse detection is enabled and triggered.
484     */
485    public function createSession($user_data)
486    {
487        $app =& App::getInstance();
488        $db =& DB::getInstance();
489
490        $this->initDB();
491
492        $this->clear();
493
494        // Convert 'priv' to 'user_type' nomenclature to support older implementations.
495        if (isset($user_data['priv'])) {
496            $user_data['user_type'] = $user_data['priv'];
497        }
498
499        // Register authenticated session.
500        $_SESSION['_auth_sql'][$this->_ns] = array(
501            'authenticated'         => true,
502            'user_id'               => $user_data['user_id'],
503            'username'              => $user_data['username'],
504            'login_datetime'        => date('Y-m-d H:i:s'),
505            'last_access_datetime'  => date('Y-m-d H:i:s'),
506            'remote_ip'             => getRemoteAddr(),
507            'login_abuse_exempt'    => isset($user_data['login_abuse_exempt']) ? !empty($user_data['login_abuse_exempt']) : in_array(strtolower($user_data['username']), $this->_params['login_abuse_exempt_usernames']),
508            'match_remote_ip_exempt'=> isset($user_data['match_remote_ip_exempt']) ? !empty($user_data['match_remote_ip_exempt']) : in_array(strtolower($user_data['username']), $this->_params['match_remote_ip_exempt_usernames']),
509            'user_data'             => $user_data
510        );
511
512        /**
513         * Check if the account is blocked, respond in context to reason. Cancel the login if blocked.
514         */
515        if ($this->getParam('blocking')) {
516            if (isset($user_data['blocked']) && !empty($user_data['blocked'])) {
517                switch ($this->get('blocked_reason')) {
518                case 'account abuse' :
519                    $app->raiseMsg(sprintf(_("This account has been blocked due to possible account abuse. Please contact an administrator to reactivate."), null), MSG_WARNING, __FILE__, __LINE__);
520                    break;
521                default :
522                    $app->raiseMsg(sprintf(_("This account is currently not active. %s"), $this->get('blocked_reason')), MSG_WARNING, __FILE__, __LINE__);
523                    break;
524                }
525
526                // No login: user is blocked!
527                $app->logMsg(sprintf('User_id %s (%s) login failed due to blocked account: %s', $this->get('user_id'), $this->get('username'), $this->get('blocked_reason')), LOG_NOTICE, __FILE__, __LINE__);
528                $this->clear();
529                return false;
530            }
531        }
532
533        /**
534         * Check the db_login_table for too many logins under this account.
535         * (1) Count the number of unique IP addresses that logged in under this user within the login_abuse_timeframe
536         * (2) If this number exceeds the login_abuse_max_ips, assume multiple people are logging in under the same account.
537        **/
538        // TODO: make this ipv6 compatible. At the moment, ipv6 addresses are converted into zero for remote_ip_binary.
539        // http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php
540        // https://stackoverflow.com/questions/444966/working-with-ipv6-addresses-in-php
541        if ($this->getParam('abuse_detection') && !$this->get('login_abuse_exempt')) {
542            $qid = $db->query("
543                SELECT COUNT(DISTINCT LEFT(remote_ip_binary, " . $this->_params['login_abuse_ip_bitmask'] . "))
544                FROM " . $this->_params['db_login_table'] . "
545                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
546                AND DATE_ADD(login_datetime, INTERVAL '" . $this->_params['login_abuse_timeframe'] . "' DAY_HOUR) > NOW()
547            ");
548            list($distinct_ips) = mysql_fetch_row($qid);
549            if ($distinct_ips > $this->_params['login_abuse_max_ips']) {
550                if ($this->get('abuse_warning_level') < $this->_params['login_abuse_warnings']) {
551                    // Warn the user with a password reset.
552                    $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 credentials with others. If further account abuse is detected this account will be blocked."));
553                    $app->raiseMsg(_("Your password has been reset as a security precaution. Please check your email for more information."), MSG_NOTICE, __FILE__, __LINE__);
554                    $app->logMsg(sprintf('Account abuse detected for user_id %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_WARNING, __FILE__, __LINE__);
555                } else {
556                    // Block the account with the reason of account abuse.
557                    $this->blockAccount(null, 'account abuse');
558                    $app->raiseMsg(_("Your account has been blocked as a security precaution. Please contact us for more information."), MSG_NOTICE, __FILE__, __LINE__);
559                    $app->logMsg(sprintf('Account blocked for user_id %s (%s) from IP %s', $this->get('user_id'), $this->get('username'), $this->get('remote_ip')), LOG_ALERT, __FILE__, __LINE__);
560                }
561                // Increment user's warning level.
562                $db->query("UPDATE " . $this->_params['db_table'] . " SET abuse_warning_level = abuse_warning_level + 1 WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
563                // Reset the login counter for this user.
564                $db->query("DELETE FROM " . $this->_params['db_login_table'] . " WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'");
565                // No login: reset password because of account abuse!
566                $this->clear();
567                return false;
568            }
569
570            // Update the login counter table with this login access. Convert IP to binary.
571            // TODO: this query could benefit from INSERT DELAYED.
572            $db->query("
573                INSERT INTO " . $this->_params['db_login_table'] . " (
574                    " . $this->_params['db_primary_key'] . ",
575                    login_datetime,
576                    remote_ip_binary
577                ) VALUES (
578                    '" . $this->get('user_id') . "',
579                    '" . $this->get('login_datetime') . "',
580                    '" . sprintf('%032b', ip2long($this->get('remote_ip'))) . "'
581                )
582            ");
583        }
584
585        // Update user table with this login.
586        $db->query("
587            UPDATE " . $this->_params['db_table'] . " SET
588                last_login_datetime = '" . $this->get('login_datetime') . "',
589                last_access_datetime = '" . $this->get('login_datetime') . "',
590                last_login_ip = '" . $this->get('remote_ip') . "'
591            WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
592        ");
593
594        // Session created! We're logged-in!
595        return true;
596    }
597
598    /**
599     * Test if user has a currently logged-in session.
600     *  - authentication flag set to true
601     *  - username not empty
602     *  - total logged-in time is not greater than login_timeout
603     *  - idle time is not greater than idle_timeout
604     *  - remote address is the same as the login remote address
605     *
606     * @access public
607     */
608    public function isLoggedIn($user_id=null)
609    {
610        $app =& App::getInstance();
611        $db =& DB::getInstance();
612
613        $this->initDB();
614
615        if (isset($user_id)) {
616            // Check the login status of a specific user.
617            $qid = $db->query("
618                SELECT 1 FROM " . $this->_params['db_table'] . "
619                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
620                AND last_login_datetime > DATE_SUB(NOW(), INTERVAL '" . $this->_params['login_timeout'] . "' SECOND)
621                AND last_access_datetime > DATE_SUB(NOW(), INTERVAL '" . $this->_params['idle_timeout'] . "' SECOND)
622            ");
623            $login_status = (mysql_num_rows($qid) > 0);
624            $app->logMsg(sprintf('Returning %s login status for user_id %s', ($login_status ? 'true' : 'false'), $user_id), LOG_DEBUG, __FILE__, __LINE__);
625            return $login_status;
626        }
627
628        // User login test need only be run once per script execution. We cache the result in the session.
629        if ($this->_authentication_tested && isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])) {
630            $app->logMsg(sprintf('Returning cached authentication status: %s', ($_SESSION['_auth_sql'][$this->_ns]['authenticated'] ? 'true' : 'false')), LOG_DEBUG, __FILE__, __LINE__);
631            return $_SESSION['_auth_sql'][$this->_ns]['authenticated'];
632        }
633
634        // Testing login should occur once. This is the first time. Set flag.
635        $this->_authentication_tested = true;
636
637        // Some users will access from networks with a changing IP number (i.e. behind a proxy server).
638        // These users must be allowed entry by adding their IP to the list of trusted_networks, or their usernames to the list of match_remote_ip_exempt_usernames.
639        if ($trusted_net = ipInRange(getRemoteAddr(), $this->_params['trusted_networks'])) {
640            $user_in_trusted_network = true;
641            $app->logMsg(sprintf('User_id %s accessing from trusted network %s',
642                ($this->get('user_id') ? $this->get('user_id') . ' (' .  $this->get('username') . ')' : 'unknown'),
643                $trusted_net
644            ), LOG_DEBUG, __FILE__, __LINE__);
645        } else {
646            $user_in_trusted_network = false;
647        }
648
649        // Do we match the user's remote IP at all? Yes, if set in config and not disabled for specific user.
650        if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt')) {
651            $remote_ip_is_matched = (isset($_SESSION['_auth_sql'][$this->_ns]['remote_ip']) && $_SESSION['_auth_sql'][$this->_ns]['remote_ip'] == getRemoteAddr()) || $user_in_trusted_network;
652        } else {
653            $app->logMsg(sprintf('User_id %s exempt from remote_ip match (comparing %s == %s)',
654                ($this->get('user_id') ? $this->get('user_id') . ' (' .  $this->get('username') . ')' : 'unknown'),
655                $_SESSION['_auth_sql'][$this->_ns]['remote_ip'],
656                getRemoteAddr()
657            ), LOG_DEBUG, __FILE__, __LINE__);
658            $remote_ip_is_matched = true;
659        }
660
661        // Test login with information stored in session. Skip IP matching for users from trusted networks.
662        if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated'])
663            && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']
664            && isset($_SESSION['_auth_sql'][$this->_ns]['username'])
665            && !empty($_SESSION['_auth_sql'][$this->_ns]['username'])
666            && isset($_SESSION['_auth_sql'][$this->_ns]['login_datetime'])
667            && strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) > (time() - $this->_params['login_timeout'])
668            && isset($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'])
669            && strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > (time() - $this->_params['idle_timeout'])
670            && $remote_ip_is_matched
671        ) {
672            // User is authenticated!
673            $_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'] = date('Y-m-d H:i:s');
674
675            // Update the DB with the last_access_datetime and increment the seconds_online.
676            $db->query("
677                UPDATE " . $this->_params['db_table'] . " SET
678                seconds_online = seconds_online + ABS(UNIX_TIMESTAMP() - UNIX_TIMESTAMP(last_access_datetime)) + 1,
679                last_access_datetime = '" . $this->get('last_access_datetime') . "'
680                WHERE " . $this->_params['db_primary_key'] . " = '" . $this->get('user_id') . "'
681            ");
682            if (mysql_affected_rows($db->getDBH()) > 0) {
683                // 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.
684                return true;
685            } else {
686                $app->logMsg(sprintf('Session update failed; record not found for user_id %s (%s).', $this->get('user_id'), $this->get('username')), LOG_NOTICE, __FILE__, __LINE__);
687            }
688        } else if (isset($_SESSION['_auth_sql'][$this->_ns]['authenticated']) && true === $_SESSION['_auth_sql'][$this->_ns]['authenticated']) {
689            // User is authenticated, but login has expired.
690
691            // Log the reason for login expiration.
692            $expire_reasons = array();
693            $user_notified = false;
694            if (!isset($_SESSION['_auth_sql'][$this->_ns]['username']) || empty($_SESSION['_auth_sql'][$this->_ns]['username'])) {
695                $expire_reasons[] = 'username not found';
696            }
697            if (!isset($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) || strtotime($_SESSION['_auth_sql'][$this->_ns]['login_datetime']) <= (time() - $this->_params['login_timeout'])) {
698                $expire_reasons[] = sprintf('login_timeout expired (%s older than %s seconds ago)', $_SESSION['_auth_sql'][$this->_ns]['login_datetime'], $this->_params['login_timeout']);
699            }
700            if (!isset($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) || strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) <= (time() - $this->_params['idle_timeout'])) {
701                $expire_reasons[] = sprintf('idle_timeout expired (%s older than %s seconds ago)', $_SESSION['_auth_sql'][$this->_ns]['last_access_datetime'], $this->_params['idle_timeout']);
702                if (strtotime($_SESSION['_auth_sql'][$this->_ns]['last_access_datetime']) > (time() - 43200)) {
703                    // Only raise message if last session is less than 12 hours old.
704                    // Notify user why they were logged out if they haven't yet been given a reason.
705                    $user_notified || $app->raiseMsg(sprintf(_("For your security we logged you out after being idle for %s. Please log in again."), humanTime($this->_params['idle_timeout'], 'hour', '%01.0f')), MSG_NOTICE, __FILE__, __LINE__);
706                    $user_notified = true;
707                }
708            }
709            if (!isset($_SESSION['_auth_sql'][$this->_ns]['remote_ip']) || $_SESSION['_auth_sql'][$this->_ns]['remote_ip'] != getRemoteAddr()) {
710                if ($this->getParam('match_remote_ip') && !$this->get('match_remote_ip_exempt') && !$user_in_trusted_network) {
711                    // There are three cases when a remote IP match will be the cause of a session termination:
712                    //   1. match_remote_ip config is enabled
713                    //   2. user is not match_remote_ip_exempt (set in the user_data, or in the match_remote_ip_exempt_usernames list)
714                    //   3. the user is connecting from a trusted network (their IP is listed in the trusted_networks)
715                    $expire_reasons[] = sprintf('remote_ip not matched (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
716                    // Notify user why they were logged out if they haven't yet been given a reason.
717                    $user_notified || $app->raiseMsg(sprintf(_("For your security we logged you out because your IP address has changed. Please log in again."), null), MSG_NOTICE, __FILE__, __LINE__);
718                    $user_notified = true;
719                } else {
720                    $expire_reasons[] = sprintf('remote_ip not matched but user was exempt from this check (%s != %s)', $_SESSION['_auth_sql'][$this->_ns]['remote_ip'], getRemoteAddr());
721                }
722            }
723            $app->logMsg(sprintf('User_id %s (%s) session expired: %s', $this->get('user_id'), $this->get('username'), join(', ', $expire_reasons)), LOG_INFO, __FILE__, __LINE__);
724        } else {
725            $app->logMsg('Session is not authenticated', LOG_DEBUG, __FILE__, __LINE__);
726        }
727
728        // User is not authenticated.
729        $this->clear();
730        return false;
731    }
732
733    /**
734     * Redirect user to login page if they are not logged in.
735     *
736     * @param string $message The text description of a message to raise.
737     * @param int    $type    The type of message: MSG_NOTICE,
738     *                        MSG_SUCCESS, MSG_WARNING, or MSG_ERR.
739     * @param string $file    __FILE__.
740     * @param string $line    __LINE__.
741     * @access public
742     */
743    public function requireLogin($message='', $type=MSG_NOTICE, $file=null, $line=null)
744    {
745        $app =& App::getInstance();
746
747        if (!$this->isLoggedIn()) {
748            // Display message for requiring login. (RaiseMsg will ignore empty strings.)
749            if ('' != $message) {
750                $app->raiseMsg($message, $type, $file, $line);
751            }
752
753            // Login scripts must have the same 'login' tag for boomerangURL verification/manipulation.
754            $app->setBoomerangURL(absoluteMe(), 'login');
755            $app->dieURL($this->_params['login_url']);
756        }
757    }
758
759    /**
760     * This sets the 'blocked' field for a user in the db_table, and also
761     * adds an optional reason
762     *
763     * @param  string   $reason      The reason for blocking the account.
764     */
765    public function blockAccount($user_id=null, $reason='')
766    {
767        $app =& App::getInstance();
768        $db =& DB::getInstance();
769
770        $this->initDB();
771
772        if ($this->getParam('blocking')) {
773            if (mb_strlen($db->escapeString($reason)) > 255) {
774                // blocked_reason field is varchar(255).
775                $app->logMsg(sprintf('Blocked reason provided is greater than 255 characters: %s', $reason), LOG_WARNING, __FILE__, __LINE__);
776            }
777
778            // Get user_id if specified.
779            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
780            $db->query("
781                UPDATE " . $this->_params['db_table'] . " SET
782                blocked = 'true',
783                blocked_reason = '" . $db->escapeString($reason) . "'
784                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
785            ");
786        }
787    }
788
789    /**
790     * Tests if the "blocked" flag is set for a user.
791     *
792     * @param  int      $user_id    User id to look for.
793     * @return boolean              True if the user is blocked, false otherwise.
794     */
795    public function isBlocked($user_id=null)
796    {
797        $db =& DB::getInstance();
798
799        $this->initDB();
800
801        if ($this->getParam('blocking')) {
802            // Get user_id if specified.
803            $user_id = isset($user_id) ? $user_id : $this->getVal('user_id');
804            $qid = $db->query("
805                SELECT 1
806                FROM " . $this->_params['db_table'] . "
807                WHERE blocked = 'true'
808                AND " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
809            ");
810            return mysql_num_rows($qid) === 1;
811        }
812    }
813
814    /**
815     * Unblocks a user in the db_table, and clears any blocked_reason.
816     */
817    public function unblockAccount($user_id=null)
818    {
819        $db =& DB::getInstance();
820
821        $this->initDB();
822
823        if ($this->getParam('blocking')) {
824            // Get user_id if specified.
825            $user_id = isset($user_id) ? $user_id : $this->get('user_id');
826            $db->query("
827                UPDATE " . $this->_params['db_table'] . " SET
828                blocked = '',
829                blocked_reason = ''
830                WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
831            ");
832        }
833    }
834
835    /**
836     * Returns true if username already exists in database.
837     *
838     * @param  string  $username    Username to look for.
839     * @return bool                 True if username exists.
840     */
841    public function usernameExists($username)
842    {
843        $db =& DB::getInstance();
844
845        $this->initDB();
846
847        $qid = $db->query("
848            SELECT 1
849            FROM " . $this->_params['db_table'] . "
850            WHERE " . $this->_params['db_username_column'] . " = '" . $db->escapeString($username) . "'
851        ");
852        return (mysql_num_rows($qid) > 0);
853    }
854
855    /**
856     * Returns a username for a specified user id.
857     *
858     * @param  string  $user_id     User id to look for.
859     * @return string               Username, or false if none found.
860     */
861    public function getUsername($user_id)
862    {
863        $db =& DB::getInstance();
864
865        $this->initDB();
866
867        $qid = $db->query("
868            SELECT " . $this->_params['db_username_column'] . "
869            FROM " . $this->_params['db_table'] . "
870            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
871        ");
872        if (list($username) = mysql_fetch_row($qid)) {
873            return $username;
874        } else {
875            return false;
876        }
877    }
878
879    /*
880    * Generate a cryptographically secure, random password.
881    *
882    * @access   public
883    * @param    int  $bytes     Length of password (in bytes)
884    * @return   string          Random string of characters.
885    * @author   Quinn Comendant <quinn@strangecode.com>
886    * @version  1.0
887    * @since    15 Nov 2014 20:30:27
888    */
889    public function generatePassword($bytes=10)
890    {
891        $app =& App::getInstance();
892
893        $bytes = is_numeric($bytes) ? $bytes : 10;
894        $string = strtok(base64_encode(openssl_random_pseudo_bytes($bytes, $strong)), '=');
895        if (!$strong) {
896            $app->logMsg(sprintf('Password generated was not "cryptographically strong"; check your openssl.', null), LOG_NOTICE, __FILE__, __LINE__);
897        }
898
899        return $string;
900    }
901
902    /**
903     *
904     */
905    public function encryptPassword($password, $salt=null, $hash_type=null)
906    {
907        $app =& App::getInstance();
908
909        $password = (string)$password;
910
911        // Existing password hashes rely on the same key/salt being used to compare hashs.
912        // Don't change this (or the value applied to signing_key) unless you know existing hashes or signatures will not be affected!
913        $more_salt = 'B36D18E5-3FE4-4D58-8150-F26642852B81';
914
915        $hash_type = isset($hash_type) && !empty($hash_type) ? $hash_type : $this->getParam('hash_type');
916
917        switch ($hash_type) {
918        case self::ENCRYPT_PLAINTEXT :
919            $encrypted_password = $password;
920            break;
921
922        case self::ENCRYPT_CRYPT :
923            // If comparing password with an existing hashed password, provide the hashed password as the salt.
924            $encrypted_password = isset($salt) ? crypt($password, $salt) : crypt($password);
925            break;
926
927        case self::ENCRYPT_SHA1 :
928            $encrypted_password = sha1($password);
929            break;
930
931        case self::ENCRYPT_SHA1_HARDENED :
932            $encrypted_password = sha1($app->getParam('signing_key') . $password . $more_salt);
933            for ($i=0; $i < pow(2, 20); $i++) {
934                $encrypted_password = sha1($password . $encrypted_password);
935            }
936            break;
937
938        case self::ENCRYPT_MD5 :
939            $encrypted_password = md5($password);
940            break;
941
942        case self::ENCRYPT_MD5_HARDENED :
943            $encrypted_password = md5($app->getParam('signing_key') . $password . $more_salt);
944            for ($i=0; $i < pow(2, 20); $i++) {
945                $encrypted_password = md5($password . $encrypted_password);
946            }
947            break;
948
949        case self::ENCRYPT_PASSWORD_BCRYPT :
950            $encrypted_password = password_hash($password, PASSWORD_BCRYPT, array('cost' => 12));
951            break;
952
953        case self::ENCRYPT_PASSWORD_DEFAULT :
954            $encrypted_password = password_hash($password, PASSWORD_DEFAULT, array('cost' => 12));
955            break;
956
957        default :
958            $app->logMsg(sprintf('Unknown hash type: %s', $hash_type), LOG_WARNING, __FILE__, __LINE__);
959            return false;
960        }
961
962        // In case our hashing function returns 'false' or another empty value, bail out.
963        if ('' == trim((string)$encrypted_password)) {
964            $app->logMsg(sprintf('Invalid password hash returned ("%s") for hash type %s; check yo crypto!', $encrypted_password, $hash_type), LOG_ALERT, __FILE__, __LINE__);
965            return false;
966        }
967
968        return $encrypted_password;
969    }
970
971    /*
972    *
973    *
974    * @access   public
975    * @param
976    * @return
977    * @author   Quinn Comendant <quinn@strangecode.com>
978    * @version  1.0
979    * @since    15 Nov 2014 21:37:28
980    */
981    public function verifyPassword($password, $encrypted_password, $hash_type=null)
982    {
983        $app =& App::getInstance();
984
985        $hash_type = isset($hash_type) && !empty($hash_type) ? $hash_type : $this->getParam('hash_type');
986
987        switch ($hash_type) {
988        case self::ENCRYPT_CRYPT :
989            return $this->encryptPassword($password, $encrypted_password, $hash_type) == $encrypted_password;
990
991        case self::ENCRYPT_PLAINTEXT :
992        case self::ENCRYPT_MD5 :
993        case self::ENCRYPT_MD5_HARDENED :
994        case self::ENCRYPT_SHA1 :
995        case self::ENCRYPT_SHA1_HARDENED :
996            return $this->encryptPassword($password, $encrypted_password, $hash_type) == $encrypted_password;
997
998        case self::ENCRYPT_PASSWORD_BCRYPT :
999        case self::ENCRYPT_PASSWORD_DEFAULT :
1000            return password_verify($password, $encrypted_password);
1001
1002        default :
1003            $app->logMsg(sprintf('Unknown hash type: %s', $hash_type), LOG_WARNING, __FILE__, __LINE__);
1004            return false;
1005        }
1006
1007    }
1008
1009    /**
1010     *
1011     */
1012    public function setPassword($user_id=null, $password, $hash_type=null)
1013    {
1014        $app =& App::getInstance();
1015        $db =& DB::getInstance();
1016
1017        $this->initDB();
1018
1019        // Get user_id if specified.
1020        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
1021
1022        // New hash type.
1023        $hash_type = isset($hash_type) ? $hash_type : $this->getParam('hash_type');
1024
1025        // Save the hash method used if a table exists for it.
1026        $userpass_hashtype_clause = '';
1027        if ($db->columnExists($this->_params['db_table'], 'userpass_hashtype', false)) {
1028            $userpass_hashtype_clause = ", userpass_hashtype = '" . $db->escapeString($hash_type) . "'";
1029        }
1030
1031        // Issue the password change query.
1032        $db->query("
1033            UPDATE " . $this->_params['db_table'] . " SET
1034                userpass = '" . $db->escapeString($this->encryptPassword($password, null, $hash_type)) . "',
1035                modified_datetime = NOW(),
1036                modified_by_user_id = '" . $db->escapeString($user_id) . "'
1037                $userpass_hashtype_clause
1038            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
1039        ");
1040
1041        if (mysql_affected_rows($db->getDBH()) != 1) {
1042            $app->logMsg(sprintf('Failed to update password for user_id %s (no affected rows)', $user_id), LOG_WARNING, __FILE__, __LINE__);
1043            return false;
1044        }
1045
1046        $app->logMsg(sprintf('Password change successful for user_id %s', $user_id), LOG_INFO, __FILE__, __LINE__);
1047        return true;
1048    }
1049
1050    /**
1051     * Resets the password for the user with the specified id.
1052     *
1053     * @param  string $user_id   The id of the user to reset.
1054     * @param  string $reason    Additional message to add to the reset email.
1055     * @return string            The user's new password.
1056     */
1057    public function resetPassword($user_id=null, $reason='')
1058    {
1059        $app =& App::getInstance();
1060        $db =& DB::getInstance();
1061
1062        $this->initDB();
1063
1064        // Get user_id if specified.
1065        $user_id = isset($user_id) ? $user_id : $this->get('user_id');
1066
1067        // Reset password of a specific user.
1068        $qid = $db->query("
1069            SELECT * FROM " . $this->_params['db_table'] . "
1070            WHERE " . $this->_params['db_primary_key'] . " = '" . $db->escapeString($user_id) . "'
1071        ");
1072        if (!$user_data = mysql_fetch_assoc($qid)) {
1073            $app->logMsg(sprintf('Reset password failed. User_id %s not found.', $user_id), LOG_NOTICE, __FILE__, __LINE__);
1074            return false;
1075        }
1076
1077        // Get new password.
1078        $password = $this->generatePassword();
1079
1080        // Update password query.
1081        $this->setPassword($user_id, $password);
1082
1083        // Make sure user has an email on record before continuing.
1084        if (!isset($user_data['email']) || '' == trim($user_data['email'])) {
1085            $app->logMsg(sprintf('Password reset but notification failed, no email address for user_id %s (%s).', $user_data[$this->_params['db_primary_key']], $user_data[$this->_params['db_username_column']]), LOG_NOTICE, __FILE__, __LINE__);
1086        } else {
1087            // Send the new password in an email.
1088            $email = new Email(array(
1089                'to' => $user_data['email'],
1090                'from' => sprintf('"%s" <%s>', addcslashes($app->getParam('site_name'), '"'), $app->getParam('site_email')),
1091                'subject' => sprintf('%s password change', $app->getParam('site_name'))
1092            ));
1093            $email->setTemplate('codebase/services/templates/email_reset_password.txt');
1094            $email->replace(array(
1095                'SITE_NAME' => $app->getParam('site_name'),
1096                'SITE_URL' => $app->getParam('site_url'),
1097                'SITE_EMAIL' => $app->getParam('site_email'),
1098                'NAME' => ('' != $user_data['first_name'] . $user_data['last_name'] ? $user_data['first_name'] . ' ' . $user_data['last_name'] : $user_data[$this->_params['db_username_column']]),
1099                'USERNAME' => $user_data[$this->_params['db_username_column']],
1100                'PASSWORD' => $password,
1101                'REASON' => ('' == trim($reason) ? '' : trim($reason) . ' '), // Add a space after the reason if it exists for better formatting.
1102            ));
1103            $email->send();
1104        }
1105
1106        return array(
1107            'username' => $user_data[$this->_params['db_username_column']],
1108            'userpass' => $password
1109        );
1110    }
1111
1112} // end class
Note: See TracBrowser for help on using the repository browser.