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