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