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