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