+// Do the user login
+function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&what=login&login=') {
+ // Init variables
+ $dmy = '';
+ $add = '';
+ $errorCode = '0';
+ $ext = '';
+
+ // Init array
+ $content = array(
+ 'password' => '',
+ 'userid' => '',
+ 'last_online' => 0,
+ 'last_login' => 0,
+ 'hash' => ''
+ );
+
+ // Check login data
+ if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
+ // Nickname entered
+ fetchUserData($userid, 'nickname');
+ } elseif (isNicknameUsed($userid)) {
+ // No nickname installed
+ $errorCode = getCode('EXTENSION_PROBLEM');
+ $ext = 'nickname';
+ } else {
+ // Direct userid entered
+ fetchUserData($userid);
+ }
+
+ // No error found?
+ if ($errorCode == '0') {
+ // Get user data array and set userid (e.g. important if we login with nickname)
+ $content = getUserDataArray();
+ if (!empty($content['userid'])) $userid = bigintval($content['userid']);
+ } // END - if
+
+ // Is there an entry?
+ if ((isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
+ // Check for old MD5 passwords
+ if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
+ // Just set the hash to the password from DB... :)
+ $content['hash'] = getUserData('password');
+ } else {
+ // Hash password with improved way for comparsion
+ $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
+ }
+
+ // Does the password match the hash?
+ if ($content['hash'] == getUserData('password')) {
+ // New hashed password found so let's generate a new one
+ $content['hash'] = generateHash($passwd);
+
+ // ... and update database
+ // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
+ SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
+ array($content['hash'], $userid), __FUNCTION__, __LINE__);
+
+ // No login bonus by default
+ $GLOBALS['bonus_payed'] = false;
+
+ // Probe for last online timemark
+ $probe = time() - getUserData('last_online');
+ if (getUserData('last_login') > 0) $probe = time() - getUserData('last_login');
+
+ if ((isExtensionInstalledAndNewer('bonus', '0.2.2')) && ($probe >= getConfig('login_timeout'))) {
+ // Add login bonus to user's account
+ $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
+ $GLOBALS['bonus_payed'] = true;
+
+ // Subtract login bonus from userid's account or jackpot
+ if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
+ } // END - if
+
+ // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
+
+ // Set member id
+ setMemberId($userid);
+
+ // Try to set session data (which shall normally always work!)
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
+ if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
+ // Update database records
+ SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
+ array($userid), __FUNCTION__, __LINE__);
+ if (SQL_AFFECTEDROWS() == 1) {
+ // Is a success URL set?
+ if (empty($successUrl)) {
+ // Procedure to checking for login data
+ if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
+ // Bonus added (just displaying!)
+ $url = 'modules.php?module=chk_login&mode=bonus';
+ } else {
+ // Bonus not added
+ $url = 'modules.php?module=chk_login&mode=login';
+ }
+ } else {
+ // Use this URL
+ $url = $successUrl;
+ }
+ } else {
+ // Cannot update counter!
+ $errorCode = getCode('CNTR_FAILED');
+ }
+ } else {
+ // Cookies not setable!
+ $errorCode = getCode('COOKIES_DISABLED');
+ }
+ } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
+ // Update failture counter
+ SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
+ array($userid), __FUNCTION__, __LINE__);
+
+ // Wrong password!
+ $errorCode = getCode('WRONG_PASS');
+ }
+ } elseif (getUserData('status') != 'CONFIRMED') {
+ // Create an error code from given status
+ $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
+
+ // Set userid in session
+ setSession('current_userid', getUserData('userid'));
+ } elseif (!isUserDataValid()) {
+ // User id not found!
+ $errorCode = getCode('WRONG_ID');
+ } else {
+ // Unknown error
+ $errorCode = getCode('UNKNOWN_ERROR');
+ }
+
+ // Error code provided?
+ if ($errorCode > 0) {
+ // Then reconstruct the URL
+ $url = $errorUrl . $errorCode;
+
+ // Extension set? Then add it as well.
+ if (!empty($ext)) $url .= '&ext=' . $ext;
+ } // END - if
+
+ // Return URL
+ return $url;
+}
+
+// Try to send a new password for the given user account
+function doNewUserPassword ($email, $userid) {
+ // Init result and error
+ $errorCode = '';
+ $result = false;
+
+ // Probe userid/nickname
+ // @TODO We should try to rewrite this to fetchUserData() somehow
+ if (!empty($email)) {
+ // Email entered
+ $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' OR `email`='%s' LIMIT 1",
+ array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
+ } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
+ // Nickname entered
+ $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
+ array($userid, $userid, $email), __FUNCTION__, __LINE__);
+ } elseif (($userid > 0) && (empty($email))) {
+ // Direct userid entered
+ $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
+ array(bigintval($userid)), __FUNCTION__, __LINE__);
+ } else {
+ // Userid not set!
+ logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
+ $errorCode = getCode('WRONG_ID');
+ }
+
+ // Any entry found?
+ if (SQL_NUMROWS($result) == 1) {
+ // This data is valid, so we create a new pass... :-)
+ list($userid, $status) = SQL_FETCHROW($result);
+
+ if ($status == 'CONFIRMED') {
+ // Ooppps, this was missing! ;-) We should update the database...
+ $NEW_PASS = generatePassword();
+ SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
+ array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
+
+ // Prepare data and message for email
+ $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
+
+ // ... and send it away
+ sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
+
+ // Output note to user
+ loadTemplate('admin_settings_saved', false, '{--GUEST_NEW_PASSWORD_SEND--}');
+ } else {
+ // Account is locked or unconfirmed
+ $errorCode = generateErrorCodeFromUserStatus($status);
+
+ // Load URL
+ redirectToUrl('modules.php?module=index&what=login&login='.$errorCode);
+ }
+ } else {
+ // id or email is wrong
+ loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
+ }
+
+ // Return the error code
+ return $errorCode;
+}
+
+// Get timestamp for given stats type and data
+function getTimestampFromUserStats ($statsType, $statsData, $userid = '0') {
+ // Default timestamp is zero
+ $data['inserted'] = '0';
+
+ // User id set?
+ if ((isMemberIdSet()) && ($userid == '0')) {
+ $userid = getMemberId();
+ } // END - if
+
+ // Is the extension installed and updated?
+ if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
+ // Return zero here
+ return $data['inserted'];
+ } // END - if
+
+ // Try to find the entry
+ $result = SQL_QUERY_ESC("SELECT
+ UNIX_TIMESTAMP(`inserted`) AS inserted
+FROM
+ `{?_MYSQL_PREFIX?}_user_stats_data`
+WHERE
+ `userid`=%s AND
+ `stats_type`='%s' AND
+ `stats_data`='%s'
+LIMIT 1",
+ array(
+ bigintval($userid),
+ $statsType,
+ $statsData
+ ), __FUNCTION__, __LINE__);
+
+ // Is the entry there?
+ if (SQL_NUMROWS($result) == 1) {
+ // Get this stamp
+ $data = SQL_FETCHARRAY($result);
+ } // END - if
+
+ // Free result
+ SQL_FREERESULT($result);
+
+ // Return stamp
+ return $data['inserted'];
+}
+
+// Inserts user stats
+function insertUserStatsRecord ($userid, $statsType, $statsData) {
+ // Is the extension installed and updated?
+ if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
+ // Return zero here
+ return false;
+ } // END - if
+
+ // Does it exist?
+ if ((!getTimestampFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
+ // Then insert it!
+ SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
+ array(bigintval($userid), $statsType, $statsData), __FUNCTION__, __LINE__);
+ } elseif (is_array($statsData)) {
+ // Invalid data!
+ logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$statsType},data={".gettype($statsData).": Invalid statistics data type!");
+ }
+}
+