]> git.mxchange.org Git - mailer.git/blobdiff - inc/libs/wernis_functions.php
Added more functions to handle registrations over WDS66 + encapsulated check for...
[mailer.git] / inc / libs / wernis_functions.php
index ff782fac567f9dbf6643cae438b06893ad6e0e46..50f39751be16d9225486c209725ed1029fc77f10 100644 (file)
@@ -227,7 +227,7 @@ function doAdminTestWernisApi () {
        $return = sendWernisApiRequest('balance.php', $requestData);
 
        // Did it went smoothly?
-       if ($return['status'] == 'OK') {
+       if (isHttpResponseStatusOkay($return)) {
                // All fine!
                $result = TRUE;
        } else {
@@ -240,7 +240,7 @@ function doAdminTestWernisApi () {
 }
 
 // Widthdraw this amount
-function executeWernisWithdraw ($wdsId, $userMd5, $amount) {
+function executeWernisApiWithdraw ($wdsId, $userMd5, $amount) {
        // Is the sponsor extension installed?
        if (!isWernisWithdrawActive()) {
                if (!isExtensionActive('sponsor')) {
@@ -268,7 +268,7 @@ function executeWernisWithdraw ($wdsId, $userMd5, $amount) {
        // Return the result from the lower functions
        $return = sendWernisApiRequest('book.php', $requestData);
 
-       if ($return['status'] == 'OK') {
+       if (isHttpResponseStatusOkay($return)) {
                // All fine!
                $result = TRUE;
 
@@ -287,7 +287,7 @@ function executeWernisWithdraw ($wdsId, $userMd5, $amount) {
 }
 
 // Payout this amount
-function executeWernisPayout ($wdsId, $amount) {
+function executeWernisApiPayout ($wdsId, $amount) {
        // Default is failed attempt
        $result = FALSE;
 
@@ -304,7 +304,7 @@ function executeWernisPayout ($wdsId, $amount) {
        // Return the result from the lower functions
        $return = sendWernisApiRequest('book.php', $requestData);
 
-       if ($return['status'] == 'OK') {
+       if (isHttpResponseStatusOkay($return)) {
                // All fine!
                $result = TRUE;
 
@@ -323,7 +323,7 @@ function executeWernisPayout ($wdsId, $amount) {
 }
 
 // Execute auth.php request
-function executeWernisAuth ($wernisId, $wernisPassword) {
+function executeWernisApiAuth ($wernisId, $wernisPassword) {
        // Prepare request data
        $requestData = array(
                't_uid'       => bigintval($wernisId),
@@ -337,6 +337,32 @@ function executeWernisAuth ($wernisId, $wernisPassword) {
        return $return;
 }
 
+// Execute get.php reguest with given auth data (not all are used)
+function executeWernisApiGet ($authData, $subRequest, $fields) {
+       // It must be an array
+       assert(is_array($authData));
+
+       // Check required array elements
+       assert(isset($authData['wernis_userid']));
+       assert(isset($authData['api_auth_key']));
+       assert(isset($authData['api_redirect_challenge']));
+
+       // Then create request array
+       $requestData = array(
+               'sub_request' => $subRequest,
+               'fields'      => $fields,
+               't_uid'       => bigintval($authData['wernis_userid']),
+               'auth_key'    => $authData['api_auth_key'],
+               'challenge'   => $authData['api_redirect_challenge']
+       );
+
+       // Call get.php
+       $return = sendWernisApiRequest('get.php', $requestData);
+
+       // Return full array
+       return $return;
+}
+
 // Translate the status IN/OUT
 function translateWernisTransferStatus ($status) {
        // Default status is unknown
@@ -431,11 +457,11 @@ function doDisplayWernisUserRegistrationForm () {
                        displayMessage('{--GUEST_WERNIS_REGISTRATION_PASSWORD_NOT_SET--}');
                } else {
                        // So far, all fine, then let's do the call-back on auth.php ...
-                       $response = executeWernisAuth(postRequestElement('wernis_id'), postRequestElement('wernis_password'));
+                       $response = executeWernisApiAuth(postRequestElement('wernis_id'), postRequestElement('wernis_password'));
 
                        // Was the status okay?
-                       if ((isset($response['status'])) && ($response['status'] == 'OK') && (!empty($response['response']))) {
-                               // All fine, then analyze response
+                       if (isHttpResponseStatusOkay($response)) {
+                               // All fine, then analyze API response
                                $args = convertApiResponseToArray($response['response'], '&', '=');
 
                                // Is status set?
@@ -455,7 +481,9 @@ function doDisplayWernisUserRegistrationForm () {
 
                                // Then call it
                                $status = call_user_func($callbackFunction, $args);
-                               die(__FUNCTION__ . ': status[' . gettype($status) . ']=' . $status);
+
+                               // @TODO Something more to do here?
+                               die(__FUNCTION__ . ':' . __LINE__ . ': status[' . gettype($status) . ']=' . $status . ' - Unfinished.');
                        } else {
                                // Something bad happened
                                displayMessage($response['message']);
@@ -463,17 +491,17 @@ function doDisplayWernisUserRegistrationForm () {
                }
        } // END - if
 
-       // Is the form not sent? (E.g. missing form fields)
+       // Is there a challenge + response?
        if ((isGetRequestElementSet('status')) && (isGetRequestElementSet('challenge')) && (isGetRequestElementSet('__challenge_response'))) {
                // Redirect from modules.php?module=auth, so validate challenge response ...
                // 1) Get first 24 characters = salt
                $salt = substr(getRequestElement('__challenge_response'), 0, 24);
 
-               // 2) Generate hash again
-               $response = $salt . hashSha256($salt . getWernisApiMd5() . getRequestElement('challenge'));
+               // 2) Generate hash for challenge response
+               $challengeResponse = $salt . hashSha256($salt . getWernisApiMd5() . getRequestElement('challenge'));
 
                // Is the response valid?
-               if ($response != getRequestElement('__challenge_response')) {
+               if ($challengeResponse != getRequestElement('__challenge_response')) {
                        // Not valid
                        displayMessage('{--GUEST_WERNIS_REGISTRATION_INVALID_CHALLENGE_RESPONSE--}');
                        return;
@@ -481,13 +509,151 @@ function doDisplayWernisUserRegistrationForm () {
 
                /*
                 * Now, that the challenge-response is the same, the challenge itself
-                * is also the same. So get.php can be called.
+                * is also the same. Next get the data from wernis_regs table by
+                * challenge. There is currently no other way to get the data as there
+                * is no Wernis user id provided. Later on the stored challenge response
+                * can be compared with provided.
                 */
-               die('!ojk');
+               $return = doWernisFinishUserRegistration(getRequestElement('challenge'), getRequestElement('__challenge_response'), getRequestElement('status'));
+
+               // Is the registration finished?
+               if ($return === FALSE) {
+                       // No, then abort here silently as the function should have already displayed a message
+                       return;
+               } // END - if
        } elseif (!isFormSent('register')) {
                // Form not send, so load form template
                loadTemplate('guest_wernis_registration_form');
+       }
+}
+
+// Finish user registration with WDS66 API
+function doWernisFinishUserRegistration ($challenge, $challengeResponse, $status) {
+       // Get stored registration data
+       $rows = getWernisRegistrationDataByKey('api_redirect_challenge', $challenge);
+
+       // Zero result found?
+       if (count($rows) == 0) {
+               // Nothing found
+               displayMessage('{--GUEST_WERNIS_REGISTRATION_ZERO_ROWS_FOUND--}');
+
+               // Display form
+               loadTemplate('guest_wernis_registration_form');
+               return FALSE;
        } // 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
+
+               // 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');
+
+               // Was the status okay?
+               if (isHttpResponseStatusOkay($response)) {
+                       // API returned non-errous response, 'data=' must be found
+                       assert(substr($response['response'], 0, 5) == 'data=');
+
+                       // And remove it, this is now BASE64-encoded
+                       $encodedData = urldecode(substr($response['response'], 5));
+
+                       // And decode it (all steps separated to later "easily" debug them)
+                       $decodedData = base64_decode($encodedData);
+
+                       /*
+                        * 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);
+                       die(__FUNCTION__.'<pre>'.print_r($userData, TRUE).'</pre>');
+               } else {
+                       // Something bad happened
+                       displayMessage($response['message']);
+                       return FALSE;
+               }
+       } else {
+               // Status does not need to be changed
+       }
+}
+
+// Updates auth status by given key/value pair
+function updateWernisRegistrationStatusByKey ($key, $value, $newStatus) {
+       // Run the update
+       sqlQueryEscaped("UPDATE
+       `{?_MYSQL_PREFIX?}_wernis_regs`
+SET
+       `api_auth_status`='%s'
+WHERE
+       `%s`='%s' AND
+       `api_auth_status` != '%s'
+LIMIT 1",
+               array(
+                       $newStatus,
+                       $key,
+                       $value,
+                       $newStatus
+               ), __FUNCTION__, __LINE__
+       );
+
+       // Check if rows as been affected
+       return ifSqlHasZeroAffectedRows();
+}
+
+// "Getter" for Wernis registration data by given key and value
+function getWernisRegistrationDataByKey ($key, $value, $limit = 1) {
+       // Init array
+       $rows = array();
+
+       // Now search for it
+       $result = sqlQueryEscaped("SELECT
+       `local_userid`,
+       `wernis_userid`,
+       `api_auth_status`,
+       `api_auth_key`,
+       `api_redirect_challenge`,
+       UNIX_TIMESTAMP(`record_inserted`) AS `record_inserted`
+FROM
+       `{?_MYSQL_PREFIX?}_wernis_regs`
+WHERE
+       `%s`='%s'
+ORDER BY
+       `id`
+LIMIT %d",
+               array(
+                       $key,
+                       $value,
+                       $limit
+               ), __FUNCTION__, __LINE__
+       );
+
+       // Is there an entry?
+       if (sqlNumRows($result) > 0) {
+               // At least one entry has been found, so loop through all
+               while ($row = sqlFetchArray($result)) {
+                       // Add it
+                       array_push($rows, $row);
+               } // END - while
+       } // END - if
+
+       // Free result
+       sqlFreeResult($result);
+
+       // Return found entries
+       return $rows;
 }
 
 //-----------------------------------------------------------------------------
@@ -496,8 +662,12 @@ function doDisplayWernisUserRegistrationForm () {
 
 // Handler for auth_status=PENDING
 function doWernisAuthPending ($args) {
-       // auth_key must be set
+       // $args must always be an array
+       assert(is_array($args));
+
+       // auth_key and wernis_userid must be set
        assert(isset($args['auth_key']));
+       assert(isset($args['wernis_userid']));
 
        // Generate a challenge that will be added to the URL
        $challenge = hashSha256(generatePassword(128));
@@ -551,6 +721,18 @@ LIMIT 1",
        redirectToUrl(getWernisBaseUrl() . '/modules.php?module=auth&amp;auth_key=' . $args['auth_key'] . '&amp;params=' . urlencode(base64_encode('&module=' . getModule() . '&what=' . getWhat())) . '&amp;challenge=' . $challenge);
 }
 
+// Handler for auth_status=ACCEPTED
+function doWernisAuthAccepted ($args) {
+       // $args must always be an array
+       assert(is_array($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>');
+}
+
 //-----------------------------------------------------------------------------
 //                             Wrapper functions
 //-----------------------------------------------------------------------------