More rewrites/templates swapped out:
[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(',', 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 (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 = getMessage('_ALL2');
105
106         // Prepare array with all possible sorters
107         $list = array(
108                 'userid'      => getMessage('_UID'),
109                 'family'      => getMessage('FAMILY'),
110                 'email'       => getMessage('EMAIL'),
111                 'REMOTE_ADDR' => getMessage('REMOTE_IP')
112         );
113
114         // Add nickname if extension is installed
115         if (isExtensionActive('nickname')) {
116                 $list['nickname'] = getMessage('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 ($pages, $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 <= $pages; $page++) {
159                 if (($page == getRequestParameter('page')) || ((!isGetRequestParameterSet('page')) && ($page == 1))) {
160                         $OUT .= '<strong>-';
161                 } else {
162                         if (!isGetRequestParameterSet('letter')) setGetRequestParameter('letter', getMessage('_ALL2'));
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 < $pages) $OUT .= '|';
185         } // END - for
186
187         // Remember the list
188         $content['list'] = $OUT;
189
190         // Load template
191         $OUT = loadTemplate('admin_list_user_pagenav', true, $content);
192         if ($return === true) {
193                 // Return code
194                 return $OUT;
195         } else {
196                 // Output code
197                 outputHtml($OUT);
198         }
199 }
200
201 // Create email link to user's account
202 function generateUserEmailLink($email, $mod = 'admin') {
203         // Show contact link only if user is confirmed by default
204         $locked = " AND `status`='CONFIRMED'";
205
206         // But admins shall always see it
207         if (isAdmin()) $locked = '';
208
209         $result = SQL_QUERY_ESC("SELECT
210         `userid`
211 FROM
212         `{?_MYSQL_PREFIX?}_user_data`
213 WHERE
214         `email`='%s'" . $locked."
215 LIMIT 1",
216                 array($email), __FUNCTION__, __LINE__);
217         if (SQL_NUMROWS($result) == 1) {
218                 // Load userid
219                 list($userid) = SQL_FETCHROW($result);
220
221                 // Rewrite email address to contact link
222                 $email = '{%url=modules.php?module=' . $mod . '&amp;what=user_contct&amp;userid=' . bigintval($userid) . '%}';
223         } // END - if
224
225         // Free memory
226         SQL_FREERESULT($result);
227
228         // Return rewritten (?) email address
229         return $email;
230 }
231
232 // Selects a random user id as the new referal id if they have at least X confirmed mails in this run
233 // @TODO Double-check configuration entry here
234 function determineRandomReferalId () {
235         // Default is zero refid
236         $refid = '0';
237
238         // Is the extension version fine?
239         if (isExtensionInstalledAndNewer('user', '0.3.4')) {
240                 // Get all user ids
241                 $totalUsers = countSumTotalData('CONFIRMED', 'user_data', 'userid', 'status', true, " AND `rand_confirmed` >= {?user_min_confirmed?}");
242
243                 // Do we have at least one?
244                 if ($totalUsers > 0) {
245                         // Then choose random number
246                         $randNum = mt_rand(0, ($totalUsers - 1));
247
248                         // Look for random user
249                         $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",
250                                 array($randNum), __FUNCTION__, __LINE__);
251
252                         // Do we have one entry there?
253                         if (SQL_NUMROWS($result) == 1) {
254                                 // Use that userid as new referal id
255                                 list($refid) = SQL_FETCHROW($result);
256
257                                 // Reset this user's counter
258                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0 WHERE `userid`=%s LIMIT 1",
259                                         array($refid), __FUNCTION__, __LINE__);
260                         } // END - if
261
262                         // Free result
263                         SQL_FREERESULT($result);
264                 } // END - if
265         } // END - if
266
267         // Return result
268         return $refid;
269 }
270
271 // Do the user login
272 function doUserLogin ($userid, $passwd, $successUrl = '', $errorUrl = 'modules.php?module=index&amp;what=login&amp;login=') {
273         // Init variables
274         $dmy = '';
275         $add = '';
276         $errorCode = '0';
277         $ext = '';
278
279         // Init array
280         $content = array(
281                 'password'    => '',
282                 'userid'      => '',
283                 'last_online' => 0,
284                 'last_login'  => 0,
285                 'hash'        => ''
286         );
287
288         // Check login data
289         if ((isExtensionActive('nickname')) && (isNicknameUsed($userid))) {
290                 // Nickname entered
291                 fetchUserData($userid, 'nickname');
292         } elseif (isNicknameUsed($userid)) {
293                 // No nickname installed
294                 $errorCode = getCode('EXTENSION_PROBLEM');
295                 $ext = 'nickname';
296         } else {
297                 // Direct userid entered
298                 fetchUserData($userid);
299         }
300
301         // No error found?
302         if ($errorCode == '0') {
303                 // Get user data array and set userid (e.g. important if we login with nickname)
304                 $content = getUserDataArray();
305                 if (!empty($content['userid'])) $userid = bigintval($content['userid']);
306         } // END - if
307
308         // Is there an entry?
309         if ((isUserDataValid()) && (getUserData('status') == 'CONFIRMED') && (!empty($content['userid']))) {
310                 // Check for old MD5 passwords
311                 if ((strlen(getUserData('password')) == 32) && (md5($passwd) == getUserData('password'))) {
312                         // Just set the hash to the password from DB... :)
313                         $content['hash'] = getUserData('password');
314                 } else {
315                         // Hash password with improved way for comparsion
316                         $content['hash'] = generateHash($passwd, substr(getUserData('password'), 0, -40));
317                 }
318
319                 // Does the password match the hash?
320                 if ($content['hash'] == getUserData('password')) {
321                         // New hashed password found so let's generate a new one
322                         $content['hash'] = generateHash($passwd);
323
324                         // ... and update database
325                         // @TODO Make this filter working: $ADDON = runFilterChain('post_login_update', $content);
326                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s AND `status`='CONFIRMED' LIMIT 1",
327                                 array($content['hash'], $userid), __FUNCTION__, __LINE__);
328
329                         // No login bonus by default
330                         $GLOBALS['bonus_payed'] = false;
331
332                         // Probe for last online timemark
333                         $probe = time() -  getUserData('last_online');
334                         if (getUserData('last_login') > 0) $probe = time() - getUserData('last_login');
335
336                         if ((isExtensionInstalledAndNewer('bonus', '0.2.2')) && ($probe >= getConfig('login_timeout'))) {
337                                 // Add login bonus to user's account
338                                 $add = ', `login_bonus`=`login_bonus`+{?login_bonus?}';
339                                 $GLOBALS['bonus_payed'] = true;
340
341                                 // Subtract login bonus from userid's account or jackpot
342                                 if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getConfig('bonus_mode') != 'ADD')) handleBonusPoints('login_bonus');
343                         } // END - if
344
345                         // @TODO Make this filter working: $url = runFilterChain('do_login', array('content' => $content, 'addon' => $ADDON));
346
347                         // Set member id
348                         setMemberId($userid);
349
350                         // Try to set session data (which shall normally always work!)
351                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',hash=' . $content['hash'] . '(' . strlen($content['hash']) . ')');
352                         if ((setSession('userid', $userid )) && (setSession('u_hash', encodeHashForCookie($content['hash'])))) {
353                                 // Update database records
354                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `total_logins`=`total_logins`+1" . $add . " WHERE `userid`=%s LIMIT 1",
355                                         array($userid), __FUNCTION__, __LINE__);
356                                 if (SQL_AFFECTEDROWS() == 1) {
357                                         // Is a success URL set?
358                                         if (empty($successUrl)) {
359                                                 // Procedure to checking for login data
360                                                 if (($GLOBALS['bonus_payed'] === true) && (isExtensionActive('bonus'))) {
361                                                         // Bonus added (just displaying!)
362                                                         $url = 'modules.php?module=chk_login&amp;mode=bonus';
363                                                 } else {
364                                                         // Bonus not added
365                                                         $url = 'modules.php?module=chk_login&amp;mode=login';
366                                                 }
367                                         } else {
368                                                 // Use this URL
369                                                 $url = $successUrl;
370                                         }
371                                 } else {
372                                         // Cannot update counter!
373                                         $errorCode = getCode('CNTR_FAILED');
374                                 }
375                         } else {
376                                 // Cookies not setable!
377                                 $errorCode = getCode('COOKIES_DISABLED');
378                         }
379                 } elseif (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
380                         // Update failture counter
381                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `login_failures`=`login_failures`+1,`last_failure`=NOW() WHERE `userid`=%s LIMIT 1",
382                                 array($userid), __FUNCTION__, __LINE__);
383
384                         // Wrong password!
385                         $errorCode = getCode('WRONG_PASS');
386                 }
387         } elseif (getUserData('status') != 'CONFIRMED') {
388                 // Create an error code from given status
389                 $errorCode = generateErrorCodeFromUserStatus(getUserData('status'));
390
391                 // Set userid in session
392                 setSession('current_userid', getUserData('userid'));
393         } elseif (!isUserDataValid()) {
394                 // User id not found!
395                 $errorCode = getCode('WRONG_ID');
396         } else {
397                 // Unknown error
398                 $errorCode = getCode('UNKNOWN_ERROR');
399         }
400
401         // Error code provided?
402         if ($errorCode > 0) {
403                 // Then reconstruct the URL
404                 $url = $errorUrl . $errorCode;
405
406                 // Extension set? Then add it as well.
407                 if (!empty($ext)) $url .= '&amp;ext=' . $ext;
408         } // END - if
409
410         // Return URL
411         return $url;
412 }
413
414 // Try to send a new password for the given user account
415 function doNewUserPassword ($email, $userid) {
416         // Init result and error
417         $errorCode = '';
418         $result = false;
419
420         // Probe userid/nickname
421         // @TODO We should try to rewrite this to fetchUserData() somehow
422         if (!empty($email)) {
423                 // Email entered
424                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `email`='%s' OR `email`='%s' LIMIT 1",
425                         array($email, str_replace('.', '{DOT}', $email)), __FUNCTION__, __LINE__);
426         } elseif ((isExtensionActive('nickname')) && (isNicknameOrUserid($userid))) {
427                 // Nickname entered
428                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `nickname`='%s' OR `userid`='%s' OR `email`='%s' LIMIT 1",
429                         array($userid, $userid, $email), __FUNCTION__, __LINE__);
430         } elseif (($userid > 0) && (empty($email))) {
431                 // Direct userid entered
432                 $result = SQL_QUERY_ESC("SELECT `userid`, `status` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
433                         array(bigintval($userid)), __FUNCTION__, __LINE__);
434         } else {
435                 // Userid not set!
436                 logDebugMessage(__FUNCTION__, __LINE__, 'Userid is not set! BUG!');
437                 $errorCode = getCode('WRONG_ID');
438         }
439
440         // Any entry found?
441         if (SQL_NUMROWS($result) == 1) {
442                 // This data is valid, so we create a new pass... :-)
443                 list($userid, $status) = SQL_FETCHROW($result);
444
445                 if ($status == 'CONFIRMED') {
446                         // Ooppps, this was missing! ;-) We should update the database...
447                         $NEW_PASS = generatePassword();
448                         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `password`='%s' WHERE `userid`=%s LIMIT 1",
449                                 array(generateHash($NEW_PASS), $userid), __FUNCTION__, __LINE__);
450
451                         // Prepare data and message for email
452                         $message = loadEmailTemplate('new-pass', array('new_pass' => $NEW_PASS, 'nickname' => $userid), $userid);
453
454                         // ... and send it away
455                         sendEmail($userid, getMessage('GUEST_NEW_PASSWORD'), $message);
456
457                         // Output note to user
458                         loadTemplate('admin_settings_saved', false, getMessage('GUEST_NEW_PASSWORD_SEND'));
459                 } else {
460                         // Account is locked or unconfirmed
461                         $errorCode = generateErrorCodeFromUserStatus($status);
462
463                         // Load URL
464                         redirectToUrl('modules.php?module=index&amp;what=login&amp;login='.$errorCode);
465                 }
466         } else {
467                 // id or email is wrong
468                 loadTemplate('admin_settings_saved', false, '<span class="guest_failed">{--GUEST_WRONG_ID_EMAIL--}</span>');
469         }
470
471         // Return the error code
472         return $errorCode;
473 }
474
475 // Get timestamp for given stats type and data
476 function getTimestampFromUserStats ($statsType, $statsData, $userid = '0') {
477         // Default timestamp is zero
478         $data['inserted'] = '0';
479
480         // User id set?
481         if ((isMemberIdSet()) && ($userid == '0')) {
482                 $userid = getMemberId();
483         } // END - if
484
485         // Is the extension installed and updated?
486         if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
487                 // Return zero here
488                 return $data['inserted'];
489         } // END - if
490
491         // Try to find the entry
492         $result = SQL_QUERY_ESC("SELECT
493         UNIX_TIMESTAMP(`inserted`) AS inserted
494 FROM
495         `{?_MYSQL_PREFIX?}_user_stats_data`
496 WHERE
497         `userid`=%s AND
498         `stats_type`='%s' AND
499         `stats_data`='%s'
500 LIMIT 1",
501                 array(
502                         bigintval($userid),
503                         $statsType,
504                         $statsData
505                 ), __FUNCTION__, __LINE__);
506
507         // Is the entry there?
508         if (SQL_NUMROWS($result) == 1) {
509                 // Get this stamp
510                 $data = SQL_FETCHARRAY($result);
511         } // END - if
512
513         // Free result
514         SQL_FREERESULT($result);
515
516         // Return stamp
517         return $data['inserted'];
518 }
519
520 // Inserts user stats
521 function insertUserStatsRecord ($userid, $statsType, $statsData) {
522         // Is the extension installed and updated?
523         if ((!isExtensionActive('sql_patches')) || (isExtensionOlder('sql_patches', '0.5.6'))) {
524                 // Return zero here
525                 return false;
526         } // END - if
527
528         // Does it exist?
529         if ((!getTimestampFromUserStats($statsType, $statsData, $userid)) && (!is_array($statsData))) {
530                 // Then insert it!
531                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_stats_data` (`userid`,`stats_type`,`stats_data`) VALUES (%s,'%s','%s')",
532                         array(bigintval($userid), $statsType, $statsData), __FUNCTION__, __LINE__);
533         } elseif (is_array($statsData)) {
534                 // Invalid data!
535                 logDebugMessage(__FUNCTION__, __LINE__, "userid={$userid},type={$statsType},data={".gettype($statsData).": Invalid statistics data type!");
536         }
537 }
538
539 // [EOF]
540 ?>