c768ccfbbd44bb9c8cda82518e66dcdeae6569fe
[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         // Are both passwords zero length?
178         if ((strlen(postRequestParameter('pass1')) == 0) && (strlen(postRequestParameter('pass2')) == 0) && ($isOkay === true)) {
179                 // Is the extension 'register' newer or equal 0.5.5?
180                 if ((isExtensionInstalledAndNewer('register', '0.5.5')) && (isRegisterGeneratePasswordEmptyEnabled())) {
181                         // Generate a random password
182                         $randomPassword = generatePassword();
183
184                         // Set it in both entries
185                         setPostRequestParameter('pass1', $randomPassword);
186                         setPostRequestParameter('pass2', $randomPassword);
187                 } else {
188                         // Not allowed or no recent extension version
189                         setPostRequestParameter('pass1', '!');
190                         setPostRequestParameter('pass2', '!');
191
192                         // ... which is both not okay
193                         $isOkay = false;
194                 }
195         } // END - if
196
197         // Did he enter his password twice?
198         if (((!isPostRequestParameterSet('pass1')) || (!isPostRequestParameterSet('pass2'))) || ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2')))) {
199                 if ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2'))) {
200                         setPostRequestParameter('pass1', '!');
201                         setPostRequestParameter('pass2', '!');
202                 } else {
203                         if (!isPostRequestParameterSet('pass1')) {
204                                 setPostRequestParameter('pass1', '!');
205                         } else {
206                                 setPostRequestParameter('pass1', '');
207                         }
208                         if (!isPostRequestParameterSet('pass2')) {
209                                 setPostRequestParameter('pass2', '!');
210                         } else {
211                                 setPostRequestParameter('pass2', '');
212                         }
213                 }
214                 $isOkay = false;
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 ext-theme is v0.0.8 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']    .= ", '{%%pipe,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 ((isExtensionActive('bonus')) && (!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`,`ref_payout`".$GLOBALS['register_sql_columns'].")
324         VALUES
325 ('%s','%s','%s','%s','%s',%s,'%s','%s',%s, %s,%s,'%s',%s, %s,'%s','UNCONFIRMED','%s','{%%pipe,detectRemoteAddr%%}', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), {?ref_payout?}".$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                 makeZeroToNull(postRequestParameter('refid')),
343                 $hash
344         ), __FUNCTION__, __LINE__);
345
346         // Get his userid
347         $userid = bigintval(SQL_INSERTID());
348
349         // Did this work?
350         if ($userid == '0') {
351                 // Something bad happened!
352                 displayMessage('{--USER_NOT_REGISTERED--}');
353
354                 // Stop here
355                 return;
356         } // END - if
357
358         // Shall we reset random refid? Only possible with latest ext-user
359         if (isExtensionInstalledAndNewer('user', '0.3.4')) {
360                 // Reset all accounts, registration is done
361                 SQL_QUERY('UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0', __FUNCTION__, __LINE__);
362         } // END - if
363
364         // Update referal table
365         updateReferalCounter($userid);
366
367         // Write his welcome-points
368         initReferalSystem();
369         addPointsThroughReferalSystem('register_welcome', $userid, getPointsRegister());
370
371         // Write catgories
372         if ((is_array(postRequestParameter('cat'))) && (count(postRequestParameter('cat')))) {
373                 foreach (postRequestParameter('cat') as $categoryId => $joined) {
374                         if ($joined == 'Y') {
375                                 // Insert category entry
376                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`,`cat_id`) VALUES (%s, %s)",
377                                         array(
378                                                 $userid,
379                                                 bigintval($categoryId)
380                                         ), __FUNCTION__, __LINE__);
381                         } // END - if
382                 } // END - foreach
383         } // END - if
384
385         // ... rewrite a zero referal id to the main title
386         if (!isValidUserId(postRequestParameter('refid'))) {
387                 setPostRequestParameter('refid', getMainTitle());
388         } // END - if
389
390         // Is ZIP code set?
391         if (isPostRequestParameterSet('zip')) {
392                 // Prepare data array for the email template
393                 // Start with the gender...
394                 $content = array(
395                         'hash'     => $hash,
396                         'userid'   => $userid,
397                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
398                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
399                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
400                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
401                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
402                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
403                         'zip'      => bigintval(postRequestParameter('zip')),
404                         'country'  => $countryData,
405                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
406                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
407                 );
408         } else {
409                 // No ZIP code entered
410                 $content = array(
411                         'hash'     => $hash,
412                         'userid'   => $userid,
413                         'gender'   => SQL_ESCAPE(postRequestParameter('gender')),
414                         'surname'  => SQL_ESCAPE(postRequestParameter('surname')),
415                         'family'   => SQL_ESCAPE(postRequestParameter('family')),
416                         'email'    => SQL_ESCAPE(postRequestParameter('email')),
417                         'street'   => SQL_ESCAPE(postRequestParameter('street_nr')),
418                         'city'     => SQL_ESCAPE(postRequestParameter('city')),
419                         'zip'      => '',
420                         'country'  => $countryData,
421                         'refid'    => SQL_ESCAPE(postRequestParameter('refid')),
422                         'password' => SQL_ESCAPE(postRequestParameter('pass1')),
423                 );
424         }
425
426         // Continue with birthday...
427         switch (getLanguage()) {
428                 case 'de':
429                         $content['birthday'] = bigintval(postRequestParameter('day')) . '.' . bigintval(postRequestParameter('month')) . '.' . bigintval(postRequestParameter('year'));
430                         break;
431
432                 default:
433                         $content['birthday'] = bigintval(postRequestParameter('month')) . '/' . bigintval(postRequestParameter('day')) . '/' . bigintval(postRequestParameter('year'));
434                         break;
435         } // END - switch
436
437         // Display information to the user that he got mail and send it away
438         $messageGuest = loadEmailTemplate('guest_register_done', $content, $userid, false);
439
440         // Send mail to user (confirmation link!)
441         sendEmail($userid, '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
442
443         // Send mail to admin
444         sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'admin_register_done', $content, $userid);
445 }
446
447 //-----------------------------------------------------------------------------
448 //                      Wrapper functions for ext-register
449 //-----------------------------------------------------------------------------
450
451 // Getter for 'display_refid'
452 function getDisplayRefid () {
453         // Is the cache entry set?
454         if (!isset($GLOBALS[__FUNCTION__])) {
455                 // No, so determine it
456                 $GLOBALS[__FUNCTION__] = getConfig('display_refid');
457         } // END - if
458
459         // Return cached entry
460         return $GLOBALS[__FUNCTION__];
461 }
462
463 // Checks wether 'display_refid' is "YES"
464 function isDisplayRefidEnabled () {
465         // Is the cache entry set?
466         if (!isset($GLOBALS[__FUNCTION__])) {
467                 // No, so determine it
468                 $GLOBALS[__FUNCTION__] = (getDisplayRefid() == 'Y');
469         } // END - if
470
471         // Return cached entry
472         return $GLOBALS[__FUNCTION__];
473 }
474
475 // Getter for 'ip_timeout'
476 function getIpTimeout () {
477         // Is the cache entry set?
478         if (!isset($GLOBALS[__FUNCTION__])) {
479                 // No, so determine it
480                 $GLOBALS[__FUNCTION__] = getConfig('ip_timeout');
481         } // END - if
482
483         // Return cached entry
484         return $GLOBALS[__FUNCTION__];
485 }
486
487 // Getter for 'register_default'
488 function getRegisterDefault () {
489         // Is the cache entry set?
490         if (!isset($GLOBALS[__FUNCTION__])) {
491                 // No, so determine it
492                 $GLOBALS[__FUNCTION__] = getConfig('register_default');
493         } // END - if
494
495         // Return cached entry
496         return $GLOBALS[__FUNCTION__];
497 }
498
499 // Checks wether 'register_default' is "YES"
500 function isRegisterDefaultEnabled () {
501         // Is the cache entry set?
502         if (!isset($GLOBALS[__FUNCTION__])) {
503                 // No, so determine it
504                 $GLOBALS[__FUNCTION__] = (getRegisterDefault() == 'Y');
505         } // END - if
506
507         // Return cached entry
508         return $GLOBALS[__FUNCTION__];
509 }
510
511 // Getter for 'register_generate_password_empty'
512 function getRegisterGeneratePasswordEmpty () {
513         // Is the cache entry set?
514         if (!isset($GLOBALS[__FUNCTION__])) {
515                 // No, so determine it
516                 $GLOBALS[__FUNCTION__] = getConfig('register_generate_password_empty');
517         } // END - if
518
519         // Return cached entry
520         return $GLOBALS[__FUNCTION__];
521 }
522
523 // Checks wether 'register_generate_password_empty' is "YES"
524 function isRegisterGeneratePasswordEmptyEnabled () {
525         // Is the cache entry set?
526         if (!isset($GLOBALS[__FUNCTION__])) {
527                 // No, so determine it
528                 $GLOBALS[__FUNCTION__] = (getRegisterGeneratePasswordEmpty() == 'Y');
529         } // END - if
530
531         // Return cached entry
532         return $GLOBALS[__FUNCTION__];
533 }
534
535 // [EOF]
536 ?>