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