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