More fixes for registration if ext-cache and many more are absend
[mailer.git] / inc / modules / guest / what-register.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 10/10/2003 *
4  * ===============                              Last change: 11/26/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : what-register.php                                *
8  * -------------------------------------------------------------------- *
9  * Short description : Registration form                                *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Anmeldeformular                                  *
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  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // Add description as navigation point
45 addMenuDescription('guest', __FILE__);
46
47 if (!isExtensionActive('register')) {
48         loadTemplate('admin_settings_saved', false, generateExtensionInactiveNotInstalledMessage('register'));
49         return;
50 } elseif (!isExtensionActive('country')) {
51         loadTemplate('admin_settings_saved', false, generateExtensionInactiveNotInstalledMessage('country'));
52         return;
53 }
54
55 // Initialize variables
56 $isOkay     = true;
57 $shortPass  = false;
58 $cats       = 0;
59 $ipTimedOut = false;
60
61 // Default refid is zero
62 setRequestPostElement('refid', 0);
63 if (determineReferalId() > 0) {
64         // Test if the refid is valid
65         $result = SQL_QUERY_ESC("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
66                 array(determineReferalId()), __FILE__, __LINE__);
67
68         // Userid found?
69         //* DEBUG: */ die("refid={determineReferalId()}/numRows=".SQL_NUMROWS($result)."");
70         if (SQL_NUMROWS($result) == 0) {
71                 // Not found so we set your refid!
72                 setRequestPostElement('refid', getConfig('def_refid'));
73                 setSession('refid', getConfig('def_refid'));
74         } else {
75                 // Use the refid here
76                 setRequestPostElement('refid', determineReferalId());
77         }
78 } // END - if
79
80 if (isFormSent()) {
81         // First we only check the submitted data then we continue... :)
82         //
83         // Did he agree to our Terms Of Usage?
84         if (postRequestElement('agree') != 'Y') {
85                 setRequestPostElement('agree', '!');
86                 $isOkay = false;
87         } // END - if
88
89         // Did he enter a valid email address? (we really don't care about
90         // that, he has to click on a confirmation link :P )
91         if ((!isPostRequestElementSet('email')) || (!isEmailValid(postRequestElement('email')))) {
92                 setRequestPostElement('email', '!');
93                 $isOkay = false;
94         } // END - if
95
96         // And what about surname and family's name?
97         if (!isPostRequestElementSet('surname')) {
98                 setRequestPostElement('surname', '!');
99                 $isOkay = false;
100         } // END - if
101         if (!isPostRequestElementSet('family')) {
102                 setRequestPostElement('family', '!');
103                 $isOkay = false;
104         } // END - if
105
106         // Get temporary array for modification
107         $postArray = postRequestArray();
108
109         // Check for required fields
110         if ($isOkay === true) $isOkay = ifRequiredRegisterFieldsAreSet($postArray);
111
112         // Set it back in request
113         setPostRequestArray($postArray);
114
115         // Did he enter his password twice?
116         if (((!isPostRequestElementSet('pass1')) || (!isPostRequestElementSet('pass2'))) || ((postRequestElement('pass1') != postRequestElement('pass2')) && (isPostRequestElementSet('pass1')) && (isPostRequestElementSet('pass2')))) {
117                 if ((postRequestElement('pass1') != postRequestElement('pass2')) && (isPostRequestElementSet('pass1')) && (isPostRequestElementSet('pass2'))) {
118                         setRequestPostElement('pass1', '!');
119                         setRequestPostElement('pass2', '!');
120                 } else {
121                         if (!isPostRequestElementSet('pass1')) { setRequestPostElement('pass1', '!'); } else { setRequestPostElement('pass1', ''); }
122                         if (!isPostRequestElementSet('pass2')) { setRequestPostElement('pass2', '!'); } else { setRequestPostElement('pass2', ''); }
123                 }
124                 $isOkay = false;
125         } // END - if
126
127         // Is the password long enouth?
128         if ((strlen(postRequestElement('pass1')) < getConfig('pass_len')) && ($isOkay === true)) {
129                 $shortPass = true;
130                 $isOkay = false;
131         } // END - if
132
133         // No admin? Admins can always register!
134         if (!isAdmin()) {
135                 // Do this check only when no admin is logged in
136                 foreach (postRequestElement('cat') as $id => $answer) {
137                         if ($answer == 'Y') $cats++;
138                 } // END - foreach
139
140                 if ($cats < getConfig('least_cats')) {
141                         // ... nope!
142                         $isOkay = false;
143                 } // END - if
144         } // END - if
145
146         if ((postRequestElement('email') != '!') && (getConfig('check_double_email') == 'Y')) {
147                 // Does the email address already exists in our database?
148                 $CHK = isEmailTaken(postRequestElement('email'));
149                 if ($CHK === true) {
150                         setRequestPostElement('email', '?');
151                         $isOkay = false;
152                 } // END - if
153         } // END - if
154
155         // Check for IP timeout?
156         if (getConfig('ip_timeout') > 0) {
157                 // Check his IP number
158                 $result = SQL_QUERY_ESC("SELECT
159         `userid`
160 FROM
161         `{?_MYSQL_PREFIX?}_user_data`
162 WHERE
163         `REMOTE_ADDR`='%s' AND
164         (`joined` > (UNIX_TIMESTAMP() - {?ip_timeout?}) OR `last_update` > (UNIX_TIMESTAMP() - {?ip_timeout?}))
165 LIMIT 1",
166                         array(detectRemoteAddr()), __FILE__, __LINE__);
167                 if (SQL_NUMROWS($result) == 1) {
168                         // Same IP in timeout range and different email address entered... Eat this, faker! ;-)
169                         // But admins are allowed to fake their own exchange service.
170                         $ipTimedOut = true;
171                         $isOkay = false;
172                 } // END - if
173
174                 // Free memory
175                 SQL_FREERESULT($result);
176         } // END - if
177 } // END - if
178
179 // Is the form sent and all went fine or admin logged in?
180 //* DEBUG: */ print intval(isFormSent()).'/'.intval($isOkay).'/'.intval(isAdmin()).'<br />';
181 if ((isFormSent()) && (($isOkay === true) || (isAdmin()))) {
182         // Prepapre month and day of birth
183         if (strlen(postRequestElement('day'))   == 1) setRequestPostElement('day'  , 0 . postRequestElement('day'));
184         if (strlen(postRequestElement('month')) == 1) setRequestPostElement('month', 0 . postRequestElement('month'));
185
186         // Get total ...
187         // ... confirmed, ...
188         $confirmedUsers   = countSumTotalData('CONFIRMED'  , 'user_data', 'userid', 'status', true);
189         // ... unconfirmed ...
190         $unconfirmedUsers = countSumTotalData('UNCONFIRMED', 'user_data', 'userid', 'status', true);
191         // ... and locked users!
192         $lockedUsers      = countSumTotalData('LOCKED'     , 'user_data', 'userid', 'status', true);
193
194         // Generate hash which will be inserted into confirmation mail
195         $hash = generateHash(sha1($confirmedUsers.getConfig('ENCRYPT_SEPERATOR').$unconfirmedUsers.getConfig('ENCRYPT_SEPERATOR').$lockedUsers.getConfig('ENCRYPT_SEPERATOR').postRequestElement('month') . '-'.postRequestElement('day') . '-'.postRequestElement('year').getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_NAME').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().getConfig('ENCRYPT_SEPERATOR').detectUserAgent() . '/' . getConfig('SITE_KEY') . '/' . getConfig('DATE_KEY') . '/'. getConfig('CACHE_BUSTER')));
196
197         // Add design when extension sql_patches is v0.2.7 or greater
198         // @TODO Rewrite these all to a single filter
199         $ADD1 = '';
200         $ADD2 = '';
201         if (isExtensionInstalledAndNewer('theme', '0.0.8')) {
202                 // Okay, add design here
203                 $ADD1 = ', `curr_theme`';
204                 $ADD2 = ", '".getCurrentTheme()."'";
205         } // END - if
206
207         // Check if I shall disable sending mail to newly registered members out about active/begging rallye
208         //
209         // First comes first: begging rallye
210         if (isExtensionInstalledAndNewer('beg', '0.1.7')) {
211                 // Okay, shall I disable now?
212                 if (getConfig('beg_new_mem_notify') != 'Y') {
213                         $ADD1 .= ', `beg_ral_notify`, `beg_ral_en_notify`';
214                         $ADD2 .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
215                 } // END - if
216         } // END - if
217
218         // Second: active rallye
219         if (isExtensionInstalledAndNewer('bonus', '0.7.7')) {
220                 // Okay, shall I disable now?
221                 if (getConfig('bonus_new_mem_notify') != 'Y') {
222                         $ADD1 .= ', `bonus_ral_notify`, `bonus_ral_en_notify`';
223                         $ADD2 .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
224                 } // END - if
225         } // END - if
226
227         // Write user data to table
228         if (isExtensionActive('country')) {
229                 // Save with new selectable country code
230                 $countryRow = '`country_code`';
231                 $countryData = bigintval(postRequestElement('country_code'));
232         } else {
233                 // Old way with enterable two-char-code
234                 $countryRow = '`country`';
235                 $countryData = substr(postRequestElement('cntry'), 0, 2);
236         }
237
238         //////////////////////////////
239         // Create user's account... //
240         //////////////////////////////
241         //
242         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".$ADD1.")
243 VALUES ('%s','%s','%s','%s','%s',%s,'%s','%s',%s, %s,%s,'%s',%s, %s,'%s','UNCONFIRMED','%s','%s', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()".$ADD2.")",
244         array(
245                 $countryRow,
246                 substr(postRequestElement('gender'), 0, 1),
247                 postRequestElement('surname'),
248                 postRequestElement('family'),
249                 postRequestElement('street_nr'),
250                 $countryData,
251                 bigintval(postRequestElement('zip')),
252                 postRequestElement('city'),
253                 postRequestElement('email'),
254                 bigintval(postRequestElement('day')),
255                 bigintval(postRequestElement('month')),
256                 bigintval(postRequestElement('year')),
257                 generateHash(postRequestElement('pass1')),
258                 bigintval(postRequestElement('max_mails')),
259                 bigintval(postRequestElement('max_mails')),
260                 bigintval(postRequestElement('refid')),
261                 $hash,
262                 detectRemoteAddr(),
263         ), __FILE__, __LINE__);
264
265         // Get his userid
266         $userid = SQL_INSERTID();
267
268         // Did this work?
269         if ($userid == 0) {
270                 // Something bad happened!
271                 loadTemplate('admin_settings_saved', false, getMessage('USER_NOT_REGISTERED'));
272                 return;
273         } // END - if
274
275         // Is the refback extension there?
276         // @TODO Rewrite this to a filter
277         if (isExtensionActive('refback')) {
278                 // Update refback table
279                 updateRefbackTable($userid);
280         } // END - if
281
282         // Write his welcome-points
283         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s AND `ref_depth`=0 LIMIT 1",
284                 array(bigintval($userid)), __FILE__, __LINE__);
285         if (SQL_NUMROWS($result) == 0) {
286                 // Add only when the line was not found (maybe some more secure?)
287                 $locked = 'points';
288
289                 // Pay him later. First he has to confirm some mails!
290                 if (getConfig('ref_payout') > 0) $locked = 'locked_points';
291
292                 // @TODO Rewrite this to addPointsDirectly()
293                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`, `ref_depth`, `".$locked."`) VALUES (%s,0,'{?points_register?}')",
294                         array(bigintval($userid)), __FILE__, __LINE__);
295
296                 // Update mediadata as well
297                 if ((isExtensionInstalledAndNewer('mediadata', '0.0.4')) && ($locked == 'points')) {
298                         // Update database
299                         updateMediadataEntry(array('total_points'), 'add', getConfig('points_register'));
300                 } // END - if
301         } // END - if
302
303         // Write catgories
304         if ((is_array(postRequestElement('cat'))) && (count(postRequestElement('cat')))) {
305                 foreach (postRequestElement('cat') as $cat => $joined) {
306                         if ($joined == 'Y') {
307                                 // Insert category entry
308                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (userid, cat_id) VALUES (%s, %s)",
309                                 array(bigintval($userid), bigintval($cat)), __FILE__, __LINE__);
310                         } // END - if
311                 } // END - foreach
312         } // END - if
313
314         // Rewrite gender
315         $gender = translateGender(postRequestElement('gender'));
316
317         // ... rewrite a zero referal ID to the main title
318         if (postRequestElement('refid') == 0) setRequestPostElement('refid', getConfig('MAIN_TITLE'));
319
320         // Is ZIP code set?
321         if (isPostRequestElementSet('zip')) {
322                 // Prepare data array for the email template
323                 // Start with the gender...
324                 $content = array(
325                         'hash'    => $hash,
326                         'userid'  => $userid,
327                         'gender'  => $gender,
328                         'surname' => SQL_ESCAPE(postRequestElement('surname')),
329                         'family'  => SQL_ESCAPE(postRequestElement('family')),
330                         'email'   => SQL_ESCAPE(postRequestElement('email')),
331                         'street'  => SQL_ESCAPE(postRequestElement('street_nr')),
332                         'city'    => SQL_ESCAPE(postRequestElement('city')),
333                         'zip'     => bigintval(postRequestElement('zip')),
334                         'country' => $countryData,
335                         'refid'   => SQL_ESCAPE(postRequestElement('refid')),
336                         'pass'    => SQL_ESCAPE(postRequestElement('pass1')),
337                 );
338         } else {
339                 // No ZIP code entered
340                 $content = array(
341                         'hash'    => $hash,
342                         'userid'  => $userid,
343                         'gender'  => $gender,
344                         'surname' => SQL_ESCAPE(postRequestElement('surname')),
345                         'family'  => SQL_ESCAPE(postRequestElement('family')),
346                         'email'   => SQL_ESCAPE(postRequestElement('email')),
347                         'street'  => SQL_ESCAPE(postRequestElement('street_nr')),
348                         'city'    => SQL_ESCAPE(postRequestElement('city')),
349                         'zip'     => '',
350                         'country' => $countryData,
351                         'refid'   => SQL_ESCAPE(postRequestElement('refid')),
352                         'pass'    => SQL_ESCAPE(postRequestElement('pass1')),
353                 );
354         }
355
356         // Continue with birthday...
357         switch (getLanguage()) {
358                 case 'de':
359                         $content['birthday'] = bigintval(postRequestElement('day')) . '.' . bigintval(postRequestElement('month')) . '.' . bigintval(postRequestElement('year'));
360                         break;
361
362                 default:
363                         $content['birthday'] = bigintval(postRequestElement('month')) . '/' . bigintval(postRequestElement('day')) . '/' . bigintval(postRequestElement('year'));
364                         break;
365         } // END - switch
366
367         // Display information to the user that he got mail and send it away
368         $messageGuest = loadEmailTemplate('register-member', $content, $userid);
369
370         // Send mail to user (confirmation link!)
371         $email = $content['email'];
372         sendEmail($content['email'], getMessage('GUEST_SUBJECT_CONFIRM_LINK'), $messageGuest);
373         $content['email'] = $email;
374
375         // Send mail to admin
376         sendAdminNotification(getMessage('ADMIN_SUBJECT_NEW_ACCOUNT'), 'register-admin', $content, $userid);
377
378         // Output success registration
379         loadTemplate('admin_settings_saved', false, getMessage('REGISTRATION_DONE'));
380 } else {
381         if (postRequestElement('agree') == '!') {
382                 registerOutputFailedMessage('HAVE_TO_AGREE');
383         } // END - if
384
385         if (postRequestElement('email') == '!') {
386                 registerOutputFailedMessage('ENTER_EMAIL');
387                 setRequestPostElement('email', '');
388         } elseif (postRequestElement('email') == '?') {
389                 registerOutputFailedMessage('EMAIL_ALREADY_DB');
390                 setRequestPostElement('email', '');
391         }
392
393         if (postRequestElement('surname') == '!') {
394                 registerOutputFailedMessage('ENTER_SURNAME');
395                 setRequestPostElement('surname', '');
396         } // END - if
397
398         if (postRequestElement('family') == '!') {
399                 registerOutputFailedMessage('ENTER_FAMILY');
400                 setRequestPostElement('family', '');
401         } // END - if
402
403         if ((postRequestElement('pass1') == '!') && (postRequestElement('pass2') == '!')) {
404                 registerOutputFailedMessage('ENTER_BOTH_PASSWORDS');
405         } elseif (postRequestElement('pass1') == '!') {
406                 registerOutputFailedMessage('ENTER_PASS1');
407         } elseif (postRequestElement('pass2') == '!') {
408                 registerOutputFailedMessage('ENTER_PASS2');
409         }
410
411         if ($shortPass === true) {
412                 registerOutputFailedMessage('SHORT_PASS', ": ".getConfig('pass_len'));
413         } // END - if
414
415         if ($ipTimedOut === true) {
416                 registerOutputFailedMessage('REMOTE_ADDR_TIMEOUT');
417         } // END - if
418
419         if ((!empty($cats)) && ($cats < getConfig('least_cats'))) {
420                 registerOutputFailedMessage(sprintf(getMessage('CATS_LEAST'), getConfig('least_cats')));
421         } // END - if
422
423         // Generate birthday selection
424         switch (getLanguage()) {
425                 case 'de': // German date format
426                         $content['birthday_selection'] = addSelectionBox('day', postRequestElement('day')).addSelectionBox('month', postRequestElement('month')).addSelectionBox('year', postRequestElement('year'));
427                         break;
428
429                 default: // Default is the US date format... :)
430                         $content['birthday_selection'] = addSelectionBox('month', postRequestElement('month')).addSelectionBox('day', postRequestElement('day')).addSelectionBox('year', postRequestElement('year'));
431                         break;
432         }
433
434         // Adds a table for the guests with all visible categories
435         $content['category_selection'] = registerGenerateCategoryTable('guest', true);
436
437         // Adds maximum receiveable mails list... :)
438         $content['max_receive_list'] = addMaxReceiveList('guest', '', true);
439
440         // Shall I display the refid or shall I make it editable?
441         if (getConfig('display_refid') == 'Y') {
442                 // Load "hide" form template
443                 $content['refid_content'] = loadTemplate('guest_register_refid_hide', true, determineReferalId());
444         } else {
445                 // Load template to enter it
446                 $content['refid_content'] = loadTemplate('guest_register_refid', true, determineReferalId());
447         }
448
449         // You may want to modify the register_header.tpl.xx file and not this script when you add your scripts etc. :-)
450         $content['header_content'] = loadTemplate('register_header', true);
451
452         // Other values
453         $content['surname']   = SQL_ESCAPE(postRequestElement('surname'));
454         $content['family']    = SQL_ESCAPE(postRequestElement('family'));
455         $content['street_nr'] = SQL_ESCAPE(postRequestElement('street_nr'));
456         $content['zip']       = bigintval(postRequestElement('zip'));
457         $content['city']      = SQL_ESCAPE(postRequestElement('city'));
458         $content['email']      = SQL_ESCAPE(postRequestElement('email'));
459
460         // Prepare country selection box
461         $OUT  = "<select name=\"country_code\" class=\"guest_select\" size=\"1\">\n";
462         $whereStatement = "WHERE `is_active`='Y'";
463         if (isAdmin()) $whereStatement = '';
464         $OUT .= generateOptionList('countries', 'id', 'descr', postRequestElement('country_code'), 'code', $whereStatement);
465         $OUT .= "</select>";
466         $content['country'] = $OUT;
467
468         // Set must-fillout fields
469         $content = runFilterChain('register_must_fillout', $content);
470
471         // Display registration form
472         loadTemplate('guest_register', false, $content);
473 }
474
475 // [EOF]
476 ?>