Failed SQL queries are now also reported in bug mails, SQL queries improved (more...
[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  * @copyright   2009, 2010 by Mailer Developer Team
59  */
60 class PrimeraApi {
61         /**
62          * Fehler - Interfacebenutzer
63          */
64         const PI_ERROR = -1;
65
66         /**
67          * Statuscode f�r erfolgreich ausgef�hrte Transaktion
68          */
69         const PI_DONE = 200;
70
71         /**
72          * Fehler - User existiert nicht oder ist gesperrt
73          */
74         const PI_RECEIVER_ERROR = 301;
75
76         /**
77          * Sender-Account Fehler (User nicht existent, gesperrt, ...)
78          */
79         const PI_SENDER_ERROR = 401;
80
81         /**
82          * Betrag fehler
83          */
84         const PI_AMOUNT_ERROR = 501;
85
86         /**
87          * Zu wenig Primera
88          */
89         const PI_TOO_LESS_PRIMERA = 502;
90
91         /**
92          * User nicht aktiv oder existiert nicht
93          */
94         const PI_USER_CHECK_ERROR = 601;
95
96         /**
97          * User aktiv
98          */
99         const PI_USER_CHECK_OK = 602;
100
101         /**
102          * Primerastand erfolgreich geholt
103          */
104         const PI_GET_PRIMERA_DONE = 701;
105
106         /**
107          * URL f�r das Interface auf dem Primusserver:
108          */
109         var $host = "http://www.primusportal.de";
110         var $path = "/transfer.interface.2.0.php";
111
112         var $errno = '0';
113         var $err = '';
114
115         var $seperator = ':';
116
117         var $username = '';
118         var $password = '';
119
120         var $data = array();
121
122         var $headers = '';
123
124         /**
125          * Konstruktor
126          */
127         function PrimeraApi ($PPUsername, $PPPassword) {
128                 // Set data
129                 $this->username = $PPUsername;
130                 $this->password = $PPPassword;
131         }
132
133         /**
134          * Anfrage senden und R�ckgabecode in Variable speichern
135          */
136         function queryApi ( $data = array() ) {
137                 // Base64-encode username and password hash
138                 $data['PrimusInterface_Username'] = base64_encode($this->username);
139                 $data['PrimusInterface_Password'] = base64_encode($this->password);
140
141                 // Send POST request
142                 $return = sendPostRequest($this->host.$this->path, $data);
143
144                 // Convert the array into a full string
145                 $returnStr = implode("\n", $return);
146
147                 // Extract the real content, strip header away
148                 $content = explode('<!-- return-start -->', $returnStr);
149
150                 // Store headers away for debugging
151                 $this->headers = $content[0];
152
153                 // Return the content
154                 return $content[1];
155         }
156
157         /**
158          * Funktion parst die R�ckgabe vom Transferskript:
159          */
160         function parseContent ( $content ) {
161                 $x = explode("\n", $content);
162                 $return = array();
163                 foreach($x as $currentLine) {
164                         $line_exploded = explode(':', $currentLine,2);
165                         if (count($line_exploded) > 1) {
166                                 $return[$line_exploded[0]] = $line_exploded[1];
167                         }
168                 }
169                 return $return;
170         }
171
172         /**
173          * @param int/string $Receiver UserID / Username des Empf�ngers
174          * @param int $Amount Betrag in ganzzahligen Primera
175          * @param string $Description Beschreibung (Sichtbar in Einzelauflistung)
176          */
177         function payPrimera ($Receiver, $Amount, $Description = '') {
178                 $valid = false;
179                 $postData = array('PrimusInterface_Action' => 'Pay',
180                         'PrimusInterface_Receiver' => base64_encode($Receiver),
181                         'PrimusInterface_Amount' => base64_encode($Amount),
182                         'PrimusInterface_Description' => base64_encode($Description) );
183
184                 $postReturn = $this->parseContent( $this->queryApi($postData) );
185
186                 $this->data = $postReturn;
187                 if ($postReturn['status'] == '200') {
188                         $valid = true;
189                 }
190                 return $valid;
191         }
192
193         /**
194          * �berpr�ft den Status eines Primus-Users
195          * - existiert der User
196          * - ist er aktiv
197          * @param string/int $User Userid / Username
198          */
199         function CheckPrimusUser($User) {
200                 $valid = false;
201                 $postData = array('PrimusInterface_Action'=> 'CheckPrimusUser',
202                         'PrimusInterface_CheckPrimusUser' => $User);
203
204                 $postReturn = $this->parseContent( $this->queryApi($postData) );
205
206                 $this->data = $postReturn;
207
208                 if ($postReturn['status'] == self::PI_USER_CHECK_OK) {
209                         $valid = true;
210                 }
211                 return $valid;
212         }
213
214         /**
215          * Die Funktion liefer den aktuellen Primerastand
216          */
217         function getPrimera() {
218                 $primera = false;
219                 $postData = array( 'PrimusInterface_Action' => 'GetPrimera' );
220                 $postReturn = $this->parseContent( $this->queryApi($postData) );
221
222                 $this->data = $postReturn;
223                 if ($postReturn['status'] == self::PI_GET_PRIMERA_DONE) {
224                         $primera = $postReturn['primera'];
225                 }
226                 return $primera;
227         }
228         /**
229          * Getter fuer data
230          */
231         function getData () {
232                 return $this->data;
233         }
234 }
235
236 // Function to test the Primera API by getting the amount. If the returned value
237 // is not false the API data is valid, else invalid
238 function testPrimeraApi () {
239         // Get new instance
240         $api = new PrimeraApi(postRequestParameter('primera_api_name'), postRequestParameter('primera_api_md5'));
241
242         // Was that fine?
243         return ($api->getPrimera() !== false);
244 }
245
246 // Execute the withdraw of a sponsor only!
247 function executePrimeraWithdraw ($primusNick, $userMd5, $amount) {
248         // Is the sponsor extension installed?
249         if (!isExtensionActive('sponsor')) {
250                 // No, abort here
251                 return false;
252         } elseif (!isSponsor()) {
253                 // No sponsor, not allowed to withdraw!
254                 return false;
255         }
256
257         // Get new instance
258         $api = new PrimeraApi($primusNick, $userMd5);
259
260         // Prepare purpose
261         eval("\$purpose = \"".compileRawCode(getMaskedMessage('PRIMERA_API_PURPOSE_WITHDRAW', getSession('sponsorid')))."\";");
262
263         // Pay the Primera
264         return $api->payPrimera($primusNick, $amount, $purpose);
265 }
266
267 // Execute the payout
268 function executePrimeraPayout ($primusNick, $userMd5, $amount) {
269         // Get new instance
270         $api = new PrimeraApi(getConfig('primera_api_name'), getConfig('primera_api_md5'));
271
272         // Prepare purpose
273         eval("\$purpose = \"".compileRawCode(getMaskedMessage('PRIMERA_API_PURPOSE_PAYOUT', getMemberId()))."\";");
274
275         // Pay the Primera
276         return $api->payPrimera($primusNick, $amount, $purpose);
277 }
278
279 // [EOF]
280 ?>