Table user_book renamed to user_booking, isExtensionOlder() should not be used, inste...
[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 - 2011 by Mailer Developer Team                   *
20  * For more information visit: http://www.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 alpha ($sortby, $colspan, $return=false) {
45         if (!isGetRequestParameterSet('offset')) setGetRequestParameter('offset', 0);
46         $add = '&amp;page='.getRequestParameter('page').'&amp;offset='.getRequestParameter('offset');
47         if (isGetRequestParameterSet('mode')) $add .= '&amp;mode='.getRequestParameter('mode');
48
49         /* Creates the list of letters and makes them a link. */
50         $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,');
51         $num = count($alphabet) - 1;
52         $OUT = '';
53         while (list($counter, $ltr) = each($alphabet)) {
54                 if (getRequestParameter('letter') == $ltr) {
55                         // Current letter is letter from URL
56                         $OUT .= '<strong>' . $ltr . '</strong>';
57                 } else {
58                         // Output link to letter
59                         $OUT .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat();
60                         if (isGetRequestParameterSet('mode')) $OUT .= '&amp;mode=' . getRequestParameter('mode');
61                         $OUT .= '&amp;letter=' . $ltr . '&amp;sortby=' . $sortby . $add . '%}">' . $ltr . '</a>';
62                 }
63
64                 if ((($counter / getConfig('user_alpha')) == round($counter / getConfig('user_alpha'))) && ($counter > 0)) {
65                         $OUT .= ']<br />[';
66                 } elseif ( $counter != $num ) {
67                         $OUT .= '|';
68                 }
69         } // END - while
70
71         // Prepare content
72         $content = array (
73                 'colspan2'        => $colspan,
74                 'alpha_selection' => $OUT
75         );
76
77         // Load template
78         $OUT = loadTemplate('admin_list_user_alpha', true, $content);
79         if ($return === true) {
80                 // Return generated code
81                 return $OUT;
82         } else {
83                 // Output generated code
84                 outputHtml($OUT);
85         }
86 }
87
88 // Add links for sorting
89 function addSortLinks ($letter, $sortby, $colspan, $return=false) {
90         $OUT = '';
91         if (!isGetRequestParameterSet('offset')) setGetRequestParameter('offset', 0);
92         if (!isGetRequestParameterSet('page'))   setGetRequestParameter('page'  , 0);
93
94         // Add page and offset
95         $add = '&amp;page=' . getRequestParameter('page') . '&amp;offset=' . getRequestParameter('offset');
96
97         // Add status or mode
98         if (isGetRequestParameterSet('status'))   $add .= '&amp;mode=' . getRequestParameter('status');
99         elseif (isGetRequestParameterSet('mode')) $add .= '&amp;mode=' . getRequestParameter('mode');
100
101         // Makes order by links..
102         if ($letter == 'front') $letter = '';
103
104         // Prepare array with all possible sorters
105         $list = array(
106                 'userid'      => '{--_USERID--}',
107                 'family'      => '{--FAMILY--}',
108                 'email'       => '{--EMAIL--}',
109                 'REMOTE_ADDR' => '{--REMOTE_IP--}'
110         );
111
112         // Add nickname if extension is installed
113         if (isExtensionActive('nickname')) {
114                 $list['nickname'] = '{--NICKNAME--}';
115         } // END - if
116
117         foreach ($list as $sort => $title) {
118                 if ($sortby == $sort) {
119                         $OUT .= '<strong>' . $title . '</strong>|';
120                 } else {
121                         $OUT .= '<a href="{%url=modules.php?module=admin&amp;what=list_user&amp;letter=' . $letter . '&amp;sortby=' . $sort . $add . '%}">' . $title . '</a>|';
122                 }
123         } // END - foreach
124
125         // Add list and colspan
126         $content['list'] = substr($OUT, 0, -1);
127         $content['colspan2'] = $colspan;
128
129         // Load template
130         $OUT = loadTemplate('admin_list_user_sort', true, $content);
131
132         // Should we return or output?
133         if ($return === true) {
134                 // Return code
135                 return $OUT;
136         } else {
137                 // Output code
138                 outputHtml($OUT);
139         }
140 }
141
142 // Add page navigation
143 function addPageNavigation ($numPages, $offset, $showForm, $colspan, $return=false) {
144         // @TODO These two constants are no longer used, maybe we reactivate this code?
145         //if ($showForm === true) {
146         //      // Load form for changing number of lines
147         //      define('__FORM_HEADER', loadTemplate('admin_list_user_sort_form', true));
148         //      define('__FORM_FOOTER', '<tr><td colspan="'.$colspan.'" class="seperator bottom">&nbsp;</td></tr>');
149         //} else {
150         //      // Empty row
151         //      define('__FORM_HEADER', '<tr><td colspan="' . $colspan . '" class="seperator">&nbsp;</td></tr>');
152         //      define('__FORM_FOOTER', '<tr><td colspan="' . $colspan . '" class="seperator bottom">&nbsp;</td></tr>');
153         //}
154
155         $OUT = '';
156         for ($page = 1; $page <= $numPages; $page++) {
157                 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
158                         $OUT .= '<strong>-';
159                 } else {
160                         if (!isGetRequestParameterSet('letter')) setGetRequestParameter('letter', '');
161                         if (!isGetRequestParameterSet('sortby')) setGetRequestParameter('sortby', 'userid');
162
163                         // Base link
164                         $OUT .= '<a href="{%url=modules.php?module=admin&amp;what=' . getWhat();
165
166                         // Add status or mode
167                         if (isGetRequestParameterSet('status'))    $OUT .= '&amp;mode=' . getRequestParameter('status');
168                          elseif (isGetRequestParameterSet('mode')) $OUT .= '&amp;mode=' . getRequestParameter('mode');
169
170                         // Letter and so on
171                         $OUT .= '&amp;letter=' . getRequestParameter('letter') . '&amp;sortby=' . getRequestParameter('sortby') . '&amp;page=' . $page . '&amp;offset=' . $offset . '%}">';
172                 }
173
174                 $OUT .= $page;
175
176                 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
177                         $OUT .= '-</strong>';
178                 } else  {
179                         $OUT .= '</a>';
180                 }
181
182                 if ($page < $numPages) $OUT .= '|';
183         } // END - for
184
185         // Remember the list and colspan
186         $content['list']     = $OUT;
187         $content['colspan2'] = $colspan;
188
189         // Load template
190         $OUT = loadTemplate('admin_list_user_pagenav', true, $content);
191         if ($return === true) {
192                 // Return code
193                 return $OUT;
194         } else {
195                 // Output code
196                 outputHtml($OUT);
197         }
198 }
199
200 // Create email link to user's account
201 function generateUserEmailLink ($email, $mod = 'admin') {
202         // Show contact link only if user is confirmed by default
203         $locked = " AND `status`='CONFIRMED'";
204
205         // But admins shall always see it
206         if (isAdmin()) $locked = '';
207
208         $result = SQL_QUERY_ESC("SELECT
209         `userid`
210 FROM
211         `{?_MYSQL_PREFIX?}_user_data`
212 WHERE
213         `email`='%s'" . $locked."
214 LIMIT 1",
215                 array($email), __FUNCTION__, __LINE__);
216         if (SQL_NUMROWS($result) == 1) {
217                 // Load userid
218                 list($userid) = SQL_FETCHROW($result);
219
220                 // Rewrite email address to contact link
221                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=user_contct&amp;userid=' . bigintval($userid) . '%}';
222         } // END - if
223
224         // Free memory
225         SQL_FREERESULT($result);
226
227         // Return rewritten (?) email address
228         return $email;
229 }
230
231 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
232 // @TODO Double-check configuration entry here
233 function determineRandomReferalId () {
234         // Default is zero refid
235         $refid = null;
236
237         // Is the extension version fine?
238         if (isExtensionInstalledAndNewer('user', '0.3.4')) {
239                 // Get all user ids
240                 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= {?user_min_confirmed?}");
241
242                 // Do we have at least one?
243                 if ($totalUsers > 0) {
244                         // Then choose random number
245                         $randNum = mt_rand(0, ($totalUsers - 1));
246
247                         // Look for random user
248                         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `status`='CONFIRMED' AND `rand_confirmed` >= {?user_min_confirmed?} ORDER BY `rand_confirmed` DESC LIMIT %s, 1",
249                                 array($randNum), __FUNCTION__, __LINE__);
250
251                         // Do we have one entry there?
252                         if (SQL_NUMROWS($result) == 1) {
253                                 // Use that userid as new referal id
254                                 list($refid) = SQL_FETCHROW($result);
255
256                                 // Reset all users, this makes this random referal id more challenging
257                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0",
258                                         array($refid), __FUNCTION__, __LINE__);
259                         } // END - if
260
261                         // Free result
262                         SQL_FREERESULT($result);
263                 } // END - if
264         } // END - if
265
266         // Return result
267         return $refid;
268 }
269
270 // Do the user login
271 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&amp;what=login&amp;login=') {
272         // Init variables
273         $dmy = '';
274         $add = '';
275         $errorCode = '0';
276         $ext = '';
277         $isFound = false;
278
279         // Init array
280         $content = array(
281                 'password'    => '',
282                 'userid'      => '',
283                 'last_online' => 0,
284                 'last_login'  => 0,
285                 'hash'        => ''
286         );
287
288         // Check login data
289         if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
290                 // Nickname entered
291                 fetchUserData($userid, 'nickname');
292         } elseif (isNicknameUsed($userid)) {
293                 // No nickname installed
294                 $errorCode = getCode('EXTENSION_PROBLEM');
295                 $ext = 'nickname';
296         } else {
297                 // Direct userid entered
298                 $isFound = fetchUserData($userid);
299         }
300
301         // No error found?
302         if (($errorCode == '0') && ($isFound === true)) {
303                 // Get user data array and set userid (e.g. important if we login with nickname)
304                 $content = getUserDataArray();
305                 if (!empty($content['userid'])) $userid = bigintval($content['userid']);
306         } // END - if
307
308         // Is there an entry?
309         if ((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                         // Probe for last online timemark
333                         $probe = time() -  getUserData('last_online');
334                         if (getUserData('last_login') > 0) $probe = time() - getUserData('last_login');
335
336                         if ((isExtensionInstalledAndNewer('bonus', '0.2.2')) && ($probe >= getConfig('login_timeout'))) {
337                                 // Add login bonus to user's account
338                                 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
339                                 $GLOBALS['bonus_payed'] = true;
340
341                                 // Subtract login bonus from userid's account or jackpot
342                                 if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getBonusMode() != 'ADD')) {
343                                         handleBonusPoints('login_bonus');
344                                 } // END - if
345                         } // END - if
346
347                         // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
348
349                         // Set member id
350                         setMemberId($userid);
351
352                         // Try to set session data (which shall normally always work!)
353                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
354                         if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
355                                 // Update database records
356                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
357                                         array($userid), __FUNCTION__, __LINE__);
358                                 if (!SQL_HASZEROAFFECTED()) {
359                                         // Is a success URL set?
360                                         if (empty($successUrl)) {
361                                                 // Procedure to checking for login data
362                                                 if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
363                                                         // Bonus added (just displaying!)
364                                                         $url = 'modules.php?module=chk_login&amp;mode=bonus';
365                                                 } else {
366                                                         // Bonus not added
367                                                         $url = 'modules.php?module=chk_login&amp;mode=login';
368                                                 }
369                                         } else {
370                                                 // Use this URL
371                                                 $url = $successUrl;
372                                         }
373                                 } else {
374                                         // Cannot update counter!
375                                         $errorCode = getCode('CNTR_FAILED');
376                                 }
377                         } else {
378                                 // Cookies not setable!
379                                 $errorCode = getCode('COOKIES_DISABLED');
380                         }
381                 } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
382                         // Update failture counter
383                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
384                                 array($userid), __FUNCTION__, __LINE__);
385
386                         // Wrong password!
387                         $errorCode = getCode('WRONG_PASS');
388                 }
389         } elseif ((isUserDataValid()) && (getUserData('status') != 'CONFIRMED')) {
390                 // Create an error code from given status
391                 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
392
393                 // Set userid in session
394                 setSession('current_userid', getUserData('userid'));
395         } elseif (!isUserDataValid()) {
396                 // User id not found
397                 $errorCode = getCode('WRONG_ID');
398         } else {
399                 // Unknown error
400                 $errorCode = getCode('UNKNOWN_ERROR');
401         }
402
403         // Error code provided?
404         if ($errorCode > 0) {
405                 // Then reconstruct the URL
406                 $url = $errorUrl . $errorCode;
407
408                 // Extension set? Then add it as well.
409                 if (!empty($ext)) $url .= '&amp;ext=' . $ext;
410         } // END - if
411
412         // Return URL
413         return $url;
414 }
415
416 // Try to send a new password for the given user account
417 function doNewUserPassword ($email, $userid) {
418         // Init result and error
419         $errorCode = '';
420         $result = false;
421
422         // Probe userid/nickname
423         // @TODO We should try to rewrite this to fetchUserData() somehow
424         if (!empty($email)) {
425                 // Email entered
426                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' OR `email`='%s' LIMIT 1",
427                         array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
428         } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
429                 // Nickname entered
430                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
431                         array($userid, $userid, $email), __FUNCTION__, __LINE__);
432         } elseif ((isValidUserId($userid)) && (empty($email))) {
433                 // Direct userid entered
434                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
435                         array(bigintval($userid)), __FUNCTION__, __LINE__);
436         } else {
437                 // Userid not set!
438                 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
439                 $errorCode = getCode('WRONG_ID');
440         }
441
442         // Any entry found?
443         if (SQL_NUMROWS($result) == 1) {
444                 // This data is valid, so we create a new pass... :-)
445                 list($userid, $status) = SQL_FETCHROW($result);
446
447                 if ($status == 'CONFIRMED') {
448                         // Ooppps, this was missing! ;-) We should update the database...
449                         $NEW_PASS = generatePassword();
450                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
451                                 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
452
453                         // Prepare data and message for email
454                         $message = loadEmailTemplate('guest_new_password', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
455
456                         // ... and send it away
457                         sendEmail($userid, '{--GUEST_NEW_PASSWORD--}', $message);
458
459                         // Output note to user
460                         displayMessage('{--GUEST_NEW_PASSWORD_SEND--}');
461                 } else {
462                         // Account is locked or unconfirmed
463                         $errorCode = generateErrorCodeFromUserStatus($status);
464
465                         // Load URL
466                         redirectToUrl('modules.php?module=index&amp;what=login&amp;login='.$errorCode);
467                 }
468         } else {
469                 // id or email is wrong
470                 displayMessage('<span class="notice">{--GUEST_WRONG_ID_EMAIL--}</span>');
471         }
472
473         // Return the error code
474         return $errorCode;
475 }
476
477 // Get timestamp for given stats type and data
478 function getEpocheTimeFromUserStats ($statsType, $statsData, $userid = '0') {
479         // Default timestamp is zero
480         $data['inserted'] = '0';
481
482         // User id set?
483         if ((isMemberIdSet()) && ($userid == '0')) {
484                 $userid = getMemberId();
485         } // END - if
486
487         // Is the extension installed and updated?
488         if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
489                 // Return zero here
490                 return $data['inserted'];
491         } // END - if
492
493         // Try to find the entry
494         $result = SQL_QUERY_ESC("SELECT
495         UNIX_TIMESTAMP(`inserted`) AS inserted
496 FROM
497         `{?_MYSQL_PREFIX?}_user_stats_data`
498 WHERE
499         `userid`=%s AND
500         `stats_type`='%s' AND
501         `stats_data`='%s'
502 LIMIT 1",
503                 array(
504                         bigintval($userid),
505                         $statsType,
506                         $statsData
507                 ), __FUNCTION__, __LINE__);
508
509         // Is the entry there?
510         if (SQL_NUMROWS($result) == 1) {
511                 // Get this stamp
512                 $data = SQL_FETCHARRAY($result);
513         } // END - if
514
515         // Free result
516         SQL_FREERESULT($result);
517
518         // Return stamp
519         return $data['inserted'];
520 }
521
522 // Inserts user stats
523 function insertUserStatsRecord ($userid, $statsType, $statsData) {
524         // Is the extension installed and updated?
525         if ((!isExtensionActive('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.6'))) {
526                 // Return zero here
527                 return false;
528         } // END - if
529
530         // Does it exist?
531         if ((!getEpocheTimeFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
532                 // Then insert it!
533                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
534                         array(
535                                 bigintval($userid),
536                                 $statsType,
537                                 $statsData
538                         ), __FUNCTION__, __LINE__);
539         } elseif (is_array($statsData)) {
540                 // Invalid data!
541                 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',type=' . $statsType . ',data=' . gettype($statsData) . ': Invalid statistics data type!');
542         }
543 }
544
545 // Confirms a user account
546 function doConfirmUserAccount ($hash) {
547         // Init content
548         $content = array(
549                 'message' => '{--GUEST_CONFIRMED_FAILED--}',
550                 'userid'  => 0,
551         );
552
553         // Initialize the user id
554         $userid = '0';
555
556         // Search for an unconfirmed or confirmed account
557         $result = SQL_QUERY_ESC("SELECT `userid`, `email`, `refid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `user_hash`='%s' AND (`status`='UNCONFIRMED' OR `status`='CONFIRMED') LIMIT 1",
558                 array($hash), __FILE__, __LINE__);
559         if (SQL_NUMROWS($result) == 1) {
560                 // Ok, he want's to confirm now so we load some data
561                 list($userid, $email, $refid) = SQL_FETCHROW($result);
562
563                 // Fetch user data
564                 if (!fetchUserData($userid)) {
565                         // Not found, should not happen
566                         debug_report_bug(__FILE__, __LINE__, 'User account ' . $userid . ' not found.');
567                 } // END - if
568
569                 // Load all data and add points
570                 $content = getUserDataArray();
571
572                 // Unlock his account (but only when it is on UNCONFIRMED!)
573                 SQL_QUERY_ESC("UPDATE
574         `{?_MYSQL_PREFIX?}_user_data`
575 SET
576         `status`='CONFIRMED',
577         `ref_payout`={?ref_payout?},
578         `user_hash`=NULL
579 WHERE
580         `user_hash`='%s' AND
581         `status`='UNCONFIRMED'
582 LIMIT 1",
583                         array($hash), __FILE__, __LINE__);
584
585                 // Was it updated?
586                 if (!SQL_HASZEROAFFECTED()) {
587                         // Send email if updated
588                         $message = loadEmailTemplate('guest_user_confirmed', $content, bigintval($userid));
589
590                         // And send him right away the confirmation mail
591                         sendEmail($email, '{--GUEST_THANX_CONFIRM--}', $message);
592
593                         // Maybe he got "referaled"?
594                         if (($refid > 0) && ($refid != $userid)) {
595                                 // Select the referal userid
596                                 if (fetchUserData($refid)) {
597                                         // Update ref counter...
598                                         updateReferalCounter($refid);
599
600                                         // If version matches add ref bonus to refid's account
601                                         if ((isExtensionInstalledAndNewer('bonus', '0.4.4')) && (isBonusRallyeActive())) {
602                                                 // Add points (directly only!)
603                                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `bonus_ref`=`bonus_ref`+{?bonus_ref?} WHERE `userid`=%s LIMIT 1",
604                                                         array(bigintval($refid)), __FILE__, __LINE__);
605
606                                                 // Subtract points from system
607                                                 handleBonusPoints(getConfig('bonus_ref'));
608                                         } // END - if
609
610                                         // Add one-time referal bonus over referal system or directly
611                                         // @TODO Try to rewrite the following unset()
612                                         unset($GLOBALS['ref_level']);
613                                         addPointsThroughReferalSystem('referal_bonus', $refid, getPointsRef(), true, bigintval($userid), getConfig('reg_points_mode'));
614                                 } // END - if
615                         } // END - if
616
617                         if (isExtensionActive('rallye')) {
618                                 // Add user to rallye (or not?)
619                                 addUserToReferalRallye(bigintval($userid));
620                         } // END - if
621
622                         // Account confirmed!
623                         if (isExtensionActive('lead')) {
624                                 // Set special lead cookie
625                                 setSession('lead_userid', bigintval($userid));
626
627                                 // Lead-Code mode enabled
628                                 redirectToUrl('lead-confirm.php');
629                         } else {
630                                 $content['message'] = '{--GUEST_CONFIRMED_DONE--}';
631                                 $content['userid']  = bigintval($userid);
632                         }
633                 } elseif (isExtensionActive('lead')) {
634                         // Set special lead cookie
635                         setSession('lead_userid', bigintval($userid));
636
637                         // Lead-Code mode enabled
638                         redirectToUrl('lead-confirm.php');
639                 } else {
640                         // Nobody was found unter this hash key... or our new member want's to confirm twice?
641                         $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
642                 }
643         } else {
644                 // Nobody was found unter this hash key... or our new member want's to confirm twice?
645                 $content['message'] = '{--GUEST_CONFIRMED_TWICE--}';
646         }
647
648         // Load template
649         displayMessage($content['message']);
650 }
651
652 // Does resend the user's confirmation link for given email address
653 function doResendUserConfirmationLink ($email) {
654         // Email address not registered is default message
655         $message = '{--EMAIL_404--}';
656
657         // Confirmation link requested
658         if (fetchUserData($email, 'email')) {
659                 // Email address found
660                 $content = getUserDataArray();
661
662                 // Is the account unconfirmed?
663                 if ($content['status'] == 'UNCONFIRMED') {
664                         // Load email template
665                         $message = loadEmailTemplate('guest_request_confirm', array('hash' => $content['user_hash']), $content['userid']);
666
667                         // Send email
668                         sendEmail($email, '{--GUEST_REQUEST_CONFIRM_LINK_SUBJECT--}', $message);
669                 } // END - if
670
671                 // Create message based on the status
672                 $message = getConfirmationMessageFromUserStatus($content['status']);
673         } // END - if
674
675         // Output message
676         displayMessage($message);
677 }
678
679 // Get a message (somewhat translation) from user status for confirmation link.
680 // This is different to translateUserStatus() in text messages.
681 function getConfirmationMessageFromUserStatus ($status) {
682         // Default is 'UNKNOWN'
683         $message = getMaskedMessage('GUEST_LOGIN_ID_UNKNOWN_STATUS', $status);
684
685         // Which status is it?
686         switch ($status) {
687                 case 'UNCONFIRMED': // Account is unconfirmed
688                         // And set message
689                         $message = '{--GUEST_CONFIRM_LINK_SENT--}';
690                         break;
691
692                 case 'CONFIRMED': // Account already confirmed
693                         $message = '{--GUEST_LOGIN_ID_CONFIRMED--}';
694                         break;
695
696                 case 'LOCKED': // Account is locked
697                         $message = '{--GUEST_LOGIN_ID_LOCKED--}';
698                         break;
699
700                 default: // This should not happen
701                         debug_report_bug(__FUNCTION__, __LINE__, 'Unknown user status ' . $status . ' detected.');
702                         break;
703         } // END - switch
704
705         // Return message
706         return $message;
707 }
708
709 // Expression call-back function for fetching user data
710 function doExpressionUser ($data) {
711         // Use current userid by default
712         $functionName = 'getMemberId()';
713
714         // User-related data, so is there a userid?
715         if (!empty($data['matches'][4][$data['key']])) {
716                 // Do we have a userid or $userid?
717                 if ($data['matches'][4][$data['key']] == '$userid') {
718                         // Use dynamic call
719                         $functionName = "getFetchedUserData('userid', \$userid, '" . $data['callback'] . "')";
720                 } elseif (!empty($data['matches'][4][$data['key']])) {
721                         // User data found
722                         $functionName = "getFetchedUserData('userid', " . $data['matches'][4][$data['key']] . ", '" . $data['callback'] . "')";
723                 }
724         } elseif ((!empty($data['callback'])) && (isUserDataValid())) {
725                 // "Call-back" alias column for current logged in user's data
726                 $functionName = "getUserData('" . $data['callback'] . "')";
727         }
728
729         // Do we have another function to run (e.g. translations)
730         if (!empty($data['extra_func'])) {
731                 // Surround the original function call with it
732                 $functionName = $data['extra_func'] . '(' . $functionName . ')';
733         } // END - if
734
735         // Generate replacer
736         $replacer = '{DQUOTE} . ' . $functionName . ' . {DQUOTE}';
737
738         // Now replace the code
739         $code = replaceExpressionCode($data, $replacer);
740
741         // Return replaced code
742         return $code;
743 }
744
745 // Template call-back function for list_user admin function
746 function doTemplateAdminListUserTitle ($template, $dummy = false) {
747         // Init title with "all accounts"
748         $code = '{--ADMIN_LIST_ALL_ACCOUNTS--}';
749
750         // Do we have a 'status' or 'mode' set?
751         if (isGetRequestParameterSet('status')) {
752                 // Set title according to the 'status'
753                 $code = sprintf("{--ADMIN_LIST_STATUS_%s_ACCOUNTS--}", strtoupper(getRequestParameter('status')));
754         } elseif (isGetRequestParameterSet('mode')) {
755                 // Set title according to the "mode"
756                 $code = sprintf("{--ADMIN_LIST_MODE_%s_ACCOUNTS--}", strtoupper(getRequestParameter('mode')));
757         }
758
759         // Return the code
760         return $code;
761 }
762
763 // [EOF]
764 ?>