More globals rewritten, see ticket #100
[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 - 2008 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         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
42         require($INC);
43 }
44
45 // Add links for selecting some users
46 function alpha ($sortby, $colspan, $return=false) {
47         if (!REQUEST_ISSET_GET(('offset'))) REQUEST_SET_GET('offset', 0);
48         $add = "&amp;page=".REQUEST_GET(('page'))."&amp;offset=".REQUEST_GET(('offset'));
49         if (REQUEST_ISSET_GET(('mode'))) $add .= "&amp;mode=".REQUEST_GET(('mode'));
50
51         /* Creates the list of letters and makes them a link. */
52         $alphabet = array(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'));
53         $num = count($alphabet) - 1;
54         $OUT = "";
55         while (list($counter, $ltr) = each($alphabet)) {
56                 if (REQUEST_GET('letter') == $ltr) {
57                         // Current letter is letter from URL
58                         $OUT .= "<strong>".$ltr."</strong>";
59                 } else {
60                         // Output link to letter
61                         $OUT .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$GLOBALS['what'];
62                         if (REQUEST_ISSET_GET(('mode'))) $OUT .= "&amp;mode=".REQUEST_GET(('mode'));
63                         $OUT .= "&amp;letter=".$ltr."&amp;sortby=".$sortby.$add."\">".$ltr."</a>";
64                 }
65
66                 if ((($counter / getConfig('user_alpha')) == round($counter / getConfig('user_alpha'))) && ($counter > 0)) {
67                         $OUT .= "&nbsp;]<br />[&nbsp;";
68                 } elseif ( $counter != $num ) {
69                         $OUT .= "&nbsp;|&nbsp;";
70                 }
71         } // END - while
72
73         define('__ALPHA_LIST', $OUT);
74
75         // Load template
76         $OUT = LOAD_TEMPLATE("admin_list_user_alpha", true);
77         if ($return === true) {
78                 // Return generated code
79                 return $OUT;
80         } else {
81                 // Output generated code
82                 OUTPUT_HTML($OUT);
83         }
84 }
85
86 // Add links for sorting
87 function SortLinks ($letter, $sortby, $colspan, $return=false) {
88         $OUT = "";
89         if (!REQUEST_ISSET_GET(('offset'))) REQUEST_SET_GET('offset', 0);
90         if (!REQUEST_ISSET_GET(('page')))   REQUEST_SET_GET('page'  , 0);
91
92         // Add page and offset
93         $add = "&amp;page=".REQUEST_GET(('page'))."&amp;offset=".REQUEST_GET(('offset'));
94
95         // Add status or mode
96         if (REQUEST_ISSET_GET(('status'))) $add .= "&amp;mode=".REQUEST_GET(('status'));
97          elseif (REQUEST_ISSET_GET(('mode'))) $add .= "&amp;mode=".REQUEST_GET(('mode'));
98
99         // Makes order by links..
100         if ($letter == "front") $letter = getMessage('_ALL2');
101
102         // Prepare array with all possible sorters
103         $list = array(
104                 'userid'                => getMessage('_UID'),
105                 'family'                => getMessage('FAMILY_NAME'),
106                 'email'         => getMessage('ADDY'),
107                 'REMOTE_ADDR'   => getMessage('REMOTE_IP')
108         );
109
110         // Add nickname if extension is installed
111         if (EXT_IS_ACTIVE("nickname")) {
112                 $list['nickname'] = getMessage('NICKNAME');
113         } // END - if
114
115         foreach ($list as $sort => $title) {
116                 if ($sortby == $sort) {
117                         $OUT .= "<strong>".$title."</strong>&nbsp;|&nbsp;";
118                 } else {
119                         $OUT .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=list_user&amp;letter=".$letter."&amp;sortby=".$sort.$add."\">".$title."</a>&nbsp;|&nbsp;";
120                 }
121         } // END - foreach
122
123         define('__SORT_LIST', substr($OUT, 0, -13));
124
125         // Load template
126         $OUT = LOAD_TEMPLATE("admin_list_user_sort", true);
127         if ($return === true) {
128                 // Return code
129                 return $OUT;
130         } else {
131                 // Output code
132                 OUTPUT_HTML($OUT);
133         }
134 }
135
136 // Add page navigation
137 function ADD_PAGENAV ($PAGES, $offset, $show_form, $colspan,$return=false) {
138         if (!$show_form) {
139                 // Empty row
140                 define('__FORM_HEADER', "<tr><td colspan=\"".$colspan."\" class=\"seperator\">&nbsp;</td></tr>");
141         } else {
142                 // Load form for changing number of lines
143                 define('__FORM_HEADER', LOAD_TEMPLATE("admin_list_user_sort_form", true));
144         }
145
146         if (!$show_form) {
147                 // Add line with bottom border
148                 define('__FORM_FOOTER', "<tr><td colspan=\"{!__COLSPAN2!}\" class=\"seperator bottom2\">&nbsp;</td></tr>");
149         } else {
150                 // Add line without bottom border
151                 define('__FORM_FOOTER', "<tr><td colspan=\"{!__COLSPAN2!}\" class=\"seperator bottom2\">&nbsp;</td></tr>");
152         }
153
154         $OUT = "";
155         for ($page = 1; $page <= $PAGES; $page++) {
156                 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
157                         $OUT .= "<strong>-";
158                 } else {
159                         if (!REQUEST_ISSET_GET(('letter'))) REQUEST_SET_GET('letter', getMessage('_ALL2'));
160                         if (!REQUEST_ISSET_GET(('sortby'))) REQUEST_SET_GET('sortby', "userid");
161
162                         // Base link
163                         $OUT .= "<a href=\"{!URL!}/modules.php?module=admin&amp;what=".$GLOBALS['what'];
164
165                         // Add status or mode
166                         if (REQUEST_ISSET_GET(('status'))) $OUT .= "&amp;mode=".REQUEST_GET(('status'));
167                          elseif (REQUEST_ISSET_GET(('mode'))) $OUT .= "&amp;mode=".REQUEST_GET(('mode'));
168
169                          // Letter and so on
170                         $OUT .= "&amp;letter=".REQUEST_GET(('letter'))."&amp;sortby=".REQUEST_GET(('sortby'))."&amp;page=".$page."&amp;offset=".$offset."\">";
171                 }
172
173                 $OUT .= $page;
174
175                 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
176                         $OUT .= "-</strong>";
177                 } else  {
178                         $OUT .= "</a>";
179                 }
180
181                 if ($page < $PAGES) $OUT .= "&nbsp;|&nbsp;";
182         } // END - for
183
184         define('__PAGENAV_LIST', $OUT);
185
186         // Load template
187         $OUT = LOAD_TEMPLATE("admin_list_user_pagenav", true);
188         if ($return === true) {
189                 // Return code
190                 return $OUT;
191         } else {
192                 // Output code
193                 OUTPUT_HTML($OUT);
194         }
195 }
196
197 // Create email link to user's account
198 function USER_CREATE_EMAIL_LINK($email, $mod="admin") {
199         // Show contact link only if user is confirmed by default
200         $locked = " AND `status`='CONFIRMED'";
201
202         // But admins shall always see it
203         if (IS_ADMIN()) $locked = "";
204
205         $result = SQL_QUERY_ESC("SELECT userid
206 FROM `{!_MYSQL_PREFIX!}_user_data`
207 WHERE `email`='%s'".$locked." LIMIT 1",
208          array($email), __FUNCTION__, __LINE__);
209         if (SQL_NUMROWS($result) == 1) {
210                 // Load userid
211                 list($uid) = SQL_FETCHROW($result);
212
213                 // Rewrite email address to contact link
214                 $email = "{!URL!}/modules.php?module=".$mod."&amp;what=user_contct&amp;uid=".bigintval($uid);
215         } // END - if
216
217         // Free memory
218         SQL_FREERESULT($result);
219
220         // Return rewritten (?) email address
221         return $email;
222 }
223
224 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
225 function SELECT_RANDOM_REFID () {
226         // Default is zero refid
227         $refid = 0;
228
229         // Is the extension version fine?
230         if (GET_EXT_VERSION("user") >= "0.3.4") {
231                 // Get all user ids
232                 $totalUsers = GET_TOTAL_DATA("CONFIRMED", "user_data", "userid", "status", true, " AND `rand_confirmed` >= ".getConfig('user_min_confirmed')."");
233
234                 // Do we have at least one?
235                 if ($totalUsers > 0) {
236                         // Then choose random number
237                         $randNum = mt_rand(0, ($totalUsers - 1));
238
239                         // Look for random user
240                         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `status`='CONFIRMED' AND `rand_confirmed` >= %s ORDER BY `rand_confirmed` DESC LIMIT %s, 1",
241                                 array(getConfig('user_min_confirmed'), $randNum), __FUNCTION__, __LINE__);
242
243                         // Do we have one entry there?
244                         if (SQL_NUMROWS($result) == 1) {
245                                 // Use that userid as new referal id
246                                 list($refid) = SQL_FETCHROW($result);
247
248                                 // Reset this user's counter
249                                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `rand_confirmed`=0 WHERE userid=%s LIMIT 1",
250                                         array($refid), __FUNCTION__, __LINE__);
251                         } // END - if
252
253                         // Free result
254                         SQL_FREERESULT($result);
255                 } // END - if
256         } // END - if
257
258         // Return result
259         return $refid;
260 }
261
262 // Do the user login
263 function USER_DO_LOGIN ($uid, $passwd) {
264         // Init variables
265         $dmy = "";
266
267         // Add last_login if available
268         $lastOnline = ""; 
269         if (GET_EXT_VERSION("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 ((EXT_IS_ACTIVE("nickname")) && (NICKNAME_PROBE_ON_USERID($uid))) {
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($uid), __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($uid, $content['hash']), __FUNCTION__, __LINE__);
291         }
292
293         // Load entry
294         $content = SQL_FETCHARRAY($result);
295         if (!empty($content['userid'])) $uid = bigintval($content['userid']);
296
297         // Is there an entry?
298         if ((SQL_NUMROWS($result) == 1) && ((($probe_nickname) && (!empty($content['userid']))) || ($content['userid'] == $uid))) {
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'], $uid), __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 ((GET_EXT_VERSION("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 ((GET_EXT_VERSION("bonus") >= "0.3.5") && (getConfig('bonus_mode') != "ADD")) BONUS_POINTS_HANDLER('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($uid);
344
345                         // Try to set session data (which shall normally always work!)
346                         if ((set_session('userid', $uid )) && (set_session('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($uid), __FUNCTION__, __LINE__);
350                                 if (SQL_AFFECTEDROWS() == 1) {
351                                         // Procedure to checking for login data
352                                         if (($GLOBALS['bonus_payed']) && (EXT_IS_ACTIVE("bonus"))) {
353                                                 // Bonus added (just displaying!)
354                                                 $URL = "modules.php?module=chk_login&amp;mode=bonus";
355                                         } else {
356                                                 // Bonus not added
357                                                 $URL = "modules.php?module=chk_login&amp;mode=login";
358                                         }
359                                 } else {
360                                         // Cannot update counter!
361                                         $URL = "modules.php?module=index&amp;what=login&amp;login=".getCode('CNTR_FAILED');
362                                 }
363                         } else {
364                                 // Cookies not setable!
365                                 $URL = "modules.php?module=index&amp;what=login&amp;login=".getCode('NO_COOKIES');
366                         }
367                 } elseif (GET_EXT_VERSION("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($uid), __FUNCTION__, __LINE__);
371
372                         // Wrong password!
373                         $URL = "modules.php?module=index&amp;what=login&amp;login=".getCode('WRONG_PASS');
374                 }
375         } elseif ((($probe_nickname) && (!empty($content['userid']))) || ($content['userid'] == $uid)) {
376                 // Other account status?
377                 // @TODO Can this query be merged with above query?
378                 $result = SQL_QUERY_ESC("SELECT status FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
379                         array($uid), __FUNCTION__, __LINE__);
380
381                 // Entry found?
382                 if (SQL_NUMROWS($result) == 1) {
383                         // Load status
384                         list($status) = SQL_FETCHROW($result);
385
386                         // Create an error code from given status
387                         $errorCode = GEN_ERROR_CODE_FROM_ACCOUNT_STATUS($status);
388                 } else {
389                         // ID not found!
390                         $errorCode = getCode('WRONG_ID');
391                 }
392
393                 // Construct URL
394                 $URL = "modules.php?module=index&amp;what=login&amp;login=".$errorCode;
395         } else {
396                 // ID not found!
397                 $URL = "modules.php?module=index&amp;what=login&amp;login=".getCode('WRONG_ID');
398         }
399
400         // Return URL
401         return $URL;
402 }
403
404 // Try to send a new password for the given user account
405 function USER_DO_NEW_PASSWORD ($email, $uid) {
406         // Compile email when found in address (only secure chars!)
407         if (!empty($email)) $email = str_replace("{DOT}", '.', $email);
408
409         // Init result and error
410         $errorCode = "";
411         $result = false;
412
413         // Probe userid/nickname
414         if ((EXT_IS_ACTIVE("nickname")) && (NICKNAME_PROBE_ON_USERID($uid))) {
415                 // Nickname entered
416                 $result = SQL_QUERY_ESC("SELECT userid, status FROM `{!_MYSQL_PREFIX!}_user_data` WHERE nickname='%s' OR email='%s' LIMIT 1",
417                         array($uid, $email), __FUNCTION__, __LINE__);
418         } elseif (($uid > 0) && (empty($email))) {
419                 // Direct userid entered
420                 $result = SQL_QUERY_ESC("SELECT userid, status FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
421                         array(bigintval($uid)), __FUNCTION__, __LINE__);
422         } elseif (!empty($email)) {
423                 // Email entered
424                 $result = SQL_QUERY_ESC("SELECT userid, status FROM `{!_MYSQL_PREFIX!}_user_data` WHERE email='%s' LIMIT 1",
425                         array($email), __FUNCTION__, __LINE__);
426         } else {
427                 // Userid not set!
428                 DEBUG_LOG(__FUNCTION__, __LINE__, "Userid is not set! BUG!");
429                 $errorCode = getCode('WRONG_ID');
430         }
431
432         // Any entry found?
433         if (SQL_NUMROWS($result) == 1) {
434                 // This data is valid, so we create a new pass... :-)
435                 list($uid, $status) = SQL_FETCHROW($result);
436
437                 if ($status == "CONFIRMED") {
438                         // Ooppps, this was missing! ;-) We should update the database...
439                         $NEW_PASS = GEN_PASS();
440                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET password='%s' WHERE userid=%s LIMIT 1",
441                                 array(generateHash($NEW_PASS), $uid), __FUNCTION__, __LINE__);
442
443                         // Prepare data and message for email
444                         $msg = LOAD_EMAIL_TEMPLATE("new-pass", array('new_pass' => $NEW_PASS), $uid);
445
446                         // ... and send it away
447                         SEND_EMAIL($uid, getMessage('GUEST_NEW_PASSWORD'), $msg);
448
449                         // Output note to user
450                         LOAD_TEMPLATE("admin_settings_saved", false, getMessage('GUEST_NEW_PASSWORD_SEND'));
451                 } else {
452                         // Account is locked or unconfirmed
453                         $errorCode = GEN_ERROR_CODE_FROM_ACCOUNT_STATUS($status);
454
455                         // Load URL
456                         LOAD_URL("modules.php?module=index&amp;what=login&amp;login=".$errorCode);
457                 }
458         } else {
459                 // ID or email is wrong
460                 LOAD_TEMPLATE("admin_settings_saved", false, "<span class=\"guest_failed\">{--GUEST_WRONG_ID_EMAIL--}</span>");
461         }
462
463         // Return the error code
464         return $errorCode;
465 }
466
467 // [EOF]
468 ?>