Fix for method in FrameworkConfiguration, removal of unneccessary code
[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 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 final static 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                 die();
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                 $response = $response[(count($response) - 1)];
222
223                 // Prepare the returning result for higher functions
224                 if (substr($response, 0, 1) == '&') {
225                         // Remove the leading & (which can be used in Flash)
226                         $response = substr($response, 1);
227                 }
228
229                 // Bring back the response
230                 $data = explode('=', $response);
231
232                 // Default return array (should not stay empty)
233                 $return = array();
234
235                 // We use only the first two entries (which shall be fine)
236                 if ($data[0] === "error") {
237                         // The request has failed... :(
238                         switch ($data[1]) {
239                                 case "404": // Invalid API ID
240                                 case "AUTH": // Authorization has failed
241                                         $return = array(
242                                                 'status'  => "auth_failed",
243                                                 'message' => "API-Daten scheinen nicht zu stimmen! (Access Denied)"
244                                         );
245                                         break;
246
247                                 case "LOCKED": // User account is locked!
248                                 case "PASS":   // Bad passphrase entered
249                                 case "USER":   // Missing account or invalid password
250                                         $return = array(
251                                                 'status'  => "user_failed",
252                                                 'message' => "Dein eingegebener WDS66-Username stimmt nicht, ist gesperrt oder du hast ein falsches Passwort eingegeben."
253                                         );
254                                         break;
255
256                                 case "OWN": // Transfer to own account
257                                         $return = array(
258                                                 'status'  => "own_failed",
259                                                 'message' => "Du darfst dein eigenes Spiel leider nicht spielen."
260                                         );
261                                         break;
262
263                                 case "AMOUNT": // Amount is depleted
264                                         $return = array(
265                                                 'status'  => "amount_failed",
266                                                 'message' => "Dein Guthaben reicht nicht aus, um das Spiel zu spielen."
267                                         );
268                                         break;
269
270                                 case "AMOUNT-SEND": // API amount is depleted
271                                         $return = array(
272                                                 'status'  => "api_amount_failed",
273                                                 'message' => "Nicht gen&uuml;gend Guthaben auf dem API-Account."
274                                         );
275                                         break;
276
277                                 default: // Unknown error (maybe new?)
278                                         $return = array(
279                                                 'status'  => "request_failed",
280                                                 'message' => sprintf("Unbekannter Fehler <u>%s</u> von API erhalten.", $data[1])
281                                         );
282                                         break;
283                         }
284                 } else {
285                         // All fine here
286                         $return = array(
287                                 'status'   => $this->statusOkay,
288                                 'response' => $response
289                         );
290                 }
291
292                 // Return the result
293                 return $return;
294         }
295
296         // Widthdraw this amount
297         private function executeWithdraw ($amount) {
298                 // First all fails...
299                 $result = false;
300
301                 // Prepare the purpose
302                 $purpose = "\"Bube oder Dame\"-Einsatz gesetzt.";
303
304                 // Prepare the request data
305                 $requestData = array(
306                         'sub_request'   => 'receive',
307                         't_uid'                 => $this->w_id,
308                         't_md5'                 => $this->w_md5,
309                         'r_uid'                 => (int)$this->config['wernis_refid'],
310                         'amount'                => (int)$amount,
311                         'purpose'               => urlencode(base64_encode($purpose))
312                 );
313
314                 // Return the result from the lower functions
315                 $return = $this->sendRequest("book.php", $requestData);
316
317                 if ($return['status'] == $this->statusOkay) {
318                         // All fine!
319                         $result = true;
320                 } else {
321                         // Status failture text
322                         $this->setStatusMessage($return['message'], $return['status']);
323                 }
324
325                 // Return result
326                 return $result;
327         }
328
329         // Payout this amount
330         private function executePayout ($amount) {
331                 // First all fails...
332                 $result = false;
333
334                 // Prepare the purpose
335                 $purpose = "\"Bube oder Dame\"-Gewinn erhalten.";
336
337                 // Prepare the request data
338                 $requestData = array(
339                         'sub_request'   => 'send',
340                         't_uid'                 => $this->w_id,
341                         't_md5'                 => $this->w_md5,
342                         'r_uid'                 => (int)$this->config['wernis_refid'],
343                         'amount'                => (int)$amount,
344                         'purpose'               => urlencode(base64_encode($purpose))
345                 );
346
347                 // Return the result from the lower functions
348                 $return = $this->sendRequest("book.php", $requestData);
349
350                 if ($return['status'] == $this->statusOkay) {
351                         // All fine!
352                         $result = true;
353                 } else {
354                         // Status failture text
355                         $this->setStatusMessage($return['message'], $return['status']);
356                 }
357
358                 // Return result
359                 return $result;
360         }
361
362         // Send raw GET request
363         private function sendRawRequest ($script) {
364                 // Use the hostname from script URL as new hostname
365                 $url = substr($script, 7);
366                 $extract = explode('/', $url);
367
368                 // Done extracting the URL :)
369                 $url = $extract[0];
370
371                 // Extract host name
372                 $host = str_replace("http://", '', $url);
373                 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
374
375                 // Generate relative URL
376                 $script = substr($script, (strlen($url) + 7));
377                 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
378
379                 // Open connection
380                 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
381                 if (!$fp) {
382                         // Failed!
383                         return array('', '', '');
384                 }
385
386                 // Generate request header
387                 $request  = "GET /".trim($script)." HTTP/1.0\r\n";
388                 $request .= "Host: ".$host."\r\n";
389                 $request .= sprintf("User-Agent: Bube oder Dame / 1.0 by Quix0r [Spieler: %d]\r\n\r\n", $this->w_id);
390
391                 // Initialize array
392                 $response = array();
393
394                 // Write request
395                 fputs($fp, $request);
396
397                 // Read response
398                 while(!feof($fp)) {
399                         $response[] = trim(fgets($fp, 1024));
400                 }
401
402                 // Close socket
403                 fclose($fp);
404
405                 // Was the request successfull?
406                 if ((!ereg("200 OK", $response[0])) && (empty($response[0]))) {
407                         // Not found / access forbidden
408                         $response = array('', '', '');
409                 }
410
411                 // Return response
412                 return $response;
413         }
414 }
415
416 // [EOF]
417 ?>