8eb91a20cb08d6d4e0dbfd02d8243b6b91cbaf69
[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 $cat => $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($userid, bigintval($cat)), __FUNCTION__, __LINE__);
377                         } // END - if
378                 } // END - foreach
379         } // END - if
380
381         // ... rewrite a zero referal id to the main title
382         if (!isValidUserId(postRequestParameter('refid'))) {
383                 setPostRequestParameter('refid', getMainTitle());
384         } // END - if
385
386         // Is ZIP code set?
387         if (isPostRequestParameterSet('zip')) {
388                 // Prepare data array for the email template
389                 // Start with the gender...
390                 $content = array(
391                         'hash'     => $hash,
392                         'userid'   => $userid,
393                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
394                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
395                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
396                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
397                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
398                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
399                         'zip'      => bigintval(postRequestParameter('zip')),
400                         'country'  => $countryData,
401                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
402                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
403                 );
404         } else {
405                 // No ZIP code entered
406                 $content = array(
407                         'hash'     => $hash,
408                         'userid'   => $userid,
409                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
410                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
411                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
412                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
413                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
414                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
415                         'zip'      => '',
416                         'country'  => $countryData,
417                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
418                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
419                 );
420         }
421
422         // Continue with birthday...
423         switch (getLanguage()) {
424                 case 'de':
425                         $content['birthday'] = bigintval(postRequestParameter('day')) . '.' . bigintval(postRequestParameter('month')) . '.' . bigintval(postRequestParameter('year'));
426                         break;
427
428                 default:
429                         $content['birthday'] = bigintval(postRequestParameter('month')) . '/' . bigintval(postRequestParameter('day')) . '/' . bigintval(postRequestParameter('year'));
430                         break;
431         } // END - switch
432
433         // Display information to the user that he got mail and send it away
434         $messageGuest = loadEmailTemplate('register-member', $content, $userid, false);
435
436         // Send mail to user (confirmation link!)
437         $email = $content['email'];
438         sendEmail($content['email'], '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
439         $content['email'] = $email;
440
441         // Send mail to admin
442         sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'register-admin', $content, $userid);
443 }
444
445 //-----------------------------------------------------------------------------
446 //                      Wrapper functions for ext-register
447 //-----------------------------------------------------------------------------
448
449 // Getter for 'display_refid'
450 function getDisplayRefid () {
451         // Is the cache entry set?
452         if (!isset($GLOBALS[__FUNCTION__])) {
453                 // No, so determine it
454                 $GLOBALS[__FUNCTION__] = getConfig('display_refid');
455         } // END - if
456
457         // Return cached entry
458         return $GLOBALS[__FUNCTION__];
459 }
460
461 // Checks wether 'display_refid' is "YES"
462 function isDisplayRefidEnabled () {
463         // Is the cache entry set?
464         if (!isset($GLOBALS[__FUNCTION__])) {
465                 // No, so determine it
466                 $GLOBALS[__FUNCTION__] = (getDisplayRefid() == 'Y');
467         } // END - if
468
469         // Return cached entry
470         return $GLOBALS[__FUNCTION__];
471 }
472
473 // Getter for 'ip_timeout'
474 function getIpTimeout () {
475         // Is the cache entry set?
476         if (!isset($GLOBALS[__FUNCTION__])) {
477                 // No, so determine it
478                 $GLOBALS[__FUNCTION__] = getConfig('ip_timeout');
479         } // END - if
480
481         // Return cached entry
482         return $GLOBALS[__FUNCTION__];
483 }
484
485 // Getter for 'register_default'
486 function getRegisterDefault () {
487         // Is the cache entry set?
488         if (!isset($GLOBALS[__FUNCTION__])) {
489                 // No, so determine it
490                 $GLOBALS[__FUNCTION__] = getConfig('register_default');
491         } // END - if
492
493         // Return cached entry
494         return $GLOBALS[__FUNCTION__];
495 }
496
497 // Checks wether 'register_default' is "YES"
498 function isRegisterDefaultEnabled () {
499         // Is the cache entry set?
500         if (!isset($GLOBALS[__FUNCTION__])) {
501                 // No, so determine it
502                 $GLOBALS[__FUNCTION__] = (getRegisterDefault() == 'Y');
503         } // END - if
504
505         // Return cached entry
506         return $GLOBALS[__FUNCTION__];
507 }
508
509 // Getter for 'register_generate_password_empty'
510 function getRegisterGeneratePasswordEmpty () {
511         // Is the cache entry set?
512         if (!isset($GLOBALS[__FUNCTION__])) {
513                 // No, so determine it
514                 $GLOBALS[__FUNCTION__] = getConfig('register_generate_password_empty');
515         } // END - if
516
517         // Return cached entry
518         return $GLOBALS[__FUNCTION__];
519 }
520
521 // Checks wether 'register_generate_password_empty' is "YES"
522 function isRegisterGeneratePasswordEmptyEnabled () {
523         // Is the cache entry set?
524         if (!isset($GLOBALS[__FUNCTION__])) {
525                 // No, so determine it
526                 $GLOBALS[__FUNCTION__] = (getRegisterGeneratePasswordEmpty() == 'Y');
527         } // END - if
528
529         // Return cached entry
530         return $GLOBALS[__FUNCTION__];
531 }
532
533 // [EOF]
534 ?>