New functions introduced, several rewrites:
[mailer.git] / inc / libs / primera_functions.php
1 <?php
2 /**
3  * PrimeraApi
4  * -------------------------------------------
5  * Mit dieser Klasse ist ein einfacher Primeratransfer von Ihrem Account
6  * zu dem Account eines bei Primusportal.de registrierten Mitglieds m�glich.
7  *
8  *------------------ Aenderungen durch Roland Haeder 09.08.2008 ----------------
9  * Klasse umbenannt nach PrimeraApi, damit sie in das Framework besser passt.
10  * Zudem sind alle oeffentlichen Attribute nun privat, der Konstruktor hat den
11  * neuen "magischen" Namen __construct() und "normale" Konstanten sind nach
12  * Klassenkonstanten umbenannt. Unsinnige else-Bloecke sind noch umgewandelt.
13  * Methodennamen fangen nun immer mit einem kleinen Buchstaben an. Zudem sind
14  * die Methoden Pay,Query und Parse umbenannt.
15  *------------------ Aenderungen durch Roland Haeder 09.08.2008 ----------------
16  *
17  * Die Einbindung des Interfaces geschieht folgenderma�en:
18  *  1. Einbindung der Klasse in Ihr PHP-Auszahlungsskript:
19  *     CODE:
20  *       require_once( "PFAD/ZU/DER/KLASSE/PrimeraApi.class.php" );
21  *       $PPUsername = "username"; // Ihr Username bei Primusportal
22  *       $PPPassword = "passwort"; // Ihr Passwort bei Primusportal
23  *
24  *       $Interface = new PrimeraApi($PPUsername, $PPPassword);
25  *  2. Durchf�hren einer Auszahlung:
26  *     CODE:
27  *       $Status = $Interface->payPrimera($PayReceiver, $PayAmount, $PayDescription);
28  *
29  *     Wobei $PayReicer der Username des Empf�ngers bei
30  *     Primusportal.de ist. $PayAmount ist der gerundete( !! ) Betrag an Primera,
31  *     die der Empf�nger erhalten soll. $PayDescription ist eine von Ihnen
32  *     festgelegte kurze Beschreibung. Die L�nge dieses Textes darf 100 Zeichen
33  *     nicht �berschreiten. Beispiel:
34  *       $status = $Interface->payPrimera("garbage", 10000, "Auszahlung IhreSeite.de - id: 12345");
35  *  3. �berpr�fung des Status (R�ckgabecode):
36  *     CODE:
37  *       if (!$status) {
38  *         // Ein Fehler ist aufgetreten
39  *     // Fehlerbehandlung hier einf�gen...
40  *       }else {
41  *         // Auszahlung erfolgreich durchgef�hrt
42  *         // F�hren Sie hier Ihre Datenbankabfragen durch, um die Auszahlung zu
43  *         // best�tigen...
44  *       }
45  *
46  *     Die komplette R�ckgabe des Interfaces wird als assoziatives Array in der Klassen-
47  *     variable __data gespeichert:
48  *     __data => array('status' => R�ckgabecode (PI_DONE, PI_SENDER_ERROR, ...),
49  *                     "statustext" => Status in Worten (z.B.: "Transaktion erfolgreich durchgef�hrt"),
50  *                     ")
51  *
52  *
53  * @author              Andreas Schmidt <xxgarbagexx@web.de>
54  * @author              Roland Haeder <webmaster@ship-simu.org>
55  * @version             1.0 - beta
56  * @copyright   (c) 2007 by Primusportal.de
57  * @copyright   (c) 2008 by Roland Haeder
58  */
59 class PrimeraApi {
60         /**
61          * Fehler - Interfacebenutzer
62          */
63         const PI_ERROR = -1;
64
65         /**
66          * Statuscode f�r erfolgreich ausgef�hrte Transaktion
67          */
68         const PI_DONE = 200;
69
70         /**
71          * Fehler - User existiert nicht oder ist gesperrt
72          */
73         const PI_RECEIVER_ERROR = 301;
74
75         /**
76          * Sender-Account Fehler (User nicht existent, gesperrt, ...)
77          */
78         const PI_SENDER_ERROR = 401;
79
80         /**
81          * Betrag fehler
82          */
83         const PI_AMOUNT_ERROR = 501;
84
85         /**
86          * Zu wenig Primera
87          */
88         const PI_TOO_LESS_PRIMERA = 502;
89
90         /**
91          * User nicht aktiv oder existiert nicht
92          */
93         const PI_USER_CHECK_ERROR = 601;
94
95         /**
96          * User aktiv
97          */
98         const PI_USER_CHECK_OK = 602;
99
100         /**
101          * Primerastand erfolgreich geholt
102          */
103         const PI_GET_PRIMERA_DONE = 701;
104
105         /**
106          * URL f�r das Interface auf dem Primusserver:
107          */
108         var $host = "http://www.primusportal.de";
109         var $path = "/transfer.interface.2.0.php";
110
111         var $errno = '0';
112         var $err = '';
113
114         var $seperator = ':';
115
116         var $username = '';
117         var $password = '';
118
119         var $data = array();
120
121         var $headers = '';
122
123         /**
124          * Konstruktor
125          */
126         function PrimeraApi ($PPUsername, $PPPassword) {
127                 // Set data
128                 $this->username = $PPUsername;
129                 $this->password = $PPPassword;
130         }
131
132         /**
133          * Anfrage senden und R�ckgabecode in Variable speichern
134          */
135         function queryApi ( $data = array() ) {
136                 // Base64-encode username and password hash
137                 $data['PrimusInterface_Username'] = base64_encode($this->username);
138                 $data['PrimusInterface_Password'] = base64_encode($this->password);
139
140                 // Send POST request
141                 $return = sendPostRequest($this->host.$this->path, $data);
142
143                 // Convert the array into a full string
144                 $returnStr = implode("\n", $return);
145
146                 // Extract the real content, strip header away
147                 $content = explode('<!-- return-start -->', $returnStr);
148
149                 // Store headers away for debugging
150                 $this->headers = $content[0];
151
152                 // Return the content
153                 return $content[1];
154         }
155
156         /**
157          * Funktion parst die R�ckgabe vom Transferskript:
158          */
159         function parseContent ( $content ) {
160                 $x = explode("\n", $content);
161                 $return = array();
162                 foreach($x as $currentLine) {
163                         $line_exploded = explode(':', $currentLine,2);
164                         if (count($line_exploded) > 1) {
165                                 $return[$line_exploded[0]] = $line_exploded[1];
166                         }
167                 }
168                 return $return;
169         }
170
171         /**
172          * @param int/string $Receiver UserID / Username des Empf�ngers
173          * @param int $Amount Betrag in ganzzahligen Primera
174          * @param string $Description Beschreibung (Sichtbar in Einzelauflistung)
175          */
176         function payPrimera ($Receiver, $Amount, $Description = '') {
177                 $valid = false;
178                 $postData = array('PrimusInterface_Action' => 'Pay',
179                         'PrimusInterface_Receiver' => base64_encode($Receiver),
180                         'PrimusInterface_Amount' => base64_encode($Amount),
181                         'PrimusInterface_Description' => base64_encode($Description) );
182
183                 $postReturn = $this->parseContent( $this->queryApi($postData) );
184
185                 $this->data = $postReturn;
186                 if ($postReturn['status'] == '200') {
187                         $valid = true;
188                 }
189                 return $valid;
190         }
191
192         /**
193          * �berpr�ft den Status eines Primus-Users
194          * - existiert der User
195          * - ist er aktiv
196          * @param string/int $User Userid / Username
197          */
198         function CheckPrimusUser($User) {
199                 $valid = false;
200                 $postData = array('PrimusInterface_Action'=> 'CheckPrimusUser',
201                         'PrimusInterface_CheckPrimusUser' => $User);
202
203                 $postReturn = $this->parseContent( $this->queryApi($postData) );
204
205                 $this->data = $postReturn;
206
207                 if ($postReturn['status'] == self::PI_USER_CHECK_OK) {
208                         $valid = true;
209                 }
210                 return $valid;
211         }
212
213         /**
214          * Die Funktion liefer den aktuellen Primerastand
215          */
216         function getPrimera() {
217                 $primera = false;
218                 $postData = array( 'PrimusInterface_Action' => 'GetPrimera' );
219                 $postReturn = $this->parseContent( $this->queryApi($postData) );
220
221                 $this->data = $postReturn;
222                 if ($postReturn['status'] == self::PI_GET_PRIMERA_DONE) {
223                         $primera = $postReturn['primera'];
224                 }
225                 return $primera;
226         }
227         /**
228          * Getter fuer data
229          */
230         function getData () {
231                 return $this->data;
232         }
233 }
234
235 // Function to test the Primera API by getting the amount. If the returned value
236 // is not false the API data is valid, else invalid
237 function testPrimeraApi () {
238         // Get new instance
239         $api = new PrimeraApi(postRequestElement('primera_api_name'), postRequestElement('primera_api_md5'));
240
241         // Was that fine?
242         return ($api->getPrimera() !== false);
243 }
244
245 // Execute the withdraw of a sponsor only!
246 function executePrimeraWithdraw ($primusNick, $userMd5, $amount) {
247         // Is the sponsor extension installed?
248         if (!isExtensionActive('sponsor')) {
249                 // No, abort here
250                 return false;
251         } elseif (!isSponsor()) {
252                 // No sponsor, not allowed to withdraw!
253                 return false;
254         }
255
256         // Get new instance
257         $api = new PrimeraApi($primusNick, $userMd5);
258
259         // Prepare purpose
260         eval("\$purpose = \"".compileRawCode(getMaskedMessage('PRIMERA_API_PURPOSE_WITHDRAW', getSession('sponsorid')))."\";");
261
262         // Pay the Primera
263         return $api->payPrimera($primusNick, $amount, $purpose);
264 }
265
266 // Execute the payout
267 function executePrimeraPayout ($primusNick, $userMd5, $amount) {
268         // Get new instance
269         $api = new PrimeraApi(getConfig('primera_api_name'), getConfig('primera_api_md5'));
270
271         // Prepare purpose
272         eval("\$purpose = \"".compileRawCode(getMaskedMessage('PRIMERA_API_PURPOSE_PAYOUT', getMemberId()))."\";");
273
274         // Pay the Primera
275         return $api->payPrimera($primusNick, $amount, $purpose);
276 }
277
278 // [EOF]
279 ?>