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 - 2012 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 addAlphabeticalSorting ($sortby) {
46 foreach (array('page', 'offset', 'do', '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 // Add all letter links
58 while (list($counter, $ltr) = each($alphabet)) {
59 if (getRequestElement('letter') == $ltr) {
60 // Current letter is letter from URL
61 $OUT .= '<strong>' . $ltr . '</strong>';
63 // Output link to letter
64 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat() . '&letter=' . $ltr . '&sortby=' . $sortby . $add . '%}">' . $ltr . '</a>';
67 if ((($counter / getUserAlpha()) == round($counter / getUserAlpha())) && ($counter > 0)) {
69 } elseif ($counter != $num) {
76 'alpha_selection' => $OUT,
80 $OUT = loadTemplate('admin_list_user_alpha', TRUE, $content);
82 // Return generated code
86 // Add links for sorting
87 function addSortLinks ($letter, $sortby) {
89 if (!isGetRequestElementSet('offset')) setGetRequestElement('offset', 0);
90 if (!isGetRequestElementSet('page')) setGetRequestElement('page' , 0);
92 // Add page and offset
93 $add = '&page=' . getRequestElement('page') . '&offset=' . getRequestElement('offset');
96 foreach (array('do','status') as $param) {
97 if (isGetRequestElementSet($param)) {
98 $add .= '&' . $param . '=' . getRequestElement($param);
102 // Makes order by links..
103 if ($letter == 'front') {
107 // Prepare array with all possible sorters
109 'userid' => '{--_USERID--}',
110 'family' => '{--FAMILY--}',
111 'email' => '{--EMAIL--}',
112 'REMOTE_ADDR' => '{--REMOTE_IP--}'
115 // Add nickname if extension is installed
116 if (isExtensionActive('nickname')) {
117 $list['nickname'] = '{--NICKNAME--}';
120 foreach ($list as $sort => $title) {
121 if ($sortby == $sort) {
122 $OUT .= '<strong>' . $title . '</strong>|';
124 $OUT .= '<a href="{%url=modules.php?module=admin&what=list_user&letter=' . $letter . '&sortby=' . $sort . $add . '%}">' . $title . '</a>|';
129 $content['list'] = substr($OUT, 0, -1);
132 $OUT = loadTemplate('admin_list_user_sort', TRUE, $content);
138 // Add page navigation
139 function addPageNavigation ($numPages) {
140 // Start with empty content
143 // Create only the navigation if page count > 1
145 // Create navigation links for every page
146 for ($page = 1; $page <= $numPages; $page++) {
147 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
150 if (!isGetRequestElementSet('letter')) setGetRequestElement('letter', '');
151 if (!isGetRequestElementSet('sortby')) setGetRequestElement('sortby', 'userid');
154 $OUT .= '<a href="{%url=modules.php?module=admin&what=' . getWhat();
157 foreach (array('do','status') as $param) {
158 if (isGetRequestElementSet($param)) {
159 $OUT .= '&' . $param . '=' . getRequestElement($param);
164 $OUT .= '&letter=' . getRequestElement('letter') . '&sortby=' . getRequestElement('sortby') . '&page=' . $page . '&offset=' . getUserLimit() . '%}">';
169 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
170 $OUT .= '-</strong>';
175 if ($page < $numPages) {
181 $content['list'] = $OUT;
184 $OUT = loadTemplate('admin_list_user_pagenav', TRUE, $content);
191 // Create email link to user's account
192 function generateUserEmailLink ($email, $mod = 'admin') {
193 // Show contact link only if user is confirmed by default
194 $locked = " AND `status`='CONFIRMED'";
196 // But admins shall always see it
201 // Search for the email address
202 $result = SQL_QUERY_ESC("SELECT
205 `{?_MYSQL_PREFIX?}_user_data`
210 array($email), __FUNCTION__, __LINE__);
212 // Is there an entry?
213 if (SQL_NUMROWS($result) == 1) {
215 list($userid) = SQL_FETCHROW($result);
217 // Rewrite email address to contact link
218 $email = '{%url=modules.php?module=' . $mod . '&what=user_contct&userid=' . bigintval($userid) . '%}';
222 SQL_FREERESULT($result);
224 // Return rewritten (?) email address
228 // Selects a random user id as the new referral id if they have at least X confirmed mails in this run
229 function determineRandomReferralId () {
230 // Default is zero refid
233 // Is the extension version fine?
234 if ((isRandomReferralIdEnabled()) && (isExtensionInstalledAndNewer('user', '0.3.4'))) {
236 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', TRUE, runFilterChain('user_exclusion_sql', ' AND `rand_confirmed` >= {?user_min_confirmed?}'));
238 // Is there at least one?
239 if ($totalUsers > 0) {
240 // Then choose random userid
241 $randUserid = mt_rand(0, ($totalUsers - 1));
243 // Look for random user
244 $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` " . runFilterChain('user_exclusion_sql', "WHERE `status`='CONFIRMED'") . ' AND `rand_confirmed` >= {?user_min_confirmed?} ORDER BY `rand_confirmed` DESC LIMIT %s, 1',
245 array($randUserid), __FUNCTION__, __LINE__);
247 // Is there one entry there?
248 if (SQL_NUMROWS($result) == 1) {
249 // Use that userid as new referral id
250 list($refid) = SQL_FETCHROW($result);
253 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ' - choosen!');
257 SQL_FREERESULT($result);
266 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&what=login&login=') {
284 if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
286 $isFound = fetchUserData($userid, 'nickname');
287 } elseif (isNicknameUsed($userid)) {
288 // No nickname installed
289 $errorCode = getCode('EXTENSION_PROBLEM');
292 // Direct userid entered
293 $isFound = fetchUserData($userid);
297 if (($errorCode == '0') && ($isFound === TRUE)) {
298 // Get user data array and set userid (e.g. important if we login with nickname)
299 $content = getUserDataArray();
300 if (!empty($content['userid'])) {
301 $userid = bigintval($content['userid']);
306 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',isUserDataValid()=' . intval(isUserDataValid()) . ',userStatus=' . getUserData('status') . ',errorCode=' . $errorCode . ',ext=' . $ext . ',isFound=' . intval($isFound));
308 // Is there an entry?
309 if (($errorCode == '0') && (isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
310 // Check for old MD5 passwords
311 if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
312 // Just set the hash to the password from DB... :)
313 $content['hash'] = getUserData('password');
315 // Hash password with improved way for comparsion
316 $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
319 // Does the password match the hash?
320 if ($content['hash'] == getUserData('password')) {
321 // New hashed password found so let's generate a new one
322 $content['hash'] = generateHash($passwd);
324 // ... and update database
325 // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
326 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
327 array($content['hash'], $userid), __FUNCTION__, __LINE__);
329 // No login bonus by default
330 $GLOBALS['bonus_payed'] = FALSE;
332 // Is bonus up-to-date?
333 if (isExtensionInstalledAndNewer('bonus', '0.2.2')) {
334 // Probe for last online timemark
335 $probe = time() - getUserData('last_online');
336 if (getUserData('last_login') > 0) {
337 // Use timestamp from last login
338 $probe = time() - getUserData('last_login');
341 // Is the timeout reached?
342 if ($probe >= getConfig('login_timeout')) {
343 // Add login bonus to user's account
344 $add = ',`login_bonus`=`login_bonus`+{?login_bonus?}';
345 $GLOBALS['bonus_payed'] = TRUE;
347 // Subtract login bonus from userid's account or jackpot
348 if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getBonusMode() != 'ADD')) {
349 handleBonusPoints('login_bonus', $userid);
354 // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
357 setMemberId($userid);
359 // Try to set session data (which shall normally always work!)
360 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
361 if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
362 // Update database records
363 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
364 array($userid), __FUNCTION__, __LINE__);
365 if (!SQL_HASZEROAFFECTED()) {
366 // Is a success URL set?
367 if (empty($successUrl)) {
368 // Procedure to checking for login data
369 if (($GLOBALS['bonus_payed'] === TRUE) && (isExtensionActive('bonus'))) {
370 // Bonus added (just displaying!)
371 $url = 'modules.php?module=chk_login&do=bonus';
374 $url = 'modules.php?module=chk_login&do=login';
381 // Cannot update counter!
382 $errorCode = getCode('CNTR_FAILED');
385 // Cookies not setable!
386 $errorCode = getCode('COOKIES_DISABLED');
388 } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
389 // Update failure counter
390 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
391 array($userid), __FUNCTION__, __LINE__);
394 $errorCode = getCode('WRONG_PASS');
396 } elseif ((isUserDataValid()) && (getUserData('status') != 'CONFIRMED')) {
397 // Create an error code from given status
398 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
400 // Set userid in session
401 setSession('userid', getUserData('userid'));
402 } elseif (!isUserDataValid()) {
404 $errorCode = getCode('WRONG_ID');
407 $errorCode = getCode('UNKNOWN_ERROR');
410 // Error code provided?
411 if ($errorCode > 0) {
412 // Then reconstruct the URL
413 $url = $errorUrl . $errorCode;
415 // Extension set? Then add it as well.
417 $url .= '&ext=' . $ext;
425 // Try to send a new password for the given user account
426 function doNewUserPassword ($email, $userid) {
427 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ' - ENTERED!');
428 // Init found-status and error
430 $accountFound = FALSE;
432 // Probe userid/nickname
433 if (!empty($email)) {
435 $accountFound = fetchUserData($email, 'email');
436 } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
438 $accountFound = fetchUserData($userid, 'nickname');
439 } elseif ((isValidUserId($userid)) && (empty($email))) {
440 // Direct userid entered
441 $accountFound = fetchUserData($userid);
442 } elseif (isDebugModeEnabled()) {
444 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',email=' . $email . ': Important variables are empty.');
448 if ($accountFound === TRUE) {
449 // Is the account confirmed
450 if (getUserData('status') == 'CONFIRMED') {
451 // Generate new password
452 $NEW_PASS = generatePassword();
455 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
457 generateHash($NEW_PASS),
458 getUserData('userid')
459 ), __FUNCTION__, __LINE__);
461 // Prepare data and message for email
462 $message = loadEmailTemplate('guest_new_password',
464 'new_pass' => $NEW_PASS,
465 'nickname' => $userid
466 ), getUserData('userid'));
468 // ... and send it away
469 sendEmail(bigintval(getUserData('userid')), '{--GUEST_NEW_PASSWORD--}', $message);
471 // Output note to user
472 displayMessage('{--GUEST_NEW_PASSWORD_SEND--}');
474 // Account is locked or unconfirmed
475 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
478 redirectToUrl('modules.php?module=index&what=login&login=' . $errorCode);
481 // Id or email is wrong
482 displayMessage('<span class="bad">{--GUEST_WRONG_ID_EMAIL--}</span>');
485 // Return the error code
486 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ',errorCode=' . $errorCode . ' - EXIT!');
490 // Get timestamp for given stats type and data
491 function getEpocheTimeFromUserStats ($statsType, $statsData, $userid = NULL) {
492 // Default timestamp is zero
493 $data['inserted'] = '0';
496 if ((isMemberIdSet()) && (is_null($userid))) {
497 $userid = getMemberId();
500 // Is the extension installed and updated?
501 if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
503 return $data['inserted'];
506 // Try to find the entry
507 $result = SQL_QUERY_ESC("SELECT
508 UNIX_TIMESTAMP(`inserted`) AS inserted
510 `{?_MYSQL_PREFIX?}_user_stats_data`
513 `stats_type`='%s' AND
520 ), __FUNCTION__, __LINE__);
522 // Is the entry there?
523 if (SQL_NUMROWS($result) == 1) {
525 $data = SQL_FETCHARRAY($result);
529 SQL_FREERESULT($result);
532 return $data['inserted'];
535 // Inserts user stats
536 function insertUserStatsRecord ($userid, $statsType, $statsData) {
537 // Is the extension installed and updated?
538 if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
543 // Default is not working
547 if ((!getEpocheTimeFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
549 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`, `stats_type`, `stats_data`) VALUES (%s,'%s','%s')",
554 ), __FUNCTION__, __LINE__);
556 // Does it have worked?
557 $return = (!SQL_HASZEROAFFECTED());
558 } elseif (is_array($statsData)) {
560 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',type=' . $statsType . ',data=' . gettype($statsData) . ': Invalid statistics data type!');
567 // Confirms a user account
568 function doConfirmUserAccount ($hash) {
571 'message' => '{--GUEST_CONFIRMED_FAILED--}',
575 // Initialize the user id
578 // Search for an unconfirmed or confirmed account
579 $result = SQL_QUERY_ESC("SELECT `userid`, `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `user_hash`='%s' AND (`status`='UNCONFIRMED' OR `status`='CONFIRMED') LIMIT 1",
580 array($hash), __FILE__, __LINE__);
581 if (SQL_NUMROWS($result) == 1) {
582 // Ok, he want's to confirm now so we load some data
583 list($userid, $refid) = SQL_FETCHROW($result);
586 if (!fetchUserData($userid)) {
587 // Not found, should not happen
588 reportBug(__FILE__, __LINE__, 'User account ' . $userid . ' not found.');
591 // Load all data and add points
592 $content = getUserDataArray();
594 // Unlock his account (but only when it is on UNCONFIRMED!)
595 SQL_QUERY_ESC("UPDATE
596 `{?_MYSQL_PREFIX?}_user_data`
598 `status`='CONFIRMED',
602 `status`='UNCONFIRMED'
604 array($hash), __FILE__, __LINE__);
607 if (!SQL_HASZEROAFFECTED()) {
608 // Send email if updated
609 $message = loadEmailTemplate('guest_user_confirmed', $content, bigintval($userid));
611 // And send him right away the confirmation mail
612 sendEmail($userid, '{--GUEST_THANX_CONFIRM--}', $message);
614 // Maybe he got "referraled"?
615 if ((isValidUserId($refid)) && ($refid != $userid)) {
616 // Select the referral userid
617 if (fetchUserData($refid)) {
618 // Update ref counter...
619 updateReferralCounter($refid);
621 // If version matches add ref bonus to refid's account
622 if ((isExtensionInstalledAndNewer('bonus', '0.4.4')) && (isBonusRallyeActive())) {
623 // Add points (directly only!)
624 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `bonus_ref`=`bonus_ref`+{?bonus_ref?} WHERE `userid`=%s LIMIT 1",
625 array(bigintval($refid)), __FILE__, __LINE__);
627 // Subtract points from system
628 handleBonusPoints(getConfig('bonus_ref'), $refid);
631 // Add one-time referral bonus over referral system or directly
632 initReferralSystem();
633 addPointsThroughReferralSystem('referral_bonus', $refid, getPointsRef(), bigintval($userid));
637 if (isExtensionActive('rallye')) {
638 // Add user to rallye (or not?)
639 addUserToReferralRallye(bigintval($userid));
642 // Account confirmed!
643 if (isExtensionActive('lead')) {
644 // Set special lead cookie
645 setSession('lead_userid', bigintval($userid));
647 // Lead-Code mode enabled
648 redirectToUrl('lead-confirm.php');
650 $content['message'] = '{--GUEST_CONFIRMED_DONE--}';
651 $content['userid'] = bigintval($userid);
653 } elseif (isExtensionActive('lead')) {
654 // Set special lead cookie
655 setSession('lead_userid', bigintval($userid));
657 // Lead-Code mode enabled
658 redirectToUrl('lead-confirm.php');
660 // Nobody was found unter this hash key... or our new member want's to confirm twice?
661 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
664 // Nobody was found unter this hash key... or our new member want's to confirm twice?
665 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
669 displayMessage($content['message']);
672 // Does resend the user's confirmation link for given email address
673 function doResendUserConfirmationLink ($email) {
674 // Email address not registered is default message
675 $message = '{--EMAIL_404--}';
677 // Confirmation link requested
678 if (fetchUserData($email, 'email')) {
679 // Email address found
680 $content = getUserDataArray();
682 // Is the account unconfirmed?
683 if ($content['status'] == 'UNCONFIRMED') {
684 // Load email template
685 $message = loadEmailTemplate('guest_request_confirm', array(), $content['userid']);
688 sendEmail($content['userid'], '{--GUEST_REQUEST_CONFIRM_LINK_SUBJECT--}', $message);
691 // Create message based on the status
692 $message = getConfirmationMessageFromUserStatus($content['status']);
696 displayMessage($message);
699 // Get a message (somewhat translation) from user status for confirmation link.
700 // This is different to translateUserStatus() in text messages.
701 function getConfirmationMessageFromUserStatus ($status) {
702 // Default is 'UNKNOWN'
703 $message = '{%message,GUEST_LOGIN_ID_UNKNOWN_STATUS=' . $status . '%}';
705 // Which status is it?
707 case 'UNCONFIRMED': // Account is unconfirmed
709 $message = '{--GUEST_CONFIRM_LINK_SENT--}';
712 case 'CONFIRMED': // Account already confirmed
713 $message = '{--GUEST_LOGIN_ID_CONFIRMED--}';
716 case 'LOCKED': // Account is locked
717 $message = '{--GUEST_LOGIN_ID_LOCKED--}';
720 default: // This should not happen
721 reportBug(__FUNCTION__, __LINE__, 'Unknown user status ' . $status . ' detected.');
729 // "Getter" for total tester accounts
730 function getTotalTesterUsers () {
732 if (!isset($GLOBALS[__FUNCTION__])) {
734 $GLOBALS[__FUNCTION__] = countSumTotalData('', 'user_data', 'userid', '', TRUE, runFilterChain('user_inclusion_sql'));
738 return $GLOBALS[__FUNCTION__];
741 // Checks whether the admin is allowed to create more tester accounts
742 function isNewUserTesterAllowed () {
743 // By default only admins are allowed
745 // This should not happen and must be fixed
746 reportBug(__FUNCTION__, __LINE__, 'isAdmin()=false - Not allowed.');
749 // Are more tester accounts allowed?
750 $isAllowed = (getTotalTesterUsers() < bigintval(getTesterUserMaximum() + 1));
756 // "Getter" for next free tester account number
757 function getNextFreeTesterUserNumber () {
758 // Get current total amount because we start with zero
759 $nextTester = getTotalTesterUsers();
762 $nextTester = prependZeros($nextTester, 6);
768 // Wrapper function to return a selection box for tester user default referral id
769 function addTesterUserDefaultRefidSelectionBox ($fieldName = 'tester_user_default_refid') {
771 return addMemberSelectionBox(getConfig('tester_user_default_refid'), FALSE, TRUE, TRUE, $fieldName, " WHERE `surname` LIKE '{?tester_user_surname_prefix?}%'");
774 // Checks whether given surname is a test user name
775 function isTesterUserName ($surname) {
777 return (substr($surname, 0, strlen(getTesterUserSurnamePrefix())) == getTesterUserSurnamePrefix());
780 // Creates a tester account from given POST data
781 function createTesterUserAccount () {
782 // Add generated surname
783 setPostRequestElement('surname', (getTesterUserSurnamePrefix() . getNextFreeTesterUserNumber()));
785 // Is the registration data complete?
786 if (!isRegistrationDataComplete()) {
788 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isRegistrationDataComplete()=false, please check if you e.g. have selected the required minimum of categories.');
793 $isCreated = doUserRegistration();
795 // Remove cache to force recalculation of total tester accounts
796 unset($GLOBALS['getTotalTesterUsers']);
802 // Checks whether the given sub id is fused by current member
803 function isMemberSubIdFree ($subId) {
804 // Only do this for logged-in members
808 $isFree = (countSumTotalData(getMemberId(), 'user_subids', 'id', 'userid', TRUE, sprintf(" AND `subid`='%s'", $subId)) == 0);
814 // Checks whether the sub id is valid
815 function isValidSubId ($subId) {
816 // First convert any spaces/dashes to underscores
817 $subId = str_replace(' ', '_', str_replace('-', '_', $subId));
819 // Then filter out any unwanted characters
820 $subIdTest = preg_replace('/([^a-zA-Z0-9_])/', '', $subId);
823 return ($subId == $subIdTest);
826 // Prepares found sub id for updating in database
827 function prepareFoundSubId ($subId) {
828 // Then check if it is valid and available
829 if ((!isValidSubId($subId)) || (isMemberSubIdFree($subId))) {
830 // Is not free or invalid
834 // Return prepared sub id
838 // Validates sub id and returns FALSE if not valid
839 function validateSubId ($subId) {
840 // Then check if it is valid and available
841 if (!isValidSubId($subId)) {
842 // Is not free or invalid
846 // Return prepared sub id
850 // Prepares given sub id for inserting into database
851 function prepareSubId ($subId) {
852 // Then check if it is valid and available
853 if ((!isValidSubId($subId)) || (!isMemberSubIdFree($subId))) {
854 // Is not free or invalid
858 // Return prepared sub id
862 // Check whether given sub *id* is assigned to current member
863 function isUserSubIdAssignedToMember ($subId, $userid = NULL) {
865 if (!isset($GLOBALS[__FUNCTION__][$subId][$userid])) {
867 $GLOBALS[__FUNCTION__][$subId][$userid] = (
869 // Is a userid set or current set?
870 (isValidUserId($userid)) || (isMember())
872 // .. and it assigned with subid's id?
874 (isValidUserId($userid) ? $userid : getMemberId()),
879 sprintf(" AND `id`=%s", bigintval($subId))
886 return $GLOBALS[__FUNCTION__][$subId][$userid];
889 // Getter for subid from given id number
890 function getSubId ($id) {
892 if (!isset($GLOBALS[__FUNCTION__][$id])) {
893 // Check database for record
894 $result = SQL_QUERY_ESC("SELECT `subid` FROM `{?_MYSQL_PREFIX?}_user_subids` WHERE `id`=%s LIMIT 1",
895 array(bigintval($id)), __FUNCTION__, __LINE__);
897 // Is there an entry?
898 if (SQL_NUMROWS($result) == 1) {
900 list($GLOBALS[__FUNCTION__][$id]) = SQL_FETCHROW($result);
904 SQL_FREERESULT($result);
908 return $GLOBALS[__FUNCTION__][$id];
911 // "Getter for total count of current user's sub ids
912 function getTotalMemberSubIds () {
913 // Only do this for logged-in members
917 if (!isset($GLOBALS[__FUNCTION__])) {
919 $GLOBALS[__FUNCTION__] = countSumTotalData(getMemberId(), 'user_subids', 'id', 'userid', TRUE);
923 return $GLOBALS[__FUNCTION__];
926 //-----------------------------------------------------------------------------
928 //-----------------------------------------------------------------------------
930 // Expression call-back function for fetching user data
931 function doExpressionUser ($data) {
932 // Use current userid by default
933 $functionName = 'getMemberId()';
935 // User-related data, so is there a userid?
936 if (!empty($data['matches'][4][$data['key']])) {
937 // Is there a userid or $userid?
938 if (substr($data['matches'][4][$data['key']], 0, 1) == '$') {
940 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
941 } elseif (!empty($data['matches'][4][$data['key']])) {
942 // Is there a number or a dollar sign in front of it?
943 if (preg_replace('/[^0123456789]/', '', $data['matches'][4][$data['key']]) != $data['matches'][4][$data['key']]) {
944 // Possible database column, so get it again
945 $data['matches'][4][$data['key']] = "getFetchedUserData('userid', getMemberId(), '" . $data['matches'][4][$data['key']] . "')";
949 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
951 } elseif ((!empty($data['callback'])) && (isUserDataValid())) {
952 // "Call-back" alias column for current logged in user's data
953 $functionName = "getUserData('" . $data['callback'] . "')";
956 // Is there another function to run (e.g. translations)
957 if (!empty($data['extra_func'])) {
958 // Surround the original function call with it
959 $functionName = $data['extra_func'] . '(' . $functionName . ')';
961 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'functionName=' . $functionName);
964 $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
966 // Now replace the code
967 $code = replaceExpressionCode($data, $replacer);
969 // Return replaced code
973 //-----------------------------------------------------------------------------
974 // Template helper functions
975 //-----------------------------------------------------------------------------
977 // Template call-back function for list_user admin function
978 function doTemplateAdminListUserTitle ($template, $clear = FALSE) {
979 // Init title with "all accounts"
980 $code = '{--ADMIN_LIST_ALL_ACCOUNTS--}';
982 // Is there a 'status' or 'do' set?
983 if (isGetRequestElementSet('status')) {
984 // Set title according to the 'status'
985 $code = sprintf("{--ADMIN_LIST_STATUS_%s_ACCOUNTS--}", strtoupper(getRequestElement('status')));
986 } elseif (isGetRequestElementSet('do')) {
987 // Set title according to 'do'
988 $code = sprintf("{--ADMIN_LIST_DO_%s_ACCOUNTS--}", strtoupper(getRequestElement('do')));
995 // Template call-back function for displaying "username"
996 function doTemplateDisplayUsername ($template, $clear = FALSE, $userid = NULL) {
998 if (!isValidUserId($userid)) {
999 // Please don't call this without a valid userid
1000 reportBug(__FUNCTION__, __LINE__, 'template=' . $template . ',clear=' . intval($clear) . ',userid[' . gettype($userid) . ']=' . intval($userid) . ' - Invalid userid provided.');
1004 if (!isset($GLOBALS[__FUNCTION__][$userid])) {
1006 $GLOBALS[__FUNCTION__][$userid] = $userid . ' ({%user,nickname,fixEmptyContentToDashes=' . $userid . '%})';
1010 return $GLOBALS[__FUNCTION__][$userid];
1013 // ----------------------------------------------------------------------------
1014 // XML call-back functions
1015 // ----------------------------------------------------------------------------
1017 // For 'doing' add subid, the column-index is required
1018 function addXmlSpecialMemberAddDoUserSubid () {
1019 // So set it all here
1020 $GLOBALS['__COLUMN_INDEX']['doXmlCallbackFunction'] = 'column';
1021 $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['column_index'] = 'column';
1024 // ----------------------------------------------------------------------------
1025 // Wrapper functions for configuration entries
1026 // ----------------------------------------------------------------------------
1028 // Getter for user_alpha
1029 function getUserAlpha () {
1031 if (!isset($GLOBALS[__FUNCTION__])) {
1033 $GLOBALS[__FUNCTION__] = getConfig('user_alpha');
1037 return $GLOBALS[__FUNCTION__];
1040 // Getter for user_limit
1041 function getUserLimit () {
1043 if (!isset($GLOBALS[__FUNCTION__])) {
1045 $GLOBALS[__FUNCTION__] = getConfig('user_limit');
1049 return $GLOBALS[__FUNCTION__];
1052 // Getter for tester_user_surname_prefix
1053 function getTesterUserSurnamePrefix () {
1055 if (!isset($GLOBALS[__FUNCTION__])) {
1057 $GLOBALS[__FUNCTION__] = getConfig('tester_user_surname_prefix');
1061 return $GLOBALS[__FUNCTION__];
1064 // Getter for tester_user_maximum
1065 function getTesterUserMaximum () {
1067 if (!isset($GLOBALS[__FUNCTION__])) {
1069 $GLOBALS[__FUNCTION__] = getConfig('tester_user_maximum');
1073 return $GLOBALS[__FUNCTION__];
1076 // Getter for tester_user_check_cat
1077 function getTesterUserCheckCat () {
1079 if (!isset($GLOBALS[__FUNCTION__])) {
1081 $GLOBALS[__FUNCTION__] = getConfig('tester_user_check_cat');
1085 return $GLOBALS[__FUNCTION__];
1088 // Getter for tester_user_gender
1089 function getTesterUserGender () {
1091 if (!isset($GLOBALS[__FUNCTION__])) {
1093 $GLOBALS[__FUNCTION__] = getConfig('tester_user_gender');
1097 return $GLOBALS[__FUNCTION__];
1100 // Getter for tester_user_family
1101 function getTesterUserFamily () {
1103 if (!isset($GLOBALS[__FUNCTION__])) {
1105 $GLOBALS[__FUNCTION__] = getConfig('tester_user_family');
1109 return $GLOBALS[__FUNCTION__];
1112 // Getter for tester_user_password
1113 function getTesterUserPassword () {
1115 if (!isset($GLOBALS[__FUNCTION__])) {
1117 $GLOBALS[__FUNCTION__] = getConfig('tester_user_password');
1121 return $GLOBALS[__FUNCTION__];
1124 // Getter for tester_user_street_nr
1125 function getTesterUserStreetNr () {
1127 if (!isset($GLOBALS[__FUNCTION__])) {
1129 $GLOBALS[__FUNCTION__] = getConfig('tester_user_street_nr');
1133 return $GLOBALS[__FUNCTION__];
1136 // Getter for tester_user_zip
1137 function getTesterUserZip () {
1139 if (!isset($GLOBALS[__FUNCTION__])) {
1141 $GLOBALS[__FUNCTION__] = getConfig('tester_user_zip');
1145 return $GLOBALS[__FUNCTION__];
1148 // Getter for tester_user_city
1149 function getTesterUserCity () {
1151 if (!isset($GLOBALS[__FUNCTION__])) {
1153 $GLOBALS[__FUNCTION__] = getConfig('tester_user_city');
1157 return $GLOBALS[__FUNCTION__];
1160 // Getter for tester_user_email
1161 function getTesterUserEmail () {
1163 if (!isset($GLOBALS[__FUNCTION__])) {
1165 $GLOBALS[__FUNCTION__] = getConfig('tester_user_email');
1169 return $GLOBALS[__FUNCTION__];