7e4ee7c1b5e290a18634fc78b52d9e6d2c2be2c2
[mailer.git] / inc / libs / user_functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 }
43
44 // Add links for selecting some users
45 function alpha ($sortby, $colspan, $return=false) {
46         if (!isGetRequestElementSet('offset')) setRequestGetElement('offset', 0);
47         $add = "&amp;page=".getRequestElement('page')."&amp;offset=".getRequestElement('offset');
48         if (isGetRequestElementSet('mode')) $add .= "&amp;mode=".getRequestElement('mode');
49
50         /* Creates the list of letters and makes them a link. */
51         $alphabet = explode(',', getMessage('_ALL2') . ',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,' . getMessage('_OTHERS'));
52         $num = count($alphabet) - 1;
53         $OUT = '';
54         while (list($counter, $ltr) = each($alphabet)) {
55                 if (getRequestElement('letter') == $ltr) {
56                         // Current letter is letter from URL
57                         $OUT .= "<strong>".$ltr."</strong>";
58                 } else {
59                         // Output link to letter
60                         $OUT .= "<a href=\"{?URL?}/modules.php?module=admin&amp;what=".getWhat();
61                         if (isGetRequestElementSet('mode')) $OUT .= "&amp;mode=".getRequestElement('mode');
62                         $OUT .= "&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 .= "&nbsp;]<br />[&nbsp;";
67                 } elseif ( $counter != $num ) {
68                         $OUT .= "&nbsp;|&nbsp;";
69                 }
70         } // END - while
71
72         // Load template
73         $OUT = loadTemplate('admin_list_user_alpha', true, $OUT);
74         if ($return === true) {
75                 // Return generated code
76                 return $OUT;
77         } else {
78                 // Output generated code
79                 outputHtml($OUT);
80         }
81 }
82
83 // Add links for sorting
84 function addSortLinks ($letter, $sortby, $colspan, $return=false) {
85         $OUT = '';
86         if (!isGetRequestElementSet('offset')) setRequestGetElement('offset', 0);
87         if (!isGetRequestElementSet('page'))   setRequestGetElement('page'  , 0);
88
89         // Add page and offset
90         $add = '&amp;page=' . getRequestElement('page') . '&amp;offset=' . getRequestElement('offset');
91
92         // Add status or mode
93         if (isGetRequestElementSet('status'))   $add .= '&amp;mode=' . getRequestElement('status');
94         elseif (isGetRequestElementSet('mode')) $add .= '&amp;mode=' . getRequestElement('mode');
95
96         // Makes order by links..
97         if ($letter == 'front') $letter = getMessage('_ALL2');
98
99         // Prepare array with all possible sorters
100         $list = array(
101                 'userid'      => getMessage('_UID'),
102                 'family'      => getMessage('FAMILY_NAME'),
103                 'email'       => getMessage('EMAIL_ADDRESS'),
104                 'REMOTE_ADDR' => getMessage('REMOTE_IP')
105         );
106
107         // Add nickname if extension is installed
108         if (isExtensionActive('nickname')) {
109                 $list['nickname'] = getMessage('NICKNAME');
110         } // END - if
111
112         foreach ($list as $sort => $title) {
113                 if ($sortby == $sort) {
114                         $OUT .= "<strong>" . $title . "</strong>&nbsp;|&nbsp;";
115                 } else {
116                         $OUT .= "<a href=\"{?URL?}/modules.php?module=admin&amp;what=list_user&amp;letter=" . $letter . "&amp;sortby=" . $sort.$add . "\">" . $title . "</a>&nbsp;|&nbsp;";
117                 }
118         } // END - foreach
119
120         $content['list'] = substr($OUT, 0, -13);
121
122         // Load template
123         $OUT = loadTemplate('admin_list_user_sort', true, $content);
124
125         // Should we return or output?
126         if ($return === true) {
127                 // Return code
128                 return $OUT;
129         } else {
130                 // Output code
131                 outputHtml($OUT);
132         }
133 }
134
135 // Add page navigation
136 function addPageNavigation ($PAGES, $offset, $show_form, $colspan,$return=false) {
137         // @TODO These two constants are no longer used, maybe we reactivate this code?
138         //if ($show_form === true) {
139         //      // Load form for changing number of lines
140         //      define('__FORM_HEADER', loadTemplate('admin_list_user_sort_form', true));
141         //      define('__FORM_FOOTER', '<tr><td colspan="'.$colspan.'" class="seperator bottom2">&nbsp;</td></tr>');
142         //} else {
143         //      // Empty row
144         //      define('__FORM_HEADER', '<tr><td colspan="' . $colspan . '" class="seperator">&nbsp;</td></tr>');
145         //      define('__FORM_FOOTER', '<tr><td colspan="' . $colspan . '" class="seperator bottom2">&nbsp;</td></tr>');
146         //}
147
148         $OUT = '';
149         for ($page = 1; $page <= $PAGES; $page++) {
150                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
151                         $OUT .= '<strong>-';
152                 } else {
153                         if (!isGetRequestElementSet('letter')) setRequestGetElement('letter', getMessage('_ALL2'));
154                         if (!isGetRequestElementSet('sortby')) setRequestGetElement('sortby', 'userid');
155
156                         // Base link
157                         $OUT .= '<a href="{?URL?}/modules.php?module=admin&amp;what=' . getWhat();
158
159                         // Add status or mode
160                         if (isGetRequestElementSet('status'))    $OUT .= '&amp;mode=' . getRequestElement('status');
161                          elseif (isGetRequestElementSet('mode')) $OUT .= '&amp;mode=' . getRequestElement('mode');
162
163                         // Letter and so on
164                         $OUT .= '&amp;letter=' . getRequestElement('letter') . '&amp;sortby=' . getRequestElement('sortby') . '&amp;page=' . $page . '&amp;offset=' . $offset . '">';
165                 }
166
167                 $OUT .= $page;
168
169                 if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
170                         $OUT .= '-</strong>';
171                 } else  {
172                         $OUT .= '</a>';
173                 }
174
175                 if ($page < $PAGES) $OUT .= '&nbsp;|&nbsp;';
176         } // END - for
177
178         // Remember the list
179         $content['list'] = $OUT;
180
181         // Load template
182         $OUT = loadTemplate('admin_list_user_pagenav', true, $content);
183         if ($return === true) {
184                 // Return code
185                 return $OUT;
186         } else {
187                 // Output code
188                 outputHtml($OUT);
189         }
190 }
191
192 // Create email link to user's account
193 function generateUserEmailLink($email, $mod = 'admin') {
194         // Show contact link only if user is confirmed by default
195         $locked = " AND `status`='CONFIRMED'";
196
197         // But admins shall always see it
198         if (isAdmin()) $locked = '';
199
200         $result = SQL_QUERY_ESC("SELECT
201         `userid`
202 FROM
203         `{?_MYSQL_PREFIX?}_user_data`
204 WHERE
205         `email`='%s'" . $locked."
206 LIMIT 1",
207                 array($email), __FUNCTION__, __LINE__);
208         if (SQL_NUMROWS($result) == 1) {
209                 // Load userid
210                 list($userid) = SQL_FETCHROW($result);
211
212                 // Rewrite email address to contact link
213                 $email = '{?URL?}/modules.php?module=' . $mod . '&amp;what=user_contct&amp;userid=' . bigintval($userid);
214         } // END - if
215
216         // Free memory
217         SQL_FREERESULT($result);
218
219         // Return rewritten (?) email address
220         return $email;
221 }
222
223 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
224 function determineRandomReferalId () {
225         // Default is zero refid
226         $refid = 0;
227
228         // Is the extension version fine?
229         if (getExtensionVersion('user') >= '0.3.4') {
230                 // Get all user ids
231                 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= ".getConfig('user_min_confirmed')."");
232
233                 // Do we have at least one?
234                 if ($totalUsers > 0) {
235                         // Then choose random number
236                         $randNum = mt_rand(0, ($totalUsers - 1));
237
238                         // Look for random user
239                         $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",
240                                 array($randNum), __FUNCTION__, __LINE__);
241
242                         // Do we have one entry there?
243                         if (SQL_NUMROWS($result) == 1) {
244                                 // Use that userid as new referal id
245                                 list($refid) = SQL_FETCHROW($result);
246
247                                 // Reset this user's counter
248                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0 WHERE `userid`=%s LIMIT 1",
249                                         array($refid), __FUNCTION__, __LINE__);
250                         } // END - if
251
252                         // Free result
253                         SQL_FREERESULT($result);
254                 } // END - if
255         } // END - if
256
257         // Return result
258         return $refid;
259 }
260
261 // Do the user login
262 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&amp;what=login&amp;login=') {
263         // Init variables
264         $dmy = ''; $add = '';
265         $errorCode = 0;
266
267         // Add last_login if available
268         $lastOnline = '';
269         if (getExtensionVersion('sql_patches') >= '0.2.8') {
270                 $lastOnline = ', `last_login`';
271         } // END - if
272
273         // Init array
274         $content = array(
275                 'password'    => '',
276                 'userid'      => '',
277                 'last_online' => 0,
278                 'last_login'  => 0,
279                 'hash'        => ''
280         );
281
282         // Check login data
283         if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
284                 // Nickname entered
285                 $result = SQL_QUERY_ESC("SELECT `userid`, `password`, `last_online`" . $lastOnline . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' AND `status`='CONFIRMED' LIMIT 1",
286                         array($userid), __FUNCTION__, __LINE__);
287         } else {
288                 // Direct userid entered
289                 $result = SQL_QUERY_ESC("SELECT `userid`, `password`, `last_online`" . $lastOnline . " FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
290                         array($userid, $content['hash']), __FUNCTION__, __LINE__);
291         }
292
293         // Load entry
294         $content = SQL_FETCHARRAY($result);
295         if (!empty($content['userid'])) $userid = bigintval($content['userid']);
296
297         // Is there an entry?
298         if ((SQL_NUMROWS($result) == 1) && ((isNicknameUsed($content['userid'] === true) && (!empty($content['userid']))) || ($content['userid'] == $userid))) {
299                 // Free result
300                 SQL_FREERESULT($result);
301
302                 // Check for old MD5 passwords
303                 if ((strlen($content['password']) == 32) && (md5($passwd) == $content['password'])) {
304                         // Just set the hash to the password from DB... :)
305                         $content['hash'] = $content['password'];
306                 } else {
307                         // Hash password with improved way for comparsion
308                         $content['hash'] = generateHash($passwd, substr($content['password'], 0, -40));
309                 }
310
311                 // Does the password match the hash?
312                 if ($content['hash'] == $content['password']) {
313                         // New hashed password found so let's generate a new one
314                         $content['hash'] = generateHash($passwd);
315
316                         // ... and update database
317                         // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
318                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
319                                 array($content['hash'], $userid), __FUNCTION__, __LINE__);
320
321                         // No login bonus by default
322                         $GLOBALS['bonus_payed'] = false;
323
324                         // Probe for last online timemark
325                         $probe = time() -  $content['last_online'];
326                         if (!empty($content['last_login'])) $probe = time() - $content['last_login'];
327                         if ((getExtensionVersion('bonus') >= '0.2.2') && ($probe >= getConfig('login_timeout'))) {
328                                 // Add login bonus to user's account
329                                 $add = sprintf(", `login_bonus`=`login_bonus`+%s",
330                                         (float)getConfig('login_bonus')
331                                 );
332                                 $GLOBALS['bonus_payed'] = true;
333
334                                 // Subtract login bonus from userid's account or jackpot
335                                 if ((getExtensionVersion('bonus') >= '0.3.5') && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
336                         } // END - if
337
338                         // Calculate new hash with the secret key and master salt together
339                         $content['hash'] = generatePassString($content['hash']);
340
341                         // Update global array
342                         // @TODO Make this filter working: $URL = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
343                         setUserId($userid);
344
345                         // Try to set session data (which shall normally always work!)
346                         if ((setSession('userid', $userid )) && (setSession('u_hash', $content['hash']))) {
347                                 // Update database records
348                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
349                                         array($userid), __FUNCTION__, __LINE__);
350                                 if (SQL_AFFECTEDROWS() == 1) {
351                                         // Is a success URL set?
352                                         if (empty($successUrl)) {
353                                                 // Procedure to checking for login data
354                                                 if (($GLOBALS['bonus_payed']) && (isExtensionActive('bonus'))) {
355                                                         // Bonus added (just displaying!)
356                                                         $URL = 'modules.php?module=chk_login&amp;mode=bonus';
357                                                 } else {
358                                                         // Bonus not added
359                                                         $URL = 'modules.php?module=chk_login&amp;mode=login';
360                                                 }
361                                         } else {
362                                                 // Use this URL
363                                                 $URL = $successUrl;
364                                         }
365                                 } else {
366                                         // Cannot update counter!
367                                         $errorCode = getCode('CNTR_FAILED');
368                                 }
369                         } else {
370                                 // Cookies not setable!
371                                 $errorCode = getCode('NO_COOKIES');
372                         }
373                 } elseif (getExtensionVersion('sql_patches') >= '0.6.1') {
374                         // Update failture counter
375                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
376                                 array($userid), __FUNCTION__, __LINE__);
377
378                         // Wrong password!
379                         $errorCode = getCode('WRONG_PASS');
380                 }
381         } elseif (((isNicknameUsed($content['userid'])) && (!empty($content['userid']))) || ($content['userid'] == $userid)) {
382                 // Other account status?
383                 // @TODO Can this query be merged with above query?
384                 $result = SQL_QUERY_ESC("SELECT `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
385                         array($userid), __FUNCTION__, __LINE__);
386
387                 // Entry found?
388                 if (SQL_NUMROWS($result) == 1) {
389                         // Load status
390                         list($status) = SQL_FETCHROW($result);
391
392                         // Create an error code from given status
393                         $errorCode = generateErrorCodeFromUserStatus($status);
394                 } else {
395                         // id not found!
396                         $errorCode = getCode('WRONG_ID');
397                 }
398         } else {
399                 // id not found!
400                 $errorCode = getCode('WRONG_ID');
401         }
402
403         // Error code provided?
404         if ($errorCode > 0) {
405                 // Then reconstruct the URL
406                 $URL = $errorUrl . $errorCode;
407         } // END - if
408
409         // Return URL
410         return $URL;
411 }
412
413 // Try to send a new password for the given user account
414 function doNewUserPassword ($email, $userid) {
415         // Compile email when found in address (only secure chars!)
416         if (!empty($email)) $email = str_replace('{DOT}', '.', $email);
417
418         // Init result and error
419         $errorCode = '';
420         $result = false;
421
422         // Probe userid/nickname
423         if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
424                 // Nickname entered
425                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
426                         array($userid, $userid, $email), __FUNCTION__, __LINE__);
427         } elseif (($userid > 0) && (empty($email))) {
428                 // Direct userid entered
429                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
430                         array(bigintval($userid)), __FUNCTION__, __LINE__);
431         } elseif (!empty($email)) {
432                 // Email entered
433                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' LIMIT 1",
434                         array($email), __FUNCTION__, __LINE__);
435         } else {
436                 // Userid not set!
437                 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
438                 $errorCode = getCode('WRONG_ID');
439         }
440
441         // Any entry found?
442         if (SQL_NUMROWS($result) == 1) {
443                 // This data is valid, so we create a new pass... :-)
444                 list($userid, $status) = SQL_FETCHROW($result);
445
446                 if ($status == 'CONFIRMED') {
447                         // Ooppps, this was missing! ;-) We should update the database...
448                         $NEW_PASS = generatePassword();
449                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
450                                 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
451
452                         // Prepare data and message for email
453                         $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
454
455                         // ... and send it away
456                         sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
457
458                         // Output note to user
459                         loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
460                 } else {
461                         // Account is locked or unconfirmed
462                         $errorCode = generateErrorCodeFromUserStatus($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                 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
470         }
471
472         // Return the error code
473         return $errorCode;
474 }
475
476 // [EOF]
477 ?>