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