Fixes for member registration (IP lock) and rewrites for remote IP address
[mailer.git] / inc / libs / register_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/10/2004 *
4  * ===================                          Last change: 07/10/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : register_functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : Special functions for register extension         *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Spezielle Funktion fuer register-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 }
44
45 //
46 function ifRequiredRegisterFieldsAreSet (&$array) {
47         // By default all is fine
48         $ret = true;
49         foreach ($array as $key => $value) {
50                 // Check all fields that must register
51                 $result = SQL_QUERY("SELECT `id` FROM `{?_MYSQL_PREFIX?}_must_register` WHERE `field_name`='".$key."' AND `field_required`='Y' LIMIT 1",
52                         __FUNCTION__, __LINE__);
53                 if (SQL_NUMROWS($result) == 1) {
54                         // Check if extension country is not found (you have to enter the 2-chars long country code) or
55                         // if extensions is present check if country code was selected
56                         //         01              2         21    12             3         32    234     5      54    4               43    34                      4    4      5      5432    2      3                      3210
57                         $country = ((!isExtensionActive('country')) || ((isExtensionActive('country')) && (((empty($value)) && ($key == 'cntry')) || (($key == 'country_code') && (!empty($value)))) && (!empty($array['country_code']))));
58                         if ((empty($value)) && ($country === false)) {
59                                 // Required field not set
60                                 $array[$key] = '!';
61                                 $ret = false;
62                         } // END - if
63                 } // END - if
64
65                 // Free result
66                 SQL_FREERESULT($result);
67         } // END - foreach
68
69         // Return result
70         return $ret;
71 }
72
73 // Generates a 'category table' for the registration form
74 function registerGenerateCategoryTable ($mode, $return=false) {
75         $OUT = '';
76
77         // Guests are mostly not interested in how many members has
78         // choosen an individual category
79         $AND = "WHERE `visible`='Y' ";
80
81         // Admins are allowed to see every category...
82         if (isAdmin()) $AND = '';
83
84         // Look for categories
85         $result = SQL_QUERY("SELECT `id`, `cat`, `visible` FROM `{?_MYSQL_PREFIX?}_cats` ".$AND." ORDER BY `sort` ASC",
86                 __FUNCTION__, __LINE__);
87
88         if (SQL_NUMROWS($result) > 0) {
89                 // List alle visible modules (or all to the admin)
90                 $SW = 2;
91                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
92                 while ($content = SQL_FETCHARRAY($result)) {
93                         // Prepare array for the template
94                         $content = array(
95                                 'sw'    => $SW,
96                                 'cat'   => $content['cat'],
97                                 'def_y' => '',
98                                 'def_n' => '',
99                                 'id'    => $content['id'],
100                         );
101
102                         // Mark categories
103                         if ((postRequestParameter('cat', $content['id']) == 'Y') || ((getConfig('register_default') == 'Y') && (!isPostRequestParameterSet('cat', $content['id'])))) {
104                                 $content['def_y'] = ' checked="checked"';
105                         } else {
106                                 $content['def_n'] = ' checked="checked"';
107                         }
108
109                         // Load template and switch color
110                         $OUT .= loadTemplate('guest_cat_row', true, $content);
111                         $SW = 3 - $SW;
112                 }
113                 $OUT .= '</table>';
114
115                 // Free memory
116                 SQL_FREERESULT($result);
117         } else {
118                 // No categories setted up so far...
119                 $OUT .= loadTemplate('admin_settings_saved', true, getMessage('NO_CATEGORIES_VISIBLE'));
120         }
121
122         if ($return === true) {
123                 // Return generated HTML code
124                 return $OUT;
125         } else {
126                 // Output directly (default)
127                 outputHtml($OUT);
128         }
129 }
130
131 // Outputs a 'failed message'
132 function registerOutputFailedMessage ($messageId, $extra='') {
133         if (empty($messageId)) {
134                 outputHtml('<div class="register_failed">' . $extra . '</div>');
135         } else {
136                 outputHtml('<div class="register_failed">{--' . $messageId . '--}' . $extra . '</div>');
137         }
138 }
139
140 // Run a filter for must-fillout fields
141 function FILTER_REGISTER_MUST_FILLOUT ($content) {
142         // Get all fields for output
143         $result = SQL_QUERY("SELECT `field_name`, `field_required` FROM `{?_MYSQL_PREFIX?}_must_register` ORDER BY `id` ASC",
144                 __FUNCTION__, __LINE__);
145
146         // Walk through all entries
147         while ($row = SQL_FETCHARRAY($result)) {
148                 // Must the user fill out this element?
149                 $value = '';
150                 if ($row['field_required'] == 'Y') $value = '<span class="guest_failed">(*)</span>';
151
152                 // Add it
153                 $content['must_fillout_'.strtolower($row['field_name']).''] = $value;
154         } // END - while
155
156         // Free memory
157         SQL_FREERESULT($result);
158
159         // Return it
160         return $content;
161 }
162
163 // Checks wether the registration data is complete
164 function isRegistrationDataComplete () {
165         // Init elements
166         $GLOBALS['registration_ip_timeout']     = false;
167         $GLOBALS['registration_short_password'] = false;
168         $GLOBALS['register_selected_cats']      = '0';
169
170         // Default is okay
171         $isOkay = true;
172
173         // First we only check the submitted data then we continue... :)
174         //
175         // Did he agree to our Terms Of Usage?
176         if (postRequestParameter('agree') != 'Y') {
177                 setPostRequestParameter('agree', '!');
178                 $isOkay = false;
179         } // END - if
180
181         // Did he enter a valid email address? (we really don't care about
182         // that, he has to click on a confirmation link :P )
183         if ((!isPostRequestParameterSet('email')) || (!isEmailValid(postRequestParameter('email')))) {
184                 setPostRequestParameter('email', '!');
185                 $isOkay = false;
186         } // END - if
187
188         // And what about surname and family's name?
189         if (!isPostRequestParameterSet('surname')) {
190                 setPostRequestParameter('surname', '!');
191                 $isOkay = false;
192         } // END - if
193         if (!isPostRequestParameterSet('family')) {
194                 setPostRequestParameter('family', '!');
195                 $isOkay = false;
196         } // END - if
197
198         // Get temporary array for modification
199         $postArray = postRequestArray();
200
201         // Check for required fields
202         $isOkay = ($isOkay && ifRequiredRegisterFieldsAreSet($postArray));
203
204         // Set it back in request
205         setPostRequestArray($postArray);
206
207         // Did he enter his password twice?
208         if (((!isPostRequestParameterSet('pass1')) || (!isPostRequestParameterSet('pass2'))) || ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2')))) {
209                 if ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2'))) {
210                         setPostRequestParameter('pass1', '!');
211                         setPostRequestParameter('pass2', '!');
212                 } else {
213                         if (!isPostRequestParameterSet('pass1')) { setPostRequestParameter('pass1', '!'); } else { setPostRequestParameter('pass1', ''); }
214                         if (!isPostRequestParameterSet('pass2')) { setPostRequestParameter('pass2', '!'); } else { setPostRequestParameter('pass2', ''); }
215                 }
216                 $isOkay = false;
217         } // END - if
218
219         // Is the password long enouth?
220         if ((strlen(postRequestParameter('pass1')) < getConfig('pass_len')) && ($isOkay === true)) {
221                 $GLOBALS['registration_short_password'] = true;
222                 $isOkay = false;
223         } // END - if
224
225         // Do this check only when no admin is logged in
226         if (is_array(postRequestParameter('cat'))) {
227                 // Only continue with array
228                 foreach (postRequestParameter('cat') as $id => $answer) {
229                         // Is this category choosen?
230                         if ($answer == 'Y') {
231                                 $GLOBALS['register_selected_cats']++;
232                         } // END - if
233                 } // END - foreach
234         } // END - if
235
236         // Enougth categories selected?
237         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',selected='.$GLOBALS['register_selected_cats'].'/'.getConfig('least_cats'));
238         $isOkay = (($isOkay) && ($GLOBALS['register_selected_cats'] >= getConfig('least_cats')));
239
240         if ((postRequestParameter('email') != '!') && (getConfig('check_double_email') == 'Y')) {
241                 // Does the email address already exists in our database?
242                 if ((!isAdmin()) && (isEmailTaken(postRequestParameter('email')))) {
243                         setPostRequestParameter('email', '?');
244                         $isOkay = false;
245                 } // END - if
246         } // END - if
247
248         // Check for IP timeout?
249         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
250         if ((!isAdmin()) && (getConfig('ip_timeout') > 0)) {
251                 // Check his IP number
252                 $GLOBALS['registration_ip_timeout'] = (countSumTotalData(detectRemoteAddr()  , 'user_data', 'userid', 'REMOTE_ADDR', true, " AND ((UNIX_TIMESTAMP() - `joined`) < {?ip_timeout?} OR (UNIX_TIMESTAMP() - `last_update`) < {?ip_timeout?}) LIMIT 1") == 1);
253                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',timeout='.intval($GLOBALS['registration_ip_timeout']));
254                 $isOkay = (($isOkay) && (!$GLOBALS['registration_ip_timeout']));
255         } // END - if
256
257         // Return result
258         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
259         return $isOkay;
260 }
261
262 // Do the registration
263 function doRegistration () {
264         // Prepapre month and day of birth
265         if (strlen(postRequestParameter('day'))   == 1) setPostRequestParameter('day'  , '0' . postRequestParameter('day'));
266         if (strlen(postRequestParameter('month')) == 1) setPostRequestParameter('month', '0' . postRequestParameter('month'));
267
268         // Get total ...
269         // ... confirmed, ...
270         $confirmedUsers   = countSumTotalData('CONFIRMED'  , 'user_data', 'userid', 'status', true);
271         // ... unconfirmed ...
272         $unconfirmedUsers = countSumTotalData('UNCONFIRMED', 'user_data', 'userid', 'status', true);
273         // ... and locked users!
274         $lockedUsers      = countSumTotalData('LOCKED'     , 'user_data', 'userid', 'status', true);
275
276         // Generate hash which will be inserted into confirmation mail
277         $hash = generateHash(sha1(
278                 $confirmedUsers . getConfig('ENCRYPT_SEPERATOR') .
279                 $unconfirmedUsers . getConfig('ENCRYPT_SEPERATOR') .
280                 $lockedUsers . getConfig('ENCRYPT_SEPERATOR') .
281                 postRequestParameter('month') . '-' .
282                 postRequestParameter('day') . '-' .
283                 postRequestParameter('year') . getConfig('ENCRYPT_SEPERATOR') .
284                 detectServerName() . getConfig('ENCRYPT_SEPERATOR') .
285                 detectRemoteAddr() . getConfig('ENCRYPT_SEPERATOR') .
286                 detectUserAgent() . '/' .
287                 getConfig('SITE_KEY') . '/' .
288                 getConfig('DATE_KEY') . '/' .
289                 getConfig('CACHE_BUSTER')
290         ));
291
292         // Old way with enterable two-char-code
293         $countryRow = '`country`';
294         $countryData = substr(postRequestParameter('cntry'), 0, 2);
295
296         // Add design when extension sql_patches is v0.2.7 or greater
297         // @TODO Rewrite these all to a single filter
298         $GLOBALS['register_sql_columns'] = '';
299         $GLOBALS['register_sql_data'] = '';
300         if (isExtensionInstalledAndNewer('theme', '0.0.8')) {
301                 // Okay, add design here
302                 $GLOBALS['register_sql_columns'] = ', `curr_theme`';
303                 $GLOBALS['register_sql_data'] = ", '" . getCurrentTheme() . "'";
304         } // END - if
305
306         // Check if I shall disable sending mail to newly registered members out about active/begging rallye
307         //
308         // First comes first: begging rallye
309         if (isExtensionInstalledAndNewer('beg', '0.1.7')) {
310                 // Okay, shall I disable now?
311                 if (getConfig('beg_new_mem_notify') != 'Y') {
312                         $GLOBALS['register_sql_columns'] .= ', `beg_ral_notify`, `beg_ral_en_notify`';
313                         $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
314                 } // END - if
315         } // END - if
316
317         // Second: active rallye
318         if (isExtensionInstalledAndNewer('bonus', '0.7.7')) {
319                 // Okay, shall I disable now?
320                 if (getConfig('bonus_new_mem_notify') != 'Y') {
321                         $GLOBALS['register_sql_columns'] .= ', `bonus_ral_notify`, `bonus_ral_en_notify`';
322                         $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
323                 } // END - if
324         } // END - if
325
326         // Write user data to table
327         if (isExtensionActive('country')) {
328                 // Save with new selectable country code
329                 $countryRow = '`country_code`';
330                 $countryData = bigintval(postRequestParameter('country_code'));
331         } // END - if
332
333         //////////////////////////////
334         // Create user's account... //
335         //////////////////////////////
336         //
337         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_data` (gender, surname, family, street_nr,%s, zip, city, email, birth_day, birth_month, birth_year, password, max_mails, receive_mails, refid, status, user_hash, REMOTE_ADDR, joined, last_update".$GLOBALS['register_sql_columns'].")
338 VALUES ('%s','%s','%s','%s','%s',%s,'%s','%s',%s, %s,%s,'%s',%s, %s,'%s','UNCONFIRMED','%s','%s', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()".$GLOBALS['register_sql_data'].")",
339         array(
340                 $countryRow,
341                 substr(postRequestParameter('gender'), 0, 1),
342                 postRequestParameter('surname'),
343                 postRequestParameter('family'),
344                 postRequestParameter('street_nr'),
345                 $countryData,
346                 bigintval(postRequestParameter('zip')),
347                 postRequestParameter('city'),
348                 postRequestParameter('email'),
349                 bigintval(postRequestParameter('day')),
350                 bigintval(postRequestParameter('month')),
351                 bigintval(postRequestParameter('year')),
352                 generateHash(postRequestParameter('pass1')),
353                 bigintval(postRequestParameter('max_mails')),
354                 bigintval(postRequestParameter('max_mails')),
355                 bigintval(postRequestParameter('refid')),
356                 $hash,
357                 detectRemoteAddr(),
358         ), __FILE__, __LINE__);
359
360         // Get his userid
361         $userid = bigintval(SQL_INSERTID());
362
363         // Did this work?
364         if ($userid == '0') {
365                 // Something bad happened!
366                 loadTemplate('admin_settings_saved', false, getMessage('USER_NOT_REGISTERED'));
367
368                 // Stop here
369                 return;
370         } // END - if
371
372         // Is the refback extension there?
373         // @TODO Rewrite this to a filter
374         if (isExtensionActive('refback')) {
375                 // Update refback table
376                 updateRefbackTable($userid);
377         } // END - if
378
379         // Write his welcome-points
380         // @TODO Rewrite this whole if() block to addPointsThroughReferalSystem(). This will also make following if() block obsolete
381         // @TODO Wether the registration bonus should only be added to user directly or through referal system should be configurable
382         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s AND `ref_depth`=0 LIMIT 1",
383                 array($userid), __FILE__, __LINE__);
384         if (SQL_NUMROWS($result) == '0') {
385                 // Add only when the line was not found (maybe some more secure?)
386                 $locked = 'points';
387
388                 // Pay him later. First he has to confirm some mails!
389                 if (getConfig('ref_payout') > 0) $locked = 'locked_points';
390
391                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`, `ref_depth`, `%s`) VALUES (%s,0,'{?points_register?}')",
392                         array($locked, $userid), __FILE__, __LINE__);
393
394                 // Update mediadata as well
395                 if ((isExtensionInstalledAndNewer('mediadata', '0.0.4')) && ($locked == 'points')) {
396                         // Update database
397                         updateMediadataEntry(array('total_points'), 'add', getConfig('points_register'));
398                 } // END - if
399         } // END - if
400
401         // Write catgories
402         if ((is_array(postRequestParameter('cat'))) && (count(postRequestParameter('cat')))) {
403                 foreach (postRequestParameter('cat') as $cat => $joined) {
404                         if ($joined == 'Y') {
405                                 // Insert category entry
406                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`, `cat_id`) VALUES (%s, %s)",
407                                         array($userid, bigintval($cat)), __FILE__, __LINE__);
408                         } // END - if
409                 } // END - foreach
410         } // END - if
411
412         // ... rewrite a zero referal id to the main title
413         if (postRequestParameter('refid') == '0') setPostRequestParameter('refid', getConfig('MAIN_TITLE'));
414
415         // Is ZIP code set?
416         if (isPostRequestParameterSet('zip')) {
417                 // Prepare data array for the email template
418                 // Start with the gender...
419                 $content = array(
420                         'hash'    => $hash,
421                         'userid'  => $userid,
422                         'gender'  => translateGender(postRequestParameter('gender')),
423                         'surname' => SQL_ESCAPE(postRequestParameter('surname')),
424                         'family'  => SQL_ESCAPE(postRequestParameter('family')),
425                         'email'   => SQL_ESCAPE(postRequestParameter('email')),
426                         'street'  => SQL_ESCAPE(postRequestParameter('street_nr')),
427                         'city'    => SQL_ESCAPE(postRequestParameter('city')),
428                         'zip'     => bigintval(postRequestParameter('zip')),
429                         'country' => $countryData,
430                         'refid'   => SQL_ESCAPE(postRequestParameter('refid')),
431                         'pass'    => SQL_ESCAPE(postRequestParameter('pass1')),
432                 );
433         } else {
434                 // No ZIP code entered
435                 $content = array(
436                         'hash'    => $hash,
437                         'userid'  => $userid,
438                         'gender'  => translateGender(postRequestParameter('gender')),
439                         'surname' => SQL_ESCAPE(postRequestParameter('surname')),
440                         'family'  => SQL_ESCAPE(postRequestParameter('family')),
441                         'email'   => SQL_ESCAPE(postRequestParameter('email')),
442                         'street'  => SQL_ESCAPE(postRequestParameter('street_nr')),
443                         'city'    => SQL_ESCAPE(postRequestParameter('city')),
444                         'zip'     => '',
445                         'country' => $countryData,
446                         'refid'   => SQL_ESCAPE(postRequestParameter('refid')),
447                         'pass'    => SQL_ESCAPE(postRequestParameter('pass1')),
448                 );
449         }
450
451         // Continue with birthday...
452         switch (getLanguage()) {
453                 case 'de':
454                         $content['birthday'] = bigintval(postRequestParameter('day')) . '.' . bigintval(postRequestParameter('month')) . '.' . bigintval(postRequestParameter('year'));
455                         break;
456
457                 default:
458                         $content['birthday'] = bigintval(postRequestParameter('month')) . '/' . bigintval(postRequestParameter('day')) . '/' . bigintval(postRequestParameter('year'));
459                         break;
460         } // END - switch
461
462         // Display information to the user that he got mail and send it away
463         $messageGuest = loadEmailTemplate('register-member', $content, $userid);
464
465         // Send mail to user (confirmation link!)
466         $email = $content['email'];
467         sendEmail($content['email'], getMessage('GUEST_SUBJECT_CONFIRM_LINK'), $messageGuest);
468         $content['email'] = $email;
469
470         // Send mail to admin
471         sendAdminNotification(getMessage('ADMIN_SUBJECT_NEW_ACCOUNT'), 'register-admin', $content, $userid);
472 }
473
474 // [EOF]
475 ?>