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