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