Opps, not all elements for sprintf() has been set.
[mailer.git] / inc / libs / wernis_functions.php
index 50f39751be16d9225486c209725ed1029fc77f10..263e40935d67291ca4f4e33c84b604d0e37058ce 100644 (file)
@@ -219,8 +219,8 @@ function doAdminTestWernisApi () {
 
        // Prepare the request data
        $requestData = array(
-               't_uid'       => getWernisRefid(),
-               't_md5'       => getWernisPassMd5()
+               't_uid' => getWernisRefid(),
+               't_md5' => getWernisPassMd5()
        );
 
        // Return the result from the lower functions
@@ -268,6 +268,7 @@ function executeWernisApiWithdraw ($wdsId, $userMd5, $amount) {
        // Return the result from the lower functions
        $return = sendWernisApiRequest('book.php', $requestData);
 
+       // Did it went smoothly?
        if (isHttpResponseStatusOkay($return)) {
                // All fine!
                $result = TRUE;
@@ -523,12 +524,46 @@ function doDisplayWernisUserRegistrationForm () {
                } // END - if
        } elseif (!isFormSent('register')) {
                // Form not send, so load form template
-               loadTemplate('guest_wernis_registration_form');
+               loadTemplate('guest_wernis_registration_rpc_form');
        }
 }
 
 // Finish user registration with WDS66 API
 function doWernisFinishUserRegistration ($challenge, $challengeResponse, $status) {
+       // Is the status 1? (= all fine with API call)
+       if ($status == '1') {
+               // Get mapped data based on challenge
+               $return = getWernisMappedDataFromApiByChallenge($challenge, $status);
+
+               // Is the array filled?
+               if ((count($return['mapped_data']) > 0) && (empty($return['message']))) {
+                       // Set must-fillout fields
+                       $return['mapped_data'] = runFilterChain('register_must_fillout', $return['mapped_data']);
+
+                       // Add missing elements
+                       $return['mapped_data']['gender']               = NULL;
+                       $return['mapped_data']['birthday_selection']   = generateDayMonthYearSelectionBox($return['mapped_data']['birth_day'], $return['mapped_data']['birth_month'], $return['mapped_data']['birth_year']);
+                       $return['mapped_data']['challenge']            = getRequestElement('challenge');
+                       $return['mapped_data']['__challenge_response'] = getRequestElement('__challenge_response');
+
+                       // Display form
+                       loadTemplate('guest_wernis_registration_form', FALSE, $return['mapped_data']);
+
+                       // All fine
+                       return TRUE;
+               } else {
+                       // Something unexpected happened (e.g. no API requests left)
+                       displayMessage($return['message']);
+                       return FALSE;
+               }
+       } else {
+               // Status does not need to be changed
+               die(__FUNCTION__ . ':' . __LINE__ . ': Reached!');
+       }
+}
+
+// "Getter" for mapped data by calling the API and given challenge and status
+function getWernisMappedDataFromApiByChallenge ($challenge, $status) {
        // Get stored registration data
        $rows = getWernisRegistrationDataByKey('api_redirect_challenge', $challenge);
 
@@ -538,74 +573,111 @@ function doWernisFinishUserRegistration ($challenge, $challengeResponse, $status
                displayMessage('{--GUEST_WERNIS_REGISTRATION_ZERO_ROWS_FOUND--}');
 
                // Display form
-               loadTemplate('guest_wernis_registration_form');
-               return FALSE;
+               loadTemplate('guest_wernis_registration_rpc_form');
+               return array();
        } // END - if
 
-       // Check status from GET parameters and stored value
-       if ($status == '1') {
-               // Has the auth status changed?
-               if ($rows[0]['api_auth_status'] != 'ACCEPTED') {
-                       /*
-                        * The authorization of this application has been accepted, so
-                        * update it and ignore result from function because the update
-                        * will always run.
-                        */
-                       updateWernisRegistrationStatusByKey('api_redirect_challenge', $challenge, 'ACCEPTED');
-               } // END - if
+       // Init array
+       $return = array(
+               // Mapped data
+               'mapped_data' => array(),
+               // Any error message from API
+               'message'     => ''
+       );
 
-               // Now call "get.php"
-               // @TODO Hard-coded value (anrede, etc.)
-               $response = executeWernisApiGet($rows[0], 'data', 'anrede|vorname|name|strasse|plz|ort|birth_day|birth_month|birth_year|email');
+       // Has the auth status changed?
+       if ($rows[0]['api_auth_status'] != 'ACCEPTED') {
+               /*
+                * The authorization of this application has been accepted, so
+                * update it and ignore result from function because the update
+                * will always run.
+                */
+               updateWernisRegistrationDataByKey('api_auth_status', 'api_redirect_challenge', $challenge, 'ACCEPTED');
+       } // END - if
 
-               // Was the status okay?
-               if (isHttpResponseStatusOkay($response)) {
-                       // API returned non-errous response, 'data=' must be found
-                       assert(substr($response['response'], 0, 5) == 'data=');
+       // Now call "get.php"
+       $response = executeWernisApiGet($rows[0], 'data', 'vorname|name|strasse|plz|ort|birth_day|birth_month|birth_year|email|werber');
 
-                       // And remove it, this is now BASE64-encoded
-                       $encodedData = urldecode(substr($response['response'], 5));
+       // Was the status okay?
+       if (isHttpResponseStatusOkay($response)) {
+               // API returned non-errous response, 'data=' must be found
+               assert(substr($response['response'], 0, 5) == 'data=');
 
-                       // And decode it (all steps separated to later "easily" debug them)
-                       $decodedData = base64_decode($encodedData);
+               // And remove it, this is now BASE64-encoded
+               $encodedData = urldecode(substr($response['response'], 5));
 
-                       /*
-                        * Do some checks on the decoded string, it should be a
-                        * serialized array with 10 entries (see above
-                        * executeWernisApiGet() call).
-                        */
-                       assert(substr($decodedData, 0, 6) == 'a:10:{');
-                       assert(substr($decodedData, -1, 1) == '}');
+               // And decode it (all steps separated to later "easily" debug them)
+               $decodedData = base64_decode($encodedData);
 
-                       // The array seems to be fine, unserialize it
-                       $userData = unserialize($decodedData);
-                       die(__FUNCTION__.'<pre>'.print_r($userData, TRUE).'</pre>');
-               } else {
-                       // Something bad happened
-                       displayMessage($response['message']);
-                       return FALSE;
-               }
+               /*
+                * Do some checks on the decoded string, it should be a
+                * serialized array with 10 entries (see above
+                * executeWernisApiGet() call).
+                */
+               assert(substr($decodedData, 0, 6) == 'a:10:{');
+               assert(substr($decodedData, -1, 1) == '}');
+
+               // The array seems to be fine, unserialize it
+               $userData = unserialize($decodedData);
+
+               // All mappings WDS66->mailer
+               $mappings = array(
+                       'vorname'     => 'surname',
+                       'name'        => 'family',
+                       'strasse'     => 'street_nr',
+                       'plz'         => 'zip',
+                       'ort'         => 'city',
+                       'email'       => 'email',
+                       'birth_day'   => 'birth_day',
+                       'birth_month' => 'birth_month',
+                       'birth_year'  => 'birth_year',
+                       'werber'      => 'wernis_refid'
+               );
+
+               // Map all WDS66 entries into mailer entries
+               foreach ($mappings as $from => $to) {
+                       // All must exist
+                       if (!isset($userData[$from])) {
+                               // Element $from does not exist
+                               reportBug(__FUNCTION__, __LINE__, 'Cannot map from=' . $from . ' -> to=' . $to . ': element does not exist.');
+                       } // END - if
+
+                       // "Map" all
+                       $return['mapped_data'][$to] = convertEmptyToNull($userData[$from]);
+               } // END - foreach
+
+               // Both arrays must have same size
+               assert(count($userData) == count($return['mapped_data']));
+
+               // Now add userid from WDS66
+               $return['mapped_data']['wernis_userid'] = bigintval($rows[0]['wernis_userid']);
        } else {
-               // Status does not need to be changed
+               // Something bad happened so copy the message
+               $return['message'] = $response['message'];
        }
+
+       // Return mapped data array
+       return $return;
 }
 
 // Updates auth status by given key/value pair
-function updateWernisRegistrationStatusByKey ($key, $value, $newStatus) {
+function updateWernisRegistrationDataByKey ($updatedColumn, $key, $oldValue, $newValue) {
        // Run the update
        sqlQueryEscaped("UPDATE
        `{?_MYSQL_PREFIX?}_wernis_regs`
 SET
-       `api_auth_status`='%s'
+       `%s` = '%s'
 WHERE
-       `%s`='%s' AND
-       `api_auth_status` != '%s'
+       `%s` = '%s' AND
+       `%s` != '%s'
 LIMIT 1",
                array(
-                       $newStatus,
+                       $updatedColumn,
+                       $newValue,
                        $key,
-                       $value,
-                       $newStatus
+                       $oldValue,
+                       $updatedColumn,
+                       $oldValue
                ), __FUNCTION__, __LINE__
        );
 
@@ -656,6 +728,24 @@ LIMIT %d",
        return $rows;
 }
 
+// Do local user registration with data from WDS66 API
+function doWernisUserRegistration () {
+       // Call generic registration function
+       $status = doGenericUserRegistration();
+
+       // Does this went fine?
+       if ($status === FALSE) {
+               // No, then abort here silently
+               return FALSE;
+       } // END - if
+
+       // Make sure the user id is valid
+       assert(isset($GLOBALS['register_userid']));
+       assert(isValidId($GLOBALS['register_userid']));
+
+       // Generic registration is finished, so add more data:
+}
+
 //-----------------------------------------------------------------------------
 //                      Auth status callback functions
 //-----------------------------------------------------------------------------
@@ -692,9 +782,6 @@ function doWernisAuthPending ($args) {
                                $challenge
                        ), __FUNCTION__, __LINE__
                );
-
-               // Should be inserted
-               assert(sqlAffectedRows() == 1);
        } else {
                // Update challenge
                sqlQueryEscaped("UPDATE
@@ -712,11 +799,11 @@ LIMIT 1",
                                bigintval($args['wernis_userid'])
                        ), __FUNCTION__, __LINE__
                );
-
-               // Should always be updated
-               assert(sqlAffectedRows() == 1);
        }
 
+       // Should always update/insert
+       assert(sqlAffectedRows() == 1);
+
        // Redirect to WDS66 module=auth ...
        redirectToUrl(getWernisBaseUrl() . '/modules.php?module=auth&amp;auth_key=' . $args['auth_key'] . '&amp;params=' . urlencode(base64_encode('&module=' . getModule() . '&what=' . getWhat())) . '&amp;challenge=' . $challenge);
 }
@@ -729,8 +816,7 @@ function doWernisAuthAccepted ($args) {
        // auth_key and wernis_userid must be set
        assert(isset($args['auth_key']));
        assert(isset($args['wernis_userid']));
-
-       die(__FUNCTION__ . '<pre>'.print_r($args, TRUE).'</pre>');
+       die(__FUNCTION__ . ':' . __LINE__ . '<pre>' . print_r($args, TRUE) . '</pre>');
 }
 
 //-----------------------------------------------------------------------------