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