Added new pre-registration filter for WDS66-based registration (unfinished).
[mailer.git] / inc / libs / wernis_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/19/2003 *
4  * ===================                          Last change: 08/12/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : what-points.php                                  *
8  * -------------------------------------------------------------------- *
9  * Short description : All your collected points...                     *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle Ihrer gesammelten Punkte                    *
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 - 2013 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 // Sets a status message and code
44 function setWernisStatusMessage ($message, $status) {
45         $GLOBALS['wernis_data']['message'] = $message;
46         $GLOBALS['wernis_data']['status']  = $status;
47 }
48
49 // Get the status message
50 function getWernisErrorMessage () {
51         if (isset($GLOBALS['wernis_data']['message'])) {
52                 // Use raw message
53                 return $GLOBALS['wernis_data']['message'];
54         } elseif (isset($GLOBALS['wernis_data']['status'])) {
55                 // Fall-back to status
56                 return '{%message,WERNIS_ERROR_STATUS=' . $GLOBALS['wernis_data']['status'] . '%}';
57         } else {
58                 // Something bad happend
59                 return '{--WERNIS_UNKNOWN_ERROR--}';
60         }
61 }
62
63 // Get the status code
64 function getWernisErrorCode () {
65         if (isset($GLOBALS['wernis_data']['status'])) {
66                 // Use raw message
67                 return $GLOBALS['wernis_data']['status'];
68         } else {
69                 // Something bad happend
70                 return '{--WERNIS_UNKNOWN_ERROR--}';
71         }
72 }
73
74 // Sends out a request to the API and returns it's result
75 function sendWernisApiRequest ($scriptName, $requestData = array()) {
76         // Is the requestData an array?
77         if (!is_array($requestData)) {
78                 // Then abort here!
79                 return array(
80                         'status'  => 'failed_general',
81                         'message' => '{--WERNIS_API_REQUEST_DATA_INVALID--}'
82                 );
83         } // END - if
84
85         // Is the API id and MD5 hash there?
86         if ((getWernisApiId() == '') || (getWernisApiMd5() == '')) {
87                 // Abort here...
88                 return array(
89                         'status'  => 'failed_general',
90                         'message' => '{--WERNIS_API_REQUEST_DATA_MISSING--}'
91                 );
92         } // END - if
93
94         // Add more request data
95         $requestData['api_id']  = getWernisApiId();
96         $requestData['api_key'] = getWernisApiMd5();
97
98         // Is a purpose there?
99         if (!empty($requestData['purpose'])) {
100                 // Eval the purpose
101                 eval('$purpose = "' . doFinalCompilation($requestData['purpose'], FALSE) . '";');
102
103                 // Prepare the purpose, it needs encoding
104                 $requestData['purpose'] = encodeString($purpose);
105         } // END - if
106
107         // Construct the request string
108         $requestString = getWernisApiUrl() . $scriptName;
109
110         // Get the raw response from the lower function
111         $response = sendHttpPostRequest($requestString, $requestData);
112
113         // Check the response header if all is fine
114         if (!isHttpStatusOkay($response[0])) {
115                 // Something bad happend... :(
116                 return array(
117                         'status'  => 'request_error',
118                         'message' => '{%message,WERNIS_API_REQUEST_ERROR=' . $response[0] . '%}'
119                 );
120         } // END - if
121
122         // All (maybe) fine so remove the response header from server
123         $responseLine = '*INVALID*';
124         for ($idx = (count($response) - 1); $idx > 1; $idx--) {
125                 $line = trim($response[$idx]);
126                 if (!empty($line)) {
127                         $responseLine = $line;
128                         break;
129                 } // END - if
130         } // END - for
131
132         // Is the response leaded by a & symbol?
133         if (substr($responseLine, 0, 1) != '&') {
134                 // Something badly happened on server-side
135                 return array(
136                         'status'  => 'request_problem',
137                         'message' => sprintf(getMessage('WERNIS_API_REQUEST_PROBLEM'), $response[0], secureString($responseLine))
138                 );
139         } // END - if
140
141         // Remove the leading & (which can be used in Flash)
142         $responseLine = substr($responseLine, 1);
143
144         // Bring back the response
145         $data = explode('=', $responseLine);
146
147         // Default return array (should not stay empty)
148         $return = array();
149
150         // We use only the first two entries (which shall be fine)
151         if ($data[0] === 'error') {
152                 // The request has failed... :(
153                 switch ($data[1]) {
154                         case '404': // Invalid API id
155                         case 'AUTH': // Authorization has failed
156                                 $return = array(
157                                         'status'  => 'auth_failed',
158                                         'message' => '{--WERNIS_API_REQUEST_FAILED_AUTH--}'
159                                 );
160                                 break;
161
162                         case 'LOCKED': // User account is locked!
163                         case 'PASS': // Bad passphrase entered
164                         case 'USER': // Missing account or invalid password
165                                 $return = array(
166                                         'status'  => 'user_failed',
167                                         'message' => '{--WERNIS_API_REQUEST_FAILED_USER--}'
168                                 );
169                                 break;
170
171                         case 'OWN': // Transfer to own account
172                                 $return = array(
173                                         'status'  => 'own_failed',
174                                         'message' => '{--WERNIS_API_REQUEST_FAILED_OWN--}'
175                                 );
176                                 break;
177
178                         case 'AMOUNT': // Amount is depleted
179                                 $return = array(
180                                         'status'  => 'amount_failed',
181                                         'message' => '{--WERNIS_API_REQUEST_FAILED_AMOUNT--}'
182                                 );
183                                 break;
184
185                         case 'AMOUNT-SEND': // API amount is depleted
186                                 $return = array(
187                                         'status'  => 'api_amount_failed',
188                                         'message' => '{--WERNIS_API_REQUEST_FAILED_API_AMOUNT--}'
189                                 );
190                                 break;
191
192                         default: // Unknown error (maybe new?)
193                                 logDebugMessage(__FUNCTION__, __LINE__, sprintf('Unknown error %s from WDS66 API received.', $data[1]));
194                                 $return = array(
195                                         'status'  => 'request_failed',
196                                         'message' => '{%message,WERNIS_API_REQUEST_FAILED=' . $data[1] . '%}'
197                                 );
198                                 break;
199                 }
200         } else {
201                 // All fine here
202                 $return = array(
203                         'status'   => 'OK',
204                         'response' => $responseLine
205                 );
206         }
207
208         // Return the result
209         return $return;
210 }
211
212 // Tests the function by calling balance.php on the API
213 function doAdminTestWernisApi () {
214         // Only as admin
215         assert(isAdmin());
216
217         // Result is always failed
218         $result = FALSE;
219
220         // Prepare the request data
221         $requestData = array(
222                 't_uid'       => getWernisRefid(),
223                 't_md5'       => getWernisPassMd5()
224         );
225
226         // Return the result from the lower functions
227         $return = sendWernisApiRequest('balance.php', $requestData);
228
229         // Did it went smoothly?
230         if (isHttpResponseStatusOkay($return)) {
231                 // All fine!
232                 $result = TRUE;
233         } else {
234                 // Status failure text
235                 setWernisStatusMessage($return['message'], $return['status']);
236         }
237
238         // Return result
239         return $result;
240 }
241
242 // Widthdraw this amount
243 function executeWernisApiWithdraw ($wdsId, $userMd5, $amount) {
244         // Is the sponsor extension installed?
245         if (!isWernisWithdrawActive()) {
246                 if (!isExtensionActive('sponsor')) {
247                         // No, abort here
248                         return FALSE;
249                 } elseif (!isSponsor()) {
250                         // No sponsor, not allowed to withdraw!
251                         return FALSE;
252                 }
253         } // END - if
254
255         // Default is failed attempt
256         $result = FALSE;
257
258         // Prepare the request data
259         $requestData = array(
260                 'sub_request' => 'receive',
261                 't_uid'       => bigintval($wdsId),
262                 't_md5'       => $userMd5,
263                 'r_uid'       => getWernisRefid(),
264                 'amount'      => bigintval($amount),
265                 'purpose'     => getMaskedMessage('WERNIS_API_PURPOSE_WITHDRAW', getMemberId())
266         );
267
268         // Return the result from the lower functions
269         $return = sendWernisApiRequest('book.php', $requestData);
270
271         if (isHttpResponseStatusOkay($return)) {
272                 // All fine!
273                 $result = TRUE;
274
275                 // Log the transfer
276                 logWernisTransfer($wdsId, $amount, 'WITHDRAW');
277         } else {
278                 // Status failure text
279                 setWernisStatusMessage($return['message'], $return['status']);
280
281                 // Log the transfer
282                 logWernisTransfer($wdsId, $amount, 'FAILED', $return['message'], $return['status']);
283         }
284
285         // Return result
286         return $result;
287 }
288
289 // Payout this amount
290 function executeWernisApiPayout ($wdsId, $amount) {
291         // Default is failed attempt
292         $result = FALSE;
293
294         // Prepare the request data
295         $requestData = array(
296                 'sub_request' => 'send',
297                 't_uid'       => getWernisRefid(),
298                 't_md5'       => getWernisPassMd5(),
299                 'r_uid'       => bigintval($wdsId),
300                 'amount'      => bigintval($amount),
301                 'purpose'     => getMaskedMessage('WERNIS_API_PURPOSE_PAYOUT', getMemberId())
302         );
303
304         // Return the result from the lower functions
305         $return = sendWernisApiRequest('book.php', $requestData);
306
307         if (isHttpResponseStatusOkay($return)) {
308                 // All fine!
309                 $result = TRUE;
310
311                 // Log the transfer
312                 logWernisTransfer($wdsId, $amount, 'PAYOUT');
313         } else {
314                 // Status failure text
315                 setWernisStatusMessage($return['message'], $return['status']);
316
317                 // Log the transfer
318                 logWernisTransfer($wdsId, $amount, 'FAILED', $return['message'], $return['status']);
319         }
320
321         // Return result
322         return $result;
323 }
324
325 // Execute auth.php request
326 function executeWernisApiAuth ($wernisId, $wernisPassword) {
327         // Prepare request data
328         $requestData = array(
329                 't_uid'       => bigintval($wernisId),
330                 't_md5'       => hashSha256($wernisPassword),
331         );
332
333         // Call auth.php
334         $return = sendWernisApiRequest('auth.php', $requestData);
335
336         // Return full array
337         return $return;
338 }
339
340 // Execute get.php reguest with given auth data (not all are used)
341 function executeWernisApiGet ($authData, $subRequest, $fields) {
342         // It must be an array
343         assert(is_array($authData));
344
345         // Check required array elements
346         assert(isset($authData['wernis_userid']));
347         assert(isset($authData['api_auth_key']));
348         assert(isset($authData['api_redirect_challenge']));
349
350         // Then create request array
351         $requestData = array(
352                 'sub_request' => $subRequest,
353                 'fields'      => $fields,
354                 't_uid'       => bigintval($authData['wernis_userid']),
355                 'auth_key'    => $authData['api_auth_key'],
356                 'challenge'   => $authData['api_redirect_challenge']
357         );
358
359         // Call get.php
360         $return = sendWernisApiRequest('get.php', $requestData);
361
362         // Return full array
363         return $return;
364 }
365
366 // Translate the status IN/OUT
367 function translateWernisTransferStatus ($status) {
368         // Default status is unknown
369         $return = '{%message,WERNIS_STATUS_UNKNWOWN=' . $status . '%}';
370
371         // Construct message id
372         $messageId = 'WERNIS_STATUS_' . $status;
373
374         // Is it there?
375         if (isMessageIdValid($messageId)) {
376                 // Then use it as message string
377                 $return = '{--' . $messageId . '--}';
378         } // END - if
379
380         // Return the status
381         return $return;
382 }
383
384 // Log the transfer
385 function logWernisTransfer ($wdsId, $amount, $type = 'FAILED', $message = '', $status = '') {
386         // Register this wernis movement
387         sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_user_wernis` (`userid`, `wernis_account`, `wernis_amount`, `wernis_timestamp`, `wernis_type`, `wernis_api_message`, `wernis_api_status`) VALUES (%s, %s, %s, UNIX_TIMESTAMP(), '%s', '%s', '%s')",
388                 array(
389                         getMemberId(),
390                         bigintval($wdsId),
391                         bigintval($amount),
392                         $type,
393                         $message,
394                         $status
395                 ), __FUNCTION__, __LINE__);
396 }
397
398 // Calulcate fees and factor
399 function calculateWernisFee ($points, $mode) {
400         // Payout or withdraw are allowed modes!
401         //* DEBUG: */ debugOutput('mode=' . $mode . ',points=' . $points);
402         if (!in_array($mode, array('payout', 'withdraw'))) {
403                 // Log error and abort
404                 logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . getMemberId() . ',mode=' . $mode . ',points=' . $points . ' - unknown mode detected.');
405                 return FALSE;
406         } // END - if
407
408         // Is there a percentage or fixed fee?
409         if (getConfig('wernis_' . $mode . '_fee_percent') > 0) {
410                 // Percentage fee
411                 $points -= $points * getConfig('wernis_'.$mode.'_fee_percent') / 100;
412         } elseif (getConfig('wernis_' . $mode . '_fee_fix') > 0) {
413                 // Fixed fee
414                 $points -= getConfig('wernis_' . $mode . '_fee_fix');
415         }
416
417         // Divide/multiply the factor
418         if ($mode == 'payout') {
419                 // Divide for payout
420                 $points = $points / getWernisPayoutFactor();
421         } else {
422                 // Multiply for withdraw
423                 $points = $points * getWernisWithdrawFactor();
424         }
425
426         // Return value
427         //* DEBUG: */ debugOutput('mode=' . $mode . ',points=' . $points);
428         return $points;
429 }
430
431 // Add withdraw fees and factor
432 // @TODO Unused?
433 function calulcateWernisWithdrawFee ($points) {
434         // Is there a percentage or fixed fee?
435         if (getWernisWithdrawFeePercent() > 0) {
436                 // Percentage fee
437                 $points += $points * getWernisWithdrawFeePercent() / 100;
438         } elseif (getWernisWithdrawFeeFix() > 0) {
439                 // Fixed fee
440                 $points += getWernisWithdrawFeeFix();
441         }
442
443         // Return value
444         return $points;
445 }
446
447 // Displays registration form for WDS66 registration
448 function doDisplayWernisUserRegistrationForm () {
449         // Is the form sent?
450         if (isFormSent('register')) {
451                 // Is wernis_id set?
452                 if (!isPostRequestElementSet('wernis_id')) {
453                         // Id not set
454                         displayMessage('{--GUEST_WERNIS_REGISTRATION_ID_NOT_SET--}');
455                 } elseif (!isPostRequestElementSet('wernis_password')) {
456                         // Password not set
457                         displayMessage('{--GUEST_WERNIS_REGISTRATION_PASSWORD_NOT_SET--}');
458                 } else {
459                         // So far, all fine, then let's do the call-back on auth.php ...
460                         $response = executeWernisApiAuth(postRequestElement('wernis_id'), postRequestElement('wernis_password'));
461
462                         // Was the status okay?
463                         if (isHttpResponseStatusOkay($response)) {
464                                 // All fine, then analyze API response
465                                 $args = convertApiResponseToArray($response['response'], '&', '=');
466
467                                 // Is status set?
468                                 assert(isset($args['auth_status']));
469
470                                 // Add WDS66 userid
471                                 $args['wernis_userid'] = postRequestElement('wernis_id');
472
473                                 // "Detect" auth status
474                                 $callbackFunction = 'doWernisAuth' . capitalizeUnderscoreString($args['auth_status']);
475
476                                 // Is the call-back there?
477                                 if (!is_callable($callbackFunction, FALSE, $callableName)) {
478                                         // Not there, could be bad. :(
479                                         reportBug(__FUNCTION__, __LINE__, 'Unsupported auth_status=' . $args['auth_status'] . ',args()=' . count($args) . ',callbackFunction=' . $callbackFunction . ' detected.');
480                                 } // END - if
481
482                                 // Then call it
483                                 $status = call_user_func($callbackFunction, $args);
484
485                                 // @TODO Something more to do here?
486                                 die(__FUNCTION__ . ':' . __LINE__ . ': status[' . gettype($status) . ']=' . $status . ' - Unfinished.');
487                         } else {
488                                 // Something bad happened
489                                 displayMessage($response['message']);
490                         }
491                 }
492         } // END - if
493
494         // Is there a challenge + response?
495         if ((isGetRequestElementSet('status')) && (isGetRequestElementSet('challenge')) && (isGetRequestElementSet('__challenge_response'))) {
496                 // Redirect from modules.php?module=auth, so validate challenge response ...
497                 // 1) Get first 24 characters = salt
498                 $salt = substr(getRequestElement('__challenge_response'), 0, 24);
499
500                 // 2) Generate hash for challenge response
501                 $challengeResponse = $salt . hashSha256($salt . getWernisApiMd5() . getRequestElement('challenge'));
502
503                 // Is the response valid?
504                 if ($challengeResponse != getRequestElement('__challenge_response')) {
505                         // Not valid
506                         displayMessage('{--GUEST_WERNIS_REGISTRATION_INVALID_CHALLENGE_RESPONSE--}');
507                         return;
508                 } // END - if
509
510                 /*
511                  * Now, that the challenge-response is the same, the challenge itself
512                  * is also the same. Next get the data from wernis_regs table by
513                  * challenge. There is currently no other way to get the data as there
514                  * is no Wernis user id provided. Later on the stored challenge response
515                  * can be compared with provided.
516                  */
517                 $return = doWernisFinishUserRegistration(getRequestElement('challenge'), getRequestElement('__challenge_response'), getRequestElement('status'));
518
519                 // Is the registration finished?
520                 if ($return === FALSE) {
521                         // No, then abort here silently as the function should have already displayed a message
522                         return;
523                 } // END - if
524         } elseif (!isFormSent('register')) {
525                 // Form not send, so load form template
526                 loadTemplate('guest_wernis_registration_rpc_form');
527         }
528 }
529
530 // Finish user registration with WDS66 API
531 function doWernisFinishUserRegistration ($challenge, $challengeResponse, $status) {
532         // Is the status 1? (= all fine with API call)
533         if ($status == '1') {
534                 // Get mapped data based on challenge
535                 $return = getWernisMappedDataFromApiByChallenge($challenge, $status);
536
537                 // Is the array filled?
538                 if ((count($return['mapped_data']) > 0) && (empty($return['message']))) {
539                         // Set must-fillout fields
540                         $return['mapped_data'] = runFilterChain('register_must_fillout', $return['mapped_data']);
541
542                         // Add missing elements
543                         $return['mapped_data']['gender']               = NULL;
544                         $return['mapped_data']['birthday_selection']   = generateDayMonthYearSelectionBox($return['mapped_data']['birth_day'], $return['mapped_data']['birth_month'], $return['mapped_data']['birth_year']);
545                         $return['mapped_data']['challenge']            = getRequestElement('challenge');
546                         $return['mapped_data']['__challenge_response'] = getRequestElement('__challenge_response');
547
548                         // Display form
549                         loadTemplate('guest_wernis_registration_form', FALSE, $return['mapped_data']);
550
551                         // All fine
552                         return TRUE;
553                 } else {
554                         // Something unexpected happened (e.g. no API requests left)
555                         displayMessage($return['message']);
556                         return FALSE;
557                 }
558         } else {
559                 // Status does not need to be changed
560                 die(__FUNCTION__ . ':' . __LINE__ . ': Reached!');
561         }
562 }
563
564 // "Getter" for mapped data by calling the API and given challenge and status
565 function getWernisMappedDataFromApiByChallenge ($challenge, $status) {
566         // Get stored registration data
567         $rows = getWernisRegistrationDataByKey('api_redirect_challenge', $challenge);
568
569         // Zero result found?
570         if (count($rows) == 0) {
571                 // Nothing found
572                 displayMessage('{--GUEST_WERNIS_REGISTRATION_ZERO_ROWS_FOUND--}');
573
574                 // Display form
575                 loadTemplate('guest_wernis_registration_rpc_form');
576                 return array();
577         } // END - if
578
579         // Init array
580         $return = array(
581                 // Mapped data
582                 'mapped_data' => array(),
583                 // Any error message from API
584                 'message'     => ''
585         );
586
587         // Has the auth status changed?
588         if ($rows[0]['api_auth_status'] != 'ACCEPTED') {
589                 /*
590                  * The authorization of this application has been accepted, so
591                  * update it and ignore result from function because the update
592                  * will always run.
593                  */
594                 updateWernisRegistrationDataByKey('api_auth_status', 'api_redirect_challenge', $challenge, 'ACCEPTED');
595         } // END - if
596
597         // Now call "get.php"
598         $response = executeWernisApiGet($rows[0], 'data', 'vorname|name|strasse|plz|ort|birth_day|birth_month|birth_year|email|werber');
599
600         // Was the status okay?
601         if (isHttpResponseStatusOkay($response)) {
602                 // API returned non-errous response, 'data=' must be found
603                 assert(substr($response['response'], 0, 5) == 'data=');
604
605                 // And remove it, this is now BASE64-encoded
606                 $encodedData = urldecode(substr($response['response'], 5));
607
608                 // And decode it (all steps separated to later "easily" debug them)
609                 $decodedData = base64_decode($encodedData);
610
611                 /*
612                  * Do some checks on the decoded string, it should be a
613                  * serialized array with 10 entries (see above
614                  * executeWernisApiGet() call).
615                  */
616                 assert(substr($decodedData, 0, 6) == 'a:10:{');
617                 assert(substr($decodedData, -1, 1) == '}');
618
619                 // The array seems to be fine, unserialize it
620                 $userData = unserialize($decodedData);
621
622                 // All mappings WDS66->mailer
623                 $mappings = array(
624                         'vorname'     => 'surname',
625                         'name'        => 'family',
626                         'strasse'     => 'street_nr',
627                         'plz'         => 'zip',
628                         'ort'         => 'city',
629                         'email'       => 'email',
630                         'birth_day'   => 'birth_day',
631                         'birth_month' => 'birth_month',
632                         'birth_year'  => 'birth_year',
633                         'werber'      => 'wernis_refid'
634                 );
635
636                 // Map all WDS66 entries into mailer entries
637                 foreach ($mappings as $from => $to) {
638                         // All must exist
639                         if (!isset($userData[$from])) {
640                                 // Element $from does not exist
641                                 reportBug(__FUNCTION__, __LINE__, 'Cannot map from=' . $from . ' -> to=' . $to . ': element does not exist.');
642                         } // END - if
643
644                         // "Map" all
645                         $return['mapped_data'][$to] = convertEmptyToNull($userData[$from]);
646                 } // END - foreach
647
648                 // Both arrays must have same size
649                 assert(count($userData) == count($return['mapped_data']));
650
651                 // Now add userid from WDS66
652                 $return['mapped_data']['wernis_userid'] = bigintval($rows[0]['wernis_userid']);
653         } else {
654                 // Something bad happened so copy the message
655                 $return['message'] = $response['message'];
656         }
657
658         // Return mapped data array
659         return $return;
660 }
661
662 // Updates auth status by given key/value pair
663 function updateWernisRegistrationDataByKey ($updatedColumn, $key, $oldValue, $newValue) {
664         // Run the update
665         sqlQueryEscaped("UPDATE
666         `{?_MYSQL_PREFIX?}_wernis_regs`
667 SET
668         `%s`='%s'
669 WHERE
670         `%s`='%s' AND
671         `%s` != '%s'
672 LIMIT 1",
673                 array(
674                         $updatedColumn,
675                         $newValue,
676                         $key,
677                         $updatedColumn,
678                         $oldValue
679                 ), __FUNCTION__, __LINE__
680         );
681
682         // Check if rows as been affected
683         return ifSqlHasZeroAffectedRows();
684 }
685
686 // "Getter" for Wernis registration data by given key and value
687 function getWernisRegistrationDataByKey ($key, $value, $limit = 1) {
688         // Init array
689         $rows = array();
690
691         // Now search for it
692         $result = sqlQueryEscaped("SELECT
693         `local_userid`,
694         `wernis_userid`,
695         `api_auth_status`,
696         `api_auth_key`,
697         `api_redirect_challenge`,
698         UNIX_TIMESTAMP(`record_inserted`) AS `record_inserted`
699 FROM
700         `{?_MYSQL_PREFIX?}_wernis_regs`
701 WHERE
702         `%s`='%s'
703 ORDER BY
704         `id`
705 LIMIT %d",
706                 array(
707                         $key,
708                         $value,
709                         $limit
710                 ), __FUNCTION__, __LINE__
711         );
712
713         // Is there an entry?
714         if (sqlNumRows($result) > 0) {
715                 // At least one entry has been found, so loop through all
716                 while ($row = sqlFetchArray($result)) {
717                         // Add it
718                         array_push($rows, $row);
719                 } // END - while
720         } // END - if
721
722         // Free result
723         sqlFreeResult($result);
724
725         // Return found entries
726         return $rows;
727 }
728
729 // Do local user registration with data from WDS66 API
730 function doWernisUserRegistration () {
731         // Call generic registration function
732         $status = doGenericUserRegistration();
733
734         // Does this went fine?
735         if ($status === FALSE) {
736                 // No, then abort here silently
737                 return FALSE;
738         } // END - if
739
740         // Make sure the user id is valid
741         assert(isset($GLOBALS['register_userid']));
742         assert(isValidId($GLOBALS['register_userid']));
743
744         // Generic registration is finished, so add more data:
745 }
746
747 //-----------------------------------------------------------------------------
748 //                      Auth status callback functions
749 //-----------------------------------------------------------------------------
750
751 // Handler for auth_status=PENDING
752 function doWernisAuthPending ($args) {
753         // $args must always be an array
754         assert(is_array($args));
755
756         // auth_key and wernis_userid must be set
757         assert(isset($args['auth_key']));
758         assert(isset($args['wernis_userid']));
759
760         // Generate a challenge that will be added to the URL
761         $challenge = hashSha256(generatePassword(128));
762
763         // Search entry in database by auth_key
764         if (countSumTotalData($args['auth_key'], 'wernis_regs', 'id', 'api_auth_key', TRUE) == 0) {
765                 // "Register" this call
766                 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_wernis_regs` (
767         `wernis_userid`,
768         `api_auth_status`,
769         `api_auth_key`,
770         `api_redirect_challenge`
771 ) VALUES (
772         %s,
773         'PENDING',
774         '%s',
775         '%s'
776 )",
777                         array(
778                                 bigintval($args['wernis_userid']),
779                                 $args['auth_key'],
780                                 $challenge
781                         ), __FUNCTION__, __LINE__
782                 );
783         } else {
784                 // Update challenge
785                 sqlQueryEscaped("UPDATE
786         `{?_MYSQL_PREFIX?}_wernis_regs`
787 SET
788         `api_redirect_challenge`='%s'
789 WHERE
790         `api_auth_key`='%s' AND
791         `wernis_userid`=%s
792         `api_auth_status`='PENDING'
793 LIMIT 1",
794                         array(
795                                 $challenge,
796                                 $args['auth_key'],
797                                 bigintval($args['wernis_userid'])
798                         ), __FUNCTION__, __LINE__
799                 );
800         }
801
802         // Should always update/insert
803         assert(sqlAffectedRows() == 1);
804
805         // Redirect to WDS66 module=auth ...
806         redirectToUrl(getWernisBaseUrl() . '/modules.php?module=auth&amp;auth_key=' . $args['auth_key'] . '&amp;params=' . urlencode(base64_encode('&module=' . getModule() . '&what=' . getWhat())) . '&amp;challenge=' . $challenge);
807 }
808
809 // Handler for auth_status=ACCEPTED
810 function doWernisAuthAccepted ($args) {
811         // $args must always be an array
812         assert(is_array($args));
813
814         // auth_key and wernis_userid must be set
815         assert(isset($args['auth_key']));
816         assert(isset($args['wernis_userid']));
817         die(__FUNCTION__ . ':' . __LINE__ . '<pre>' . print_r($args, TRUE) . '</pre>');
818 }
819
820 //-----------------------------------------------------------------------------
821 //                             Wrapper functions
822 //-----------------------------------------------------------------------------
823
824 // Wrapper function for 'wernis_refid'
825 function getWernisRefid () {
826         // Is there cache?
827         if (!isset($GLOBALS[__FUNCTION__])) {
828                 // Get config entry
829                 $GLOBALS[__FUNCTION__] = getConfig('wernis_refid');
830         } // END - if
831
832         // Return cache
833         return $GLOBALS[__FUNCTION__];
834 }
835
836 // Wrapper function for 'wernis_pass_md5'
837 function getWernisPassMd5 () {
838         // Is there cache?
839         if (!isset($GLOBALS[__FUNCTION__])) {
840                 // Get config entry
841                 $GLOBALS[__FUNCTION__] = getConfig('wernis_pass_md5');
842         } // END - if
843
844         // Return cache
845         return $GLOBALS[__FUNCTION__];
846 }
847
848 // Wrapper function for 'wernis_api_id'
849 function getWernisApiId () {
850         // Is there cache?
851         if (!isset($GLOBALS[__FUNCTION__])) {
852                 // Get config entry
853                 $GLOBALS[__FUNCTION__] = getConfig('wernis_api_id');
854         } // END - if
855
856         // Return cache
857         return $GLOBALS[__FUNCTION__];
858 }
859
860 // Wrapper function for 'wernis_api_md5'
861 function getWernisApiMd5 () {
862         // Is there cache?
863         if (!isset($GLOBALS[__FUNCTION__])) {
864                 // Get config entry
865                 $GLOBALS[__FUNCTION__] = getConfig('wernis_api_md5');
866         } // END - if
867
868         // Return cache
869         return $GLOBALS[__FUNCTION__];
870 }
871
872 // Wrapper function for 'wernis_api_url'
873 function getWernisApiUrl () {
874         // Is there cache?
875         if (!isset($GLOBALS[__FUNCTION__])) {
876                 // Get config entry
877                 $GLOBALS[__FUNCTION__] = getConfig('wernis_api_url');
878         } // END - if
879
880         // Return cache
881         return $GLOBALS[__FUNCTION__];
882 }
883
884 // Wrapper function for 'wernis_withdraw_active'
885 function getWernisWithdrawActive () {
886         // Is there cache?
887         if (!isset($GLOBALS[__FUNCTION__])) {
888                 // Get config entry
889                 $GLOBALS[__FUNCTION__] = getConfig('wernis_withdraw_active');
890         } // END - if
891
892         // Return cache
893         return $GLOBALS[__FUNCTION__];
894 }
895
896 // Wrapper function for 'wernis_payout_active'
897 function getWernisPayoutActive () {
898         // Is there cache?
899         if (!isset($GLOBALS[__FUNCTION__])) {
900                 // Get config entry
901                 $GLOBALS[__FUNCTION__] = getConfig('wernis_payout_active');
902         } // END - if
903
904         // Return cache
905         return $GLOBALS[__FUNCTION__];
906 }
907
908 // Wrapper function for 'wernis_withdraw_active'
909 function isWernisWithdrawActive () {
910         // Is there cache?
911         if (!isset($GLOBALS[__FUNCTION__])) {
912                 // Get config entry
913                 $GLOBALS[__FUNCTION__] = (getConfig('wernis_withdraw_active') == 'Y');
914         } // END - if
915
916         // Return cache
917         return $GLOBALS[__FUNCTION__];
918 }
919
920 // Wrapper function for 'wernis_payout_active'
921 function isWernisPayoutActive () {
922         // Is there cache?
923         if (!isset($GLOBALS[__FUNCTION__])) {
924                 // Get config entry
925                 $GLOBALS[__FUNCTION__] = (getConfig('wernis_payout_active') == 'Y');
926         } // END - if
927
928         // Return cache
929         return $GLOBALS[__FUNCTION__];
930 }
931
932 // Wrapper function for 'wernis_withdraw_factor'
933 function getWernisWithdrawFactor () {
934         // Is there cache?
935         if (!isset($GLOBALS[__FUNCTION__])) {
936                 // Get config entry
937                 $GLOBALS[__FUNCTION__] = getConfig('wernis_withdraw_factor');
938         } // END - if
939
940         // Return cache
941         return $GLOBALS[__FUNCTION__];
942 }
943
944 // Wrapper function for 'wernis_payout_factor'
945 function getWernisPayoutFactor () {
946         // Is there cache?
947         if (!isset($GLOBALS[__FUNCTION__])) {
948                 // Get config entry
949                 $GLOBALS[__FUNCTION__] = getConfig('wernis_payout_factor');
950         } // END - if
951
952         // Return cache
953         return $GLOBALS[__FUNCTION__];
954 }
955
956 // Wrapper function for 'wernis_withdraw_fee_percent'
957 function getWernisWithdrawFeePercent () {
958         // Is there cache?
959         if (!isset($GLOBALS[__FUNCTION__])) {
960                 // Get config entry
961                 $GLOBALS[__FUNCTION__] = getConfig('wernis_withdraw_fee_percent');
962         } // END - if
963
964         // Return cache
965         return $GLOBALS[__FUNCTION__];
966 }
967
968 // Wrapper function for 'wernis_withdraw_fee_fix'
969 function getWernisWithdrawFeeFix () {
970         // Is there cache?
971         if (!isset($GLOBALS[__FUNCTION__])) {
972                 // Get config entry
973                 $GLOBALS[__FUNCTION__] = getConfig('wernis_withdraw_fee_fix');
974         } // END - if
975
976         // Return cache
977         return $GLOBALS[__FUNCTION__];
978 }
979
980 // Wrapper function for 'wernis_payout_fee_percent'
981 function getWernisPayoutFeePercent () {
982         // Is there cache?
983         if (!isset($GLOBALS[__FUNCTION__])) {
984                 // Get config entry
985                 $GLOBALS[__FUNCTION__] = getConfig('wernis_payout_fee_percent');
986         } // END - if
987
988         // Return cache
989         return $GLOBALS[__FUNCTION__];
990 }
991
992 // Wrapper function for 'wernis_payout_fee_fix'
993 function getWernisPayoutFeeFix () {
994         // Is there cache?
995         if (!isset($GLOBALS[__FUNCTION__])) {
996                 // Get config entry
997                 $GLOBALS[__FUNCTION__] = getConfig('wernis_payout_fee_fix');
998         } // END - if
999
1000         // Return cache
1001         return $GLOBALS[__FUNCTION__];
1002 }
1003
1004 // Wrapper function for 'wernis_min_payout'
1005 function getWernisMinPayout () {
1006         // Is there cache?
1007         if (!isset($GLOBALS[__FUNCTION__])) {
1008                 // Get config entry
1009                 $GLOBALS[__FUNCTION__] = getConfig('wernis_min_payout');
1010         } // END - if
1011
1012         // Return cache
1013         return $GLOBALS[__FUNCTION__];
1014 }
1015
1016 // Wrapper function for 'wernis_min_withdraw'
1017 function getWernisMinWithdraw () {
1018         // Is there cache?
1019         if (!isset($GLOBALS[__FUNCTION__])) {
1020                 // Get config entry
1021                 $GLOBALS[__FUNCTION__] = getConfig('wernis_min_withdraw');
1022         } // END - if
1023
1024         // Return cache
1025         return $GLOBALS[__FUNCTION__];
1026 }
1027
1028 // Wrapper function for 'wernis_base_url'
1029 function getWernisBaseUrl () {
1030         // Is there cache?
1031         if (!isset($GLOBALS[__FUNCTION__])) {
1032                 // Get config entry
1033                 $GLOBALS[__FUNCTION__] = getConfig('wernis_base_url');
1034         } // END - if
1035
1036         // Return cache
1037         return $GLOBALS[__FUNCTION__];
1038 }
1039
1040 // [EOF]
1041 ?>