Countless fixes, ext-grade started:
[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 - 2011 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') || ((isRegisterDefaultEnabled()) && (!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 .= displayMessage('{--NO_CATEGORIES_VISIBLE--}', true);
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 // Checks wether the registration data is complete
134 function isRegistrationDataComplete () {
135         // Init elements
136         $GLOBALS['registration_ip_timeout']     = false;
137         $GLOBALS['registration_short_password'] = false;
138         $GLOBALS['registration_selected_cats']  = '0';
139
140         // Default is okay
141         $isOkay = true;
142
143         // First we only check the submitted data then we continue... :)
144         //
145         // Did he agree to our Terms Of Usage?
146         if (postRequestParameter('agree') != 'Y') {
147                 setPostRequestParameter('agree', '!');
148                 $isOkay = false;
149         } // END - if
150
151         // Did he enter a valid email address? (we really don't care about
152         // that, he has to click on a confirmation link :P )
153         if ((!isPostRequestParameterSet('email')) || (!isEmailValid(postRequestParameter('email')))) {
154                 setPostRequestParameter('email', '!');
155                 $isOkay = false;
156         } // END - if
157
158         // And what about surname and family's name?
159         if (!isPostRequestParameterSet('surname')) {
160                 setPostRequestParameter('surname', '!');
161                 $isOkay = false;
162         } // END - if
163         if (!isPostRequestParameterSet('family')) {
164                 setPostRequestParameter('family', '!');
165                 $isOkay = false;
166         } // END - if
167
168         // Get temporary array for modification
169         $postArray = postRequestArray();
170
171         // Check for required fields
172         $isOkay = ($isOkay && ifRequiredRegisterFieldsAreSet($postArray));
173
174         // Set it back in request
175         setPostRequestArray($postArray);
176
177         // Did he enter his password twice?
178         if (((!isPostRequestParameterSet('pass1')) || (!isPostRequestParameterSet('pass2'))) || ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2')))) {
179                 if ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2'))) {
180                         setPostRequestParameter('pass1', '!');
181                         setPostRequestParameter('pass2', '!');
182                 } else {
183                         if (!isPostRequestParameterSet('pass1')) {
184                                 setPostRequestParameter('pass1', '!');
185                         } else {
186                                 setPostRequestParameter('pass1', '');
187                         }
188                         if (!isPostRequestParameterSet('pass2')) {
189                                 setPostRequestParameter('pass2', '!');
190                         } else {
191                                 setPostRequestParameter('pass2', '');
192                         }
193                 }
194                 $isOkay = false;
195         } // END - if
196
197         // Are both passwords zero length?
198         if ((strlen(postRequestParameter('pass1')) == 0) && (strlen(postRequestParameter('pass2')) == 0) && ($isOkay === true)) {
199                 // Is the extension 'register' newer or equal 0.5.5?
200                 if ((isExtensionInstalledAndNewer('register', '0.5.5')) && (isRegisterGeneratePasswordEmptyEnabled())) {
201                         // Generate a random password
202                         $randomPassword = generatePassword();
203
204                         // Set it in both entries
205                         setPostRequestParameter('pass1', $randomPassword);
206                         setPostRequestParameter('pass2', $randomPassword);
207                 } else {
208                         // Not allowed or no recent extension version
209                         setPostRequestParameter('pass1', '!');
210                         setPostRequestParameter('pass2', '!');
211
212                         // ... which is both not okay
213                         $isOkay = false;
214                 }
215         } // END - if
216
217         // Is the password long enouth?
218         if ((strlen(postRequestParameter('pass1')) < getPassLen()) && ($isOkay === true)) {
219                 $GLOBALS['registration_short_password'] = true;
220                 $isOkay = false;
221         } // END - if
222
223         // Do this check only when no admin is logged in
224         if (is_array(postRequestParameter('cat'))) {
225                 // Only continue with array
226                 foreach (postRequestParameter('cat') as $id => $answer) {
227                         // Is this category choosen?
228                         if ($answer == 'Y') {
229                                 $GLOBALS['registration_selected_cats']++;
230                         } // END - if
231                 } // END - foreach
232         } // END - if
233
234         // Enougth categories selected?
235         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',selected='.$GLOBALS['registration_selected_cats'].'/'.getLeastCats());
236         $isOkay = (($isOkay) && ($GLOBALS['registration_selected_cats'] >= getLeastCats()));
237
238         if ((postRequestParameter('email') != '!') && (isCheckDoubleEmailEnabled())) {
239                 // Does the email address already exists in our database?
240                 if ((isEmailTaken(postRequestParameter('email'))) && (!isAdmin())) {
241                         setPostRequestParameter('email', '?');
242                         $isOkay = false;
243                 } // END - if
244         } // END - if
245
246         // Check for IP timeout?
247         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
248         if ((!isAdmin()) && (getIpTimeout() > 0)) {
249                 // Check his IP number
250                 $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);
251                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',timeout='.intval($GLOBALS['registration_ip_timeout']));
252                 $isOkay = (($isOkay) && (!$GLOBALS['registration_ip_timeout']));
253         } // END - if
254
255         // Return result
256         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
257         return $isOkay;
258 }
259
260 // Do the registration
261 function doRegistration () {
262         // Prepapre month and day of birth
263         if (strlen(postRequestParameter('day'))   == 1) setPostRequestParameter('day'  , '0' . postRequestParameter('day'));
264         if (strlen(postRequestParameter('month')) == 1) setPostRequestParameter('month', '0' . postRequestParameter('month'));
265
266         // Generate hash which will be inserted into confirmation mail
267         $hash = generateHash(sha1(
268                 // Get total confirmed, ...
269                 getTotalConfirmedUser() . getEncryptSeperator() .
270                 // ... unconfirmed ...
271                 getTotalUnconfirmedUser() . getEncryptSeperator() .
272                 // ... and locked users!
273                 getTotalLockedUser() . getEncryptSeperator() .
274                 postRequestParameter('month') . '-' .
275                 postRequestParameter('day') . '-' .
276                 postRequestParameter('year') . getEncryptSeperator() .
277                 detectServerName() . getEncryptSeperator() .
278                 detectRemoteAddr() . getEncryptSeperator() .
279                 detectUserAgent() . '/' .
280                 getSiteKey() . '/' .
281                 getDateKey() . '/' .
282                 getConfig('CACHE_BUSTER')
283         ));
284
285         // Old way with enterable two-char-code
286         $countryRow = '`country`';
287         $countryData = substr(postRequestParameter('cntry'), 0, 2);
288
289         // Add design when extension sql_patches is v0.2.7 or greater
290         // @TODO Rewrite these all to a single filter
291         $GLOBALS['register_sql_columns'] = '';
292         $GLOBALS['register_sql_data'] = '';
293         if (isExtensionInstalledAndNewer('theme', '0.0.8')) {
294                 // Okay, add design here
295                 $GLOBALS['register_sql_columns'] .= ', `curr_theme`';
296                 $GLOBALS['register_sql_data']    .= ", '" . getCurrentTheme() . "'";
297         } // END - if
298
299         // Check if I shall disable sending mail to newly registered members out about active/begging rallye
300         //
301         // First comes first: begging rallye
302         if ((isExtensionInstalledAndNewer('beg', '0.2.7')) && (!isBegNewMemberNotifyEnabled())) {
303                 $GLOBALS['register_sql_columns'] .= ', `beg_rallye_enable_notify`, `beg_rallye_disable_notify`';
304                 $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
305         } // END - if
306
307         // Second: active rallye
308         if (!isBonusNewMemberNotifyEnabled()) {
309                 $GLOBALS['register_sql_columns'] .= ', `bonus_rallye_enable_notify`, `bonus_rallye_disable_notify`';
310                 $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
311         } // END - if
312
313         // Write user data to table
314         if (isExtensionActive('country')) {
315                 // Save with new selectable country code
316                 $countryRow = '`country_code`';
317                 $countryData = bigintval(postRequestParameter('country_code'));
318         } // END - if
319
320         // Create user's account...
321         SQL_QUERY_ESC("INSERT INTO
322         `{?_MYSQL_PREFIX?}_user_data`
323 (`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'].")
324         VALUES
325 ('%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'].")",
326         array(
327                 $countryRow,
328                 substr(postRequestParameter('gender'), 0, 1),
329                 postRequestParameter('surname'),
330                 postRequestParameter('family'),
331                 postRequestParameter('street_nr'),
332                 $countryData,
333                 bigintval(postRequestParameter('zip')),
334                 postRequestParameter('city'),
335                 postRequestParameter('email'),
336                 bigintval(postRequestParameter('day')),
337                 bigintval(postRequestParameter('month')),
338                 bigintval(postRequestParameter('year')),
339                 generateHash(postRequestParameter('pass1')),
340                 bigintval(postRequestParameter('max_mails')),
341                 bigintval(postRequestParameter('max_mails')),
342                 makeDatabaseUserId(postRequestParameter('refid')),
343                 $hash,
344                 detectRemoteAddr(),
345         ), __FUNCTION__, __LINE__);
346
347         // Get his userid
348         $userid = bigintval(SQL_INSERTID());
349
350         // Did this work?
351         if ($userid == '0') {
352                 // Something bad happened!
353                 displayMessage('{--USER_NOT_REGISTERED--}');
354
355                 // Stop here
356                 return;
357         } // END - if
358
359         // Is the refback extension there?
360         // @TODO Rewrite this to a filter
361         if (isExtensionActive('refback')) {
362                 // Update refback table
363                 updateRefbackTable($userid);
364         } // END - if
365
366         // Write his welcome-points
367         // @TODO Wether the registration bonus should only be added to user directly or through referal system should be configurable
368         addPointsDirectly('register_welcome', $userid, getPointsRegister());
369
370         // Write catgories
371         if ((is_array(postRequestParameter('cat'))) && (count(postRequestParameter('cat')))) {
372                 foreach (postRequestParameter('cat') as $categoryId => $joined) {
373                         if ($joined == 'Y') {
374                                 // Insert category entry
375                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`, `cat_id`) VALUES (%s, %s)",
376                                         array(
377                                                 $userid,
378                                                 bigintval($categoryId)
379                                         ), __FUNCTION__, __LINE__);
380                         } // END - if
381                 } // END - foreach
382         } // END - if
383
384         // ... rewrite a zero referal id to the main title
385         if (!isValidUserId(postRequestParameter('refid'))) {
386                 setPostRequestParameter('refid', getMainTitle());
387         } // END - if
388
389         // Is ZIP code set?
390         if (isPostRequestParameterSet('zip')) {
391                 // Prepare data array for the email template
392                 // Start with the gender...
393                 $content = array(
394                         'hash'     => $hash,
395                         'userid'   => $userid,
396                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
397                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
398                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
399                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
400                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
401                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
402                         'zip'      => bigintval(postRequestParameter('zip')),
403                         'country'  => $countryData,
404                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
405                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
406                 );
407         } else {
408                 // No ZIP code entered
409                 $content = array(
410                         'hash'     => $hash,
411                         'userid'   => $userid,
412                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
413                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
414                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
415                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
416                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
417                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
418                         'zip'      => '',
419                         'country'  => $countryData,
420                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
421                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
422                 );
423         }
424
425         // Continue with birthday...
426         switch (getLanguage()) {
427                 case 'de':
428                         $content['birthday'] = bigintval(postRequestParameter('day')) . '.' . bigintval(postRequestParameter('month')) . '.' . bigintval(postRequestParameter('year'));
429                         break;
430
431                 default:
432                         $content['birthday'] = bigintval(postRequestParameter('month')) . '/' . bigintval(postRequestParameter('day')) . '/' . bigintval(postRequestParameter('year'));
433                         break;
434         } // END - switch
435
436         // Display information to the user that he got mail and send it away
437         $messageGuest = loadEmailTemplate('guest_register_done', $content, $userid, false);
438
439         // Send mail to user (confirmation link!)
440         $email = $content['email'];
441         sendEmail($content['email'], '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
442         $content['email'] = $email;
443
444         // Send mail to admin
445         sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'admin_register_done', $content, $userid);
446 }
447
448 //-----------------------------------------------------------------------------
449 //                      Wrapper functions for ext-register
450 //-----------------------------------------------------------------------------
451
452 // Getter for 'display_refid'
453 function getDisplayRefid () {
454         // Is the cache entry set?
455         if (!isset($GLOBALS[__FUNCTION__])) {
456                 // No, so determine it
457                 $GLOBALS[__FUNCTION__] = getConfig('display_refid');
458         } // END - if
459
460         // Return cached entry
461         return $GLOBALS[__FUNCTION__];
462 }
463
464 // Checks wether 'display_refid' is "YES"
465 function isDisplayRefidEnabled () {
466         // Is the cache entry set?
467         if (!isset($GLOBALS[__FUNCTION__])) {
468                 // No, so determine it
469                 $GLOBALS[__FUNCTION__] = (getDisplayRefid() == 'Y');
470         } // END - if
471
472         // Return cached entry
473         return $GLOBALS[__FUNCTION__];
474 }
475
476 // Getter for 'ip_timeout'
477 function getIpTimeout () {
478         // Is the cache entry set?
479         if (!isset($GLOBALS[__FUNCTION__])) {
480                 // No, so determine it
481                 $GLOBALS[__FUNCTION__] = getConfig('ip_timeout');
482         } // END - if
483
484         // Return cached entry
485         return $GLOBALS[__FUNCTION__];
486 }
487
488 // Getter for 'register_default'
489 function getRegisterDefault () {
490         // Is the cache entry set?
491         if (!isset($GLOBALS[__FUNCTION__])) {
492                 // No, so determine it
493                 $GLOBALS[__FUNCTION__] = getConfig('register_default');
494         } // END - if
495
496         // Return cached entry
497         return $GLOBALS[__FUNCTION__];
498 }
499
500 // Checks wether 'register_default' is "YES"
501 function isRegisterDefaultEnabled () {
502         // Is the cache entry set?
503         if (!isset($GLOBALS[__FUNCTION__])) {
504                 // No, so determine it
505                 $GLOBALS[__FUNCTION__] = (getRegisterDefault() == 'Y');
506         } // END - if
507
508         // Return cached entry
509         return $GLOBALS[__FUNCTION__];
510 }
511
512 // Getter for 'register_generate_password_empty'
513 function getRegisterGeneratePasswordEmpty () {
514         // Is the cache entry set?
515         if (!isset($GLOBALS[__FUNCTION__])) {
516                 // No, so determine it
517                 $GLOBALS[__FUNCTION__] = getConfig('register_generate_password_empty');
518         } // END - if
519
520         // Return cached entry
521         return $GLOBALS[__FUNCTION__];
522 }
523
524 // Checks wether 'register_generate_password_empty' is "YES"
525 function isRegisterGeneratePasswordEmptyEnabled () {
526         // Is the cache entry set?
527         if (!isset($GLOBALS[__FUNCTION__])) {
528                 // No, so determine it
529                 $GLOBALS[__FUNCTION__] = (getRegisterGeneratePasswordEmpty() == 'Y');
530         } // END - if
531
532         // Return cached entry
533         return $GLOBALS[__FUNCTION__];
534 }
535
536 // [EOF]
537 ?>