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