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