Renamed ifSqlHasZeroNums() to ifSqlHasZeroNumRows() and improved some queries.
[mailer.git] / inc / libs / register_functions.php
index 36fa9eb37eef60e61b7b7efaa1e5851b64f67c1b..1bb911df8f768f3c49a57e1e3748c19517f88dc8 100644 (file)
  * $Date::                                                            $ *
  * $Tag:: 0.2.1-FINAL                                                 $ *
  * $Author::                                                          $ *
- * Needs to be in all Files and every File needs "svn propset           *
- * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
- * For more information visit: http://www.mxchange.org                  *
+ * Copyright (c) 2009 - 2015 by Mailer Developer Team                   *
+ * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
  * it under the terms of the GNU General Public License as published by *
 // Some security stuff...
 if (!defined('__SECURITY')) {
        die();
-}
+} // END - if
 
-//
+// Checks whether all required registration fields are set
 function ifRequiredRegisterFieldsAreSet (&$array) {
        // By default all is fine
-       $ret = true;
+       $ret = TRUE;
        foreach ($array as $key => $value) {
                // Check all fields that must register
-               $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_must_register` WHERE `field_name`='%s' AND `field_required`='Y' LIMIT 1",
+               $result = sqlQueryEscaped("SELECT `id` FROM `{?_MYSQL_PREFIX?}_must_register` WHERE `field_name`='%s' AND `field_required`='Y' LIMIT 1",
                        array($key), __FUNCTION__, __LINE__);
 
                // Entry found?
-               if (SQL_NUMROWS($result) == 1) {
+               if (sqlNumRows($result) == 1) {
                        // Check if extension country is not found (you have to enter the 2-chars long country code) or
                        // if extensions is present check if country code was selected
                        //         01              2         21    12             3         32    234     5      54    4               43    34                      4    4      5      5432    2      3                      3210
                        $country = ((!isExtensionActive('country')) || ((isExtensionActive('country')) && (((empty($value)) && ($key == 'cntry')) || (($key == 'country_code') && (!empty($value)))) && (!empty($array['country_code']))));
-                       if ((empty($value)) && ($country === false)) {
+                       if ((empty($value)) && ($country === FALSE)) {
                                // Required field not set
                                $array[$key] = '!';
-                               $ret = false;
+                               $ret = FALSE;
                        } // END - if
                } // END - if
 
                // Free result
-               SQL_FREERESULT($result);
+               sqlFreeResult($result);
        } // END - foreach
 
        // Return result
@@ -73,121 +71,111 @@ function ifRequiredRegisterFieldsAreSet (&$array) {
 }
 
 // Generates a 'category table' for the registration form
-function registerGenerateCategoryTable ($mode, $return=false) {
+function registerGenerateCategoryTable ($mode, $configEntry = 'register_default') {
+       // Init output
        $OUT = '';
 
-       // Guests are mostly not interested in how many members has
-       // choosen an individual category
-       $AND = "WHERE `visible`='Y' ";
+       /*
+        * Guests are mostly not interested in how many members has choosen an
+        * individual category.
+        */
+       $whereStatement = "WHERE `visible`='Y' ";
 
        // Admins are allowed to see every category...
-       if (isAdmin()) $AND = '';
+       if (isAdmin()) {
+               $whereStatement = '';
+       } // END - if
 
        // Look for categories
-       $result = SQL_QUERY('SELECT `id`, `cat`, `visible` FROM `{?_MYSQL_PREFIX?}_cats` ' . $AND . ' ORDER BY `sort` ASC',
+       $result = sqlQuery('SELECT
+       `id`,
+       `cat`,
+       `visible`
+FROM
+       `{?_MYSQL_PREFIX?}_cats`
+' . $whereStatement . '
+ORDER BY
+       `sort` ASC',
                __FUNCTION__, __LINE__);
 
-       if (!SQL_HASZERONUMS($result)) {
+       if (!ifSqlHasZeroNumRows($result)) {
                // List alle visible modules (or all to the admin)
                $OUT .= '<table border="0" cellspacing="0" cellpadding="0" width="100%">';
-               while ($content = SQL_FETCHARRAY($result)) {
+               while ($content = sqlFetchArray($result)) {
                        // Prepare array for the template
                        $content['default_yes'] = '';
                        $content['default_no']  = '';
 
                        // Mark categories
-                       if ((postRequestParameter('cat', $content['id']) == 'Y') || ((getConfig('register_default') == 'Y') && (!isPostRequestParameterSet('cat', $content['id'])))) {
+                       if ((postRequestElement('cat', $content['id']) == 'Y') || ((getConfig($configEntry) == 'Y') && (!isPostRequestElementSet('cat', $content['id'])))) {
                                $content['default_yes'] = ' checked="checked"';
                        } else {
                                $content['default_no']  = ' checked="checked"';
                        }
 
                        // Load template and switch color
-                       $OUT .= loadTemplate('guest_cat_row', true, $content);
+                       $OUT .= loadTemplate('guest_cat_row', TRUE, $content);
                } // END - while
                $OUT .= '</table>';
 
                // Free memory
-               SQL_FREERESULT($result);
+               sqlFreeResult($result);
        } else {
                // No categories setted up so far...
-               $OUT .= loadTemplate('admin_settings_saved', true, '{--NO_CATEGORIES_VISIBLE--}');
+               $OUT .= displayMessage('{--NO_CATEGORIES_VISIBLE--}', TRUE);
        }
 
-       if ($return === true) {
-               // Return generated HTML code
-               return $OUT;
-       } else {
-               // Output directly (default)
-               outputHtml($OUT);
-       }
+       // Return generated HTML code
+       return $OUT;
 }
 
 // Outputs a 'failed message'
-function registerOutputFailedMessage ($messageId, $extra='') {
+function registerOutputFailedMessage ($messageId, $extra = '') {
        if (empty($messageId)) {
-               outputHtml('<div class="register_failed">' . $extra . '</div>');
+               outputHtml('<div class="bad">' . $extra . '</div>');
        } else {
-               outputHtml('<div class="register_failed">{--' . $messageId . '--}' . $extra . '</div>');
+               outputHtml('<div class="bad">{--' . $messageId . '--}' . $extra . '</div>');
        }
 }
 
-// Run a filter for must-fillout fields
-function FILTER_REGISTER_MUST_FILLOUT ($content) {
-       // Get all fields for output
-       $result = SQL_QUERY('SELECT `field_name`, `field_required` FROM `{?_MYSQL_PREFIX?}_must_register` ORDER BY `id` ASC',
-               __FUNCTION__, __LINE__);
-
-       // Walk through all entries
-       while ($row = SQL_FETCHARRAY($result)) {
-               // Must the user fill out this element?
-               $value = '';
-               if ($row['field_required'] == 'Y') $value = '<span class="guest_failed">(*)</span>';
-
-               // Add it
-               $content['must_fillout_' . strtolower($row['field_name']) . ''] = $value;
-       } // END - while
-
-       // Free memory
-       SQL_FREERESULT($result);
-
-       // Return it
-       return $content;
-}
-
-// Checks wether the registration data is complete
+// Checks whether the registration data is complete
 function isRegistrationDataComplete () {
        // Init elements
-       $GLOBALS['registration_ip_timeout']     = false;
-       $GLOBALS['registration_short_password'] = false;
-       $GLOBALS['register_selected_cats']      = '0';
+       $GLOBALS['registration_ip_timeout']    = FALSE;
+       $GLOBALS['registration_weak_password'] = FALSE;
+       $GLOBALS['registration_selected_cats'] = '0';
 
        // Default is okay
-       $isOkay = true;
+       $isOkay = TRUE;
+       $isRandom = FALSE;
 
        // First we only check the submitted data then we continue... :)
        //
-       // Did he agree to our Terms Of Usage?
-       if (postRequestParameter('agree') != 'Y') {
-               setPostRequestParameter('agree', '!');
-               $isOkay = false;
+       // Did he agree to the terms of usage?
+       if (postRequestElement('agree') != 'Y') {
+               setPostRequestElement('agree', '!');
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'agree=N - User did not agree with terms of usage.');
+               $isOkay = FALSE;
        } // END - if
 
        // Did he enter a valid email address? (we really don't care about
        // that, he has to click on a confirmation link :P )
-       if ((!isPostRequestParameterSet('email')) || (!isEmailValid(postRequestParameter('email')))) {
-               setPostRequestParameter('email', '!');
-               $isOkay = false;
+       if ((!isAdmin()) && ((!isPostRequestElementSet('email')) || (!isEmailValid(postRequestElement('email'))))) {
+               setPostRequestElement('email', '!');
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did not enter proper email address.');
+               $isOkay = FALSE;
        } // END - if
 
        // And what about surname and family's name?
-       if (!isPostRequestParameterSet('surname')) {
-               setPostRequestParameter('surname', '!');
-               $isOkay = false;
+       if (!isPostRequestElementSet('surname')) {
+               setPostRequestElement('surname', '!');
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did not enter surname.');
+               $isOkay = FALSE;
        } // END - if
-       if (!isPostRequestParameterSet('family')) {
-               setPostRequestParameter('family', '!');
-               $isOkay = false;
+       if (!isPostRequestElementSet('family')) {
+               setPostRequestElement('family', '!');
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did not enter family name.');
+               $isOkay = FALSE;
        } // END - if
 
        // Get temporary array for modification
@@ -199,247 +187,547 @@ function isRegistrationDataComplete () {
        // Set it back in request
        setPostRequestArray($postArray);
 
+       // Are both passwords zero length?
+       if ((strlen(postRequestElement('password1')) == 0) && (strlen(postRequestElement('password2')) == 0) && ($isOkay === TRUE)) {
+               // Is the extension 'register' newer or equal 0.5.5?
+               if ((isExtensionInstalledAndNewer('register', '0.5.5')) && (isRegisterGeneratePasswordEmptyEnabled())) {
+                       // Generate a random password
+                       $randomPassword = generatePassword();
+                       $isRandom = TRUE;
+
+                       // Set it in both entries
+                       setPostRequestElement('password1', $randomPassword);
+                       setPostRequestElement('password2', $randomPassword);
+               } else {
+                       // Not allowed or no recent extension version
+                       setPostRequestElement('password1', '!');
+                       setPostRequestElement('password2', '!');
+
+                       // ... which is both not okay
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Random password generation not possible, isExtensionInstalledAndNewer(register, 0.5.5)=' . intval(isExtensionInstalledAndNewer('register', '0.5.5')) . ',isRegisterGeneratePasswordEmptyEnabled()=' . intval(isRegisterGeneratePasswordEmptyEnabled()));
+                       $isOkay = FALSE;
+               }
+       } // END - if
+
        // Did he enter his password twice?
-       if (((!isPostRequestParameterSet('pass1')) || (!isPostRequestParameterSet('pass2'))) || ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2')))) {
-               if ((postRequestParameter('pass1') != postRequestParameter('pass2')) && (isPostRequestParameterSet('pass1')) && (isPostRequestParameterSet('pass2'))) {
-                       setPostRequestParameter('pass1', '!');
-                       setPostRequestParameter('pass2', '!');
+       if (((!isPostRequestElementSet('password1')) || (!isPostRequestElementSet('password2'))) || ((postRequestElement('password1') != postRequestElement('password2')) && (isPostRequestElementSet('password1')) && (isPostRequestElementSet('password2')))) {
+               if ((postRequestElement('password1') != postRequestElement('password2')) && (isPostRequestElementSet('password1')) && (isPostRequestElementSet('password2'))) {
+                       // Both passwords did not match
+                       setPostRequestElement('password1', '!');
+                       setPostRequestElement('password2', '!');
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did not enter same passwords.');
                } else {
-                       if (!isPostRequestParameterSet('pass1')) { setPostRequestParameter('pass1', '!'); } else { setPostRequestParameter('pass1', ''); }
-                       if (!isPostRequestParameterSet('pass2')) { setPostRequestParameter('pass2', '!'); } else { setPostRequestParameter('pass2', ''); }
+                       if (!isPostRequestElementSet('password1')) {
+                               // Password 1 is empty
+                               setPostRequestElement('password1', '!');
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did not enter password1.');
+                       } else {
+                               // Password 2 is empty
+                               setPostRequestElement('password1', '');
+                       }
+                       if (!isPostRequestElementSet('password2')) {
+                               // Password 2 is empty
+                               setPostRequestElement('password2', '!');
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did not enter password2.');
+                       } else {
+                               // Password 1 is empty
+                               setPostRequestElement('password2', '');
+                       }
                }
-               $isOkay = false;
+               $isOkay = FALSE;
        } // END - if
 
-       // Is the password long enouth?
-       if ((strlen(postRequestParameter('pass1')) < getConfig('pass_len')) && ($isOkay === true)) {
-               $GLOBALS['registration_short_password'] = true;
-               $isOkay = false;
+       // Is the password strong enough?
+       if (($isRandom === FALSE) && (!isStrongPassword(postRequestElement('password1')))) {
+               $GLOBALS['registration_weak_password'] = TRUE;
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did enter a short password.');
+               $isOkay = FALSE;
        } // END - if
 
        // Do this check only when no admin is logged in
-       if (is_array(postRequestParameter('cat'))) {
+       if (ifPostContainsSelections('cat')) {
                // Only continue with array
-               foreach (postRequestParameter('cat') as $id => $answer) {
+               foreach (postRequestElement('cat') as $id => $answer) {
                        // Is this category choosen?
                        if ($answer == 'Y') {
-                               $GLOBALS['register_selected_cats']++;
+                               $GLOBALS['registration_selected_cats']++;
                        } // END - if
                } // END - foreach
        } // END - if
 
        // Enougth categories selected?
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',selected='.$GLOBALS['register_selected_cats'].'/'.getConfig('least_cats'));
-       $isOkay = (($isOkay) && ($GLOBALS['register_selected_cats'] >= getConfig('least_cats')));
-
-       if ((postRequestParameter('email') != '!') && (getConfig('check_double_email') == 'Y')) {
-               // Does the email address already exists in our database?
-               if ((!isAdmin()) && (isEmailTaken(postRequestParameter('email')))) {
-                       setPostRequestParameter('email', '?');
-                       $isOkay = false;
-               } // END - if
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay=' . intval($isOkay) . ',selected=' . $GLOBALS['registration_selected_cats'] . '/' . getLeastCats());
+       $isOkay = (($isOkay) && ($GLOBALS['registration_selected_cats'] >= getLeastCats()));
+
+       // Check if email is taken, if configured
+       if ((isExtensionInstalledAndNewer('other', '0.3.0')) && (isCheckDoubleEmailEnabled()) && (postRequestElement('email') != '!') && (isEmailTaken(postRequestElement('email'))) && (!isAdmin())) {
+               // Is already used
+               setPostRequestElement('email', '?');
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'User did enter a already used email address.');
+               $isOkay = FALSE;
        } // END - if
 
        // Check for IP timeout?
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
-       if ((!isAdmin()) && (getConfig('ip_timeout') > 0)) {
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay=' . intval($isOkay));
+       if ((!isAdmin()) && (getIpTimeout() > 0)) {
                // Check his IP number
-               $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);
-               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay).',timeout='.intval($GLOBALS['registration_ip_timeout']));
+               $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);
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay=' . intval($isOkay).',timeout='.intval($GLOBALS['registration_ip_timeout']));
                $isOkay = (($isOkay) && (!$GLOBALS['registration_ip_timeout']));
        } // END - if
 
        // Return result
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay='.intval($isOkay));
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'isOkay=' . intval($isOkay) . ' - EXIT!');
        return $isOkay;
 }
 
 // Do the registration
-function doRegistration () {
-       // Prepapre month and day of birth
-       if (strlen(postRequestParameter('day'))   == 1) setPostRequestParameter('day'  , '0' . postRequestParameter('day'));
-       if (strlen(postRequestParameter('month')) == 1) setPostRequestParameter('month', '0' . postRequestParameter('month'));
-
-       // Get total ...
-       // ... confirmed, ...
-       $confirmedUsers   = getTotalConfirmedUser();
-       // ... unconfirmed ...
-       $unconfirmedUsers = getTotalUnconfirmedUser();
-       // ... and locked users!
-       $lockedUsers      = getTotalLockedUser();
-
-       // Generate hash which will be inserted into confirmation mail
-       $hash = generateHash(sha1(
-               $confirmedUsers . getEncryptSeperator() .
-               $unconfirmedUsers . getEncryptSeperator() .
-               $lockedUsers . getEncryptSeperator() .
-               postRequestParameter('month') . '-' .
-               postRequestParameter('day') . '-' .
-               postRequestParameter('year') . getEncryptSeperator() .
-               detectServerName() . getEncryptSeperator() .
-               detectRemoteAddr() . getEncryptSeperator() .
-               detectUserAgent() . '/' .
-               getConfig('SITE_KEY') . '/' .
-               getConfig('DATE_KEY') . '/' .
-               getConfig('CACHE_BUSTER')
-       ));
-
-       // Old way with enterable two-char-code
-       $countryRow = '`country`';
-       $countryData = substr(postRequestParameter('cntry'), 0, 2);
-
-       // Add design when extension sql_patches is v0.2.7 or greater
-       // @TODO Rewrite these all to a single filter
-       $GLOBALS['register_sql_columns'] = '';
-       $GLOBALS['register_sql_data'] = '';
-       if (isExtensionInstalledAndNewer('theme', '0.0.8')) {
-               // Okay, add design here
-               $GLOBALS['register_sql_columns'] .= ', `curr_theme`';
-               $GLOBALS['register_sql_data']    .= ", '" . getCurrentTheme() . "'";
+function doUserRegistration () {
+       // Do not register an account on absent ext-user
+       if (!isExtensionInstalled('user')) {
+               // Please report this
+               reportBug(__FUNCTION__, __LINE__, 'Tried to register a user account without ext-user installed.');
        } // END - if
 
-       // Check if I shall disable sending mail to newly registered members out about active/begging rallye
-       //
-       // First comes first: begging rallye
-       if (!isBegNewMemberNotifyEnabled()) {
-               $GLOBALS['register_sql_columns'] .= ', `beg_rallye_enable_notify`, `beg_rallye_disable_notify`';
-               $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
-       } // END - if
+       // Init filter data array
+       $filterData = array(
+               // Registration status is always FALSE by default
+               'status' => FALSE,
+       );
 
-       // Second: active rallye
-       if (!isBonusNewMemberNotifyEnabled()) {
-               $GLOBALS['register_sql_columns'] .= ', `bonus_rallye_enable_notify`, `bonus_rallye_disable_notify`';
-               $GLOBALS['register_sql_data']    .= ', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()';
-       } // END - if
+       // Run filter chain for user registration
+       $filterData = runFilterChain('user_registration', $filterData);
 
-       // Write user data to table
-       if (isExtensionActive('country')) {
-               // Save with new selectable country code
-               $countryRow = '`country_code`';
-               $countryData = bigintval(postRequestParameter('country_code'));
+       // Return status
+       return $filterData['status'];
+}
+
+// Generic user registration
+function doGenericUserRegistration () {
+       // Init extra SQL data
+       initExtraRegistrationSql();
+
+       // Init filter data
+       $filterData = array(
+               // Initialization not done by default
+               'init_done'   => FALSE,
+               'post_data'   => postRequestArray(),
+               'blacklisted' => '',
+               'message'     => '{--PRE_USER_REGISTRATION_FAILED--}',
+       );
+
+       // Run the pre-registration chain
+       $filterData = runFilterChain('pre_user_registration', $filterData);
+
+       // Did the initialization work?
+       if ($filterData['init_done'] === FALSE) {
+               // Something bad happened!
+               displayMessage($filterData['message']);
+
+               // Stop here
+               return FALSE;
        } // END - if
 
+       // These elements must be set
+       assert(isset($GLOBALS['register_country_row']));
+       assert(isset($GLOBALS['register_country_data']));
+       assert(isset($GLOBALS['register_confirm_hash']));
+
+       // Only comment this in if you develop
+       //* DEVELOPER-CODE: */ $GLOBALS['register_userid'] = 1; return TRUE;
+
        // Create user's account...
-       SQL_QUERY_ESC("INSERT INTO
+       sqlQueryEscaped("INSERT INTO
        `{?_MYSQL_PREFIX?}_user_data`
-(`gender`, `surname`, `family`, `street_nr`,%s, `zip`, `city`, `email`, `birth_day`, `birth_month`, `birth_year`, `password`, `max_mails`, `receive_mails`, `refid`, `status`, `user_hash`, `REMOTE_ADDR`, `joined`, `last_update`".$GLOBALS['register_sql_columns'].")
-       VALUES
-('%s','%s','%s','%s','%s',%s,'%s','%s',%s, %s,%s,'%s',%s, %s,'%s','UNCONFIRMED','%s','%s', UNIX_TIMESTAMP(), UNIX_TIMESTAMP()".$GLOBALS['register_sql_data'].")",
+(
+       `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'] . "
+) VALUES (
+       '%s',
+       '%s',
+       '%s',
+       '%s',
+       '%s',
+       %s,
+       '%s',
+       '%s',
+       %s,
+       %s,
+       %s,
+       '%s',
+       %s,
+       %s,
+       %s,
+       '%s',
+       '%s',
+       '{%%pipe,detectRemoteAddr%%}',
+       UNIX_TIMESTAMP(),
+       UNIX_TIMESTAMP(),
+       {?ref_payout?}
+       " . $GLOBALS['register_sql_data'] . "
+)",
        array(
-               $countryRow,
-               substr(postRequestParameter('gender'), 0, 1),
-               postRequestParameter('surname'),
-               postRequestParameter('family'),
-               postRequestParameter('street_nr'),
-               $countryData,
-               bigintval(postRequestParameter('zip')),
-               postRequestParameter('city'),
-               postRequestParameter('email'),
-               bigintval(postRequestParameter('day')),
-               bigintval(postRequestParameter('month')),
-               bigintval(postRequestParameter('year')),
-               generateHash(postRequestParameter('pass1')),
-               bigintval(postRequestParameter('max_mails')),
-               bigintval(postRequestParameter('max_mails')),
-               bigintval(postRequestParameter('refid')),
-               $hash,
-               detectRemoteAddr(),
+               $GLOBALS['register_country_row'],
+               substr(postRequestElement('gender'), 0, 1),
+               postRequestElement('surname'),
+               postRequestElement('family'),
+               postRequestElement('street_nr'),
+               $GLOBALS['register_country_data'],
+               bigintval(postRequestElement('zip')),
+               postRequestElement('city'),
+               postRequestElement('email'),
+               bigintval(postRequestElement('day')),
+               bigintval(postRequestElement('month')),
+               bigintval(postRequestElement('year')),
+               generateHash(postRequestElement('password1')),
+               bigintval(postRequestElement('max_mails')),
+               bigintval(postRequestElement('max_mails')),
+               convertZeroToNull(postRequestElement('refid')),
+               postRequestElement('status'),
+               $GLOBALS['register_confirm_hash']
        ), __FUNCTION__, __LINE__);
 
        // Get his userid
