Renamed Registry -> GenericRegistry to make it clear that this registry does
[core.git] / framework / main / third_party / api / wernisportal / class_WernisApi.php
1 <?php
2 // Own namespace
3 namespace 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 - 2017 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         protected function __construct () {
78                 // Call parent constructor
79                 parent::__construct(__CLASS__);
80         }
81
82         /**
83          * Creates an instance of this API class
84          *
85          * @param       $cfg                    Configuration array
86          * @return      $apiInstance    An instance of this API class
87          */
88         public static final function createWernisApi (array $cfg) {
89                 // Create a new instance
90                 $apiInstance = new WernisApi();
91
92                 // Fix missing
93                 if (!isset($cfg['api_url'])) $cfg['api_url'] = self::$apiUrl;
94
95                 // Konfiguration uebertragen
96                 $apiInstance->setCoonfigArray($cfg);
97
98                 // Return the instance
99                 return $apiInstance;
100         }
101
102         /**
103          * Setter for gamer data
104          *
105          * @param       $w_id   Username (id) of the gamer
106          * @param       $w_pwd  Clear password of the gamer
107          * @return      void
108          */
109         public function setUser ($w_id, $w_pwd) {
110                 // Set username (id)
111                 $this->w_id = $w_id;
112
113                 // Hash clear password and set it
114                 $this->w_md5 = md5($w_pwd);
115         }
116
117         /************************************************
118          * The following methods are not yet rewritten! *
119          ************************************************/
120
121         public function einziehen ($amount) {
122                 // amount auf Gueltigkeit pruefen
123                 $amount = isset($amount) ? $amount+0 : 0;
124
125                 if ($amount < $this->config['mineinsatz']) {
126                         $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
127                         return false;
128                 }
129
130                 // Abfrage senden
131                 return $this->executeWithdraw($amount);
132         }
133
134         public function verschicken ($amount) {
135                 // amount auf Gueltigkeit pruefen
136                 $amount = isset($amount) ? $amount+0 : 0;
137
138                 if ($amount < $this->config['mineinsatz']) {
139                         $this->setStatusMessage('low_stakes', sprintf('Dein Einsatz muss mindestens %d Wernis betragen.', $this->config['mineinsatz']));
140                         return false;
141                 }
142
143                 // Abfrage senden
144                 return $this->executePayout($amount);
145         }
146
147         // Script abbrechen mit Zurueck-Buttom
148         public function ende () {
149                 global $_CONFIG;
150                 include 'templates/zurueck.html';
151                 include 'templates/fuss.html';
152                 exit();
153         }
154
155         // Fehlermeldung ausgeben und beenden
156         public function error () {
157                 print "<div class=\"fehler\">Fehler im Spiel: ".$this->getErrorMessage()."<div><br />\n";
158                 $this->ende();
159         }
160
161         // Sets a status message and code
162         public function setStatusMessage ($msg, $status) {
163                 $this->statusArray['message'] = $msg;
164                 $this->statusArray['status'] = $status;
165         }
166
167         // Get the status message
168         public function getErrorMessage () {
169                 if (isset($this->statusArray['message'])) {
170                         // Use raw message
171                         return $this->statusArray['message'];
172                 } else {
173                         // Fall-back to status
174                         return sprintf('Fehler-Code <u>%s</u> ist keiner Nachricht zugewiesen.', $this->getErrorCode());
175                 }
176         }
177
178         // Get the status code
179         public function getErrorCode () {
180                 if (isset($this->statusArray['status'])) {
181                         // Use raw message
182                         return $this->statusArray['status'];
183                 } else {
184                         // Something bad happend
185                         return 'unknown';
186                 }
187         }
188
189         // Sends out a request to the API and returns it's result
190         private function sendRequest ($scriptName, array $requestData = array()) {
191                 // Is the requestData an array?
192                 if (!is_array($requestData)) {
193                         // Then abort here!
194                         return array(
195                                 'status'  => 'failed_general',
196                                 'message' => 'API-Daten in <strong>config</strong> sind ung&uuml;ltig!'
197                         );
198                 }
199
200                 // Is the API id and MD5 hash there?
201                 if ((empty($this->config['wernis_api_id'])) || (empty($this->config['wernis_api_key']))) {
202                         // Abort here...
203                         return array(
204                                 'status'  => 'failed_general',
205                                 'message' => 'API-Daten in config.php sind leer!'
206                         );
207                 }
208
209                 // Construct the request string
210                 $requestString = $this->config['api_url'] . $scriptName . '?api_id=' . $this->config['wernis_api_id'] . '&api_key='.$this->config['wernis_api_key'];
211                 foreach ($requestData as $key => $value) {
212                         $requestString .= '&' . $key . '=' . $value;
213                 }
214
215                 // Get the raw response from the lower function
216                 $response = $this->sendRawRequest($requestString);
217
218                 // Check the response header if all is fine
219                 if (strpos($response[0], '200') === false) {
220                         // Something bad happend... :(
221                         return array(
222                                 'status'  => 'request_error',
223                                 'message' => sprintf('Servermeldung <u>%s</u> von WDS66-API erhalten.', $response[0])
224                         );
225                 }
226
227                 // All (maybe) fine so remove the response header from server
228                 for ($idx = (count($response) - 1); $idx > 1; $idx--) {
229                         $line = trim($response[$idx]);
230                         if (!empty($line)) {
231                                 $response = $line;
232                                 break;
233                         }
234                 }
235
236                 // Prepare the returning result for higher functions
237                 if (substr($response, 0, 1) == '&') {
238                         // Remove the leading & (which can be used in Flash)
239                         $response = substr($response, 1);
240                 }
241
242                 // Bring back the response
243                 $data = explode('=', $response);
244
245                 // Default return array (should not stay empty)
246                 $return = array();
247
248                 // We use only the first two entries (which shall be fine)
249                 if ($data[0] === 'error') {
250                         // The request has failed... :(
251                         switch ($data[1]) {
252                                 case '404': // Invalid API ID
253                                 case 'AUTH': // Authorization has failed
254                                         $return = array(
255                                                 'status'  => 'auth_failed',
256                                                 'message' => 'API-Daten scheinen nicht zu stimmen! (Access Denied)'
257                                         );
258                                         break;
259
260                                 case 'LOCKED': // User account is locked!
261                                 case 'PASS':   // Bad passphrase entered
262                                 case 'USER':   // Missing account or invalid password
263                                         $return = array(
264                                                 'status'  => 'user_failed',
265                                                 'message' => 'Dein eingegebener WDS66-Username stimmt nicht, ist gesperrt oder du hast ein falsches Passwort eingegeben.'
266                                         );
267                                         break;
268
269                                 case 'OWN': // Transfer to own account
270                                         $return = array(
271                                                 'status'  => 'own_failed',
272                                                 'message' => 'Du darfst dein eigenes Spiel leider nicht spielen.'
273                                         );
274                                         break;
275
276                                 case 'AMOUNT': // Amount is depleted
277                                         $return = array(
278                                                 'status'  => 'amount_failed',
279                                                 'message' => 'Dein Guthaben reicht nicht aus, um das Spiel zu spielen.'
280                                         );
281                                         break;
282
283                                 case 'AMOUNT-SEND': // API amount is depleted
284                                         $return = array(
285                                                 'status'  => 'api_amount_failed',
286                                                 'message' => 'Nicht gen&uuml;gend Guthaben auf dem API-Account.'
287                                         );
288                                         break;
289
290                                 default: // Unknown error (maybe new?)
291                                         $return = array(
292                                                 'status'  => 'request_failed',
293                                                 'message' => sprintf('Unbekannter Fehler <u>%s</u> von API erhalten.', $data[1])
294                                         );
295                                         break;
296                         }
297                 } else {
298                         // All fine here
299                         $return = array(
300                                 'status'   => $this->statusOkay,
301                                 'response' => $response
302                         );
303                 }
304
305                 // Return the result
306                 return $return;
307         }
308
309         // Widthdraw this amount
310         private function executeWithdraw ($amount) {
311                 // First all fails...
312                 $result = false;
313
314                 // Prepare the purpose
315                 $purpose = "\"Bube oder Dame\"-Einsatz gesetzt.";
316
317                 // Prepare the request data
318                 $requestData = array(
319                         'sub_request'   => 'receive',
320                         't_uid'                 => $this->w_id,
321                         't_md5'                 => $this->w_md5,
322                         'r_uid'                 => (int) $this->config['wernis_refid'],
323                         'amount'                => (int) $amount,
324                         'purpose'               => urlencode(base64_encode($purpose))
325                 );
326
327                 // Return the result from the lower functions
328                 $return = $this->sendRequest('book.php', $requestData);
329
330                 if ($return['status'] == $this->statusOkay) {
331                         // All fine!
332                         $result = true;
333                 } else {
334                         // Status failture text
335                         $this->setStatusMessage($return['message'], $return['status']);
336                 }
337
338                 // Return result
339                 return $result;
340         }
341
342         // Payout this amount
343         private function executePayout ($amount) {
344                 // First all fails...
345                 $result = false;
346
347                 // Prepare the purpose
348                 $purpose = "\"Bube oder Dame\"-Gewinn erhalten.";
349
350                 // Prepare the request data
351                 $requestData = array(
352                         'sub_request'   => 'send',
353                         't_uid'                 => $this->w_id,
354                         't_md5'                 => $this->w_md5,
355                         'r_uid'                 => (int) $this->config['wernis_refid'],
356                         'amount'                => (int) $amount,
357                         'purpose'               => urlencode(base64_encode($purpose))
358                 );
359
360                 // Return the result from the lower functions
361                 $return = $this->sendRequest("book.php", $requestData);
362
363                 if ($return['status'] == $this->statusOkay) {
364                         // All fine!
365                         $result = true;
366                 } else {
367                         // Status failture text
368                         $this->setStatusMessage($return['message'], $return['status']);
369                 }
370
371                 // Return result
372                 return $result;
373         }
374
375         // Send raw GET request
376         private function sendRawRequest ($script) {
377                 // Use the hostname from script URL as new hostname
378                 $url = substr($script, 7);
379                 $extract = explode('/', $url);
380
381                 // Done extracting the URL :)
382                 $url = $extract[0];
383
384                 // Extract host name
385                 $host = str_replace('http://', '', $url);
386                 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
387
388                 // Generate relative URL
389                 $script = substr($script, (strlen($url) + 7));
390                 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
391
392                 // Open connection
393                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
394                 if (!$fp) {
395                         // Failed!
396                         return array('', '', '');
397                 }
398
399                 // Generate request header
400                 $request  = "GET /" . trim($script) . " HTTP/1.0\r\n";
401                 $request .= "Host: " . $host . "\r\n";
402                 $request .= sprintf("User-Agent: WernisApi/1.0 by Quix0r [Spieler: %d]\r\n\r\n", $this->w_id);
403
404                 // Initialize array
405                 $response = array();
406
407                 // Write request
408                 fputs($fp, $request);
409
410                 // Read response
411                 while(!feof($fp)) {
412                         array_push($response, trim(fgets($fp, 1024)));
413                 } // END - while
414
415                 // Close socket
416                 fclose($fp);
417
418                 // Was the request successfull?
419                 if ((!ereg('200 OK', $response[0])) && (empty($response[0]))) {
420                         // Not found / access forbidden
421                         $response = array('', '', '');
422                 } // END - if
423
424                 // Return response
425                 return $response;
426         }
427
428 }