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=') {
264 $dmy = ''; $add = '';
267 // Add last_login if available
269 if (getExtensionVersion('sql_patches') >= '0.2.8') {
270 $lastOnline = ', `last_login`';
283 if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
285 $result = SQL_QUERY_ESC("SELECT `userid`, `password`, `last_online`" . $lastOnline . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' AND `status`='CONFIRMED' LIMIT 1",
286 array($userid), __FUNCTION__, __LINE__);
288 // Direct userid entered
289 $result = SQL_QUERY_ESC("SELECT `userid`, `password`, `last_online`" . $lastOnline . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
290 array($userid, $content['hash']), __FUNCTION__, __LINE__);
294 $content = SQL_FETCHARRAY($result);
295 if (!empty($content['userid'])) $userid = bigintval($content['userid']);
297 // Is there an entry?
298 if ((SQL_NUMROWS($result) == 1) && ((isNicknameUsed($content['userid'] === true) && (!empty($content['userid']))) || ($content['userid'] == $userid))) {
300 SQL_FREERESULT($result);
302 // Check for old MD5 passwords
303 if ((strlen($content['password']) == 32) && (md5($passwd) == $content['password'])) {
304 // Just set the hash to the password from DB... :)
305 $content['hash'] = $content['password'];
307 // Hash password with improved way for comparsion
308 $content['hash'] = generateHash($passwd, substr($content['password'], 0, -40));
311 // Does the password match the hash?
312 if ($content['hash'] == $content['password']) {
313 // New hashed password found so let's generate a new one
314 $content['hash'] = generateHash($passwd);
316 // ... and update database
317 // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
318 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
319 array($content['hash'], $userid), __FUNCTION__, __LINE__);
321 // No login bonus by default
322 $GLOBALS['bonus_payed'] = false;
324 // Probe for last online timemark
325 $probe = time() - $content['last_online'];
326 if (!empty($content['last_login'])) $probe = time() - $content['last_login'];
327 if ((getExtensionVersion('bonus') >= '0.2.2') && ($probe >= getConfig('login_timeout'))) {
328 // Add login bonus to user's account
329 $add = sprintf(", `login_bonus`=`login_bonus`+%s",
330 (float)getConfig('login_bonus')
332 $GLOBALS['bonus_payed'] = true;
334 // Subtract login bonus from userid's account or jackpot
335 if ((getExtensionVersion('bonus') >= '0.3.5') && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
338 // Calculate new hash with the secret key and master salt together
339 $content['hash'] = generatePassString($content['hash']);
341 // Update global array
342 // @TODO Make this filter working: $URL = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
345 // Try to set session data (which shall normally always work!)
346 if ((setSession('userid', $userid )) && (setSession('u_hash', $content['hash']))) {
347 // Update database records
348 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
349 array($userid), __FUNCTION__, __LINE__);
350 if (SQL_AFFECTEDROWS() == 1) {
351 // Is a success URL set?
352 if (empty($successUrl)) {
353 // Procedure to checking for login data
354 if (($GLOBALS['bonus_payed']) && (isExtensionActive('bonus'))) {
355 // Bonus added (just displaying!)
356 $URL = 'modules.php?module=chk_login&mode=bonus';
359 $URL = 'modules.php?module=chk_login&mode=login';
366 // Cannot update counter!
367 $errorCode = getCode('CNTR_FAILED');
370 // Cookies not setable!
371 $errorCode = getCode('NO_COOKIES');
373 } elseif (getExtensionVersion('sql_patches') >= '0.6.1') {
374 // Update failture counter
375 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
376 array($userid), __FUNCTION__, __LINE__);
379 $errorCode = getCode('WRONG_PASS');
381 } elseif (((isNicknameUsed($content['userid'])) && (!empty($content['userid']))) || ($content['userid'] == $userid)) {
382 // Other account status?
383 // @TODO Can this query be merged with above query?
384 $result = SQL_QUERY_ESC("SELECT `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
385 array($userid), __FUNCTION__, __LINE__);
388 if (SQL_NUMROWS($result) == 1) {
390 list($status) = SQL_FETCHROW($result);
392 // Create an error code from given status
393 $errorCode = generateErrorCodeFromUserStatus($status);
396 $errorCode = getCode('WRONG_ID');
400 $errorCode = getCode('WRONG_ID');
403 // Error code provided?
404 if ($errorCode > 0) {
405 // Then reconstruct the URL
406 $URL = $errorUrl . $errorCode;
413 // Try to send a new password for the given user account
414 function doNewUserPassword ($email, $userid) {
415 // Compile email when found in address (only secure chars!)
416 if (!empty($email)) $email = str_replace('{DOT}', '.', $email);
418 // Init result and error
422 // Probe userid/nickname
423 if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
425 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
426 array($userid, $userid, $email), __FUNCTION__, __LINE__);
427 } elseif (($userid > 0) && (empty($email))) {
428 // Direct userid entered
429 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
430 array(bigintval($userid)), __FUNCTION__, __LINE__);
431 } elseif (!empty($email)) {
433 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' LIMIT 1",
434 array($email), __FUNCTION__, __LINE__);
437 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
438 $errorCode = getCode('WRONG_ID');
442 if (SQL_NUMROWS($result) == 1) {
443 // This data is valid, so we create a new pass... :-)
444 list($userid, $status) = SQL_FETCHROW($result);
446 if ($status == 'CONFIRMED') {
447 // Ooppps, this was missing! ;-) We should update the database...
448 $NEW_PASS = generatePassword();
449 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
450 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
452 // Prepare data and message for email
453 $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS), $userid);
455 // ... and send it away
456 sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
458 // Output note to user
459 loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
461 // Account is locked or unconfirmed
462 $errorCode = generateErrorCodeFromUserStatus($status);
465 redirectToUrl('modules.php?module=index&what=login&login='.$errorCode);
468 // ID or email is wrong
469 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
472 // Return the error code