-       $userid = bigintval(SQL_INSERTID());
+       $filterData['register_insert_id'] = getSqlInsertId();
 
        // Did this work?
-       if ($userid == '0') {
+       if (!isValidId($filterData['register_insert_id'])) {
                // Something bad happened!
-               loadTemplate('admin_settings_saved', false, '{--USER_NOT_REGISTERED--}');
+               displayMessage('{--USER_NOT_REGISTERED--}');
 
                // Stop here
-               return;
+               return FALSE;
        } // END - if
 
-       // Is the refback extension there?
-       // @TODO Rewrite this to a filter
-       if (isExtensionActive('refback')) {
-               // Update refback table
-               updateRefbackTable($userid);
+       // Set new user id globally
+       $GLOBALS['register_userid'] = $filterData['register_insert_id'];
+
+       // Shall we reset random refid? Only possible with latest ext-user
+       if (isExtensionInstalledAndNewer('user', '0.3.4')) {
+               // Reset all accounts, registration is done
+               sqlQuery('UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `rand_confirmed`=0', __FUNCTION__, __LINE__);
        } // END - if
 
+       // Update referral table
+       updateReferralCounter($filterData['register_insert_id']);
+
        // Write his welcome-points
-       // @TODO Wether the registration bonus should only be added to user directly or through referal system should be configurable
-       addPointsDirectly('register_welcome', $userid, getPointsRegister());
+       initReferralSystem();
+       addPointsThroughReferralSystem(
+               // Subject
+               'register_welcome',
+               // User's id number
+               $filterData['register_insert_id'],
+               // Points to add
+               getPointsRegister(),
+               // Referral id (or NULL if none set)
+               convertZeroToNull(postRequestElement('refid'))
+       );
 
        // Write catgories
-       if ((is_array(postRequestParameter('cat'))) && (count(postRequestParameter('cat')))) {
-               foreach (postRequestParameter('cat') as $cat => $joined) {
+       if (ifPostContainsSelections('cat')) {
+               // Init SQL
+               $sql = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`, `cat_id`) VALUES';
+
+               // Write all entries
+               foreach (postRequestElement('cat') as $categoryId => $joined) {
+                       // "Join" this group?
                        if ($joined == 'Y') {
                                // Insert category entry
-                               SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_cats` (`userid`, `cat_id`) VALUES (%s, %s)",
-                                       array($userid, bigintval($cat)), __FUNCTION__, __LINE__);
+                               $sql .= ' (' . $filterData['register_insert_id'] . ', ' . bigintval($categoryId) . '),';
                        } // END - if
                } // END - foreach
+
+               // Run SQL without last commata
+               sqlQuery(substr($sql, 0, -1), __FUNCTION__, __LINE__);
+       } // END - if
+
+       // Registration phase is done here, so for tester accounts we end here
+       if (((getExtensionVersion('user') >= '0.5.0')) && (isTesterUserName(postRequestElement('surname'))) && (ifTesterAccountsAllowed())) {
+               // All fine here
+               return TRUE;
        } // END - if
 
-       // ... rewrite a zero referal id to the main title
-       if (postRequestParameter('refid') == '0') setPostRequestParameter('refid', getMainTitle());
+       // ... rewrite a zero referral id to the main title
+       if (!isValidId(postRequestElement('refid'))) {
+               setPostRequestElement('refid', getMainTitle());
+       } // END - if
 
        // Is ZIP code set?
-       if (isPostRequestParameterSet('zip')) {
+       if (isPostRequestElementSet('zip')) {
                // Prepare data array for the email template
-               // Start with the gender...
                $content = array(
-                       'hash'    => $hash,
-                       'userid'  => $userid,
-                       'gender'  => SQL_ESCAPE(postRequestParameter('gender')),
-                       'surname' => SQL_ESCAPE(postRequestParameter('surname')),
-                       'family'  => SQL_ESCAPE(postRequestParameter('family')),
-                       'email'   => SQL_ESCAPE(postRequestParameter('email')),
-                       'street'  => SQL_ESCAPE(postRequestParameter('street_nr')),
-                       'city'    => SQL_ESCAPE(postRequestParameter('city')),
-                       'zip'     => bigintval(postRequestParameter('zip')),
-                       'country' => $countryData,
-                       'refid'   => SQL_ESCAPE(postRequestParameter('refid')),
-                       'pass'    => SQL_ESCAPE(postRequestParameter('pass1')),
+                       'hash'     => $GLOBALS['register_confirm_hash'],
+                       'userid'   => $filterData['register_insert_id'],
+                       'gender'   => sqlEscapeString(postRequestElement('gender')),
+                       'surname'  => sqlEscapeString(postRequestElement('surname')),
+                       'family'   => sqlEscapeString(postRequestElement('family')),
+                       'email'    => sqlEscapeString(postRequestElement('email')),
+                       'street'   => sqlEscapeString(postRequestElement('street_nr')),
+                       'city'     => sqlEscapeString(postRequestElement('city')),
+                       'zip'      => bigintval(postRequestElement('zip')),
+                       'country'  => $GLOBALS['register_country_data'],
+                       'refid'    => sqlEscapeString(postRequestElement('refid')),
+                       'password' => sqlEscapeString(postRequestElement('password1')),
                );
        } else {
                // No ZIP code entered
                $content = array(
-                       'hash'    => $hash,
-                       'userid'  => $userid,
-                       'gender'  => SQL_ESCAPE(postRequestParameter('gender')),
-                       'surname' => SQL_ESCAPE(postRequestParameter('surname')),
-                       'family'  => SQL_ESCAPE(postRequestParameter('family')),
-                       'email'   => SQL_ESCAPE(postRequestParameter('email')),
-                       'street'  => SQL_ESCAPE(postRequestParameter('street_nr')),
-                       'city'    => SQL_ESCAPE(postRequestParameter('city')),
-                       'zip'     => '',
-                       'country' => $countryData,
-                       'refid'   => SQL_ESCAPE(postRequestParameter('refid')),
-                       'pass'    => SQL_ESCAPE(postRequestParameter('pass1')),
+                       'hash'     => $GLOBALS['register_confirm_hash'],
+                       'userid'   => $filterData['register_insert_id'],
+                       'gender'   => sqlEscapeString(postRequestElement('gender')),
+                       'surname'  => sqlEscapeString(postRequestElement('surname')),
+                       'family'   => sqlEscapeString(postRequestElement('family')),
+                       'email'    => sqlEscapeString(postRequestElement('email')),
+                       'street'   => sqlEscapeString(postRequestElement('street_nr')),
+                       'city'     => sqlEscapeString(postRequestElement('city')),
+                       'zip'      => '',
+                       'country'  => $GLOBALS['register_country_data'],
+                       'refid'    => sqlEscapeString(postRequestElement('refid')),
+                       'password' => sqlEscapeString(postRequestElement('password1')),
                );
        }
 
        // Continue with birthday...
        switch (getLanguage()) {
                case 'de':
-                       $content['birthday'] = bigintval(postRequestParameter('day')) . '.' . bigintval(postRequestParameter('month')) . '.' . bigintval(postRequestParameter('year'));
+                       $content['birthday'] = bigintval(postRequestElement('day')) . '.' . bigintval(postRequestElement('month')) . '.' . bigintval(postRequestElement('year'));
                        break;
 
                default:
-                       $content['birthday'] = bigintval(postRequestParameter('month')) . '/' . bigintval(postRequestParameter('day')) . '/' . bigintval(postRequestParameter('year'));
+                       $content['birthday'] = bigintval(postRequestElement('month')) . '/' . bigintval(postRequestElement('day')) . '/' . bigintval(postRequestElement('year'));
                        break;
        } // END - switch
 
        // Display information to the user that he got mail and send it away
-       $messageGuest = loadEmailTemplate('register-member', $content, $userid);
+       $messageGuest = loadEmailTemplate('guest_register_done', $content, $filterData['register_insert_id'], FALSE);
 
        // Send mail to user (confirmation link!)
-       $email = $content['email'];
-       sendEmail($content['email'], '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
-       $content['email'] = $email;
+       sendEmail($filterData['register_insert_id'], '{--GUEST_CONFIRM_LINK_SUBJECT--}', $messageGuest);
 
        // Send mail to admin
-       sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'register-admin', $content, $userid);
+       sendAdminNotification('{--ADMIN_NEW_ACCOUNT_SUBJECT--}', 'admin_register_done', $content, $filterData['register_insert_id']);
+
+       // All fine
+       return TRUE;
+}
+
+// Initialize extra registration SQL
+function initExtraRegistrationSql () {
+       $GLOBALS['register_sql_columns'] = '';
+       $GLOBALS['register_sql_data']    = '';
+}
+
+// Add extra column for registration SQL
+function addExtraRegistrationColumns ($column) {
+       // Add column
+       $GLOBALS['register_sql_columns'] .= $column;
+}
+
+// Add extra data for registration SQL
+function addExtraRegistrationData ($data) {
+       // Add column
+       $GLOBALS['register_sql_data'] .= $data;
+}
+
+//-----------------------------------------------------------------------------
+//                      Wrapper functions for ext-register
+//-----------------------------------------------------------------------------
+
+// Getter for 'display_refid'
+function getDisplayRefid () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = getConfig('display_refid');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Checks whether 'display_refid' is "Y"
+function isDisplayRefidEnabled () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = (getDisplayRefid() == 'Y');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Getter for 'ip_timeout'
+function getIpTimeout () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = getConfig('ip_timeout');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Getter for 'register_default'
+function getRegisterDefault () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = getConfig('register_default');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Checks whether 'register_default' is "YES"
+function isRegisterDefaultEnabled () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = (getRegisterDefault() == 'Y');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Getter for 'register_generate_password_empty'
+function getRegisterGeneratePasswordEmpty () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = getConfig('register_generate_password_empty');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Checks whether 'register_generate_password_empty' is "YES"
+function isRegisterGeneratePasswordEmptyEnabled () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = (getRegisterGeneratePasswordEmpty() == 'Y');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// Getter for 'default_registration_provider'
+function getDefaultRegistrationProvider () {
+       // Is the cache entry set?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // No, so determine it
+               $GLOBALS[__FUNCTION__] = getConfig('default_registration_provider');
+       } // END - if
+
+       // Return cached entry
+       return $GLOBALS[__FUNCTION__];
+}
+
+// "Getter" for least_cats
+function getLeastCats () {
+       // Is there cache?
+       if (!isset($GLOBALS[__FUNCTION__])) {
+               // Determine it
+               $GLOBALS[__FUNCTION__] = getConfig('least_cats');
+       } // END - if
+
+       // Return cache
+       return $GLOBALS[__FUNCTION__];
+}
+
+// ----------------------------------------------------------------------------
+//                            Template helper functions
+// ----------------------------------------------------------------------------
+
+// Template helper for generating a category selection table for admin area with given configuration entry
+function doTemplateAdminRegisterCategoryTable ($templateName, $clear = FALSE, $configEntry) {
+       // Call the inner function
+       return registerGenerateCategoryTable('admin', $configEntry);
+}
+
+// Template helper for generating a list of all activated user registration provider
+function doTemplateGuestRegistrationList ($templateName, $clear = FALSE) {
+       // Init output
+       $content = '';
+
+       // Default is only activated provider
+       $addSql = " AND `provider_is_active`='Y'";
+
+       // Is admin logged-in?
+       if (isAdmin()) {
+               // Then show all
+               $addSql = '';
+       } // END - if
+
+       // Search for all
+       $result = sqlQuery("SELECT
+       `provider_name`,
+       `provider_extension`
+FROM
+       `{?_MYSQL_PREFIX?}_user_register_provider`
+WHERE
+       `provider_extension` != 'register'
+       " . $addSql . "
+ORDER BY
+       `provider_name` ASC", __FUNCTION__, __LINE__);
+
+       // Are there entries?
+       if (sqlNumRows($result) > 0) {
+               // Loop through all
+               $row = '';
+               while ($content = sqlFetchArray($result)) {
+                       // Load row template
+                       $row .= loadTemplate('guest_registration_provider_row', TRUE, $content);
+               } // END - while
+
+               // Load main template
+               $content = loadTemplate('guest_registration_provider', TRUE, $row);
+       } else {
+               // Nothing found
+               $content = returnMessage('{--GUEST_EXTRA_REGISTRATION_PROVIDER_404--}');
+       }
+
+       // Free result
+       sqlFreeResult($result);
+
+       // Return the generated content
+       return $content;
+}
+
+// ----------------------------------------------------------------------------
+//                            "Translator" functions
+// ----------------------------------------------------------------------------
+
+function translateRegistrationProviderName ($providerName) {
+       // "Translate it"
+       return '{--REGISTRATION_PROVIDER_' . strtoupper($providerName) . '--}';
 }
 
 // [EOF]