9ab8d984f3853504d2f3973a7cd65c80a6d1caed
[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 = '';
265         $add = '';
266         $errorCode = 0;
267
268         // Add last_login if available
269         $lastOnline = '';
270         if (getExtensionVersion('sql_patches') >= '0.2.8') {
271                 $lastOnline = ', `last_login`';
272         } // END - if
273
274         // Init array
275         $content = array(
276                 'password'    => '',
277                 'userid'      => '',
278                 'last_online' => 0,
279                 'last_login'  => 0,
280                 'hash'        => ''
281         );
282
283         // Check login data
284         if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
285                 // Nickname entered
286                 fetchUserData($userid, 'nickname');
287         } else {
288                 // Direct userid entered
289                 fetchUserData($userid);
290         }
291
292         // Load entry
293         $content = getUserDataArray();
294         if (!empty($content['userid'])) $userid = bigintval($content['userid']);
295
296         // Is there an entry?
297         if ((isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && ((isNicknameUsed($content['userid'] === true) && (!empty($content['userid']))) || ($content['userid'] == $userid))) {
298                 // Check for old MD5 passwords
299                 if ((strlen($content['password']) == 32) && (md5($passwd) == $content['password'])) {
300                         // Just set the hash to the password from DB... :)
301                         $content['hash'] = $content['password'];
302                 } else {
303                         // Hash password with improved way for comparsion
304                         $content['hash'] = generateHash($passwd, substr($content['password'], 0, -40));
305                 }
306
307                 // Does the password match the hash?
308                 if ($content['hash'] == $content['password']) {
309                         // New hashed password found so let's generate a new one
310                         $content['hash'] = generateHash($passwd);
311
312                         // ... and update database
313                         // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
314                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
315                                 array($content['hash'], $userid), __FUNCTION__, __LINE__);
316
317                         // No login bonus by default
318                         $GLOBALS['bonus_payed'] = false;
319
320                         // Probe for last online timemark
321                         $probe = time() -  $content['last_online'];
322                         if (!empty($content['last_login'])) $probe = time() - $content['last_login'];
323                         if ((getExtensionVersion('bonus') >= '0.2.2') && ($probe >= getConfig('login_timeout'))) {
324                                 // Add login bonus to user's account
325                                 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
326                                 $GLOBALS['bonus_payed'] = true;
327
328                                 // Subtract login bonus from userid's account or jackpot
329                                 if ((getExtensionVersion('bonus') >= '0.3.5') && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
330                         } // END - if
331
332                         // Calculate new hash with the secret key and master salt together
333                         $content['hash'] = generatePassString($content['hash']);
334
335                         // Update global array
336                         // @TODO Make this filter working: $URL = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
337                         setMemberId($userid);
338
339                         // Try to set session data (which shall normally always work!)
340                         if ((setSession('userid', $userid )) && (setSession('u_hash', $content['hash']))) {
341                                 // Update database records
342                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
343                                         array($userid), __FUNCTION__, __LINE__);
344                                 if (SQL_AFFECTEDROWS() == 1) {
345                                         // Is a success URL set?
346                                         if (empty($successUrl)) {
347                                                 // Procedure to checking for login data
348                                                 if (($GLOBALS['bonus_payed']) && (isExtensionActive('bonus'))) {
349                                                         // Bonus added (just displaying!)
350                                                         $URL = 'modules.php?module=chk_login&amp;mode=bonus';
351                                                 } else {
352                                                         // Bonus not added
353                                                         $URL = 'modules.php?module=chk_login&amp;mode=login';
354                                                 }
355                                         } else {
356                                                 // Use this URL
357                                                 $URL = $successUrl;
358                                         }
359                                 } else {
360                                         // Cannot update counter!
361                                         $errorCode = getCode('CNTR_FAILED');
362                                 }
363                         } else {
364                                 // Cookies not setable!
365                                 $errorCode = getCode('NO_COOKIES');
366                         }
367                 } elseif (getExtensionVersion('sql_patches') >= '0.6.1') {
368                         // Update failture counter
369                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
370                                 array($userid), __FUNCTION__, __LINE__);
371
372                         // Wrong password!
373                         $errorCode = getCode('WRONG_PASS');
374                 }
375         } elseif (((isNicknameUsed($content['userid'])) && (!empty($content['userid']))) || ($content['userid'] == $userid)) {
376                 // Other account status?
377                 if (fetchUserData($userid)) {
378                         // Create an error code from given status
379                         $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
380                 } else {
381                         // id not found!
382                         $errorCode = getCode('WRONG_ID');
383                 }
384         } else {
385                 // id not found!
386                 $errorCode = getCode('WRONG_ID');
387         }
388
389         // Error code provided?
390         if ($errorCode > 0) {
391                 // Then reconstruct the URL
392                 $URL = $errorUrl . $errorCode;
393         } // END - if
394
395         // Return URL
396         return $URL;
397 }
398
399 // Try to send a new password for the given user account
400 function doNewUserPassword ($email, $userid) {
401         // Compile email when found in address (only secure chars!)
402         if (!empty($email)) $email = str_replace('{DOT}', '.', $email);
403
404         // Init result and error
405         $errorCode = '';
406         $result = false;
407
408         // Probe userid/nickname
409         // @TODO We should try to rewrite this to fetchUserData() somehow
410         if ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
411                 // Nickname entered
412                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
413                         array($userid, $userid, $email), __FUNCTION__, __LINE__);
414         } elseif (($userid > 0) && (empty($email))) {
415                 // Direct userid entered
416                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
417                         array(bigintval($userid)), __FUNCTION__, __LINE__);
418         } elseif (!empty($email)) {
419                 // Email entered
420                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' LIMIT 1",
421                         array($email), __FUNCTION__, __LINE__);
422         } else {
423                 // Userid not set!
424                 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
425                 $errorCode = getCode('WRONG_ID');
426         }
427
428         // Any entry found?
429         if (SQL_NUMROWS($result) == 1) {
430                 // This data is valid, so we create a new pass... :-)
431                 list($userid, $status) = SQL_FETCHROW($result);
432
433                 if ($status == 'CONFIRMED') {
434                         // Ooppps, this was missing! ;-) We should update the database...
435                         $NEW_PASS = generatePassword();
436                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
437                                 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
438
439                         // Prepare data and message for email
440                         $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
441
442                         // ... and send it away
443                         sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
444
445                         // Output note to user
446                         loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
447                 } else {
448                         // Account is locked or unconfirmed
449                         $errorCode = generateErrorCodeFromUserStatus($status);
450
451                         // Load URL
452                         redirectToUrl('modules.php?module=index&amp;what=login&amp;login='.$errorCode);
453                 }
454         } else {
455                 // id or email is wrong
456                 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
457         }
458
459         // Return the error code
460         return $errorCode;
461 }
462
463 // [EOF]
464 ?>