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