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