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 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Add links for selecting some users
44 function alpha ($sortby) {
46 foreach (array('page','offset','mode','status') as $param) {
47 if (isGetRequestParameterSet($param)) {
48 $add .= '&' . $param . '=' . getRequestParameter($param);
52 /* Creates the list of letters and makes them a link. */
53 $alphabet = explode(',', '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,');
54 $num = count($alphabet) - 1;
56 while (list($counter, $ltr) = each($alphabet)) {
57 if (getRequestParameter('letter') == $ltr) {
58 // Current letter is letter from URL
59 $OUT .= '<strong>' . $ltr . '</strong>';
61 // Output link to letter
62 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&letter=' . $ltr . '&sortby=' . $sortby . $add . '%}">' . $ltr . '</a>';
65 if ((($counter / getConfig('user_alpha')) == round($counter / getConfig('user_alpha'))) && ($counter > 0)) {
67 } elseif ( $counter != $num ) {
74 'alpha_selection' => $OUT
78 $OUT = loadTemplate('admin_list_user_alpha', true, $content);
80 // Return generated code
84 // Add links for sorting
85 function addSortLinks ($letter, $sortby) {
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 foreach (array('mode','status') as $param) {
95 if (isGetRequestParameterSet($param)) {
96 $add .= '&' . $param . '=' . getRequestParameter($param);
100 // Makes order by links..
101 if ($letter == 'front') {
105 // Prepare array with all possible sorters
107 'userid' => '{--_USERID--}',
108 'family' => '{--FAMILY--}',
109 'email' => '{--EMAIL--}',
110 'REMOTE_ADDR' => '{--REMOTE_IP--}'
113 // Add nickname if extension is installed
114 if (isExtensionActive('nickname')) {
115 $list['nickname'] = '{--NICKNAME--}';
118 foreach ($list as $sort => $title) {
119 if ($sortby == $sort) {
120 $OUT .= '<strong>' . $title . '</strong>|';
122 $OUT .= '<a href="{%url=modules.php?module=admin&what=list_user&letter=' . $letter . '&sortby=' . $sort . $add . '%}">' . $title . '</a>|';
127 $content['list'] = substr($OUT, 0, -1);
130 $OUT = loadTemplate('admin_list_user_sort', true, $content);
136 // Add page navigation
137 function addPageNavigation ($numPages) {
138 // Start with empty content
141 // Create only the navigation if page count > 1
143 // Create navigation links for every page
144 for ($page = 1; $page <= $numPages; $page++) {
145 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
148 if (!isGetRequestParameterSet('letter')) setGetRequestParameter('letter', '');
149 if (!isGetRequestParameterSet('sortby')) setGetRequestParameter('sortby', 'userid');
152 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat();
155 foreach (array('mode','status') as $param) {
156 if (isGetRequestParameterSet($param)) {
157 $OUT .= '&' . $param . '=' . getRequestParameter($param);
162 $OUT .= '&letter=' . getRequestParameter('letter') . '&sortby=' . getRequestParameter('sortby') . '&page=' . $page . '&offset=' . getConfig('user_limit') . '%}">';
167 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
168 $OUT .= '-</strong>';
173 if ($page < $numPages) {
179 $content['list'] = $OUT;
182 $OUT = loadTemplate('admin_list_user_pagenav', true, $content);
189 // Create email link to user's account
190 function generateUserEmailLink ($email, $mod = 'admin') {
191 // Show contact link only if user is confirmed by default
192 $locked = " AND `status`='CONFIRMED'";
194 // But admins shall always see it
195 if (isAdmin()) $locked = '';
197 $result = SQL_QUERY_ESC("SELECT
200 `{?_MYSQL_PREFIX?}_user_data`
202 `email`='%s'" . $locked."
204 array($email), __FUNCTION__, __LINE__);
205 if (SQL_NUMROWS($result) == 1) {
207 list($userid) = SQL_FETCHROW($result);
209 // Rewrite email address to contact link
210 $email = '{%url=modules.php?module=' . $mod . '&what=user_contct&userid=' . bigintval($userid) . '%}';
214 SQL_FREERESULT($result);
216 // Return rewritten (?) email address
220 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
221 // @TODO Double-check configuration entry here
222 function determineRandomReferalId () {
223 // Default is zero refid
226 // Is the extension version fine?
227 if (isExtensionInstalledAndNewer('user', '0.3.4')) {
229 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= {?user_min_confirmed?}");
231 // Do we have at least one?
232 if ($totalUsers > 0) {
233 // Then choose random number
234 $randNum = mt_rand(0, ($totalUsers - 1));
236 // Look for random user
237 $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",
238 array($randNum), __FUNCTION__, __LINE__);
240 // Do we have one entry there?
241 if (SQL_NUMROWS($result) == 1) {
242 // Use that userid as new referal id
243 list($refid) = SQL_FETCHROW($result);
247 SQL_FREERESULT($result);
256 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&what=login&login=') {
274 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
276 fetchUserData($userid, 'nickname');
277 } elseif (isNicknameUsed($userid)) {
278 // No nickname installed
279 $errorCode = getCode('EXTENSION_PROBLEM');
282 // Direct userid entered
283 $isFound = fetchUserData($userid);
287 if (($errorCode == '0') && ($isFound === true)) {
288 // Get user data array and set userid (e.g. important if we login with nickname)
289 $content = getUserDataArray();
290 if (!empty($content['userid'])) {
291 $userid = bigintval($content['userid']);
295 // Is there an entry?
296 if (($errorCode == '0') && (isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
297 // Check for old MD5 passwords
298 if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
299 // Just set the hash to the password from DB... :)
300 $content['hash'] = getUserData('password');
302 // Hash password with improved way for comparsion
303 $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
306 // Does the password match the hash?
307 if ($content['hash'] == getUserData('password')) {
308 // New hashed password found so let's generate a new one
309 $content['hash'] = generateHash($passwd);
311 // ... and update database
312 // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
313 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
314 array($content['hash'], $userid), __FUNCTION__, __LINE__);
316 // No login bonus by default
317 $GLOBALS['bonus_payed'] = false;
319 // Is bonus up-to-date?
320 if (isExtensionInstalledAndNewer('bonus', '0.2.2')) {
321 // Probe for last online timemark
322 $probe = time() - getUserData('last_online');
323 if (getUserData('last_login') > 0) {
324 // Use timestamp from last login
325 $probe = time() - getUserData('last_login');
328 // Is the timeout reached?
329 if ($probe >= getConfig('login_timeout')) {
330 // Add login bonus to user's account
331 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
332 $GLOBALS['bonus_payed'] = true;
334 // Subtract login bonus from userid's account or jackpot
335 if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getBonusMode() != 'ADD')) {
336 handleBonusPoints('login_bonus');
341 // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
344 setMemberId($userid);
346 // Try to set session data (which shall normally always work!)
347 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
348 if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
349 // Update database records
350 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
351 array($userid), __FUNCTION__, __LINE__);
352 if (!SQL_HASZEROAFFECTED()) {
353 // Is a success URL set?
354 if (empty($successUrl)) {
355 // Procedure to checking for login data
356 if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
357 // Bonus added (just displaying!)
358 $url = 'modules.php?module=chk_login&mode=bonus';
361 $url = 'modules.php?module=chk_login&mode=login';
368 // Cannot update counter!
369 $errorCode = getCode('CNTR_FAILED');
372 // Cookies not setable!
373 $errorCode = getCode('COOKIES_DISABLED');
375 } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
376 // Update failure counter
377 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
378 array($userid), __FUNCTION__, __LINE__);
381 $errorCode = getCode('WRONG_PASS');
383 } elseif ((isUserDataValid()) && (getUserData('status') != 'CONFIRMED')) {
384 // Create an error code from given status
385 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
387 // Set userid in session
388 setSession('current_userid', getUserData('userid'));
389 } elseif (!isUserDataValid()) {
391 $errorCode = getCode('WRONG_ID');
394 $errorCode = getCode('UNKNOWN_ERROR');
397 // Error code provided?
398 if ($errorCode > 0) {
399 // Then reconstruct the URL
400 $url = $errorUrl . $errorCode;
402 // Extension set? Then add it as well.
404 $url .= '&ext=' . $ext;
412 // Try to send a new password for the given user account
413 function doNewUserPassword ($email, $userid) {
414 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ' - ENTERED!');
415 // Init found-status and error
417 $accountFound = false;
419 // Probe userid/nickname
420 if (!empty($email)) {
422 $accountFound = fetchUserData($email, 'email');
423 } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
425 $accountFound = fetchUserData($userid, 'nickname');
426 } elseif ((isValidUserId($userid)) && (empty($email))) {
427 // Direct userid entered
428 $accountFound = fetchUserData($userid);
431 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',email=' . $email . ': Important variables are empty.');
435 if ($accountFound === true) {
436 // Is the account confirmed
437 if (getUserData('status') == 'CONFIRMED') {
438 // Generate new password
439 $NEW_PASS = generatePassword();
442 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
443 array(generateHash($NEW_PASS), getUserData('userid')), __FUNCTION__, __LINE__);
445 // Prepare data and message for email
446 $message = loadEmailTemplate('guest_new_password',
448 'new_pass' => $NEW_PASS,
449 'nickname' => $userid
450 ), bigintval(getUserData('userid')));
452 // ... and send it away
453 sendEmail(bigintval(getUserData('userid')), '{--GUEST_NEW_PASSWORD--}', $message);
455 // Output note to user
456 displayMessage('{--GUEST_NEW_PASSWORD_SEND--}');
458 // Account is locked or unconfirmed
459 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
462 redirectToUrl('modules.php?module=index&what=login&login=' . $errorCode);
465 // id or email is wrong
466 displayMessage('<span class="notice">{--GUEST_WRONG_ID_EMAIL--}</span>');
469 // Return the error code
470 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ',errorCode=' . $errorCode . ' - EXIT!');
474 // Get timestamp for given stats type and data
475 function getEpocheTimeFromUserStats ($statsType, $statsData, $userid = NULL) {
476 // Default timestamp is zero
477 $data['inserted'] = '0';
480 if ((isMemberIdSet()) && ($userid == '0')) {
481 $userid = getMemberId();
484 // Is the extension installed and updated?
485 if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
487 return $data['inserted'];
490 // Try to find the entry
491 $result = SQL_QUERY_ESC("SELECT
492 UNIX_TIMESTAMP(`inserted`) AS inserted
494 `{?_MYSQL_PREFIX?}_user_stats_data`
497 `stats_type`='%s' AND
504 ), __FUNCTION__, __LINE__);
506 // Is the entry there?
507 if (SQL_NUMROWS($result) == 1) {
509 $data = SQL_FETCHARRAY($result);
513 SQL_FREERESULT($result);
516 return $data['inserted'];
519 // Inserts user stats
520 function insertUserStatsRecord ($userid, $statsType, $statsData) {
521 // Is the extension installed and updated?
522 if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
528 if ((!getEpocheTimeFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
530 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`, `stats_type`, `stats_data`) VALUES (%s,'%s','%s')",
535 ), __FUNCTION__, __LINE__);
536 } elseif (is_array($statsData)) {
538 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',type=' . $statsType . ',data=' . gettype($statsData) . ': Invalid statistics data type!');
542 // Confirms a user account
543 function doConfirmUserAccount ($hash) {
546 'message' => '{--GUEST_CONFIRMED_FAILED--}',
550 // Initialize the user id
553 // Search for an unconfirmed or confirmed account
554 $result = SQL_QUERY_ESC("SELECT `userid`, `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `user_hash`='%s' AND (`status`='UNCONFIRMED' OR `status`='CONFIRMED') LIMIT 1",
555 array($hash), __FILE__, __LINE__);
556 if (SQL_NUMROWS($result) == 1) {
557 // Ok, he want's to confirm now so we load some data
558 list($userid, $refid) = SQL_FETCHROW($result);
561 if (!fetchUserData($userid)) {
562 // Not found, should not happen
563 debug_report_bug(__FILE__, __LINE__, 'User account ' . $userid . ' not found.');
566 // Load all data and add points
567 $content = getUserDataArray();
569 // Unlock his account (but only when it is on UNCONFIRMED!)
570 SQL_QUERY_ESC("UPDATE
571 `{?_MYSQL_PREFIX?}_user_data`
573 `status`='CONFIRMED',
577 `status`='UNCONFIRMED'
579 array($hash), __FILE__, __LINE__);
582 if (!SQL_HASZEROAFFECTED()) {
583 // Send email if updated
584 $message = loadEmailTemplate('guest_user_confirmed', $content, bigintval($userid));
586 // And send him right away the confirmation mail
587 sendEmail($userid, '{--GUEST_THANX_CONFIRM--}', $message);
589 // Maybe he got "referaled"?
590 if ((isValidUserId($refid)) && ($refid != $userid)) {
591 // Select the referal userid
592 if (fetchUserData($refid)) {
593 // Update ref counter...
594 updateReferalCounter($refid);
596 // If version matches add ref bonus to refid's account
597 if ((isExtensionInstalledAndNewer('bonus', '0.4.4')) && (isBonusRallyeActive())) {
598 // Add points (directly only!)
599 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `bonus_ref`=`bonus_ref`+{?bonus_ref?} WHERE `userid`=%s LIMIT 1",
600 array(bigintval($refid)), __FILE__, __LINE__);
602 // Subtract points from system
603 handleBonusPoints(getConfig('bonus_ref'));
606 // Add one-time referal bonus over referal system or directly
608 addPointsThroughReferalSystem('referal_bonus', $refid, getPointsRef(), bigintval($userid));
612 if (isExtensionActive('rallye')) {
613 // Add user to rallye (or not?)
614 addUserToReferalRallye(bigintval($userid));
617 // Account confirmed!
618 if (isExtensionActive('lead')) {
619 // Set special lead cookie
620 setSession('lead_userid', bigintval($userid));
622 // Lead-Code mode enabled
623 redirectToUrl('lead-confirm.php');
625 $content['message'] = '{--GUEST_CONFIRMED_DONE--}';
626 $content['userid'] = bigintval($userid);
628 } elseif (isExtensionActive('lead')) {
629 // Set special lead cookie
630 setSession('lead_userid', bigintval($userid));
632 // Lead-Code mode enabled
633 redirectToUrl('lead-confirm.php');
635 // Nobody was found unter this hash key... or our new member want's to confirm twice?
636 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
639 // Nobody was found unter this hash key... or our new member want's to confirm twice?
640 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
644 displayMessage($content['message']);
647 // Does resend the user's confirmation link for given email address
648 function doResendUserConfirmationLink ($email) {
649 // Email address not registered is default message
650 $message = '{--EMAIL_404--}';
652 // Confirmation link requested
653 if (fetchUserData($email, 'email')) {
654 // Email address found
655 $content = getUserDataArray();
657 // Is the account unconfirmed?
658 if ($content['status'] == 'UNCONFIRMED') {
659 // Load email template
660 $message = loadEmailTemplate('guest_request_confirm', array(), $content['userid']);
663 sendEmail($content['userid'], '{--GUEST_REQUEST_CONFIRM_LINK_SUBJECT--}', $message);
666 // Create message based on the status
667 $message = getConfirmationMessageFromUserStatus($content['status']);
671 displayMessage($message);
674 // Get a message (somewhat translation) from user status for confirmation link.
675 // This is different to translateUserStatus() in text messages.
676 function getConfirmationMessageFromUserStatus ($status) {
677 // Default is 'UNKNOWN'
678 $message = '{%message,GUEST_LOGIN_ID_UNKNOWN_STATUS=' . $status . '%}';
680 // Which status is it?
682 case 'UNCONFIRMED': // Account is unconfirmed
684 $message = '{--GUEST_CONFIRM_LINK_SENT--}';
687 case 'CONFIRMED': // Account already confirmed
688 $message = '{--GUEST_LOGIN_ID_CONFIRMED--}';
691 case 'LOCKED': // Account is locked
692 $message = '{--GUEST_LOGIN_ID_LOCKED--}';
695 default: // This should not happen
696 debug_report_bug(__FUNCTION__, __LINE__, 'Unknown user status ' . $status . ' detected.');
704 // Expression call-back function for fetching user data
705 function doExpressionUser ($data) {
706 // Use current userid by default
707 $functionName = 'getMemberId()';
709 // User-related data, so is there a userid?
710 if (!empty($data['matches'][4][$data['key']])) {
711 // Do we have a userid or $userid?
712 if (substr($data['matches'][4][$data['key']], 0, 1) == '$') {
714 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
715 } elseif (!empty($data['matches'][4][$data['key']])) {
716 // Do we have a number or a dollar sign in front of it?
717 if (preg_replace('/[^0123456789]/', '', $data['matches'][4][$data['key']]) != $data['matches'][4][$data['key']]) {
718 // Possible database column, so get it again
719 $data['matches'][4][$data['key']] = "getFetchedUserData('userid', getMemberId(), '" . $data['matches'][4][$data['key']] . "')";
723 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
725 } elseif ((!empty($data['callback'])) && (isUserDataValid())) {
726 // "Call-back" alias column for current logged in user's data
727 $functionName = "getUserData('" . $data['callback'] . "')";
730 // Do we have another function to run (e.g. translations)
731 if (!empty($data['extra_func'])) {
732 // Surround the original function call with it
733 $functionName = $data['extra_func'] . '(' . $functionName . ')';
735 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'functionName=' . $functionName);
738 $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
740 // Now replace the code
741 $code = replaceExpressionCode($data, $replacer);
743 // Return replaced code
747 // Template call-back function for list_user admin function
748 function doTemplateAdminListUserTitle ($template, $dummy = false) {
749 // Init title with "all accounts"
750 $code = '{--ADMIN_LIST_ALL_ACCOUNTS--}';
752 // Do we have a 'status' or 'mode' set?
753 if (isGetRequestParameterSet('status')) {
754 // Set title according to the 'status'
755 $code = sprintf("{--ADMIN_LIST_STATUS_%s_ACCOUNTS--}", strtoupper(getRequestParameter('status')));
756 } elseif (isGetRequestParameterSet('mode')) {
757 // Set title according to the "mode"
758 $code = sprintf("{--ADMIN_LIST_MODE_%s_ACCOUNTS--}", strtoupper(getRequestParameter('mode')));