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