Code style changed, ext-user continued:
[mailer.git] / inc / libs / user_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/16/2004 *
4  * ===================                          Last change: 10/27/2004 *
5  *                                                                      *
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  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                      *
21  *                                                                      *
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.                                  *
26  *                                                                      *
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.                         *
31  *                                                                      *
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,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Add links for selecting some users
44 function addAlphabeticalSorting ($sortby) {
45         $add = '';
46         foreach (array('page', 'offset', 'do', 'status') as $param) {
47                 if (isGetRequestElementSet($param)) {
48                         $add .= '&amp;' . $param . '=' . getRequestElement($param);
49                 } // END - if
50         } // END - foreach
51
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;
55
56         // Add all letter links
57         $OUT = '';
58         while (list($counter, $ltr) = each($alphabet)) {
59                 if (getRequestElement('letter') == $ltr) {
60                         // Current letter is letter from URL
61                         $OUT .= '<strong>' . $ltr . '</strong>';
62                 } else {
63                         // Output link to letter
64                         $OUT .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat() . '&amp;letter=' . $ltr . '&amp;sortby=' . $sortby . $add . '%}">' . $ltr . '</a>';
65                 }
66
67                 if ((($counter / getUserAlpha()) == round($counter / getUserAlpha())) && ($counter > 0)) {
68                         $OUT .= ']<br />[';
69                 } elseif ($counter != $num) {
70                         $OUT .= '|';
71                 }
72         } // END - while
73
74         // Prepare content
75         $content = array (
76                 'alpha_selection' => $OUT,
77         );
78
79         // Load template
80         $OUT = loadTemplate('admin_list_user_alpha', TRUE, $content);
81
82         // Return generated code
83         return $OUT;
84 }
85
86 // Add links for sorting
87 function addSortLinks ($letter, $sortby) {
88         $OUT = '';
89         if (!isGetRequestElementSet('offset')) setGetRequestElement('offset', 0);
90         if (!isGetRequestElementSet('page'))   setGetRequestElement('page'  , 0);
91
92         // Add page and offset
93         $add = '&amp;page=' . getRequestElement('page') . '&amp;offset=' . getRequestElement('offset');
94
95         // Add status/ mode
96         foreach (array('do','status') as $param) {
97                 if (isGetRequestElementSet($param)) {
98                         $add .= '&amp;' . $param . '=' . getRequestElement($param);
99                 } // END - if
100         } // END - foreach
101
102         // Makes order by links..
103         if ($letter == 'front') {
104                 $letter = '';
105         } // END - if
106
107         // Prepare array with all possible sorters
108         $list = array(
109                 'userid'      => '{--_USERID--}',
110                 'family'      => '{--FAMILY--}',
111                 'email'       => '{--EMAIL--}',
112                 'REMOTE_ADDR' => '{--REMOTE_IP--}'
113         );
114
115         // Add nickname if extension is installed
116         if (isExtensionActive('nickname')) {
117                 $list['nickname'] = '{--NICKNAME--}';
118         } // END - if
119
120         foreach ($list as $sort => $title) {
121                 if ($sortby == $sort) {
122                         $OUT .= '<strong>' . $title . '</strong>|';
123                 } else {
124                         $OUT .= '<a href="{%url=modules.php?module=admin&amp;what=list_user&amp;letter=' . $letter . '&amp;sortby=' . $sort . $add . '%}">' . $title . '</a>|';
125                 }
126         } // END - foreach
127
128         // Add output
129         $content['list'] = substr($OUT, 0, -1);
130
131         // Load template
132         $OUT = loadTemplate('admin_list_user_sort', TRUE, $content);
133
134         // Return code
135         return $OUT;
136 }
137
138 // Add page navigation
139 function addPageNavigation ($numPages) {
140         // Start with empty content
141         $OUT = '';
142
143         // Create only the navigation if page count > 1
144         if ($numPages > 1) {
145                 // Create navigation links for every page
146                 for ($page = 1; $page <= $numPages; $page++) {
147                         if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
148                                 $OUT .= '<strong>-';
149                         } else {
150                                 if (!isGetRequestElementSet('letter')) setGetRequestElement('letter', '');
151                                 if (!isGetRequestElementSet('sortby')) setGetRequestElement('sortby', 'userid');
152
153                                 // Base link
154                                 $OUT .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat();
155
156                                 // Add status/mode
157                                 foreach (array('do','status') as $param) {
158                                         if (isGetRequestElementSet($param)) {
159                                                 $OUT .= '&amp;' . $param . '=' . getRequestElement($param);
160                                         } // END - if
161                                 } // END - foreach
162
163                                 // Letter and so on
164                                 $OUT .= '&amp;letter=' . getRequestElement('letter') . '&amp;sortby=' . getRequestElement('sortby') . '&amp;page=' . $page . '&amp;offset=' . getUserLimit() . '%}">';
165                         }
166
167                         $OUT .= $page;
168
169                         if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
170                                 $OUT .= '-</strong>';
171                         } else  {
172                                 $OUT .= '</a>';
173                         }
174
175                         if ($page < $numPages) {
176                                 $OUT .= '|';
177                         } // END - if
178                 } // END - for
179
180                 // Add list output
181                 $content['list'] = $OUT;
182
183                 // Load template
184                 $OUT = loadTemplate('admin_list_user_pagenav', TRUE, $content);
185         } // END - if
186
187         // Return code
188         return $OUT;
189 }
190
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'";
195
196         // But admins shall always see it
197         if (isAdmin()) {
198                 $locked = '';
199         } // END - if
200
201         // Search for the email address
202         $result = SQL_QUERY_ESC("SELECT
203         `userid`
204 FROM
205         `{?_MYSQL_PREFIX?}_user_data`
206 WHERE
207         '%s' REGEXP `email`
208         " . $locked . "
209 LIMIT 1",
210                 array($email), __FUNCTION__, __LINE__);
211
212         // Is there an entry?
213         if (SQL_NUMROWS($result) == 1) {
214                 // Load userid
215                 list($userid) = SQL_FETCHROW($result);
216
217                 // Rewrite email address to contact link
218                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=user_contct&amp;userid=' . bigintval($userid) . '%}';
219         } // END - if
220
221         // Free memory
222         SQL_FREERESULT($result);
223
224         // Return rewritten (?) email address
225         return $email;
226 }
227
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
231         $refid = NULL;
232
233         // Is the extension version fine?
234         if ((isRandomReferralIdEnabled()) && (isExtensionInstalledAndNewer('user', '0.3.4'))) {
235                 // Get all user ids
236                 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', TRUE, runFilterChain('user_exclusion_sql', ' AND `rand_confirmed` >= {?user_min_confirmed?}'));
237
238                 // Is there at least one?
239                 if ($totalUsers > 0) {
240                         // Then choose random userid
241                         $randUserid = mt_rand(0, ($totalUsers - 1));
242
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__);
246
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);
251
252                                 // Debug message
253                                 /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ' - choosen!');
254                         } // END - if
255
256                         // Free result
257                         SQL_FREERESULT($result);
258                 } // END - if
259         } // END - if
260
261         // Return result
262         return $refid;
263 }
264
265 // Do the user login
266 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&amp;what=login&amp;login=') {
267         // Init variables
268         $dmy = '';
269         $add = '';
270         $errorCode = '0';
271         $ext = '';
272         $isFound = FALSE;
273
274         // Init array
275         $content = array(
276                 'password'    => '',
277                 'userid'      => '',
278                 'last_online' => 0,
279                 'last_login'  => 0,
280                 'hash'        => ''
281         );
282
283         // Check login data
284         if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
285                 // Nickname entered
286                 $isFound = fetchUserData($userid, 'nickname');
287         } elseif (isNicknameUsed($userid)) {
288                 // No nickname installed
289                 $errorCode = getCode('EXTENSION_PROBLEM');
290                 $ext = 'nickname';
291         } else {
292                 // Direct userid entered
293                 $isFound = fetchUserData($userid);
294         }
295
296         // No error found?
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']);
302                 } // END - if
303         } // END - if
304
305         // Debug message
306         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',isUserDataValid()=' . intval(isUserDataValid()) . ',userStatus=' . getUserData('status') . ',errorCode=' . $errorCode . ',ext=' . $ext . ',isFound=' . intval($isFound));
307
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');
314                 } else {
315                         // Hash password with improved way for comparsion
316                         $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
317                 }
318
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);
323
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__);
328
329                         // No login bonus by default
330                         $GLOBALS['bonus_payed'] = FALSE;
331
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');
339                                 } // END - if
340
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;
346
347                                         // Subtract login bonus from userid's account or jackpot
348                                         if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getBonusMode() != 'ADD')) {
349                                                 handleBonusPoints('login_bonus', $userid);
350                                         } // END - if
351                                 } // END - if
352                         } // END - if
353
354                         // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
355
356                         // Set member id
357                         setMemberId($userid);
358
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&amp;do=bonus';
372                                                 } else {
373                                                         // Bonus not added
374                                                         $url = 'modules.php?module=chk_login&amp;do=login';
375                                                 }
376                                         } else {
377                                                 // Use this URL
378                                                 $url = $successUrl;
379                                         }
380                                 } else {
381                                         // Cannot update counter!
382                                         $errorCode = getCode('CNTR_FAILED');
383                                 }
384                         } else {
385                                 // Cookies not setable!
386                                 $errorCode = getCode('COOKIES_DISABLED');
387                         }
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__);
392
393                         // Wrong password!
394                         $errorCode = getCode('WRONG_PASS');
395                 }
396         } elseif ((isUserDataValid()) && (getUserData('status') != 'CONFIRMED')) {
397                 // Create an error code from given status
398                 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
399
400                 // Set userid in session
401                 setSession('userid', getUserData('userid'));
402         } elseif (!isUserDataValid()) {
403                 // User id not found
404                 $errorCode = getCode('WRONG_ID');
405         } else {
406                 // Unknown error
407                 $errorCode = getCode('UNKNOWN_ERROR');
408         }
409
410         // Error code provided?
411         if ($errorCode > 0) {
412                 // Then reconstruct the URL
413                 $url = $errorUrl . $errorCode;
414
415                 // Extension set? Then add it as well.
416                 if (!empty($ext)) {
417                         $url .= '&amp;ext=' . $ext;
418                 } // END - if
419         } // END - if
420
421         // Return URL
422         return $url;
423 }
424
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
429         $errorCode = '';
430         $accountFound = FALSE;
431
432         // Probe userid/nickname
433         if (!empty($email)) {
434                 // Email entered
435                 $accountFound = fetchUserData($email, 'email');
436         } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
437                 // Nickname entered
438                 $accountFound = fetchUserData($userid, 'nickname');
439         } elseif ((isValidUserId($userid)) && (empty($email))) {
440                 // Direct userid entered
441                 $accountFound = fetchUserData($userid);
442         } else {
443                 // Userid not set!
444                 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',email=' . $email . ': Important variables are empty.');
445         }
446
447         // Any entry found?
448         if ($accountFound === TRUE) {
449                 // Is the account confirmed
450                 if (getUserData('status') == 'CONFIRMED') {
451                         // Generate new password
452                         $NEW_PASS = generatePassword();
453
454                         // Update database
455                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
456                                 array(generateHash($NEW_PASS), getUserData('userid')), __FUNCTION__, __LINE__);
457
458                         // Prepare data and message for email
459                         $message = loadEmailTemplate('guest_new_password',
460                                 array(
461                                         'new_pass' => $NEW_PASS,
462                                         'nickname' => $userid
463                                 ), bigintval(getUserData('userid')));
464
465                         // ... and send it away
466                         sendEmail(bigintval(getUserData('userid')), '{--GUEST_NEW_PASSWORD--}', $message);
467
468                         // Output note to user
469                         displayMessage('{--GUEST_NEW_PASSWORD_SEND--}');
470                 } else {
471                         // Account is locked or unconfirmed
472                         $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
473
474                         // Load URL
475                         redirectToUrl('modules.php?module=index&amp;what=login&amp;login=' . $errorCode);
476                 }
477         } else {
478                 // Id or email is wrong
479                 displayMessage('<span class="bad">{--GUEST_WRONG_ID_EMAIL--}</span>');
480         }
481
482         // Return the error code
483         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',userid=' . $userid . ',errorCode=' . $errorCode . ' - EXIT!');
484         return $errorCode;
485 }
486
487 // Get timestamp for given stats type and data
488 function getEpocheTimeFromUserStats ($statsType, $statsData, $userid = NULL) {
489         // Default timestamp is zero
490         $data['inserted'] = '0';
491
492         // User id set?
493         if ((isMemberIdSet()) && (is_null($userid))) {
494                 $userid = getMemberId();
495         } // END - if
496
497         // Is the extension installed and updated?
498         if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
499                 // Return zero here
500                 return $data['inserted'];
501         } // END - if
502
503         // Try to find the entry
504         $result = SQL_QUERY_ESC("SELECT
505         UNIX_TIMESTAMP(`inserted`) AS inserted
506 FROM
507         `{?_MYSQL_PREFIX?}_user_stats_data`
508 WHERE
509         `userid`=%s AND
510         `stats_type`='%s' AND
511         `stats_data`='%s'
512 LIMIT 1",
513                 array(
514                         bigintval($userid),
515                         $statsType,
516                         $statsData
517                 ), __FUNCTION__, __LINE__);
518
519         // Is the entry there?
520         if (SQL_NUMROWS($result) == 1) {
521                 // Get this stamp
522                 $data = SQL_FETCHARRAY($result);
523         } // END - if
524
525         // Free result
526         SQL_FREERESULT($result);
527
528         // Return stamp
529         return $data['inserted'];
530 }
531
532 // Inserts user stats
533 function insertUserStatsRecord ($userid, $statsType, $statsData) {
534         // Is the extension installed and updated?
535         if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
536                 // Return zero here
537                 return FALSE;
538         } // END - if
539
540         // Default is not working
541         $return = FALSE;
542
543         // Does it exist?
544         if ((!getEpocheTimeFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
545                 // Then insert it!
546                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`, `stats_type`, `stats_data`) VALUES (%s,'%s','%s')",
547                         array(
548                                 bigintval($userid),
549                                 $statsType,
550                                 $statsData
551                         ), __FUNCTION__, __LINE__);
552
553                 // Does it have worked?
554                 $return = (!SQL_HASZEROAFFECTED());
555         } elseif (is_array($statsData)) {
556                 // Invalid data!
557                 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',type=' . $statsType . ',data=' . gettype($statsData) . ': Invalid statistics data type!');
558         }
559
560         // Return status
561         return $return;
562 }
563
564 // Confirms a user account
565 function doConfirmUserAccount ($hash) {
566         // Init content
567         $content = array(
568                 'message' => '{--GUEST_CONFIRMED_FAILED--}',
569                 'userid'  => 0,
570         );
571
572         // Initialize the user id
573         $userid = NULL;
574
575         // Search for an unconfirmed or confirmed account
576         $result = SQL_QUERY_ESC("SELECT `userid`, `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `user_hash`='%s' AND (`status`='UNCONFIRMED' OR `status`='CONFIRMED') LIMIT 1",
577                 array($hash), __FILE__, __LINE__);
578         if (SQL_NUMROWS($result) == 1) {
579                 // Ok, he want's to confirm now so we load some data
580                 list($userid, $refid) = SQL_FETCHROW($result);
581
582                 // Fetch user data
583                 if (!fetchUserData($userid)) {
584                         // Not found, should not happen
585                         reportBug(__FILE__, __LINE__, 'User account ' . $userid . ' not found.');
586                 } // END - if
587
588                 // Load all data and add points
589                 $content = getUserDataArray();
590
591                 // Unlock his account (but only when it is on UNCONFIRMED!)
592                 SQL_QUERY_ESC("UPDATE
593         `{?_MYSQL_PREFIX?}_user_data`
594 SET
595         `status`='CONFIRMED',
596         `user_hash`=NULL
597 WHERE
598         `user_hash`='%s' AND
599         `status`='UNCONFIRMED'
600 LIMIT 1",
601                         array($hash), __FILE__, __LINE__);
602
603                 // Was it updated?
604                 if (!SQL_HASZEROAFFECTED()) {
605                         // Send email if updated
606                         $message = loadEmailTemplate('guest_user_confirmed', $content, bigintval($userid));
607
608                         // And send him right away the confirmation mail
609                         sendEmail($userid, '{--GUEST_THANX_CONFIRM--}', $message);
610
611                         // Maybe he got "referraled"?
612                         if ((isValidUserId($refid)) && ($refid != $userid)) {
613                                 // Select the referral userid
614                                 if (fetchUserData($refid)) {
615                                         // Update ref counter...
616                                         updateReferralCounter($refid);
617
618                                         // If version matches add ref bonus to refid's account
619                                         if ((isExtensionInstalledAndNewer('bonus', '0.4.4')) && (isBonusRallyeActive())) {
620                                                 // Add points (directly only!)
621                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `bonus_ref`=`bonus_ref`+{?bonus_ref?} WHERE `userid`=%s LIMIT 1",
622                                                         array(bigintval($refid)), __FILE__, __LINE__);
623
624                                                 // Subtract points from system
625                                                 handleBonusPoints(getConfig('bonus_ref'), $refid);
626                                         } // END - if
627
628                                         // Add one-time referral bonus over referral system or directly
629                                         initReferralSystem();
630                                         addPointsThroughReferralSystem('referral_bonus', $refid, getPointsRef(), bigintval($userid));
631                                 } // END - if
632                         } // END - if
633
634                         if (isExtensionActive('rallye')) {
635                                 // Add user to rallye (or not?)
636                                 addUserToReferralRallye(bigintval($userid));
637                         } // END - if
638
639                         // Account confirmed!
640                         if (isExtensionActive('lead')) {
641                                 // Set special lead cookie
642                                 setSession('lead_userid', bigintval($userid));
643
644                                 // Lead-Code mode enabled
645                                 redirectToUrl('lead-confirm.php');
646                         } else {
647                                 $content['message'] = '{--GUEST_CONFIRMED_DONE--}';
648                                 $content['userid']  = bigintval($userid);
649                         }
650                 } elseif (isExtensionActive('lead')) {
651                         // Set special lead cookie
652                         setSession('lead_userid', bigintval($userid));
653
654                         // Lead-Code mode enabled
655                         redirectToUrl('lead-confirm.php');
656                 } else {
657                         // Nobody was found unter this hash key... or our new member want's to confirm twice?
658                         $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
659                 }
660         } else {
661                 // Nobody was found unter this hash key... or our new member want's to confirm twice?
662                 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
663         }
664
665         // Load template
666         displayMessage($content['message']);
667 }
668
669 // Does resend the user's confirmation link for given email address
670 function doResendUserConfirmationLink ($email) {
671         // Email address not registered is default message
672         $message = '{--EMAIL_404--}';
673
674         // Confirmation link requested
675         if (fetchUserData($email, 'email')) {
676                 // Email address found
677                 $content = getUserDataArray();
678
679                 // Is the account unconfirmed?
680                 if ($content['status'] == 'UNCONFIRMED') {
681                         // Load email template
682                         $message = loadEmailTemplate('guest_request_confirm', array(), $content['userid']);
683
684                         // Send email
685                         sendEmail($content['userid'], '{--GUEST_REQUEST_CONFIRM_LINK_SUBJECT--}', $message);
686                 } // END - if
687
688                 // Create message based on the status
689                 $message = getConfirmationMessageFromUserStatus($content['status']);
690         } // END - if
691
692         // Output message
693         displayMessage($message);
694 }
695
696 // Get a message (somewhat translation) from user status for confirmation link.
697 // This is different to translateUserStatus() in text messages.
698 function getConfirmationMessageFromUserStatus ($status) {
699         // Default is 'UNKNOWN'
700         $message = '{%message,GUEST_LOGIN_ID_UNKNOWN_STATUS=' . $status . '%}';
701
702         // Which status is it?
703         switch ($status) {
704                 case 'UNCONFIRMED': // Account is unconfirmed
705                         // And set message
706                         $message = '{--GUEST_CONFIRM_LINK_SENT--}';
707                         break;
708
709                 case 'CONFIRMED': // Account already confirmed
710                         $message = '{--GUEST_LOGIN_ID_CONFIRMED--}';
711                         break;
712
713                 case 'LOCKED': // Account is locked
714                         $message = '{--GUEST_LOGIN_ID_LOCKED--}';
715                         break;
716
717                 default: // This should not happen
718                         reportBug(__FUNCTION__, __LINE__, 'Unknown user status ' . $status . ' detected.');
719                         break;
720         } // END - switch
721
722         // Return message
723         return $message;
724 }
725
726 // "Getter" for total tester accounts
727 function getTotalTesterUsers () {
728         // Is there cache?
729         if (!isset($GLOBALS[__FUNCTION__])) {
730                 // Determine it
731                 $GLOBALS[__FUNCTION__] = countSumTotalData('', 'user_data', 'userid', '', TRUE, runFilterChain('user_inclusion_sql'));
732         } // END - if
733
734         // Return cache
735         return $GLOBALS[__FUNCTION__];
736 }
737
738 // Checks whether the admin is allowed to create more tester accounts
739 function isNewUserTesterAllowed () {
740         // By default only admins are allowed
741         if (!isAdmin()) {
742                 // This should not happen and must be fixed
743                 reportBug(__FUNCTION__, __LINE__, 'isAdmin()=false - Not allowed.');
744         } // END - if
745
746         // Are more tester accounts allowed?
747         $isAllowed = (getTotalTesterUsers() < bigintval(getTesterUserMaximum() + 1));
748
749         // Return result
750         return $isAllowed;
751 }
752
753 // "Getter" for next free tester account number
754 function getNextFreeTesterUserNumber () {
755         // Get current total amount because we start with zero
756         $nextTester = getTotalTesterUsers();
757
758         // Prepend zeros
759         $nextTester = prependZeros($nextTester, 6);
760
761         // Return it
762         return $nextTester;
763 }
764
765 // Wrapper function to return a selection box for tester user default referral id
766 function addTesterUserDefaultRefidSelectionBox ($fieldName = 'tester_user_default_refid') {
767         // Return it
768         return addMemberSelectionBox(getConfig('tester_user_default_refid'), FALSE, TRUE, TRUE, $fieldName, " WHERE `surname` LIKE '{?tester_user_surname_prefix?}%'");
769 }
770
771 // Checks whether given surname is a test user name
772 function isTesterUserName ($surname) {
773         // Determine it
774         return (substr($surname, 0, strlen(getTesterUserSurnamePrefix())) == getTesterUserSurnamePrefix());
775 }
776
777 // Creates a tester account from given POST data
778 function createTesterUserAccount () {
779         // Add generated surname
780         setPostRequestElement('surname', (getTesterUserSurnamePrefix() . getNextFreeTesterUserNumber()));
781
782         // Is the registration data complete?
783         if (!isRegistrationDataComplete()) {
784                 // Then abort here
785                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isRegistrationDataComplete()=false, please check if you e.g. have selected the required minimum of categories.');
786                 return FALSE;
787         } // END - if
788
789         // Do registration
790         $isCreated = doUserRegistration();
791
792         // Remove cache to force recalculation of total tester accounts
793         unset($GLOBALS['getTotalTesterUsers']);
794
795         // Return status
796         return $isCreated;
797 }
798
799 // Checks whether the given sub id is fused by current member
800 function isMemberSubIdFree ($subId) {
801         // Only do this for logged-in members
802         assert(isMember());
803
804         // Check it
805         $isFree = (countSumTotalData(getMemberId(), 'user_subids', 'id', 'userid', TRUE, sprintf(" AND `subid`='%s'", $subId)) == 0);
806
807         // Return result
808         return $isFree;
809 }
810
811 // Checks whether the sub id is valid
812 function isValidSubId ($subId) {
813         // First convert any spaces/dashes to underscores
814         $subId = str_replace(' ', '_', str_replace('-', '_', $subId));
815
816         // Then filter out any unwanted characters
817         $subIdTest = preg_replace('/([^a-zA-Z0-9_])/', '', $subId);
818
819         // Is it valid?
820         return ($subId == $subIdTest);
821 } // END - if
822
823 // Prepares found sub id for updating in database
824 function prepareFoundSubId ($subId) {
825         // Then check if it is valid and available
826         if ((!isValidSubId($subId)) || (isMemberSubIdFree($subId))) {
827                 // Is not free or invalid
828                 $subId = FALSE;
829         } // END - if
830
831         // Return prepared sub id
832         return $subId;
833 }
834
835 // Validates sub id and returns FALSE if not valid
836 function validateSubId ($subId) {
837         // Then check if it is valid and available
838         if (!isValidSubId($subId)) {
839                 // Is not free or invalid
840                 $subId = FALSE;
841         } // END - if
842
843         // Return prepared sub id
844         return $subId;
845 }
846
847 // Prepares given sub id for inserting into database
848 function prepareSubId ($subId) {
849         // Then check if it is valid and available
850         if ((!isValidSubId($subId)) || (!isMemberSubIdFree($subId))) {
851                 // Is not free or invalid
852                 $subId = FALSE;
853         } // END - if
854
855         // Return prepared sub id
856         return $subId;
857 }
858
859 // Check whether given sub *id* is assigned to current member
860 function isUserSubIdAssignedToMember ($subId, $userid = NULL) {
861         // Is there cache?
862         if (!isset($GLOBALS[__FUNCTION__][$subId][$userid])) {
863                 // Determine it
864                 $GLOBALS[__FUNCTION__][$subId][$userid] = (
865                         (
866                                 // Is a userid set or current set?
867                                 (isValidUserId($userid)) || (isMember())
868                         ) && (
869                                 // .. and it assigned with subid's id?
870                                 countSumTotalData(
871                                         (isValidUserId($userid) ? $userid : getMemberId()),
872                                                 'user_subids',
873                                                 'id',
874                                                 'userid',
875                                                 true,
876                                                 sprintf(" AND `id`=%s", bigintval($subId))
877                                 ) == 1
878                         )
879                 );
880         } // END - if
881
882         // Return cache
883         return $GLOBALS[__FUNCTION__][$subId][$userid];
884 }
885
886 // Getter for subid from given id number
887 function getSubId ($id) {
888         // Is there cache?
889         if (!isset($GLOBALS[__FUNCTION__][$id])) {
890                 // Check database for record
891                 $result = SQL_QUERY_ESC("SELECT `subid` FROM `{?_MYSQL_PREFIX?}_user_subids` WHERE `id`=%s LIMIT 1",
892                         array(bigintval($id)), __FUNCTION__, __LINE__);
893
894                 // Is there an entry?
895                 if (SQL_NUMROWS($result) == 1) {
896                         // Load it
897                         list($GLOBALS[__FUNCTION__][$id]) = SQL_FETCHROW($result);
898                 } // END - if
899
900                 // Free result
901                 SQL_FREERESULT($result);
902         } // END - if
903
904         // Return cache
905         return $GLOBALS[__FUNCTION__][$id];
906 }
907
908 // "Getter for total count of current user's sub ids
909 function getTotalMemberSubIds () {
910         // Only do this for logged-in members
911         assert(isMember());
912
913         // Is there cache?
914         if (!isset($GLOBALS[__FUNCTION__])) {
915                 // Determine it
916                 $GLOBALS[__FUNCTION__] = countSumTotalData(getMemberId(), 'user_subids', 'id', 'userid', TRUE);
917         } // END - if
918
919         // Return cache
920         return $GLOBALS[__FUNCTION__];
921 }
922
923 //-----------------------------------------------------------------------------
924 //                                EL code functions
925 //-----------------------------------------------------------------------------
926
927 // Expression call-back function for fetching user data
928 function doExpressionUser ($data) {
929         // Use current userid by default
930         $functionName = 'getMemberId()';
931
932         // User-related data, so is there a userid?
933         if (!empty($data['matches'][4][$data['key']])) {
934                 // Is there a userid or $userid?
935                 if (substr($data['matches'][4][$data['key']], 0, 1) == '$') {
936                         // Use dynamic call
937                         $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
938                 } elseif (!empty($data['matches'][4][$data['key']])) {
939                         // Is there a number or a dollar sign in front of it?
940                         if (preg_replace('/[^0123456789]/', '', $data['matches'][4][$data['key']]) != $data['matches'][4][$data['key']]) {
941                                 // Possible database column, so get it again
942                                 $data['matches'][4][$data['key']] = "getFetchedUserData('userid', getMemberId(), '" . $data['matches'][4][$data['key']] . "')";
943                         } // END - if
944
945                         // Fix all together
946                         $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
947                 }
948         } elseif ((!empty($data['callback'])) && (isUserDataValid())) {
949                 // "Call-back" alias column for current logged in user's data
950                 $functionName = "getUserData('" . $data['callback'] . "')";
951         }
952
953         // Is there another function to run (e.g. translations)
954         if (!empty($data['extra_func'])) {
955                 // Surround the original function call with it
956                 $functionName = $data['extra_func'] . '(' . $functionName . ')';
957         } // END - if
958         //* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'functionName=' . $functionName);
959
960         // Generate replacer
961         $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
962
963         // Now replace the code
964         $code = replaceExpressionCode($data, $replacer);
965
966         // Return replaced code
967         return $code;
968 }
969
970 //-----------------------------------------------------------------------------
971 //                             Template helper functions
972 //-----------------------------------------------------------------------------
973
974 // Template call-back function for list_user admin function
975 function doTemplateAdminListUserTitle ($template, $clear = FALSE) {
976         // Init title with "all accounts"
977         $code = '{--ADMIN_LIST_ALL_ACCOUNTS--}';
978
979         // Is there a 'status' or 'do' set?
980         if (isGetRequestElementSet('status')) {
981                 // Set title according to the 'status'
982                 $code = sprintf("{--ADMIN_LIST_STATUS_%s_ACCOUNTS--}", strtoupper(getRequestElement('status')));
983         } elseif (isGetRequestElementSet('do')) {
984                 // Set title according to 'do'
985                 $code = sprintf("{--ADMIN_LIST_DO_%s_ACCOUNTS--}", strtoupper(getRequestElement('do')));
986         }
987
988         // Return the code
989         return $code;
990 }
991
992 // Template call-back function for displaying "username"
993 function doTemplateDisplayUsername ($template, $clear = FALSE, $userid = NULL) {
994         // Is a userid set?
995         if (!isValidUserId($userid)) {
996                 // Please don't call this without a valid userid
997                 reportBug(__FUNCTION__, __LINE__, 'template=' . $template . ',clear=' . intval($clear) . ',userid[' . gettype($userid) . ']=' . intval($userid) . ' - Invalid userid provided.');
998         } // END - if
999
1000         // Is there cache?
1001         if (!isset($GLOBALS[__FUNCTION__][$userid])) {
1002                 // Generate code
1003                 $GLOBALS[__FUNCTION__][$userid] = $userid . ' ({%user,nickname,fixEmptyContentToDashes=' . $userid . '%})';
1004         } // END - if
1005
1006         // Return cache
1007         return $GLOBALS[__FUNCTION__][$userid];
1008 }
1009
1010 // ----------------------------------------------------------------------------
1011 //                             XML call-back functions
1012 // ----------------------------------------------------------------------------
1013
1014 // For 'doing' add subid, the column-index is required
1015 function addXmlSpecialMemberAddDoUserSubid () {
1016         // So set it all here
1017         $GLOBALS['__COLUMN_INDEX']['doXmlCallbackFunction']  = 'column';
1018         $GLOBALS['__XML_ARGUMENTS']['doXmlCallbackFunction']['column_index'] = 'column';
1019 }
1020
1021 // ----------------------------------------------------------------------------
1022 //                 Wrapper functions for configuration entries
1023 // ----------------------------------------------------------------------------
1024
1025 // Getter for user_alpha
1026 function getUserAlpha () {
1027         // Is there cache?
1028         if (!isset($GLOBALS[__FUNCTION__])) {
1029                 // Determine it
1030                 $GLOBALS[__FUNCTION__] = getConfig('user_alpha');
1031         } // END - if
1032
1033         // Return cache
1034         return $GLOBALS[__FUNCTION__];
1035 }
1036
1037 // Getter for user_limit
1038 function getUserLimit () {
1039         // Is there cache?
1040         if (!isset($GLOBALS[__FUNCTION__])) {
1041                 // Determine it
1042                 $GLOBALS[__FUNCTION__] = getConfig('user_limit');
1043         } // END - if
1044
1045         // Return cache
1046         return $GLOBALS[__FUNCTION__];
1047 }
1048
1049 // Getter for tester_user_surname_prefix
1050 function getTesterUserSurnamePrefix () {
1051         // Is there cache?
1052         if (!isset($GLOBALS[__FUNCTION__])) {
1053                 // Determine it
1054                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_surname_prefix');
1055         } // END - if
1056
1057         // Return cache
1058         return $GLOBALS[__FUNCTION__];
1059 }
1060
1061 // Getter for tester_user_maximum
1062 function getTesterUserMaximum () {
1063         // Is there cache?
1064         if (!isset($GLOBALS[__FUNCTION__])) {
1065                 // Determine it
1066                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_maximum');
1067         } // END - if
1068
1069         // Return cache
1070         return $GLOBALS[__FUNCTION__];
1071 }
1072
1073 // Getter for tester_user_check_cat
1074 function getTesterUserCheckCat () {
1075         // Is there cache?
1076         if (!isset($GLOBALS[__FUNCTION__])) {
1077                 // Determine it
1078                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_check_cat');
1079         } // END - if
1080
1081         // Return cache
1082         return $GLOBALS[__FUNCTION__];
1083 }
1084
1085 // Getter for tester_user_gender
1086 function getTesterUserGender () {
1087         // Is there cache?
1088         if (!isset($GLOBALS[__FUNCTION__])) {
1089                 // Determine it
1090                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_gender');
1091         } // END - if
1092
1093         // Return cache
1094         return $GLOBALS[__FUNCTION__];
1095 }
1096
1097 // Getter for tester_user_family
1098 function getTesterUserFamily () {
1099         // Is there cache?
1100         if (!isset($GLOBALS[__FUNCTION__])) {
1101                 // Determine it
1102                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_family');
1103         } // END - if
1104
1105         // Return cache
1106         return $GLOBALS[__FUNCTION__];
1107 }
1108
1109 // Getter for tester_user_password
1110 function getTesterUserPassword () {
1111         // Is there cache?
1112         if (!isset($GLOBALS[__FUNCTION__])) {
1113                 // Determine it
1114                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_password');
1115         } // END - if
1116
1117         // Return cache
1118         return $GLOBALS[__FUNCTION__];
1119 }
1120
1121 // Getter for tester_user_street_nr
1122 function getTesterUserStreetNr () {
1123         // Is there cache?
1124         if (!isset($GLOBALS[__FUNCTION__])) {
1125                 // Determine it
1126                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_street_nr');
1127         } // END - if
1128
1129         // Return cache
1130         return $GLOBALS[__FUNCTION__];
1131 }
1132
1133 // Getter for tester_user_zip
1134 function getTesterUserZip () {
1135         // Is there cache?
1136         if (!isset($GLOBALS[__FUNCTION__])) {
1137                 // Determine it
1138                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_zip');
1139         } // END - if
1140
1141         // Return cache
1142         return $GLOBALS[__FUNCTION__];
1143 }
1144
1145 // Getter for tester_user_city
1146 function getTesterUserCity () {
1147         // Is there cache?
1148         if (!isset($GLOBALS[__FUNCTION__])) {
1149                 // Determine it
1150                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_city');
1151         } // END - if
1152
1153         // Return cache
1154         return $GLOBALS[__FUNCTION__];
1155 }
1156
1157 // Getter for tester_user_email
1158 function getTesterUserEmail () {
1159         // Is there cache?
1160         if (!isset($GLOBALS[__FUNCTION__])) {
1161                 // Determine it
1162                 $GLOBALS[__FUNCTION__] = getConfig('tester_user_email');
1163         } // END - if
1164
1165         // Return cache
1166         return $GLOBALS[__FUNCTION__];
1167 }
1168
1169 // [EOF]
1170 ?>