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)) {
68 } elseif ( $counter != $num ) {
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 (isExtensionInstalledAndNewer('user', '0.3.4')) {
233 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= {?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);
294 if ($errorCode == '0') {
295 // Get user data array and set userid (e.g. important if we login with nickname)
296 $content = getUserDataArray();
297 if (!empty($content['userid'])) $userid = bigintval($content['userid']);
300 // Is there an entry?
301 if ((isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
302 // Check for old MD5 passwords
303 if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
304 // Just set the hash to the password from DB... :)
305 $content['hash'] = getUserData('password');
307 // Hash password with improved way for comparsion
308 $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
311 // Does the password match the hash?
312 if ($content['hash'] == getUserData('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() - getUserData('last_online');
326 if (getUserData('last_login') > 0) $probe = time() - getUserData('last_login');
328 if ((isExtensionInstalledAndNewer('bonus', '0.2.2')) && ($probe >= getConfig('login_timeout'))) {
329 // Add login bonus to user's account
330 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
331 $GLOBALS['bonus_payed'] = true;
333 // Subtract login bonus from userid's account or jackpot
334 if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
337 // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
340 setMemberId($userid);
342 // Try to set session data (which shall normally always work!)
343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
344 if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
345 // Update database records
346 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
347 array($userid), __FUNCTION__, __LINE__);
348 if (SQL_AFFECTEDROWS() == 1) {
349 // Is a success URL set?
350 if (empty($successUrl)) {
351 // Procedure to checking for login data
352 if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
353 // Bonus added (just displaying!)
354 $url = 'modules.php?module=chk_login&mode=bonus';
357 $url = 'modules.php?module=chk_login&mode=login';
364 // Cannot update counter!
365 $errorCode = getCode('CNTR_FAILED');
368 // Cookies not setable!
369 $errorCode = getCode('COOKIES_DISABLED');
371 } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
372 // Update failture counter
373 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
374 array($userid), __FUNCTION__, __LINE__);
377 $errorCode = getCode('WRONG_PASS');
379 } elseif (getUserData('status') != 'CONFIRMED') {
380 // Create an error code from given status
381 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
383 // Set userid in session
384 setSession('current_userid', getUserData('userid'));
385 } elseif (!isUserDataValid()) {
386 // User id not found!
387 $errorCode = getCode('WRONG_ID');
390 $errorCode = getCode('UNKNOWN_ERROR');
393 // Error code provided?
394 if ($errorCode > 0) {
395 // Then reconstruct the URL
396 $url = $errorUrl . $errorCode;
398 // Extension set? Then add it as well.
399 if (!empty($ext)) $url .= '&ext=' . $ext;
406 // Try to send a new password for the given user account
407 function doNewUserPassword ($email, $userid) {
408 // Init result and error
412 // Probe userid/nickname
413 // @TODO We should try to rewrite this to fetchUserData() somehow
414 if (!empty($email)) {
416 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' OR `email`='%s' LIMIT 1",
417 array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
418 } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
420 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
421 array($userid, $userid, $email), __FUNCTION__, __LINE__);
422 } elseif (($userid > 0) && (empty($email))) {
423 // Direct userid entered
424 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
425 array(bigintval($userid)), __FUNCTION__, __LINE__);
428 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
429 $errorCode = getCode('WRONG_ID');
433 if (SQL_NUMROWS($result) == 1) {
434 // This data is valid, so we create a new pass... :-)
435 list($userid, $status) = SQL_FETCHROW($result);
437 if ($status == 'CONFIRMED') {
438 // Ooppps, this was missing! ;-) We should update the database...
439 $NEW_PASS = generatePassword();
440 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
441 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
443 // Prepare data and message for email
444 $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
446 // ... and send it away
447 sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
449 // Output note to user
450 loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
452 // Account is locked or unconfirmed
453 $errorCode = generateErrorCodeFromUserStatus($status);
456 redirectToUrl('modules.php?module=index&what=login&login='.$errorCode);
459 // id or email is wrong
460 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
463 // Return the error code
467 // Get timestamp for given stats type and data
468 function getTimestampFromUserStats ($statsType, $statsData, $userid = '0') {
469 // Default timestamp is zero
470 $data['inserted'] = '0';
473 if ((isMemberIdSet()) && ($userid == '0')) {
474 $userid = getMemberId();
477 // Is the extension installed and updated?
478 if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
480 return $data['inserted'];
483 // Try to find the entry
484 $result = SQL_QUERY_ESC("SELECT
485 UNIX_TIMESTAMP(`inserted`) AS inserted
487 `{?_MYSQL_PREFIX?}_user_stats_data`
490 `stats_type`='%s' AND
497 ), __FUNCTION__, __LINE__);
499 // Is the entry there?
500 if (SQL_NUMROWS($result) == 1) {
502 $data = SQL_FETCHARRAY($result);
506 SQL_FREERESULT($result);
509 return $data['inserted'];
512 // Inserts user stats
513 function insertUserStatsRecord ($userid, $statsType, $statsData) {
514 // Is the extension installed and updated?
515 if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
521 if ((!getTimestampFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
523 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
524 array(bigintval($userid), $statsType, $statsData), __FUNCTION__, __LINE__);
525 } elseif (is_array($statsData)) {
527 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$statsType},data={".gettype($statsData).": Invalid statistics data type!");