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://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 (isGetRequestElementSet($param)) {
48 $add .= '&' . $param . '=' . getRequestElement($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 (getRequestElement('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 (!isGetRequestElementSet('offset')) setGetRequestElement('offset', 0);
88 if (!isGetRequestElementSet('page')) setGetRequestElement('page' , 0);
90 // Add page and offset
91 $add = '&page=' . getRequestElement('page') . '&offset=' . getRequestElement('offset');
94 foreach (array('mode','status') as $param) {
95 if (isGetRequestElementSet($param)) {
96 $add .= '&' . $param . '=' . getRequestElement($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 == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
148 if (!isGetRequestElementSet('letter')) setGetRequestElement('letter', '');
149 if (!isGetRequestElementSet('sortby')) setGetRequestElement('sortby', 'userid');
152 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat();
155 foreach (array('mode','status') as $param) {
156 if (isGetRequestElementSet($param)) {
157 $OUT .= '&' . $param . '=' . getRequestElement($param);
162 $OUT .= '&letter=' . getRequestElement('letter') . '&sortby=' . getRequestElement('sortby') . '&page=' . $page . '&offset=' . getConfig('user_limit') . '%}">';
167 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('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
199 // Search for the email address
200 $result = SQL_QUERY_ESC("SELECT
203 `{?_MYSQL_PREFIX?}_user_data`
208 array($email), __FUNCTION__, __LINE__);
210 // Do we have an entry?
211 if (SQL_NUMROWS($result) == 1) {
213 list($userid) = SQL_FETCHROW($result);
215 // Rewrite email address to contact link
216 $email = '{%url=modules.php?module=' . $mod . '&what=user_contct&userid=' . bigintval($userid) . '%}';
220 SQL_FREERESULT($result);
222 // Return rewritten (?) email address
226 // Selects a random user id as the new referral id if they have at least X confirmed mails in this run
227 // @TODO Double-check configuration entry here
228 function determineRandomReferralId () {
229 // Default is zero refid
232 // Is the extension version fine?
233 if (isExtensionInstalledAndNewer('user', '0.3.4')) {
235 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= {?user_min_confirmed?}");
237 // Do we have at least one?
238 if ($totalUsers > 0) {
239 // Then choose random number
240 $randNum = mt_rand(0, ($totalUsers - 1));
242 // Look for random user
243 $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",
244 array($randNum), __FUNCTION__, __LINE__);
246 // Do we have one entry there?
247 if (SQL_NUMROWS($result) == 1) {
248 // Use that userid as new referral id
249 list($refid) = SQL_FETCHROW($result);
253 SQL_FREERESULT($result);
262 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&what=login&login=') {
280 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
282 fetchUserData($userid, 'nickname');
283 } elseif (isNicknameUsed($userid)) {
284 // No nickname installed
285 $errorCode = getCode('EXTENSION_PROBLEM');
288 // Direct userid entered
289 $isFound = fetchUserData($userid);
293 if (($errorCode == '0') && ($isFound === true)) {
294 // Get user data array and set userid (e.g. important if we login with nickname)
295 $content = getUserDataArray();
296 if (!empty($content['userid'])) {
297 $userid = bigintval($content['userid']);
301 // Is there an entry?
302 if (($errorCode == '0') && (isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
303 // Check for old MD5 passwords
304 if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
305 // Just set the hash to the password from DB... :)
306 $content['hash'] = getUserData('password');
308 // Hash password with improved way for comparsion
309 $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
312 // Does the password match the hash?
313 if ($content['hash'] == getUserData('password')) {
314 // New hashed password found so let's generate a new one
315 $content['hash'] = generateHash($passwd);
317 // ... and update database
318 // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
319 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
320 array($content['hash'], $userid), __FUNCTION__, __LINE__);
322 // No login bonus by default
323 $GLOBALS['bonus_payed'] = false;
325 // Is bonus up-to-date?
326 if (isExtensionInstalledAndNewer('bonus', '0.2.2')) {
327 // Probe for last online timemark
328 $probe = time() - getUserData('last_online');
329 if (getUserData('last_login') > 0) {
330 // Use timestamp from last login
331 $probe = time() - getUserData('last_login');
334 // Is the timeout reached?
335 if ($probe >= getConfig('login_timeout')) {
336 // Add login bonus to user's account
337 $add = ',`login_bonus`=`login_bonus`+{?login_bonus?}';
338 $GLOBALS['bonus_payed'] = true;
340 // Subtract login bonus from userid's account or jackpot
341 if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getBonusMode() != 'ADD')) {
342 handleBonusPoints('login_bonus', $userid);
347 // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
350 setMemberId($userid);
352 // Try to set session data (which shall normally always work!)
353 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
354 if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
355 // Update database records
356 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
357 array($userid), __FUNCTION__, __LINE__);
358 if (!SQL_HASZEROAFFECTED()) {
359 // Is a success URL set?
360 if (empty($successUrl)) {
361 // Procedure to checking for login data
362 if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
363 // Bonus added (just displaying!)
364 $url = 'modules.php?module=chk_login&mode=bonus';
367 $url = 'modules.php?module=chk_login&mode=login';
374 // Cannot update counter!
375 $errorCode = getCode('CNTR_FAILED');
378 // Cookies not setable!
379 $errorCode = getCode('COOKIES_DISABLED');
381 } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
382 // Update failure counter
383 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
384 array($userid), __FUNCTION__, __LINE__);
387 $errorCode = getCode('WRONG_PASS');
389 } elseif ((isUserDataValid()) && (getUserData('status') != 'CONFIRMED')) {
390 // Create an error code from given status
391 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
393 // Set userid in session
394 setSession('current_userid', getUserData('userid'));
395 } elseif (!isUserDataValid()) {
397 $errorCode = getCode('WRONG_ID');
400 $errorCode = getCode('UNKNOWN_ERROR');
403 // Error code provided?
404 if ($errorCode > 0) {
405 // Then reconstruct the URL
406 $url = $errorUrl . $errorCode;
408 // Extension set? Then add it as well.
410 $url .= '&ext=' . $ext;
418 // Try to send a new password for the given user account
419 function doNewUserPassword ($email, $userid) {
420 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ' - ENTERED!');
421 // Init found-status and error
423 $accountFound = false;
425 // Probe userid/nickname
426 if (!empty($email)) {
428 $accountFound = fetchUserData($email, 'email');
429 } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
431 $accountFound = fetchUserData($userid, 'nickname');
432 } elseif ((isValidUserId($userid)) && (empty($email))) {
433 // Direct userid entered
434 $accountFound = fetchUserData($userid);
437 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',email=' . $email . ': Important variables are empty.');
441 if ($accountFound === true) {
442 // Is the account confirmed
443 if (getUserData('status') == 'CONFIRMED') {
444 // Generate new password
445 $NEW_PASS = generatePassword();
448 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
449 array(generateHash($NEW_PASS), getUserData('userid')), __FUNCTION__, __LINE__);
451 // Prepare data and message for email
452 $message = loadEmailTemplate('guest_new_password',
454 'new_pass' => $NEW_PASS,
455 'nickname' => $userid
456 ), bigintval(getUserData('userid')));
458 // ... and send it away
459 sendEmail(bigintval(getUserData('userid')), '{--GUEST_NEW_PASSWORD--}', $message);
461 // Output note to user
462 displayMessage('{--GUEST_NEW_PASSWORD_SEND--}');
464 // Account is locked or unconfirmed
465 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
468 redirectToUrl('modules.php?module=index&what=login&login=' . $errorCode);
471 // Id or email is wrong
472 displayMessage('<span class="bad">{--GUEST_WRONG_ID_EMAIL--}</span>');
475 // Return the error code
476 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ',errorCode=' . $errorCode . ' - EXIT!');
480 // Get timestamp for given stats type and data
481 function getEpocheTimeFromUserStats ($statsType, $statsData, $userid = NULL) {
482 // Default timestamp is zero
483 $data['inserted'] = '0';
486 if ((isMemberIdSet()) && (is_null($userid))) {
487 $userid = getMemberId();
490 // Is the extension installed and updated?
491 if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
493 return $data['inserted'];
496 // Try to find the entry
497 $result = SQL_QUERY_ESC("SELECT
498 UNIX_TIMESTAMP(`inserted`) AS inserted
500 `{?_MYSQL_PREFIX?}_user_stats_data`
503 `stats_type`='%s' AND
510 ), __FUNCTION__, __LINE__);
512 // Is the entry there?
513 if (SQL_NUMROWS($result) == 1) {
515 $data = SQL_FETCHARRAY($result);
519 SQL_FREERESULT($result);
522 return $data['inserted'];
525 // Inserts user stats
526 function insertUserStatsRecord ($userid, $statsType, $statsData) {
527 // Is the extension installed and updated?
528 if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
533 // Default is not working
537 if ((!getEpocheTimeFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
539 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
544 ), __FUNCTION__, __LINE__);
546 // Does it have worked?
547 $return = (!SQL_HASZEROAFFECTED());
548 } elseif (is_array($statsData)) {
550 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',type=' . $statsType . ',data=' . gettype($statsData) . ': Invalid statistics data type!');
557 // Confirms a user account
558 function doConfirmUserAccount ($hash) {
561 'message' => '{--GUEST_CONFIRMED_FAILED--}',
565 // Initialize the user id
568 // Search for an unconfirmed or confirmed account
569 $result = SQL_QUERY_ESC("SELECT `userid`,`refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `user_hash`='%s' AND (`status`='UNCONFIRMED' OR `status`='CONFIRMED') LIMIT 1",
570 array($hash), __FILE__, __LINE__);
571 if (SQL_NUMROWS($result) == 1) {
572 // Ok, he want's to confirm now so we load some data
573 list($userid, $refid) = SQL_FETCHROW($result);
576 if (!fetchUserData($userid)) {
577 // Not found, should not happen
578 debug_report_bug(__FILE__, __LINE__, 'User account ' . $userid . ' not found.');
581 // Load all data and add points
582 $content = getUserDataArray();
584 // Unlock his account (but only when it is on UNCONFIRMED!)
585 SQL_QUERY_ESC("UPDATE
586 `{?_MYSQL_PREFIX?}_user_data`
588 `status`='CONFIRMED',
592 `status`='UNCONFIRMED'
594 array($hash), __FILE__, __LINE__);
597 if (!SQL_HASZEROAFFECTED()) {
598 // Send email if updated
599 $message = loadEmailTemplate('guest_user_confirmed', $content, bigintval($userid));
601 // And send him right away the confirmation mail
602 sendEmail($userid, '{--GUEST_THANX_CONFIRM--}', $message);
604 // Maybe he got "referraled"?
605 if ((isValidUserId($refid)) && ($refid != $userid)) {
606 // Select the referral userid
607 if (fetchUserData($refid)) {
608 // Update ref counter...
609 updateReferralCounter($refid);
611 // If version matches add ref bonus to refid's account
612 if ((isExtensionInstalledAndNewer('bonus', '0.4.4')) && (isBonusRallyeActive())) {
613 // Add points (directly only!)
614 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `bonus_ref`=`bonus_ref`+{?bonus_ref?} WHERE `userid`=%s LIMIT 1",
615 array(bigintval($refid)), __FILE__, __LINE__);
617 // Subtract points from system
618 handleBonusPoints(getConfig('bonus_ref'), $refid);
621 // Add one-time referral bonus over referral system or directly
622 initReferralSystem();
623 addPointsThroughReferralSystem('referral_bonus', $refid, getPointsRef(), bigintval($userid));
627 if (isExtensionActive('rallye')) {
628 // Add user to rallye (or not?)
629 addUserToReferralRallye(bigintval($userid));
632 // Account confirmed!
633 if (isExtensionActive('lead')) {
634 // Set special lead cookie
635 setSession('lead_userid', bigintval($userid));
637 // Lead-Code mode enabled
638 redirectToUrl('lead-confirm.php');
640 $content['message'] = '{--GUEST_CONFIRMED_DONE--}';
641 $content['userid'] = bigintval($userid);
643 } elseif (isExtensionActive('lead')) {
644 // Set special lead cookie
645 setSession('lead_userid', bigintval($userid));
647 // Lead-Code mode enabled
648 redirectToUrl('lead-confirm.php');
650 // Nobody was found unter this hash key... or our new member want's to confirm twice?
651 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
654 // Nobody was found unter this hash key... or our new member want's to confirm twice?
655 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
659 displayMessage($content['message']);
662 // Does resend the user's confirmation link for given email address
663 function doResendUserConfirmationLink ($email) {
664 // Email address not registered is default message
665 $message = '{--EMAIL_404--}';
667 // Confirmation link requested
668 if (fetchUserData($email, 'email')) {
669 // Email address found
670 $content = getUserDataArray();
672 // Is the account unconfirmed?
673 if ($content['status'] == 'UNCONFIRMED') {
674 // Load email template
675 $message = loadEmailTemplate('guest_request_confirm', array(), $content['userid']);
678 sendEmail($content['userid'], '{--GUEST_REQUEST_CONFIRM_LINK_SUBJECT--}', $message);
681 // Create message based on the status
682 $message = getConfirmationMessageFromUserStatus($content['status']);
686 displayMessage($message);
689 // Get a message (somewhat translation) from user status for confirmation link.
690 // This is different to translateUserStatus() in text messages.
691 function getConfirmationMessageFromUserStatus ($status) {
692 // Default is 'UNKNOWN'
693 $message = '{%message,GUEST_LOGIN_ID_UNKNOWN_STATUS=' . $status . '%}';
695 // Which status is it?
697 case 'UNCONFIRMED': // Account is unconfirmed
699 $message = '{--GUEST_CONFIRM_LINK_SENT--}';
702 case 'CONFIRMED': // Account already confirmed
703 $message = '{--GUEST_LOGIN_ID_CONFIRMED--}';
706 case 'LOCKED': // Account is locked
707 $message = '{--GUEST_LOGIN_ID_LOCKED--}';
710 default: // This should not happen
711 debug_report_bug(__FUNCTION__, __LINE__, 'Unknown user status ' . $status . ' detected.');
719 // Expression call-back function for fetching user data
720 function doExpressionUser ($data) {
721 // Use current userid by default
722 $functionName = 'getMemberId()';
724 // User-related data, so is there a userid?
725 if (!empty($data['matches'][4][$data['key']])) {
726 // Do we have a userid or $userid?
727 if (substr($data['matches'][4][$data['key']], 0, 1) == '$') {
729 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
730 } elseif (!empty($data['matches'][4][$data['key']])) {
731 // Do we have a number or a dollar sign in front of it?
732 if (preg_replace('/[^0123456789]/', '', $data['matches'][4][$data['key']]) != $data['matches'][4][$data['key']]) {
733 // Possible database column, so get it again
734 $data['matches'][4][$data['key']] = "getFetchedUserData('userid', getMemberId(), '" . $data['matches'][4][$data['key']] . "')";
738 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
740 } elseif ((!empty($data['callback'])) && (isUserDataValid())) {
741 // "Call-back" alias column for current logged in user's data
742 $functionName = "getUserData('" . $data['callback'] . "')";
745 // Do we have another function to run (e.g. translations)
746 if (!empty($data['extra_func'])) {
747 // Surround the original function call with it
748 $functionName = $data['extra_func'] . '(' . $functionName . ')';
750 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'functionName=' . $functionName);
753 $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
755 // Now replace the code
756 $code = replaceExpressionCode($data, $replacer);
758 // Return replaced code
762 // Template call-back function for list_user admin function
763 function doTemplateAdminListUserTitle ($template, $clear = false) {
764 // Init title with "all accounts"
765 $code = '{--ADMIN_LIST_ALL_ACCOUNTS--}';
767 // Do we have a 'status' or 'mode' set?
768 if (isGetRequestElementSet('status')) {
769 // Set title according to the 'status'
770 $code = sprintf("{--ADMIN_LIST_STATUS_%s_ACCOUNTS--}", strtoupper(getRequestElement('status')));
771 } elseif (isGetRequestElementSet('mode')) {
772 // Set title according to the "mode"
773 $code = sprintf("{--ADMIN_LIST_MODE_%s_ACCOUNTS--}", strtoupper(getRequestElement('mode')));