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