]> git.mxchange.org Git - core.git/blob - framework/main/third_party/api/wernisportal/class_WernisApi.php
Continued:
[core.git] / framework / main / third_party / api / wernisportal / class_WernisApi.php
1 <?php
2 // Own namespace
3 namespace Com\Wds66\Api;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Object\BaseFrameworkSystem;
7
8 /**
9  * Class for connecting to the Wernis-Portal at http://www.wds66.com
10  *
11  * @author              Roland Haeder <webmaster@shipsimu.org>
12  * @version             0.0.0
13  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2021 Core Developer Team
14  * @license             GNU GPL 3.0 or any newer version
15  * @link                http://www.shipsimu.org
16  * @todo                Out-dated since 0.6-BETA
17  *
18  * This program is free software: you can redistribute it and/or modify
19  * it under the terms of the GNU General Public License as published by
20  * the Free Software Foundation, either version 3 of the License, or
21  * (at your option) any later version.
22  *
23  * This program is distributed in the hope that it will be useful,
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
26  * GNU General Public License for more details.
27  *
28  * You should have received a copy of the GNU General Public License
29  * along with this program. If not, see <http://www.gnu.org/licenses/>.
30  */
31 class WernisApi extends BaseFrameworkSystem {
32         /**
33          * Static base API URL
34          */
35         private static $apiUrl = 'https://www.wds66.com/api/';
36
37         /**
38          * API Wernis amount
39          */
40         private $wernis_amount = 0;
41
42         /**
43          * API username
44          */
45         private $w_id = 0;
46
47         /**
48          * API Wernis password (not account password!)
49          */
50         private $w_md5 = '';
51
52         /**
53          * Nickname of the user
54          */
55         private $w_nick = '';
56
57         /**
58          * Wernis amount of the user
59          */
60         private $w_amount = 0;
61
62         /**
63          * Array with status informations
64          */
65         private $statusArray = array();
66
67         /**
68          * Status for 'okay'
69          */
70         private $statusOkay = 'OK';
71
72         /**
73          * Protected constructor
74          *
75          * @return      void
76          */
77         private function __construct () {
78                 // Call parent constructor
79                 parent::__construct(__CLASS__);
80         }
81
82         /**
83          * Creates an instance of this API class
84          *
85          * @param       $configArray                    Configuration array
86          * @return      $apiInstance    An instance of this API class
87          */
88         public static final function createWernisApi (array $configArray) {
89                 // Create a new instance
90                 $apiInstance = new WernisApi();
91
92                 // If not an api_url is given (e.g. on local development system)
93                 if (!isset($configArray['api_url'])) {
94                         // ... then set the productive URL
95                         $configArray['api_url'] = self::$apiUrl;
96                 }
97
98                 // Konfiguration uebertragen
99                 $apiInstance->setCoonfigArray($configArray);
100
101                 // Return the instance
102                 return $apiInstance;
103         }
104
105         /**
106          * Setter for gamer data
107          *
108          * @param       $w_id   Username (id) of the gamer
109          * @param       $w_pwd  Clear password of the gamer
110          * @return      void
111          */
112         public function setUser (int $w_id, string $w_pwd) {
113                 // Set username (id)
114                 $this->w_id = $w_id;
115
116                 // Hash clear password and set it
117                 $this->w_md5 = md5($w_pwd);
118         }
119
120         /************************************************
121          * The following methods are not yet rewritten! *
122          ************************************************/
123
124         public function einziehen (int $amount) {
125                 // amount auf Gueltigkeit pruefen
126                 if ($amount < $this->config['mineinsatz']) {
127                         $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
128                         return false;
129                 }
130
131                 // Abfrage senden
132                 return $this->executeWithdraw($amount);
133         }
134
135         public function verschicken (int $amount) {
136                 // amount auf Gueltigkeit pruefen
137                 if ($amount < $this->config['mineinsatz']) {
138                         $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
139                         return false;
140                 }
141
142                 // Abfrage senden
143                 return $this->executePayout($amount);
144         }
145
146         // Script abbrechen mit Zurueck-Buttom
147         public function ende () {
148                 global $_CONFIG;
149                 include 'templates/zurueck.html';
150                 include 'templates/fuss.html';
151                 exit();
152         }
153
154         // Fehlermeldung ausgeben und beenden
155         public function error () {
156                 print "<div class=\"fehler\">Fehler im Spiel: ".$this->getErrorMessage()."<div><br />\n";
157                 $this->ende();
158         }
159
160         // Sets a status message and code
161         public function setStatusMessage (string $msg, string $status) {
162                 $this->statusArray['message'] = $msg;
163                 $this->statusArray['status'] = $status;
164         }
165
166         // Get the status message
167         public function getErrorMessage () {
168                 if (isset($this->statusArray['message'])) {
169                         // Use raw message
170                         return $this->statusArray['message'];
171                 } else {
172                         // Fall-back to status
173                         return sprintf('Fehler-Code <u>%s</u> ist keiner Nachricht zugewiesen.', $this->getErrorCode());
174                 }
175         }
176
177         // Get the status code
178         public function getErrorCode () {
179                 if (isset($this->statusArray['status'])) {
180                         // Use raw message
181                         return $this->statusArray['status'];
182                 } else {
183                         // Something bad happend
184                         return 'unknown';
185                 }
186         }
187
188         // Sends out a request to the API and returns it's result
189         private function sendRequest (string $scriptName, array $requestData = []) {
190                 // Is the requestData an array?
191                 if (!is_array($requestData)) {
192                         // Then abort here!
193                         return array(
194                                 'status'  => 'failed_general',
195                                 'message' => 'API-Daten in <strong>config</strong> sind ung&uuml;ltig!'
196                         );
197                 }
198
199                 // Is the API id and MD5 hash there?
200                 if ((empty($this->config['wernis_api_id'])) || (empty($this->config['wernis_api_key']))) {
201                         // Abort here...
202                         return array(
203                                 'status'  => 'failed_general',
204                                 'message' => 'API-Daten in config.php sind leer!'
205                         );
206                 }
207
208                 // Construct the request string
209                 $requestString = $this->config['api_url'] . $scriptName . '?api_id=' . $this->config['wernis_api_id'] . '&api_key='.$this->config['wernis_api_key'];
210                 foreach ($requestData as $key => $value) {
211                         $requestString .= '&' . $key . '=' . $value;
212                 }
213
214                 // Get the raw response from the lower function
215                 $response = $this->sendRawRequest($requestString);
216
217                 // Check the response header if all is fine
218                 if (strpos($response[0], '200') === false) {
219                         // Something bad happend... :(
220                         return array(
221                                 'status'  => 'request_error',
222                                 'message' => sprintf('Servermeldung <u>%s</u> von WDS66-API erhalten.', $response[0])
223                         );
224                 }
225
226                 // All (maybe) fine so remove the response header from server
227                 for ($idx = (count($response) - 1); $idx > 1; $idx--) {
228                         $line = trim($response[$idx]);
229                         if (!empty($line)) {
230                                 $response = $line;
231                                 break;
232                         }
233                 }
234
235                 // Prepare the returning result for higher functions
236                 if (substr($response, 0, 1) == '&') {
237                         // Remove the leading & (which can be used in Flash)
238                         $response = substr($response, 1);
239                 }
240
241                 // Bring back the response
242                 $data = explode('=', $response);
243
244                 // Default return array (should not stay empty)
245                 $return = array();
246
247                 // We use only the first two entries (which shall be fine)
248                 if ($data[0] === 'error') {
249                         // The request has failed... :(
250                         switch ($data[1]) {
251                                 case '404': // Invalid API ID
252                                 case 'AUTH': // Authorization has failed
253                                         $return = array(
254                                                 'status'  => 'auth_failed',
255                                                 'message' => 'API-Daten scheinen nicht zu stimmen! (Access Denied)'
256                                         );
257                                         break;
258
259                                 case 'LOCKED': // User account is locked!
260                                 case 'PASS':   // Bad passphrase entered
261                                 case 'USER':   // Missing account or invalid password
262                                         $return = array(
263                                                 'status'  => 'user_failed',
264                                                 'message' => 'Dein eingegebener WDS66-Username stimmt nicht, ist gesperrt oder du hast ein falsches Passwort eingegeben.'
265                                         );
266                                         break;
267
268                                 case 'OWN': // Transfer to own account
269                                         $return = array(
270                                                 'status'  => 'own_failed',
271                                                 'message' => 'Du darfst dein eigenes Spiel leider nicht spielen.'
272                                         );
273                                         break;
274
275                                 case 'AMOUNT': // Amount is depleted
276                                         $return = array(
277                                                 'status'  => 'amount_failed',
278                                                 'message' => 'Dein Guthaben reicht nicht aus, um das Spiel zu spielen.'
279                                         );
280                                         break;
281
282                                 case 'AMOUNT-SEND': // API amount is depleted
283                                         $return = array(
284                                                 'status'  => 'api_amount_failed',
285                                                 'message' => 'Nicht gen&uuml;gend Guthaben auf dem API-Account.'
286                                         );
287                                         break;
288
289                                 default: // Unknown error (maybe new?)
290                                         $return = array(
291                                                 'status'  => 'request_failed',
292                                                 'message' => sprintf('Unbekannter Fehler <u>%s</u> von API erhalten.', $data[1])
293                                         );
294                                         break;
295                         }
296                 } else {
297                         // All fine here
298                         $return = array(
299                                 'status'   => $this->statusOkay,
300                                 'response' => $response
301                         );
302                 }
303
304                 // Return the result
305                 return $return;
306         }
307
308         // Widthdraw this amount
309         private function executeWithdraw (int $amount) {
310                 // First all fails...
311                 $result = false;
312
313                 // Prepare the purpose
314                 $purpose = "\"Bube oder Dame\"-Einsatz gesetzt.";
315
316                 // Prepare the request data
317                 $requestData = array(
318                         'sub_request'   => 'receive',
319                         't_uid'                 => $this->w_id,
320                         't_md5'                 => $this->w_md5,
321                         'r_uid'                 => (int) $this->config['wernis_refid'],
322                         'amount'                => (int) $amount,
323                         'purpose'               => urlencode(base64_encode($purpose))
324                 );
325
326                 // Return the result from the lower functions
327                 $return = $this->sendRequest('book.php', $requestData);
328
329                 if ($return['status'] == $this->statusOkay) {
330                         // All fine!
331                         $result = true;
332                 } else {
333                         // Status failture text
334                         $this->setStatusMessage($return['message'], $return['status']);
335                 }
336
337                 // Return result
338                 return $result;
339         }
340
341         // Payout this amount
342         private function executePayout (int $amount) {
343                 // First all fails...
344                 $result = false;
345
346                 // Prepare the purpose
347                 $purpose = "\"Bube oder Dame\"-Gewinn erhalten.";
348
349                 // Prepare the request data
350                 $requestData = array(
351                         'sub_request'   => 'send',
352                         't_uid'                 => $this->w_id,
353                         't_md5'                 => $this->w_md5,
354                         'r_uid'                 => (int) $this->config['wernis_refid'],
355                         'amount'                => (int) $amount,
356                         'purpose'               => urlencode(base64_encode($purpose))
357                 );
358
359                 // Return the result from the lower functions
360                 $return = $this->sendRequest("book.php", $requestData);
361
362                 if ($return['status'] == $this->statusOkay) {
363                         // All fine!
364                         $result = true;
365                 } else {
366                         // Status failture text
367                         $this->setStatusMessage($return['message'], $return['status']);
368                 }
369
370                 // Return result
371                 return $result;
372         }
373
374         // Send raw GET request
375         private function sendRawRequest (string $script) {
376                 // Use the hostname from script URL as new hostname
377                 $url = substr($script, 7);
378                 $extract = explode('/', $url);
379
380                 // Done extracting the URL :)
381                 $url = $extract[0];
382
383                 // Extract host name
384                 $host = str_replace('http://', '', $url);
385                 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
386
387                 // Generate relative URL
388                 $script = substr($script, (strlen($url) + 7));
389                 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
390
391                 // Open connection
392                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
393                 if (!$fp) {
394                         // Failed!
395                         return array('', '', '');
396                 }
397
398                 // Generate request header
399                 $request  = "GET /" . trim($script) . " HTTP/1.0\r\n";
400                 $request .= "Host: " . $host . "\r\n";
401                 $request .= sprintf("User-Agent: WernisApi/1.0 by Quix0r [Spieler: %d]\r\n\r\n", $this->w_id);
402
403                 // Initialize array
404                 $response = array();
405
406                 // Write request
407                 fputs($fp, $request);
408
409                 // Read response
410                 while(!feof($fp)) {
411                         array_push($response, trim(fgets($fp, 1024)));
412                 } // END - while
413
414                 // Close socket
415                 fclose($fp);
416
417                 // Was the request successfull?
418                 if ((!ereg('200 OK', $response[0])) && (empty($response[0]))) {
419                         // Not found / access forbidden
420                         $response = array('', '', '');
421                 } // END - if
422
423                 // Return response
424                 return $response;
425         }
426
427 }