Extension ext-network continued, functions renamed:
[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://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) {
75         // Init output
76         $OUT = '';
77
78         // Guests are mostly not interested in how many members has
79         // choosen an individual category
80         $whereStatement = "WHERE `visible`='Y' ";
81
82         // Admins are allowed to see every category...
83         if (isAdmin()) $whereStatement = '';
84
85         // Look for categories
86         $result = SQL_QUERY('SELECT `id`,`cat`,`visible` FROM `{?_MYSQL_PREFIX?}_cats` ' . $whereStatement . ' ORDER BY `sort` ASC',
87                 __FUNCTION__, __LINE__);
88
89         if (!SQL_HASZERONUMS($result)) {
90                 // List alle visible modules (or all to the admin)
91                 $OUT .= '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
92                 while ($content = SQL_FETCHARRAY($result)) {
93                         // Prepare array for the template
94                         $content['default_yes'] = '';
95                         $content['default_no']  = '';
96
97                         // Mark categories
98                         if ((postRequestElement('cat', $content['id']) == 'Y') || ((isRegisterDefaultEnabled()) && (!isPostRequestElementSet('cat', $content['id'])))) {
99                                 $content['default_yes'] = ' checked="checked"';
100                         } else {
101                                 $content['default_no']  = ' checked="checked"';
102                         }
103
104                         // Load template and switch color
105                         $OUT .= loadTemplate('guest_cat_row', true, $content);
106                 } // END - while
107                 $OUT .= '</table>';
108
109                 // Free memory
110                 SQL_FREERESULT($result);
111         } else {
112                 // No categories setted up so far...
113                 $OUT .= displayMessage('{--NO_CATEGORIES_VISIBLE--}', true);
114         }
115
116         // Return generated HTML code
117         return $OUT;
118 }
119
120 // Outputs a 'failed message'
121 function registerOutputFailedMessage ($messageId, $extra='') {
122         if (empty($messageId)) {
123                 outputHtml('<div class="bad">' . $extra . '</div>');
124         } else {
125                 outputHtml('<div class="bad">{--' . $messageId . '--}' . $extra . '</div>');
126         }
127 }
128
129 // Checks wether the registration data is complete
130 function isRegistrationDataComplete () {
131         // Init elements
132         $GLOBALS['registration_ip_timeout']     = false;
133         $GLOBALS['registration_short_password'] = false;
134         $GLOBALS['registration_selected_cats']  = '0';
135
136         // Default is okay
137         $isOkay = true;
138
139         // First we only check the submitted data then we continue... :)
140         //
141         // Did he agree to our Terms Of Usage?
142         if (postRequestElement('agree') != 'Y') {
143                 setPostRequestElement('agree', '!');
144                 $isOkay = false;
145         } // END - if
146
147         // Did he enter a valid email address? (we really don't care about
148         // that, he has to click on a confirmation link :P )
149         if ((!isPostRequestElementSet('email')) || (!isEmailValid(postRequestElement('email')))) {
150                 setPostRequestElement('email', '!');
151                 $isOkay = false;
152         } // END - if
153
154         // And what about surname and family's name?
155         if (!isPostRequestElementSet('surname')) {
156                 setPostRequestElement('surname', '!');
157                 $isOkay = false;
158         } // END - if
159         if (!isPostRequestElementSet('family')) {
160                 setPostRequestElement('family', '!');
161                 $isOkay = false;
162         } // END - if
163
164         // Get temporary array for modification
165         $postArray = postRequestArray();
166
167         // Check for required fields
168         $isOkay = ($isOkay && ifRequiredRegisterFieldsAreSet($postArray));
169
170         // Set it back in request
171         setPostRequestArray($postArray);
172
173         // Are both passwords zero length?
174         if ((strlen(postRequestElement('pass1')) == 0) && (strlen(postRequestElement('pass2')) == 0) && ($isOkay === true)) {
175                 // Is the extension 'register' newer or equal 0.5.5?
176                 if ((isExtensionInstalledAndNewer('register', '0.5.5')) && (isRegisterGeneratePasswordEmptyEnabled())) {
177                         // Generate a random password
178                         $randomPassword = generatePassword();
179
180                         // Set it in both entries
181                         setPostRequestElement('pass1', $randomPassword);
182                         setPostRequestElement('pass2', $randomPassword);
183                 } else {
184                         // Not allowed or no recent extension version
185                         setPostRequestElement('pass1', '!');
186                         setPostRequestElement('pass2', '!');
187
188                         // ... which is both not okay
189                         $isOkay = false;
190                 }
191         } // END - if
192
193         // Did he enter his password twice?
194         if (((!isPostRequestElementSet('pass1')) || (!isPostRequestElementSet('pass2'))) || ((postRequestElement('pass1') != postRequestElement('pass2')) && (isPostRequestElementSet('pass1')) && (isPostRequestElementSet('pass2')))) {
195                 if ((postRequestElement('pass1') != postRequestElement('pass2')) && (isPostRequestElementSet('pass1')) && (isPostRequestElementSet('pass2'))) {
196                         setPostRequestElement('pass1', '!');
197                         setPostRequestElement('pass2', '!');
198                 } else {
199                         if (!isPostRequestElementSet('pass1')) {
200                                 setPostRequestElement('pass1', '!');
201                         } else {
202                                 setPostRequestElement('pass1', '');
203                         }
204                         if (!isPostRequestElementSet('pass2')) {
205                                 setPostRequestElement('pass2', '!');
206                         } else {
207                                 setPostRequestElement('pass2', '');
208                         }
209                 }
210                 $isOkay = false;
211         } // END - if
212
213         // Is the password long enouth?
214         if ((strlen(postRequestElement('pass1')) < getPassLen()) && ($isOkay === true)) {
215                 $GLOBALS['registration_short_password'] = true;
216                 $isOkay = false;
217         } // END - if
218
219         // Do this check only when no admin is logged in
220         if (is_array(postRequestElement('cat'))) {
221                 // Only continue with array
222                 foreach (postRequestElement('cat') as $id => $answer) {
223                         // Is this category choosen?
224                         if ($answer == 'Y') {
225                                 $GLOBALS['registration_selected_cats']++;
226                         } // END - if
227                 } // END - foreach
228         } // END - if
229
230         // Enougth categories selected?
231         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',selected='.$GLOBALS['registration_selected_cats'].'/'.getLeastCats());
232         $isOkay = (($isOkay) && ($GLOBALS['registration_selected_cats'] >= getLeastCats()));
233
234         if ((postRequestElement('email') != '!') && (isCheckDoubleEmailEnabled())) {
235                 // Does the email address already exists in our database?
236                 if ((isEmailTaken(postRequestElement('email'))) && (!isAdmin())) {
237                         setPostRequestElement('email', '?');
238                         $isOkay = false;
239                 } // END - if
240         } // END - if
241
242         // Check for IP timeout?
243         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
244         if ((!isAdmin()) && (getIpTimeout() > 0)) {
245                 // Check his IP number
246                 $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?})') == 1);
247                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',timeout='.intval($GLOBALS['registration_ip_timeout']));
248                 $isOkay = (($isOkay) && (!$GLOBALS['registration_ip_timeout']));
249         } // END - if
250
251         // Return result
252         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
253         return $isOkay;
254 }
255
256 // Do the registration
257 function doRegistration () {
258         // Prepapre month and day of birth
259         if (strlen(postRequestElement('day'))   == 1) setPostRequestElement('day'  , '0' . postRequestElement('day'));
260         if (strlen(postRequestElement('month')) == 1) setPostRequestElement('month', '0' . postRequestElement('month'));
261
262         // Generate hash which will be inserted into confirmation mail
263         $hash = generateHash(sha1(
264                 // Get total confirmed, ...
265                 getTotalConfirmedUser() . getEncryptSeparator() .
266                 // ... unconfirmed ...
267                 getTotalUnconfirmedUser() . getEncryptSeparator() .
268                 // ... and locked users!
269                 getTotalLockedUser() . getEncryptSeparator() .
270                 postRequestElement('month') . '-' .
271                 postRequestElement('day') . '-' .
272                 postRequestElement('year') . getEncryptSeparator() .
273                 detectServerName() . getEncryptSeparator() .
274                 detectRemoteAddr() . getEncryptSeparator() .
275                 detectUserAgent() . '/' .
276                 getSiteKey() . '/' .
277                 getDateKey() . '/' .
278                 getConfig('CACHE_BUSTER')
279         ));
280
281         // Old way with enterable two-char-code
282         $countryRow = '`country`';
283         $countryData = substr(postRequestElement('cntry'), 0, 2);
284
285         // Add design when extension ext-theme is v0.0.8 or greater
286         // @TODO Rewrite these all to a single filter
287         $GLOBALS['register_sql_columns'] = '';
288         $GLOBALS['register_sql_data'] = '';
289         if (isExtensionInstalledAndNewer('theme', '0.0.8')) {
290                 // Okay, add design here
291                 $GLOBALS['register_sql_columns'] .= ',`curr_theme`';
292                 $GLOBALS['register_sql_data']    .= ", '{%%pipe,getCurrentTheme%%}'";
293         } // END - if
294
295         // Check if I shall disable sending mail to newly registered members out about active/begging rallye
296         //
297         // First comes first: begging rallye
298         if ((isExtensionInstalledAndNewer('beg', '0.2.7')) && (!isBegNewMemberNotifyEnabled())) {
299                 $GLOBALS['register_sql_columns'] .= ',`beg_rallye_enable_notify`,`beg_rallye_disable_notify`';
300                 $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
301         } // END - if
302
303         // Second: active rallye
304         if ((isExtensionActive('bonus')) && (!isBonusNewMemberNotifyEnabled())) {
305                 $GLOBALS['register_sql_columns'] .= ',`bonus_rallye_enable_notify`,`bonus_rallye_disable_notify`';
306                 $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
307         } // END - if
308
309         // Write user data to table
310         if (isExtensionActive('country')) {
311                 // Save with new selectable country code
312                 $countryRow = '`country_code`';
313                 $countryData = bigintval(postRequestElement('country_code'));
314         } // END - if
315
316         // Create user's account...
317         SQL_QUERY_ESC("INSERT INTO
318         `{?_MYSQL_PREFIX?}_user_data`
319 (
320         `gender`,
321         `surname`,
322         `family`,
323         `street_nr`,
324         %s,
325         `zip`,
326         `city`,
327         `email`,
328         `birth_day`,
329         `birth_month`,
330         `birth_year`,
331         `password`,
332         `max_mails`,
333         `receive_mails`,
334         `refid`,
335         `status`,
336         `user_hash`,
337         `REMOTE_ADDR`,
338         `joined`,
339         `last_update`,
340         `ref_payout`
341         ".$GLOBALS['register_sql_columns']."
342 ) VALUES (
343         '%s'
344         '%s'
345         '%s'
346         '%s'
347         '%s',
348         %s,
349         '%s',
350         '%s',
351         %s,
352         %s,
353         %s,
354         '%s',
355         %s,
356         %s,
357         %s,
358         'UNCONFIRMED',
359         '%s',
360         '{%%pipe,detectRemoteAddr%%}',
361         UNIX_TIMESTAMP(),
362         UNIX_TIMESTAMP(),
363         {?ref_payout?}
364         ".$GLOBALS['register_sql_data'].")",
365         array(
366                 $countryRow,
367                 substr(postRequestElement('gender'), 0, 1),
368                 postRequestElement('surname'),
369                 postRequestElement('family'),
370                 postRequestElement('street_nr'),
371                 $countryData,
372                 bigintval(postRequestElement('zip')),
373                 postRequestElement('city'),
374                 postRequestElement('email'),
375                 bigintval(postRequestElement('day')),
376                 bigintval(postRequestElement('month')),
377                 bigintval(postRequestElement('year')),
378                 generateHash(postRequestElement('pass1')),
379                 bigintval(postRequestElement('max_mails')),
380                 bigintval(postRequestElement('max_mails')),
381                 convertZeroToNull(postRequestElement('refid')),
382                 $hash
383         ), __FUNCTION__, __LINE__);
384
385         // Get his userid
386         $userid = bigintval(SQL_INSERTID());
387
388         // Did this work?
389         if ($userid == '0') {
390                 // Something bad happened!
391                 displayMessage('{--USER_NOT_REGISTERED--}');
392
393                 // Stop here
394                 return;
395         } // END - if
396
397         // Shall we reset random refid? Only possible with latest ext-user
398         if (isExtensionInstalledAndNewer('user', '0.3.4')) {
399                 // Reset all accounts, registration is done
400                 SQL_QUERY('UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0', __FUNCTION__, __LINE__);
401         } // END - if
402
403         // Update referral table
404         updateReferralCounter($userid);
405
406         // Write his welcome-points
407         initReferralSystem();
408         addPointsThroughReferralSystem('register_welcome', $userid, getPointsRegister());
409
410         // Write catgories
411         if ((is_array(postRequestElement('cat'))) && (count(postRequestElement('cat')))) {
412                 foreach (postRequestElement('cat') as $categoryId => $joined) {
413                         if ($joined == 'Y') {
414                                 // Insert category entry
415                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`,`cat_id`) VALUES (%s, %s)",
416                                         array(
417                                                 $userid,
418                                                 bigintval($categoryId)
419                                         ), __FUNCTION__, __LINE__);
420                         } // END - if
421                 } // END - foreach
422         } // END - if
423
424         // ... rewrite a zero referral id to the main title
425         if (!isValidUserId(postRequestElement('refid'))) {
426                 setPostRequestElement('refid', getMainTitle());
427         } // END - if
428
429         // Is ZIP code set?
430         if (isPostRequestElementSet('zip')) {
431                 // Prepare data array for the email template
432                 // Start with the gender...
433                 $content = array(
434                         'hash'     => $hash,
435                         'userid'   => $userid,
436                         'gender'   => SQL_ESCAPE(postRequestElement('gender')),
437                         'surname'  => SQL_ESCAPE(postRequestElement('surname')),
438                         'family'   => SQL_ESCAPE(postRequestElement('family')),
439                         'email'    => SQL_ESCAPE(postRequestElement('email')),
440                         'street'   => SQL_ESCAPE(postRequestElement('street_nr')),
441                         'city'     => SQL_ESCAPE(postRequestElement('city')),
442                         'zip'      => bigintval(postRequestElement('zip')),
443                         'country'  => $countryData,
444                         'refid'    => SQL_ESCAPE(postRequestElement('refid')),
445                         'password' => SQL_ESCAPE(postRequestElement('pass1')),
446                 );
447         } else {
448                 // No ZIP code entered
449                 $content = array(
450                         'hash'     => $hash,
451                         'userid'   => $userid,
452                         'gender'   => SQL_ESCAPE(postRequestElement('gender')),
453                         'surname'  => SQL_ESCAPE(postRequestElement('surname')),
454                         'family'   => SQL_ESCAPE(postRequestElement('family')),
455                         'email'    => SQL_ESCAPE(postRequestElement('email')),
456                         'street'   => SQL_ESCAPE(postRequestElement('street_nr')),
457                         'city'     => SQL_ESCAPE(postRequestElement('city')),
458                         'zip'      => '',
459                         'country'  => $countryData,
460                         'refid'    => SQL_ESCAPE(postRequestElement('refid')),
461                         'password' => SQL_ESCAPE(postRequestElement('pass1')),
462                 );
463         }
464
465         // Continue with birthday...
466         switch (getLanguage()) {
467                 case 'de':
468                         $content['birthday'] = bigintval(postRequestElement('day')) . '.' . bigintval(postRequestElement('month')) . '.' . bigintval(postRequestElement('year'));
469                         break;
470
471                 default:
472                         $content['birthday'] = bigintval(postRequestElement('month')) . '/' . bigintval(postRequestElement('day')) . '/' . bigintval(postRequestElement('year'));
473                         break;
474         } // END - switch
475
476         // Display information to the user that he got mail and send it away
477         $messageGuest = loadEmailTemplate('guest_register_done', $content, $userid, false);
478
479         // Send mail to user (confirmation link!)
480         sendEmail($userid, '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
481
482         // Send mail to admin
483         sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'admin_register_done', $content, $userid);
484 }
485
486 //-----------------------------------------------------------------------------
487 //                      Wrapper functions for ext-register
488 //-----------------------------------------------------------------------------
489
490 // Getter for 'display_refid'
491 function getDisplayRefid () {
492         // Is the cache entry set?
493         if (!isset($GLOBALS[__FUNCTION__])) {
494                 // No, so determine it
495                 $GLOBALS[__FUNCTION__] = getConfig('display_refid');
496         } // END - if
497
498         // Return cached entry
499         return $GLOBALS[__FUNCTION__];
500 }
501
502 // Checks wether 'display_refid' is "YES"
503 function isDisplayRefidEnabled () {
504         // Is the cache entry set?
505         if (!isset($GLOBALS[__FUNCTION__])) {
506                 // No, so determine it
507                 $GLOBALS[__FUNCTION__] = (getDisplayRefid() == 'Y');
508         } // END - if
509
510         // Return cached entry
511         return $GLOBALS[__FUNCTION__];
512 }
513
514 // Getter for 'ip_timeout'
515 function getIpTimeout () {
516         // Is the cache entry set?
517         if (!isset($GLOBALS[__FUNCTION__])) {
518                 // No, so determine it
519                 $GLOBALS[__FUNCTION__] = getConfig('ip_timeout');
520         } // END - if
521
522         // Return cached entry
523         return $GLOBALS[__FUNCTION__];
524 }
525
526 // Getter for 'register_default'
527 function getRegisterDefault () {
528         // Is the cache entry set?
529         if (!isset($GLOBALS[__FUNCTION__])) {
530                 // No, so determine it
531                 $GLOBALS[__FUNCTION__] = getConfig('register_default');
532         } // END - if
533
534         // Return cached entry
535         return $GLOBALS[__FUNCTION__];
536 }
537
538 // Checks wether 'register_default' is "YES"
539 function isRegisterDefaultEnabled () {
540         // Is the cache entry set?
541         if (!isset($GLOBALS[__FUNCTION__])) {
542                 // No, so determine it
543                 $GLOBALS[__FUNCTION__] = (getRegisterDefault() == 'Y');
544         } // END - if
545
546         // Return cached entry
547         return $GLOBALS[__FUNCTION__];
548 }
549
550 // Getter for 'register_generate_password_empty'
551 function getRegisterGeneratePasswordEmpty () {
552         // Is the cache entry set?
553         if (!isset($GLOBALS[__FUNCTION__])) {
554                 // No, so determine it
555                 $GLOBALS[__FUNCTION__] = getConfig('register_generate_password_empty');
556         } // END - if
557
558         // Return cached entry
559         return $GLOBALS[__FUNCTION__];
560 }
561
562 // Checks wether 'register_generate_password_empty' is "YES"
563 function isRegisterGeneratePasswordEmptyEnabled () {
564         // Is the cache entry set?
565         if (!isset($GLOBALS[__FUNCTION__])) {
566                 // No, so determine it
567                 $GLOBALS[__FUNCTION__] = (getRegisterGeneratePasswordEmpty() == 'Y');
568         } // END - if
569
570         // Return cached entry
571         return $GLOBALS[__FUNCTION__];
572 }
573
574 // [EOF]
575 ?>