Code syncronized with shipsimu code base
[mailer.git] / inc / classes / third_party / api / wernisportal / class_WernisApi.php
diff --git a/inc/classes/third_party/api/wernisportal/class_WernisApi.php b/inc/classes/third_party/api/wernisportal/class_WernisApi.php
new file mode 100644 (file)
index 0000000..4c306dd
--- /dev/null
@@ -0,0 +1,416 @@
+<?php
+/**
+ * Class for connecting to the Wernis-Portal at http://www.wds66.com
+ *
+ * @author             Roland Haeder <webmaster@ship-simu.org>
+ * @version            0.0.0
+ * @copyright  Copyright (c) 2007, 2008 Roland Haeder, this is free software
+ * @license            GNU GPL 3.0 or any newer version
+ * @link               http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class WernisApi extends BaseFrameworkSystem {
+       /**
+        * Static base API URL
+        */
+       private static $apiUrl = "http://www.wds66.com/api/";
+
+       /**
+        * API Wernis amount
+        */
+       private $wernis_amount = 0;
+
+       /**
+        * API username
+        */
+       private $w_id = 0;
+
+       /**
+        * API Wernis password (not account password!)
+        */
+       private $w_md5 = "";
+
+       /**
+        * Nickname of the user
+        */
+       private $w_nick = "";
+
+       /**
+        * Wernis amount of the user
+        */
+       private $w_amount = 0;
+
+       /**
+        * Array with status informations
+        */
+       private $statusArray = array();
+
+       /**
+        * Protected constructor
+        *
+        * @return      void
+        */
+       protected function __construct () {
+               // Call parent constructor
+               parent::__construct(__CLASS__);
+
+               // Clean up a little
+               $this->removeNumberFormaters();
+               $this->removeSystemArray();
+       }
+
+       /**
+        * Creates an instance of this API class
+        *
+        * @param       $cfg                    Configuration array
+        * @return      $apiInstance    An instance of this API class
+        */
+       public final static function createWernisApi (array $cfg) {
+               // Create a new instance
+               $apiInstance = new WernisApi();
+
+               // Fix missing
+               if (!isset($cfg['api_url'])) $cfg['api_url'] = self::$apiUrl;
+
+               // Konfiguration uebertragen
+               $apiInstance->setCoonfigArray($cfg);
+
+               // Return the instance
+               return $apiInstance;
+       }
+
+       /**
+        * Setter for gamer data
+        *
+        * @param       $w_id   Username (id) of the gamer
+        * @param       $w_pwd  Clear password of the gamer
+        * @return      void
+        */
+       public function setUser ($w_id, $w_pwd) {
+               // Set username (id)
+               $this->w_id = $w_id;
+
+               // Hash clear password and set it
+               $this->w_md5 = md5($w_pwd);
+       }
+
+       /************************************************
+        * The following methods are not yet rewritten! *
+        ************************************************/
+
+       public function einziehen ($amount) {
+               // amount auf Gueltigkeit pruefen
+               $amount = isset($amount) ? $amount+0 : 0;
+
+               if ($amount < $this->config['mineinsatz']) {
+                       $this->setStatusMessage('low_stakes', sprintf("Dein Einsatz muss mindestens %d Wernis betragen.", $this->config['mineinsatz']));
+                       return false;
+               }
+
+               // Abfrage senden
+               return $this->executeWithdraw($amount);
+       }
+
+       public function verschicken ($amount) {
+               // amount auf Gueltigkeit pruefen
+               $amount = isset($amount) ? $amount+0 : 0;
+
+               if ($amount < $this->config['mineinsatz']) {
+                       $this->setStatusMessage('low_stakes', sprintf("Dein Einsatz muss mindestens %d Wernis betragen.", $this->config['mineinsatz']));
+                       return false;
+               }
+
+               // Abfrage senden
+               return $this->executePayout($amount);
+       }
+
+       // Script abbrechen mit Zurueck-Buttom
+       public function ende () {
+               global $_CONFIG;
+               include "templates/zurueck.html";
+               include "templates/fuss.html";
+               die();
+       }
+
+       // Fehlermeldung ausgeben und beenden
+       public function error () {
+               print "<div class=\"fehler\">Fehler im Spiel: ".$this->getErrorMessage()."<div><br />\n";
+               $this->ende();
+       }
+
+       // Sets a status message and code
+       public function setStatusMessage ($msg, $status) {
+               $this->statusArray['message'] = $msg;
+               $this->statusArray['status'] = $status;
+       }
+
+       // Get the status message
+       public function getErrorMessage () {
+               if (isset($this->statusArray['message'])) {
+                       // Use raw message
+                       return $this->statusArray['message'];
+               } else {
+                       // Fall-back to status
+                       return sprintf("Fehler-Code <u>%s</u> ist keiner Nachricht zugewiesen.", $this->getErrorCode());
+               }
+       }
+
+       // Get the status code
+       public function getErrorCode () {
+               if (isset($this->statusArray['status'])) {
+                       // Use raw message
+                       return $this->statusArray['status'];
+               } else {
+                       // Something bad happend
+                       return 'unknown';
+               }
+       }
+
+       // Sends out a request to the API and returns it's result
+       private function sendRequest ($scriptName, array $requestData =  array()) {
+               // Is the requestData an array?
+               if (!is_array($requestData)) {
+                       // Then abort here!
+                       return array(
+                               'status'  => "failed_general",
+                               'message' => "API-Daten in <strong>config</strong> sind ung&uuml;ltig!"
+                       );
+               }
+
+               // Is the API id and MD5 hash there?
+               if ((empty($this->config['wernis_api_id'])) || (empty($this->config['wernis_api_key']))) {
+                       // Abort here...
+                       return array(
+                               'status'  => "failed_general",
+                               'message' => "API-Daten in config.php sind leer!"
+                       );
+               }
+
+               // Construct the request string
+               $requestString = $this->config['api_url'] . $scriptName."?api_id=".$this->config['wernis_api_id']."&api_key=".$this->config['wernis_api_key'];
+               foreach ($requestData as $key=>$value) {
+                       $requestString .= "&".$key."=".$value;
+               }
+
+               // Get the raw response from the lower function
+               $response = $this->sendRawRequest($requestString);
+
+               // Check the response header if all is fine
+               if (strpos($response[0], "200") === false) {
+                       // Something bad happend... :(
+                       return array(
+                               'status'  => "request_error",
+                               'message' => sprintf("Servermeldung <u>%s</u> von WDS66-API erhalten.", $response[0])
+                       );
+               }
+
+               // All (maybe) fine so remove the response header from server
+               $response = $response[(count($response) - 1)];
+
+               // Prepare the returning result for higher functions
+               if (substr($response, 0, 1) == "&") {
+                       // Remove the leading & (which can be used in Flash)
+                       $response = substr($response, 1);
+               }
+
+               // Bring back the response
+               $data = explode("=", $response);
+
+               // Default return array (should not stay empty)
+               $return = array();
+
+               // We use only the first two entries (which shall be fine)
+               if ($data[0] === "error") {
+                       // The request has failed... :(
+                       switch ($data[1]) {
+                               case "404": // Invalid API ID
+                               case "AUTH": // Authorization has failed
+                                       $return = array(
+                                               'status'  => "auth_failed",
+                                               'message' => "API-Daten scheinen nicht zu stimmen! (Access Denied)"
+                                       );
+                                       break;
+
+                               case "LOCKED": // User account is locked!
+                               case "PASS":   // Bad passphrase entered
+                               case "USER":   // Missing account or invalid password
+                                       $return = array(
+                                               'status'  => "user_failed",
+                                               'message' => "Dein eingegebener WDS66-Username stimmt nicht, ist gesperrt oder du hast ein falsches Passwort eingegeben."
+                                       );
+                                       break;
+
+                               case "OWN": // Transfer to own account
+                                       $return = array(
+                                               'status'  => "own_failed",
+                                               'message' => "Du darfst dein eigenes Spiel leider nicht spielen."
+                                       );
+                                       break;
+
+                               case "AMOUNT": // Amount is depleted
+                                       $return = array(
+                                               'status'  => "amount_failed",
+                                               'message' => "Dein Guthaben reicht nicht aus, um das Spiel zu spielen."
+                                       );
+                                       break;
+
+                               case "AMOUNT-SEND": // API amount is depleted
+                                       $return = array(
+                                               'status'  => "api_amount_failed",
+                                               'message' => "Nicht gen&uuml;gend Guthaben auf dem API-Account."
+                                       );
+                                       break;
+
+                               default: // Unknown error (maybe new?)
+                                       $return = array(
+                                               'status'  => "request_failed",
+                                               'message' => sprintf("Unbekannter Fehler <u>%s</u> von API erhalten.", $data[1])
+                                       );
+                                       break;
+                       }
+               } else {
+                       // All fine here
+                       $return = array(
+                               'status'   => "OK",
+                               'response' => $response
+                       );
+               }
+
+               // Return the result
+               return $return;
+       }
+
+       // Widthdraw this amount
+       private function executeWithdraw ($amount) {
+               // First all fails...
+               $result = false;
+
+               // Prepare the purpose
+               $purpose = "\"Bube oder Dame\"-Einsatz gesetzt.";
+
+               // Prepare the request data
+               $requestData = array(
+                       'sub_request'   => "receive",
+                       't_uid'                 => $this->w_id,
+                       't_md5'                 => $this->w_md5,
+                       'r_uid'                 => (int)$this->config['wernis_refid'],
+                       'amount'                => (int)$amount,
+                       'purpose'               => urlencode(base64_encode($purpose))
+               );
+
+               // Return the result from the lower functions
+               $return = $this->sendRequest("book.php", $requestData);
+
+               if ($return['status'] == "OK") {
+                       // All fine!
+                       $result = true;
+               } else {
+                       // Status failture text
+                       $this->setStatusMessage($return['message'], $return['status']);
+               }
+
+               // Return result
+               return $result;
+       }
+
+       // Payout this amount
+       private function executePayout ($amount) {
+               // First all fails...
+               $result = false;
+
+               // Prepare the purpose
+               $purpose = "\"Bube oder Dame\"-Gewinn erhalten.";
+
+               // Prepare the request data
+               $requestData = array(
+                       'sub_request'   => "send",
+                       't_uid'                 => $this->w_id,
+                       't_md5'                 => $this->w_md5,
+                       'r_uid'                 => (int)$this->config['wernis_refid'],
+                       'amount'                => (int)$amount,
+                       'purpose'               => urlencode(base64_encode($purpose))
+               );
+
+               // Return the result from the lower functions
+               $return = $this->sendRequest("book.php", $requestData);
+
+               if ($return['status'] == "OK") {
+                       // All fine!
+                       $result = true;
+               } else {
+                       // Status failture text
+                       $this->setStatusMessage($return['message'], $return['status']);
+               }
+
+               // Return result
+               return $result;
+       }
+
+       // Send raw GET request
+       private function sendRawRequest ($script) {
+               // Use the hostname from script URL as new hostname
+               $url = substr($script, 7);
+               $extract = explode("/", $url);
+
+               // Done extracting the URL :)
+               $url = $extract[0];
+
+               // Extract host name
+               $host = str_replace("http://", "", $url);
+               if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
+
+               // Generate relative URL
+               $script = substr($script, (strlen($url) + 7));
+               if (substr($script, 0, 1) == "/") $script = substr($script, 1);
+
+               // Open connection
+               $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
+               if (!$fp) {
+                       // Failed!
+                       return array("", "", "");
+               }
+
+               // Generate request header
+               $request  = "GET /".trim($script)." HTTP/1.0\r\n";
+               $request .= "Host: ".$host."\r\n";
+               $request .= sprintf("User-Agent: Bube oder Dame / 1.0 by Quix0r [Spieler: %d]\r\n\r\n", $this->w_id);
+
+               // Initialize array
+               $response = array();
+
+               // Write request
+               fputs($fp, $request);
+
+               // Read response
+               while(!feof($fp)) {
+                       $response[] = trim(fgets($fp, 1024));
+               }
+
+               // Close socket
+               fclose($fp);
+
+               // Was the request successfull?
+               if ((!ereg("200 OK", $response[0])) && (empty($response[0]))) {
+                       // Not found / access forbidden
+                       $response = array("", "", "");
+               }
+
+               // Return response
+               return $response;
+       }
+}
+
+// [EOF]
+?>