Removed comment introduced by Profi-Concept, this comment should fine (in a much...
[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  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 //
44 function ifRequiredRegisterFieldsAreSet (&$array) {
45         // By default all is fine
46         $ret = true;
47         foreach ($array as $key => $value) {
48                 // Check all fields that must register
49                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_must_register` WHERE `field_name`='%s' AND `field_required`='Y' LIMIT 1",
50                         array($key), __FUNCTION__, __LINE__);
51
52                 // Entry found?
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_HASZERONUMS($result)) {
89                 // List alle visible modules (or all to the admin)
90                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
91                 while ($content = SQL_FETCHARRAY($result)) {
92                         // Prepare array for the template
93                         $content['default_yes'] = '';
94                         $content['default_no']  = '';
95
96                         // Mark categories
97                         if ((postRequestParameter('cat', $content['id']) == 'Y') || ((getConfig('register_default') == 'Y') && (!isPostRequestParameterSet('cat', $content['id'])))) {
98                                 $content['default_yes'] = ' checked="checked"';
99                         } else {
100                                 $content['default_no']  = ' checked="checked"';
101                         }
102
103                         // Load template and switch color
104                         $OUT .= loadTemplate('guest_cat_row', true, $content);
105                 } // END - while
106                 $OUT .= '</table>';
107
108                 // Free memory
109                 SQL_FREERESULT($result);
110         } else {
111                 // No categories setted up so far...
112                 $OUT .= loadTemplate('admin_settings_saved', true, '{--NO_CATEGORIES_VISIBLE--}');
113         }
114
115         if ($return === true) {
116                 // Return generated HTML code
117                 return $OUT;
118         } else {
119                 // Output directly (default)
120                 outputHtml($OUT);
121         }
122 }
123
124 // Outputs a 'failed message'
125 function registerOutputFailedMessage ($messageId, $extra='') {
126         if (empty($messageId)) {
127                 outputHtml('<div class="notice">' . $extra . '</div>');
128         } else {
129                 outputHtml('<div class="notice">{--' . $messageId . '--}' . $extra . '</div>');
130         }
131 }
132
133 // Run a filter for must-fillout fields
134 function FILTER_REGISTER_MUST_FILLOUT ($content) {
135         // Get all fields for output
136         $result = SQL_QUERY('SELECT `field_name`, `field_required` FROM `{?_MYSQL_PREFIX?}_must_register` ORDER BY `id` ASC',
137                 __FUNCTION__, __LINE__);
138
139         // Walk through all entries
140         while ($row = SQL_FETCHARRAY($result)) {
141                 // Must the user fill out this element?
142                 $value = '';
143                 if ($row['field_required'] == 'Y') $value = '<span class="notice">(*)</span>';
144
145                 // Add it
146                 $content['must_fillout_' . strtolower($row['field_name']) . ''] = $value;
147         } // END - while
148
149         // Free memory
150         SQL_FREERESULT($result);
151
152         // Return it
153         return $content;
154 }
155
156 // Checks wether the registration data is complete
157 function isRegistrationDataComplete () {
158         // Init elements
159         $GLOBALS['registration_ip_timeout']     = false;
160         $GLOBALS['registration_short_password'] = false;
161         $GLOBALS['register_selected_cats']      = '0';
162
163         // Default is okay
164         $isOkay = true;
165
166         // First we only check the submitted data then we continue... :)
167         //
168         // Did he agree to our Terms Of Usage?
169         if (postRequestParameter('agree') != 'Y') {
170                 setPostRequestParameter('agree', '!');
171                 $isOkay = false;
172         } // END - if
173
174         // Did he enter a valid email address? (we really don't care about
175         // that, he has to click on a confirmation link :P )
176         if ((!isPostRequestParameterSet('email')) || (!isEmailValid(postRequestParameter('email')))) {
177                 setPostRequestParameter('email', '!');
178                 $isOkay = false;
179         } // END - if
180
181         // And what about surname and family's name?
182         if (!isPostRequestParameterSet('surname')) {
183                 setPostRequestParameter('surname', '!');
184                 $isOkay = false;
185         } // END - if
186         if (!isPostRequestParameterSet('family')) {
187                 setPostRequestParameter('family', '!');
188                 $isOkay = false;
189         } // END - if
190
191         // Get temporary array for modification
192         $postArray = postRequestArray();
193
194         // Check for required fields
195         $isOkay = ($isOkay && ifRequiredRegisterFieldsAreSet($postArray));
196
197         // Set it back in request
198         setPostRequestArray($postArray);
199
200         // Did he enter his password twice?
201         if (((!isPostRequestParameterSet('pass1')) || (!isPostRequestParameterSet('pass2'))) || ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2')))) {
202                 if ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2'))) {
203                         setPostRequestParameter('pass1', '!');
204                         setPostRequestParameter('pass2', '!');
205                 } else {
206                         if (!isPostRequestParameterSet('pass1')) { setPostRequestParameter('pass1', '!'); } else { setPostRequestParameter('pass1', ''); }
207                         if (!isPostRequestParameterSet('pass2')) { setPostRequestParameter('pass2', '!'); } else { setPostRequestParameter('pass2', ''); }
208                 }
209                 $isOkay = false;
210         } // END - if
211
212         // Is the password long enouth?
213         if ((strlen(postRequestParameter('pass1')) < getConfig('pass_len')) && ($isOkay === true)) {
214                 $GLOBALS['registration_short_password'] = true;
215                 $isOkay = false;
216         } // END - if
217
218         // Do this check only when no admin is logged in
219         if (is_array(postRequestParameter('cat'))) {
220                 // Only continue with array
221                 foreach (postRequestParameter('cat') as $id => $answer) {
222                         // Is this category choosen?
223                         if ($answer == 'Y') {
224                                 $GLOBALS['register_selected_cats']++;
225                         } // END - if
226                 } // END - foreach
227         } // END - if
228
229         // Enougth categories selected?
230         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',selected='.$GLOBALS['register_selected_cats'].'/'.getConfig('least_cats'));
231         $isOkay = (($isOkay) && ($GLOBALS['register_selected_cats'] >= getConfig('least_cats')));
232
233         if ((postRequestParameter('email') != '!') && (getConfig('check_double_email') == 'Y')) {
234                 // Does the email address already exists in our database?
235                 if ((!isAdmin()) && (isEmailTaken(postRequestParameter('email')))) {
236                         setPostRequestParameter('email', '?');
237                         $isOkay = false;
238                 } // END - if
239         } // END - if
240
241         // Check for IP timeout?
242         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
243         if ((!isAdmin()) && (getConfig('ip_timeout') > 0)) {
244                 // Check his IP number
245                 $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);
246                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',timeout='.intval($GLOBALS['registration_ip_timeout']));
247                 $isOkay = (($isOkay) && (!$GLOBALS['registration_ip_timeout']));
248         } // END - if
249
250         // Return result
251         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
252         return $isOkay;
253 }
254
255 // Do the registration
256 function doRegistration () {
257         // Prepapre month and day of birth
258         if (strlen(postRequestParameter('day'))   == 1) setPostRequestParameter('day'  , '0' . postRequestParameter('day'));
259         if (strlen(postRequestParameter('month')) == 1) setPostRequestParameter('month', '0' . postRequestParameter('month'));
260
261         // Generate hash which will be inserted into confirmation mail
262         $hash = generateHash(sha1(
263                 // Get total confirmed, ...
264                 getTotalConfirmedUser() . getEncryptSeperator() .
265                 // ... unconfirmed ...
266                 getTotalUnconfirmedUser() . getEncryptSeperator() .
267                 // ... and locked users!
268                 getTotalLockedUser() . getEncryptSeperator() .
269                 postRequestParameter('month') . '-' .
270                 postRequestParameter('day') . '-' .
271                 postRequestParameter('year') . getEncryptSeperator() .
272                 detectServerName() . getEncryptSeperator() .
273                 detectRemoteAddr() . getEncryptSeperator() .
274                 detectUserAgent() . '/' .
275                 getConfig('SITE_KEY') . '/' .
276                 getConfig('DATE_KEY') . '/' .
277                 getConfig('CACHE_BUSTER')
278         ));
279
280         // Old way with enterable two-char-code
281         $countryRow = '`country`';
282         $countryData = substr(postRequestParameter('cntry'), 0, 2);
283
284         // Add design when extension sql_patches is v0.2.7 or greater
285         // @TODO Rewrite these all to a single filter
286         $GLOBALS['register_sql_columns'] = '';
287         $GLOBALS['register_sql_data'] = '';
288         if (isExtensionInstalledAndNewer('theme', '0.0.8')) {
289                 // Okay, add design here
290                 $GLOBALS['register_sql_columns'] .= ', `curr_theme`';
291                 $GLOBALS['register_sql_data']    .= ", '" . getCurrentTheme() . "'";
292         } // END - if
293
294         // Check if I shall disable sending mail to newly registered members out about active/begging rallye
295         //
296         // First comes first: begging rallye
297         if (!isBegNewMemberNotifyEnabled()) {
298                 $GLOBALS['register_sql_columns'] .= ', `beg_rallye_enable_notify`, `beg_rallye_disable_notify`';
299                 $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
300         } // END - if
301
302         // Second: active rallye
303         if (!isBonusNewMemberNotifyEnabled()) {
304                 $GLOBALS['register_sql_columns'] .= ', `bonus_rallye_enable_notify`, `bonus_rallye_disable_notify`';
305                 $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
306         } // END - if
307
308         // Write user data to table
309         if (isExtensionActive('country')) {
310                 // Save with new selectable country code
311                 $countryRow = '`country_code`';
312                 $countryData = bigintval(postRequestParameter('country_code'));
313         } // END - if
314
315         // Create user's account...
316         SQL_QUERY_ESC("INSERT INTO
317         `{?_MYSQL_PREFIX?}_user_data`
318 (`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'].")
319         VALUES
320 ('%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'].")",
321         array(
322                 $countryRow,
323                 substr(postRequestParameter('gender'), 0, 1),
324                 postRequestParameter('surname'),
325                 postRequestParameter('family'),
326                 postRequestParameter('street_nr'),
327                 $countryData,
328                 bigintval(postRequestParameter('zip')),
329                 postRequestParameter('city'),
330                 postRequestParameter('email'),
331                 bigintval(postRequestParameter('day')),
332                 bigintval(postRequestParameter('month')),
333                 bigintval(postRequestParameter('year')),
334                 generateHash(postRequestParameter('pass1')),
335                 bigintval(postRequestParameter('max_mails')),
336                 bigintval(postRequestParameter('max_mails')),
337                 bigintval(postRequestParameter('refid')),
338                 $hash,
339                 detectRemoteAddr(),
340         ), __FUNCTION__, __LINE__);
341
342         // Get his userid
343         $userid = bigintval(SQL_INSERTID());
344
345         // Did this work?
346         if ($userid == '0') {
347                 // Something bad happened!
348                 loadTemplate('admin_settings_saved', false, '{--USER_NOT_REGISTERED--}');
349
350                 // Stop here
351                 return;
352         } // END - if
353
354         // Is the refback extension there?
355         // @TODO Rewrite this to a filter
356         if (isExtensionActive('refback')) {
357                 // Update refback table
358                 updateRefbackTable($userid);
359         } // END - if
360
361         // Write his welcome-points
362         // @TODO Wether the registration bonus should only be added to user directly or through referal system should be configurable
363         addPointsDirectly('register_welcome', $userid, getPointsRegister());
364
365         // Write catgories
366         if ((is_array(postRequestParameter('cat'))) && (count(postRequestParameter('cat')))) {
367                 foreach (postRequestParameter('cat') as $cat => $joined) {
368                         if ($joined == 'Y') {
369                                 // Insert category entry
370                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`, `cat_id`) VALUES (%s, %s)",
371                                         array($userid, bigintval($cat)), __FUNCTION__, __LINE__);
372                         } // END - if
373                 } // END - foreach
374         } // END - if
375
376         // ... rewrite a zero referal id to the main title
377         if (!isValidUserId(postRequestParameter('refid'))) setPostRequestParameter('refid', getMainTitle());
378
379         // Is ZIP code set?
380         if (isPostRequestParameterSet('zip')) {
381                 // Prepare data array for the email template
382                 // Start with the gender...
383                 $content = array(
384                         'hash'     => $hash,
385                         'userid'   => $userid,
386                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
387                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
388                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
389                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
390                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
391                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
392                         'zip'      => bigintval(postRequestParameter('zip')),
393                         'country'  => $countryData,
394                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
395                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
396                 );
397         } else {
398                 // No ZIP code entered
399                 $content = array(
400                         'hash'     => $hash,
401                         'userid'   => $userid,
402                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
403                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
404                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
405                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
406                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
407                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
408                         'zip'      => '',
409                         'country'  => $countryData,
410                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
411                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
412                 );
413         }
414
415         // Continue with birthday...
416         switch (getLanguage()) {
417                 case 'de':
418                         $content['birthday'] = bigintval(postRequestParameter('day')) . '.' . bigintval(postRequestParameter('month')) . '.' . bigintval(postRequestParameter('year'));
419                         break;
420
421                 default:
422                         $content['birthday'] = bigintval(postRequestParameter('month')) . '/' . bigintval(postRequestParameter('day')) . '/' . bigintval(postRequestParameter('year'));
423                         break;
424         } // END - switch
425
426         // Display information to the user that he got mail and send it away
427         $messageGuest = loadEmailTemplate('register-member', $content, $userid);
428
429         // Send mail to user (confirmation link!)
430         $email = $content['email'];
431         sendEmail($content['email'], '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
432         $content['email'] = $email;
433
434         // Send mail to admin
435         sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'register-admin', $content, $userid);
436 }
437
438 // [EOF]
439 ?>