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