2 /************************************************************************
3 * Mailer v0.2.1-FINAL 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 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Add links for selecting some users
46 function alpha ($sortby, $colspan, $return=false) {
47 if (!isGetRequestParameterSet('offset')) setGetRequestParameter('offset', 0);
48 $add = '&page='.getRequestParameter('page').'&offset='.getRequestParameter('offset');
49 if (isGetRequestParameterSet('mode')) $add .= '&mode='.getRequestParameter('mode');
51 /* Creates the list of letters and makes them a link. */
52 $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'));
53 $num = count($alphabet) - 1;
55 while (list($counter, $ltr) = each($alphabet)) {
56 if (getRequestParameter('letter') == $ltr) {
57 // Current letter is letter from URL
58 $OUT .= '<strong>' . $ltr . '</strong>';
60 // Output link to letter
61 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat();
62 if (isGetRequestParameterSet('mode')) $OUT .= '&mode=' . getRequestParameter('mode');
63 $OUT .= '&letter=' . $ltr . '&sortby=' . $sortby . $add . '%}">' . $ltr . '</a>';
66 if ((($counter / getConfig('user_alpha')) == round($counter / getConfig('user_alpha'))) && ($counter > 0)) {
67 $OUT .= ' ]<br />[ ';
68 } elseif ( $counter != $num ) {
69 $OUT .= ' | ';
74 $OUT = loadTemplate('admin_list_user_alpha', true, $OUT);
75 if ($return === true) {
76 // Return generated code
79 // Output generated code
84 // Add links for sorting
85 function addSortLinks ($letter, $sortby, $colspan, $return=false) {
87 if (!isGetRequestParameterSet('offset')) setGetRequestParameter('offset', 0);
88 if (!isGetRequestParameterSet('page')) setGetRequestParameter('page' , 0);
90 // Add page and offset
91 $add = '&page=' . getRequestParameter('page') . '&offset=' . getRequestParameter('offset');
94 if (isGetRequestParameterSet('status')) $add .= '&mode=' . getRequestParameter('status');
95 elseif (isGetRequestParameterSet('mode')) $add .= '&mode=' . getRequestParameter('mode');
97 // Makes order by links..
98 if ($letter == 'front') $letter = getMessage('_ALL2');
100 // Prepare array with all possible sorters
102 'userid' => getMessage('_UID'),
103 'family' => getMessage('FAMILY'),
104 'email' => getMessage('EMAIL'),
105 'REMOTE_ADDR' => getMessage('REMOTE_IP')
108 // Add nickname if extension is installed
109 if (isExtensionActive('nickname')) {
110 $list['nickname'] = getMessage('NICKNAME');
113 foreach ($list as $sort => $title) {
114 if ($sortby == $sort) {
115 $OUT .= '<strong>' . $title . '</strong> | ';
117 $OUT .= '<a href="{%url=modules.php?module=admin&what=list_user&letter=' . $letter . '&sortby=' . $sort.$add . '%}">' . $title . '</a> | ';
121 $content['list'] = substr($OUT, 0, -13);
124 $OUT = loadTemplate('admin_list_user_sort', true, $content);
126 // Should we return or output?
127 if ($return === true) {
136 // Add page navigation
137 function addPageNavigation ($pages, $offset, $showForm, $colspan, $return=false) {
138 // @TODO These two constants are no longer used, maybe we reactivate this code?
139 //if ($showForm === true) {
140 // // Load form for changing number of lines
141 // define('__FORM_HEADER', loadTemplate('admin_list_user_sort_form', true));
142 // define('__FORM_FOOTER', '<tr><td colspan="'.$colspan.'" class="seperator bottom"> </td></tr>');
145 // define('__FORM_HEADER', '<tr><td colspan="' . $colspan . '" class="seperator"> </td></tr>');
146 // define('__FORM_FOOTER', '<tr><td colspan="' . $colspan . '" class="seperator bottom"> </td></tr>');
150 for ($page = 1; $page <= $pages; $page++) {
151 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
154 if (!isGetRequestParameterSet('letter')) setGetRequestParameter('letter', getMessage('_ALL2'));
155 if (!isGetRequestParameterSet('sortby')) setGetRequestParameter('sortby', 'userid');
158 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat();
160 // Add status or mode
161 if (isGetRequestParameterSet('status')) $OUT .= '&mode=' . getRequestParameter('status');
162 elseif (isGetRequestParameterSet('mode')) $OUT .= '&mode=' . getRequestParameter('mode');
165 $OUT .= '&letter=' . getRequestParameter('letter') . '&sortby=' . getRequestParameter('sortby') . '&page=' . $page . '&offset=' . $offset . '%}">';
170 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
171 $OUT .= '-</strong>';
176 if ($page < $pages) $OUT .= ' | ';
180 $content['list'] = $OUT;
183 $OUT = loadTemplate('admin_list_user_pagenav', true, $content);
184 if ($return === true) {
193 // Create email link to user's account
194 function generateUserEmailLink($email, $mod = 'admin') {
195 // Show contact link only if user is confirmed by default
196 $locked = " AND `status`='CONFIRMED'";
198 // But admins shall always see it
199 if (isAdmin()) $locked = '';
201 $result = SQL_QUERY_ESC("SELECT
204 `{?_MYSQL_PREFIX?}_user_data`
206 `email`='%s'" . $locked."
208 array($email), __FUNCTION__, __LINE__);
209 if (SQL_NUMROWS($result) == 1) {
211 list($userid) = SQL_FETCHROW($result);
213 // Rewrite email address to contact link
214 $email = '{%url=modules.php?module=' . $mod . '&what=user_contct&userid=' . bigintval($userid) . '%}';
218 SQL_FREERESULT($result);
220 // Return rewritten (?) email address
224 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
225 // @TODO Double-check configuration entry here
226 function determineRandomReferalId () {
227 // Default is zero refid
230 // Is the extension version fine?
231 if (getExtensionVersion('user') >= '0.3.4') {
233 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= ".getConfig('user_min_confirmed')."");
235 // Do we have at least one?
236 if ($totalUsers > 0) {
237 // Then choose random number
238 $randNum = mt_rand(0, ($totalUsers - 1));
240 // Look for random user
241 $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",
242 array($randNum), __FUNCTION__, __LINE__);
244 // Do we have one entry there?
245 if (SQL_NUMROWS($result) == 1) {
246 // Use that userid as new referal id
247 list($refid) = SQL_FETCHROW($result);
249 // Reset this user's counter
250 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0 WHERE `userid`=%s LIMIT 1",
251 array($refid), __FUNCTION__, __LINE__);
255 SQL_FREERESULT($result);
264 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&what=login&login=') {
281 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
283 fetchUserData($userid, 'nickname');
284 } elseif (isNicknameUsed($userid)) {
285 // No nickname installed
286 $errorCode = getCode('EXTENSION_PROBLEM');
289 // Direct userid entered
290 fetchUserData($userid);
293 // Get user data array and set userid (e.g. important if we login with nickname)
294 $content = getUserDataArray();
295 if (!empty($content['userid'])) $userid = bigintval($content['userid']);
297 // Is there an entry?
298 if ((isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
299 // Check for old MD5 passwords
300 if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
301 // Just set the hash to the password from DB... :)
302 $content['hash'] = getUserData('password');
304 // Hash password with improved way for comparsion
305 $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
308 // Does the password match the hash?
309 if ($content['hash'] == getUserData('password')) {
310 // New hashed password found so let's generate a new one
311 $content['hash'] = generateHash($passwd);
313 // ... and update database
314 // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
315 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
316 array($content['hash'], $userid), __FUNCTION__, __LINE__);
318 // No login bonus by default
319 $GLOBALS['bonus_payed'] = false;
321 // Probe for last online timemark
322 $probe = time() - getUserData('last_online');
323 if (getUserData('last_login') > 0) $probe = time() - getUserData('last_login');
325 if ((isExtensionInstalledAndNewer('bonus', '0.2.2')) && ($probe >= getConfig('login_timeout'))) {
326 // Add login bonus to user's account
327 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
328 $GLOBALS['bonus_payed'] = true;
330 // Subtract login bonus from userid's account or jackpot
331 if ((getExtensionVersion('bonus') >= '0.3.5') && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
334 // @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 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
341 if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
342 // Update database records
343 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
344 array($userid), __FUNCTION__, __LINE__);
345 if (SQL_AFFECTEDROWS() == 1) {
346 // Is a success URL set?
347 if (empty($successUrl)) {
348 // Procedure to checking for login data
349 if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
350 // Bonus added (just displaying!)
351 $URL = 'modules.php?module=chk_login&mode=bonus';
354 $URL = 'modules.php?module=chk_login&mode=login';
361 // Cannot update counter!
362 $errorCode = getCode('CNTR_FAILED');
365 // Cookies not setable!
366 $errorCode = getCode('COOKIES_DISABLED');
368 } elseif (getExtensionVersion('sql_patches') >= '0.6.1') {
369 // Update failture counter
370 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
371 array($userid), __FUNCTION__, __LINE__);
374 $errorCode = getCode('WRONG_PASS');
376 } elseif (getUserData('status') != 'CONFIRMED') {
377 // Create an error code from given status
378 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
380 // Set userid in session
381 setSession('current_userid', getUserData('userid'));
382 } elseif (!isUserDataValid()) {
383 // User id not found!
384 $errorCode = getCode('WRONG_ID');
387 $errorCode = getCode('UNKNOWN_ERROR');
390 // Error code provided?
391 if ($errorCode > 0) {
392 // Then reconstruct the URL
393 $URL = $errorUrl . $errorCode;
395 // Extension set? Then add it as well.
396 if (!empty($ext)) $URL .= '&ext=' . $ext;
403 // Try to send a new password for the given user account
404 function doNewUserPassword ($email, $userid) {
405 // Init result and error
409 // Probe userid/nickname
410 // @TODO We should try to rewrite this to fetchUserData() somehow
411 if (!empty($email)) {
413 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' OR `email`='%s' LIMIT 1",
414 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
415 } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
417 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
418 array($userid, $userid, $email), __FUNCTION__, __LINE__);
419 } elseif (($userid > 0) && (empty($email))) {
420 // Direct userid entered
421 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
422 array(bigintval($userid)), __FUNCTION__, __LINE__);
425 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
426 $errorCode = getCode('WRONG_ID');
430 if (SQL_NUMROWS($result) == 1) {
431 // This data is valid, so we create a new pass... :-)
432 list($userid, $status) = SQL_FETCHROW($result);
434 if ($status == 'CONFIRMED') {
435 // Ooppps, this was missing! ;-) We should update the database...
436 $NEW_PASS = generatePassword();
437 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
438 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
440 // Prepare data and message for email
441 $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
443 // ... and send it away
444 sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
446 // Output note to user
447 loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
449 // Account is locked or unconfirmed
450 $errorCode = generateErrorCodeFromUserStatus($status);
453 redirectToUrl('modules.php?module=index&what=login&login='.$errorCode);
456 // id or email is wrong
457 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
460 // Return the error code