2 /************************************************************************
3 * MXChange v0.2.1 Start: 07/16/2004 *
4 * =============== Last change: 10/27/2004 *
6 * -------------------------------------------------------------------- *
7 * File : user_functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Special functions for user extension *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Spezielle Funktionen fuer die user-Erweiterung *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Add links for selecting some users
45 function alpha ($sortby, $colspan, $return=false) {
46 if (!isGetRequestElementSet('offset')) setRequestGetElement('offset', 0);
47 $add = "&page=".getRequestElement('page')."&offset=".getRequestElement('offset');
48 if (isGetRequestElementSet('mode')) $add .= "&mode=".getRequestElement('mode');
50 /* Creates the list of letters and makes them a link. */
51 $alphabet = explode(',', getMessage('_ALL2') . ',A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,' . getMessage('_OTHERS'));
52 $num = count($alphabet) - 1;
54 while (list($counter, $ltr) = each($alphabet)) {
55 if (getRequestElement('letter') == $ltr) {
56 // Current letter is letter from URL
57 $OUT .= "<strong>".$ltr."</strong>";
59 // Output link to letter
60 $OUT .= "<a href=\"{?URL?}/modules.php?module=admin&what=".getWhat();
61 if (isGetRequestElementSet('mode')) $OUT .= "&mode=".getRequestElement('mode');
62 $OUT .= "&letter=".$ltr."&sortby=".$sortby.$add."\">".$ltr."</a>";
65 if ((($counter / getConfig('user_alpha')) == round($counter / getConfig('user_alpha'))) && ($counter > 0)) {
66 $OUT .= " ]<br />[ ";
67 } elseif ( $counter != $num ) {
68 $OUT .= " | ";
73 $OUT = loadTemplate('admin_list_user_alpha', true, $OUT);
74 if ($return === true) {
75 // Return generated code
78 // Output generated code
83 // Add links for sorting
84 function addSortLinks ($letter, $sortby, $colspan, $return=false) {
86 if (!isGetRequestElementSet('offset')) setRequestGetElement('offset', 0);
87 if (!isGetRequestElementSet('page')) setRequestGetElement('page' , 0);
89 // Add page and offset
90 $add = '&page=' . getRequestElement('page') . '&offset=' . getRequestElement('offset');
93 if (isGetRequestElementSet('status')) $add .= '&mode=' . getRequestElement('status');
94 elseif (isGetRequestElementSet('mode')) $add .= '&mode=' . getRequestElement('mode');
96 // Makes order by links..
97 if ($letter == 'front') $letter = getMessage('_ALL2');
99 // Prepare array with all possible sorters
101 'userid' => getMessage('_UID'),
102 'family' => getMessage('FAMILY_NAME'),
103 'email' => getMessage('EMAIL_ADDRESS'),
104 'REMOTE_ADDR' => getMessage('REMOTE_IP')
107 // Add nickname if extension is installed
108 if (isExtensionActive('nickname')) {
109 $list['nickname'] = getMessage('NICKNAME');
112 foreach ($list as $sort => $title) {
113 if ($sortby == $sort) {
114 $OUT .= "<strong>" . $title . "</strong> | ";
116 $OUT .= "<a href=\"{?URL?}/modules.php?module=admin&what=list_user&letter=" . $letter . "&sortby=" . $sort.$add . "\">" . $title . "</a> | ";
120 $content['list'] = substr($OUT, 0, -13);
123 $OUT = loadTemplate('admin_list_user_sort', true, $content);
125 // Should we return or output?
126 if ($return === true) {
135 // Add page navigation
136 function addPageNavigation ($PAGES, $offset, $show_form, $colspan,$return=false) {
137 // @TODO These two constants are no longer used, maybe we reactivate this code?
138 //if ($show_form === true) {
139 // // Load form for changing number of lines
140 // define('__FORM_HEADER', loadTemplate('admin_list_user_sort_form', true));
141 // define('__FORM_FOOTER', '<tr><td colspan="'.$colspan.'" class="seperator bottom2"> </td></tr>');
144 // define('__FORM_HEADER', '<tr><td colspan="' . $colspan . '" class="seperator"> </td></tr>');
145 // define('__FORM_FOOTER', '<tr><td colspan="' . $colspan . '" class="seperator bottom2"> </td></tr>');
149 for ($page = 1; $page <= $PAGES; $page++) {
150 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
153 if (!isGetRequestElementSet('letter')) setRequestGetElement('letter', getMessage('_ALL2'));
154 if (!isGetRequestElementSet('sortby')) setRequestGetElement('sortby', 'userid');
157 $OUT .= '<a href="{?URL?}/modules.php?module=admin&what=' . getWhat();
159 // Add status or mode
160 if (isGetRequestElementSet('status')) $OUT .= '&mode=' . getRequestElement('status');
161 elseif (isGetRequestElementSet('mode')) $OUT .= '&mode=' . getRequestElement('mode');
164 $OUT .= '&letter=' . getRequestElement('letter') . '&sortby=' . getRequestElement('sortby') . '&page=' . $page . '&offset=' . $offset . '">';
169 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
170 $OUT .= '-</strong>';
175 if ($page < $PAGES) $OUT .= ' | ';
179 $content['list'] = $OUT;
182 $OUT = loadTemplate('admin_list_user_pagenav', true, $content);
183 if ($return === true) {
192 // Create email link to user's account
193 function generateUserEmailLink($email, $mod = 'admin') {
194 // Show contact link only if user is confirmed by default
195 $locked = " AND `status`='CONFIRMED'";
197 // But admins shall always see it
198 if (isAdmin()) $locked = '';
200 $result = SQL_QUERY_ESC("SELECT
203 `{?_MYSQL_PREFIX?}_user_data`
205 `email`='%s'" . $locked."
207 array($email), __FUNCTION__, __LINE__);
208 if (SQL_NUMROWS($result) == 1) {
210 list($userid) = SQL_FETCHROW($result);
212 // Rewrite email address to contact link
213 $email = '{?URL?}/modules.php?module=' . $mod . '&what=user_contct&userid=' . bigintval($userid);
217 SQL_FREERESULT($result);
219 // Return rewritten (?) email address
223 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
224 function determineRandomReferalId () {
225 // Default is zero refid
228 // Is the extension version fine?
229 if (getExtensionVersion('user') >= '0.3.4') {
231 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= ".getConfig('user_min_confirmed')."");
233 // Do we have at least one?
234 if ($totalUsers > 0) {
235 // Then choose random number
236 $randNum = mt_rand(0, ($totalUsers - 1));
238 // Look for random user
239 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `status`='CONFIRMED' AND `rand_confirmed` >= {?user_min_confirmed?} ORDER BY `rand_confirmed` DESC LIMIT %s, 1",
240 array($randNum), __FUNCTION__, __LINE__);
242 // Do we have one entry there?
243 if (SQL_NUMROWS($result) == 1) {
244 // Use that userid as new referal id
245 list($refid) = SQL_FETCHROW($result);
247 // Reset this user's counter
248 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0 WHERE `userid`=%s LIMIT 1",
249 array($refid), __FUNCTION__, __LINE__);
253 SQL_FREERESULT($result);
262 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&what=login&login=') {
268 // Add last_login if available
270 if (getExtensionVersion('sql_patches') >= '0.2.8') {
271 $lastOnline = ', `last_login`';
284 if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
286 fetchUserData($userid, 'nickname');
288 // Direct userid entered
289 fetchUserData($userid);
293 $content = getUserDataArray();
294 if (!empty($content['userid'])) $userid = bigintval($content['userid']);
296 // Is there an entry?
297 if ((isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && ((isNicknameUsed($content['userid'] === true) && (!empty($content['userid']))) || ($content['userid'] == $userid))) {
298 // Check for old MD5 passwords
299 if ((strlen($content['password']) == 32) && (md5($passwd) == $content['password'])) {
300 // Just set the hash to the password from DB... :)
301 $content['hash'] = $content['password'];
303 // Hash password with improved way for comparsion
304 $content['hash'] = generateHash($passwd, substr($content['password'], 0, -40));
307 // Does the password match the hash?
308 if ($content['hash'] == $content['password']) {
309 // New hashed password found so let's generate a new one
310 $content['hash'] = generateHash($passwd);
312 // ... and update database
313 // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
314 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
315 array($content['hash'], $userid), __FUNCTION__, __LINE__);
317 // No login bonus by default
318 $GLOBALS['bonus_payed'] = false;
320 // Probe for last online timemark
321 $probe = time() - $content['last_online'];
322 if (!empty($content['last_login'])) $probe = time() - $content['last_login'];
323 if ((getExtensionVersion('bonus') >= '0.2.2') && ($probe >= getConfig('login_timeout'))) {
324 // Add login bonus to user's account
325 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
326 $GLOBALS['bonus_payed'] = true;
328 // Subtract login bonus from userid's account or jackpot
329 if ((getExtensionVersion('bonus') >= '0.3.5') && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
332 // Calculate new hash with the secret key and master salt together
333 $content['hash'] = generatePassString($content['hash']);
335 // Update global array
336 // @TODO Make this filter working: $URL = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
337 setMemberId($userid);
339 // Try to set session data (which shall normally always work!)
340 if ((setSession('userid', $userid )) && (setSession('u_hash', $content['hash']))) {
341 // Update database records
342 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
343 array($userid), __FUNCTION__, __LINE__);
344 if (SQL_AFFECTEDROWS() == 1) {
345 // Is a success URL set?
346 if (empty($successUrl)) {
347 // Procedure to checking for login data
348 if (($GLOBALS['bonus_payed']) && (isExtensionActive('bonus'))) {
349 // Bonus added (just displaying!)
350 $URL = 'modules.php?module=chk_login&mode=bonus';
353 $URL = 'modules.php?module=chk_login&mode=login';
360 // Cannot update counter!
361 $errorCode = getCode('CNTR_FAILED');
364 // Cookies not setable!
365 $errorCode = getCode('NO_COOKIES');
367 } elseif (getExtensionVersion('sql_patches') >= '0.6.1') {
368 // Update failture counter
369 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
370 array($userid), __FUNCTION__, __LINE__);
373 $errorCode = getCode('WRONG_PASS');
375 } elseif (((isNicknameUsed($content['userid'])) && (!empty($content['userid']))) || ($content['userid'] == $userid)) {
376 // Other account status?
377 if (fetchUserData($userid)) {
378 // Create an error code from given status
379 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
382 $errorCode = getCode('WRONG_ID');
386 $errorCode = getCode('WRONG_ID');
389 // Error code provided?
390 if ($errorCode > 0) {
391 // Then reconstruct the URL
392 $URL = $errorUrl . $errorCode;
399 // Try to send a new password for the given user account
400 function doNewUserPassword ($email, $userid) {
401 // Compile email when found in address (only secure chars!)
402 if (!empty($email)) $email = str_replace('{DOT}', '.', $email);
404 // Init result and error
408 // Probe userid/nickname
409 // @TODO We should try to rewrite this to fetchUserData() somehow
410 if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
412 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
413 array($userid, $userid, $email), __FUNCTION__, __LINE__);
414 } elseif (($userid > 0) && (empty($email))) {
415 // Direct userid entered
416 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
417 array(bigintval($userid)), __FUNCTION__, __LINE__);
418 } elseif (!empty($email)) {
420 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' LIMIT 1",
421 array($email), __FUNCTION__, __LINE__);
424 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
425 $errorCode = getCode('WRONG_ID');
429 if (SQL_NUMROWS($result) == 1) {
430 // This data is valid, so we create a new pass... :-)
431 list($userid, $status) = SQL_FETCHROW($result);
433 if ($status == 'CONFIRMED') {
434 // Ooppps, this was missing! ;-) We should update the database...
435 $NEW_PASS = generatePassword();
436 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
437 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
439 // Prepare data and message for email
440 $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
442 // ... and send it away
443 sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
445 // Output note to user
446 loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
448 // Account is locked or unconfirmed
449 $errorCode = generateErrorCodeFromUserStatus($status);
452 redirectToUrl('modules.php?module=index&what=login&login='.$errorCode);
455 // id or email is wrong
456 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
459 // Return the error code