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