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 - 2013 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 = sqlQueryEscaped("SELECT
205 `{?_MYSQL_PREFIX?}_user_data`
210 array($email), __FUNCTION__, __LINE__);
212 // Is there an entry?
213 if (sqlNumRows($result) == 1) {
215 list($userid) = sqlFetchRow($result);
217 // Rewrite email address to contact link
218 $email = '{%url=modules.php?module=' . $mod . '&what=user_contct&userid=' . bigintval($userid) . '%}';
222 sqlFreeResult($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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
249 // Use that userid as new referral id
250 list($refid) = sqlFetchRow($result);
253 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ' - choosen!');
257 sqlFreeResult($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 . ',isValidUserData()=' . intval(isValidUserData()) . ',userStatus=' . getUserData('status') . ',errorCode=' . $errorCode . ',ext=' . $ext . ',isFound=' . intval($isFound));
308 // Is there an entry?
309 if (($errorCode == '0') && (isValidUserData()) && (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 sqlQueryEscaped("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 >= getLoginTimeout()) {
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 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
364 array($userid), __FUNCTION__, __LINE__);
365 if (!ifSqlHasZeroAffectedRows()) {
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 sqlQueryEscaped("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 ((isValidUserData()) && (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 (!isValidUserData()) {
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 ((isValidId($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 $newPassword = generatePassword();
455 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
457 generateHash($newPassword),
458 getUserData('userid')
459 ), __FUNCTION__, __LINE__);
461 // Prepare data and message for email
462 $message = loadEmailTemplate('guest_new_password',
464 'new_pass' => $newPassword,
465 'nickname' => $userid
466 ), getUserData('userid'));
468 // ... and send it away
469 sendEmail(bigintval(getUserData('userid')), '{--GUEST_NEW_PASSWORD_SUBJECT--}', $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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
525 $data = sqlFetchArray($result);
529 sqlFreeResult($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 sqlQueryEscaped("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 = (!ifSqlHasZeroAffectedRows());
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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
582 // Ok, he want's to confirm now so we load some data
583 list($userid, $refid) = sqlFetchRow($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 sqlQueryEscaped("UPDATE
596 `{?_MYSQL_PREFIX?}_user_data`
598 `status`='CONFIRMED',
602 `status`='UNCONFIRMED'
604 array($hash), __FILE__, __LINE__);
607 if (!ifSqlHasZeroAffectedRows()) {
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 ((isValidId($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 sqlQueryEscaped("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(getBonusRef(), $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 = padLeftZero($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 (isValidId($userid)) || (isMember())
872 // .. and it assigned with subid's id?
874 (isValidId($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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
900 list($GLOBALS[__FUNCTION__][$id]) = sqlFetchRow($result);
904 sqlFreeResult($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 // Displays generic user registration form
927 function doDisplayGenericUserRegistrationForm () {
928 // Do this only if form is sent
930 if (postRequestElement('agree') == '!') {
931 registerOutputFailedMessage('HAVE_TO_AGREE');
934 if (postRequestElement('email') == '!') {
935 registerOutputFailedMessage('ENTER_EMAIL');
936 setPostRequestElement('email', '');
937 } elseif (postRequestElement('email') == '?') {
938 registerOutputFailedMessage('GUEST_EMAIL_IS_ALREADY_REGISTERED');
939 setPostRequestElement('email', '');
942 if (postRequestElement('surname') == '!') {
943 registerOutputFailedMessage('ENTER_SURNAME');
944 setPostRequestElement('surname', '');
947 if (postRequestElement('family') == '!') {
948 registerOutputFailedMessage('ENTER_FAMILY');
949 setPostRequestElement('family', '');
952 if ((postRequestElement('password1') == '!') && (postRequestElement('password2') == '!')) {
953 registerOutputFailedMessage('ENTER_BOTH_PASSWORDS');
954 } elseif (postRequestElement('password1') == '!') {
955 registerOutputFailedMessage('ENTER_PASSWORD1');
956 } elseif (postRequestElement('password2') == '!') {
957 registerOutputFailedMessage('ENTER_PASSWORD2');
960 if ((isset($GLOBALS['registration_weak_password'])) && ($GLOBALS['registration_weak_password'] === TRUE)) {
961 registerOutputFailedMessage('GUEST_WEAK_PASSWORD');
964 if ((isset($GLOBALS['registration_ip_timeout'])) && ($GLOBALS['registration_ip_timeout'] === TRUE)) {
965 registerOutputFailedMessage('REMOTE_ADDR_TIMEOUT');
968 if ((!empty($GLOBALS['registration_selected_cats'])) && ($GLOBALS['registration_selected_cats'] < getLeastCats())) {
969 registerOutputFailedMessage('', '{--CHOOSE_MORE_CATEGORIES--}');
973 // Generate birthday selection
974 switch (getLanguage()) {
975 case 'de': // German date format
976 $content['birthday_selection'] = addSelectionBox('da', postRequestElement('day')).addSelectionBox('mo', postRequestElement('month')).addSelectionBox('ye', postRequestElement('year'));
979 default: // Default is the US date format... :)
980 $content['birthday_selection'] = addSelectionBox('mo', postRequestElement('month')).addSelectionBox('da', postRequestElement('day')).addSelectionBox('ye', postRequestElement('year'));
984 // Shall I display the refid or shall I make it editable?
985 if (isDisplayRefidEnabled()) {
986 // Load "hide" form template
987 $content['refid_content'] = loadTemplate('guest_register_refid_hide', TRUE);
989 // Load template to enter it
990 $content['refid_content'] = loadTemplate('guest_register_refid', TRUE);
993 // ZIP codes are numerical values
994 $content['zip'] = '';
995 if ((isPostRequestElementSet('zip')) && (isValidNumber(postRequestElement('zip')))) {
996 $content['zip'] = bigintval(postRequestElement('zip'));
1000 foreach (array('gender', 'surname', 'family', 'street_nr', 'city', 'email') as $entry) {
1001 $content[$entry] = sqlEscapeString(postRequestElement($entry));
1004 // Set must-fillout fields
1005 $content = runFilterChain('register_must_fillout', $content);
1007 // Display registration form
1008 loadTemplate('guest_register', FALSE, $content);
1011 //-----------------------------------------------------------------------------
1012 // EL code functions
1013 //-----------------------------------------------------------------------------
1015 // Expression call-back function for fetching user data
1016 function doExpressionUser ($data) {
1017 // Use current userid by default
1018 $functionName = 'getMemberId()';
1020 // User-related data, so is there a userid?
1021 if (!empty($data['matches'][4][$data['key']])) {
1022 // Is there a userid or $userid?
1023 if (substr($data['matches'][4][$data['key']], 0, 1) == '$') {
1025 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
1026 } elseif (!empty($data['matches'][4][$data['key']])) {
1027 // Is there a number or a dollar sign in front of it?
1028 if (preg_replace('/[^0123456789]/', '', $data['matches'][4][$data['key']]) != $data['matches'][4][$data['key']]) {
1029 // Possible database column, so get it again
1030 $data['matches'][4][$data['key']] = "getFetchedUserData('userid', getMemberId(), '" . $data['matches'][4][$data['key']] . "')";
1034 $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
1036 } elseif ((!empty($data['callback'])) && (isValidUserData())) {
1037 // "Call-back" alias column for current logged in user's data
1038 $functionName = "getUserData('" . $data['callback'] . "')";
1041 // Is there another function to run (e.g. translations)
1042 if (!empty($data['extra_func'])) {
1043 // Surround the original function call with it
1044 $functionName = $data['extra_func'] . '(' . $functionName . ')';
1046 //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'functionName=' . $functionName);
1048 // Generate replacer
1049 $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
1051 // Now replace the code
1052 $code = replaceExpressionCode($data, $replacer);
1054 // Return replaced code
1058 //-----------------------------------------------------------------------------
1059 // Template helper functions
1060 //-----------------------------------------------------------------------------
1062 // Template call-back function for list_user admin function
1063 function doTemplateAdminListUserTitle ($template, $clear = FALSE) {
1064 // Init title with "all accounts"
1065 $code = '{--ADMIN_LIST_ALL_ACCOUNTS--}';
1067 // Is there a 'status' or 'do' set?
1068 if (isGetRequestElementSet('status')) {
1069 // Set title according to the 'status'
1070 $code = sprintf("{--ADMIN_LIST_STATUS_%s_ACCOUNTS--}", strtoupper(getRequestElement('status')));
1071 } elseif (isGetRequestElementSet('do')) {
1072 // Set title according to 'do'
1073 $code = sprintf("{--ADMIN_LIST_DO_%s_ACCOUNTS--}", strtoupper(getRequestElement('do')));
1080 // Template call-back function for displaying "username"
1081 function doTemplateDisplayUsername ($template, $clear = FALSE, $userid = NULL) {
1083 if (!isValidId($userid)) {
1084 // Please don't call this without a valid userid
1085 reportBug(__FUNCTION__, __LINE__, 'template=' . $template . ',clear=' . intval($clear) . ',userid[' . gettype($userid) . ']=' . intval($userid) . ' - Invalid userid provided.');
1089 if (!isset($GLOBALS[__FUNCTION__][$userid])) {
1091 $GLOBALS[__FUNCTION__][$userid] = $userid . ' ({%user,nickname,fixEmptyContentToDashes=' . $userid . '%})';
1095 return $GLOBALS[__FUNCTION__][$userid];
1098 // ----------------------------------------------------------------------------
1099 // XML call-back functions
1100 // ----------------------------------------------------------------------------
1102 // For 'doing' add subid, the column-index is required
1103 function addXmlSpecialMemberAddDoUserSubid () {
1104 // So set it all here
1105 $GLOBALS['__COLUMN_INDEX']['doXmlCallbackFunction'] = 'column';
1106 $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['column_index'] = 'column';
1109 // ----------------------------------------------------------------------------
1110 // Wrapper functions for configuration entries
1111 // ----------------------------------------------------------------------------
1113 // Getter for user_alpha
1114 function getUserAlpha () {
1116 if (!isset($GLOBALS[__FUNCTION__])) {
1118 $GLOBALS[__FUNCTION__] = getConfig('user_alpha');
1122 return $GLOBALS[__FUNCTION__];
1125 // Getter for user_limit
1126 function getUserLimit () {
1128 if (!isset($GLOBALS[__FUNCTION__])) {
1130 $GLOBALS[__FUNCTION__] = getConfig('user_limit');
1134 return $GLOBALS[__FUNCTION__];
1137 // Getter for tester_user_surname_prefix
1138 function getTesterUserSurnamePrefix () {
1140 if (!isset($GLOBALS[__FUNCTION__])) {
1142 $GLOBALS[__FUNCTION__] = getConfig('tester_user_surname_prefix');
1146 return $GLOBALS[__FUNCTION__];
1149 // Getter for tester_user_maximum
1150 function getTesterUserMaximum () {
1152 if (!isset($GLOBALS[__FUNCTION__])) {
1154 $GLOBALS[__FUNCTION__] = getConfig('tester_user_maximum');
1158 return $GLOBALS[__FUNCTION__];
1161 // Getter for tester_user_check_cat
1162 function getTesterUserCheckCat () {
1164 if (!isset($GLOBALS[__FUNCTION__])) {
1166 $GLOBALS[__FUNCTION__] = getConfig('tester_user_check_cat');
1170 return $GLOBALS[__FUNCTION__];
1173 // Getter for tester_user_gender
1174 function getTesterUserGender () {
1176 if (!isset($GLOBALS[__FUNCTION__])) {
1178 $GLOBALS[__FUNCTION__] = getConfig('tester_user_gender');
1182 return $GLOBALS[__FUNCTION__];
1185 // Getter for tester_user_family
1186 function getTesterUserFamily () {
1188 if (!isset($GLOBALS[__FUNCTION__])) {
1190 $GLOBALS[__FUNCTION__] = getConfig('tester_user_family');
1194 return $GLOBALS[__FUNCTION__];
1197 // Getter for tester_user_password
1198 function getTesterUserPassword () {
1200 if (!isset($GLOBALS[__FUNCTION__])) {
1202 $GLOBALS[__FUNCTION__] = getConfig('tester_user_password');
1206 return $GLOBALS[__FUNCTION__];
1209 // Getter for tester_user_street_nr
1210 function getTesterUserStreetNr () {
1212 if (!isset($GLOBALS[__FUNCTION__])) {
1214 $GLOBALS[__FUNCTION__] = getConfig('tester_user_street_nr');
1218 return $GLOBALS[__FUNCTION__];
1221 // Getter for tester_user_zip
1222 function getTesterUserZip () {
1224 if (!isset($GLOBALS[__FUNCTION__])) {
1226 $GLOBALS[__FUNCTION__] = getConfig('tester_user_zip');
1230 return $GLOBALS[__FUNCTION__];
1233 // Getter for tester_user_city
1234 function getTesterUserCity () {
1236 if (!isset($GLOBALS[__FUNCTION__])) {
1238 $GLOBALS[__FUNCTION__] = getConfig('tester_user_city');
1242 return $GLOBALS[__FUNCTION__];
1245 // Getter for tester_user_email
1246 function getTesterUserEmail () {
1248 if (!isset($GLOBALS[__FUNCTION__])) {
1250 $GLOBALS[__FUNCTION__] = getConfig('tester_user_email');
1254 return $GLOBALS[__FUNCTION__];
1257 // Getter for 'ap_subids' config entry
1258 function getApSubids () {
1260 if (!isset($GLOBALS[__FUNCTION__])) {
1262 $GLOBALS[__FUNCTION__] = getConfig('ap_subids');
1266 return $GLOBALS[__FUNCTION__];
1269 // Determines whether 'ap_subids' is set to 'Y'
1270 function isApSubidsEnabled () {
1272 if (!isset($GLOBALS[__FUNCTION__])) {
1274 $GLOBALS[__FUNCTION__] = (getApSubids() == 'Y');
1278 return $GLOBALS[__FUNCTION__];
1281 // Getter for 'ap_subids_since' config entry
1282 function getApSubidsSince () {
1284 if (!isset($GLOBALS[__FUNCTION__])) {
1286 $GLOBALS[__FUNCTION__] = getConfig('ap_subids_since');
1290 return $GLOBALS[__FUNCTION__];
1293 // Getter for 'select_user_zero_refid' config entry
1294 function getSelectUserZeroRefid () {
1296 if (!isset($GLOBALS[__FUNCTION__])) {
1298 $GLOBALS[__FUNCTION__] = getConfig('select_user_zero_refid');
1302 return $GLOBALS[__FUNCTION__];