More rewrites, and output-mode fixed (we should documentate this)
[mailer.git] / inc / modules / member / what-payout.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 04/12/2004 *
4  * ================                             Last change: 12/01/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : what-payout.php                                  *
8  * -------------------------------------------------------------------- *
9  * Short description : Payout requests                                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Auszahlungsanfragen                              *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         // Don't call this directly!
42         die();
43 } elseif (!isMember()) {
44         // Not logged in
45         redirectToIndexMemberOnlyModule();
46 }
47
48 // Add description as navigation point
49 addMenuDescription('member', __FILE__);
50
51 if ((!isExtensionActive('payout')) && (!isAdmin())) {
52         loadTemplate('admin_settings_saved', false, generateExtensionInactiveNotInstalledMessage('payout'));
53         return;
54 } // END - if
55
56 $result_depths = SQL_QUERY("SELECT level, percents FROM `{?_MYSQL_PREFIX?}_refdepths` ORDER BY level", __FILE__, __LINE__);
57 $totalPoints = 0;
58 while ($content = SQL_FETCHARRAY($result_depths)) {
59         // Load referal points
60         $result_points = SQL_QUERY_ESC("SELECT `points` FROM `{?_MYSQL_PREFIX?}_user_points` WHERE `userid`=%s AND `ref_dept`h=%d LIMIT 1",
61                 array(getUserId(), bigintval($content['level'])), __FILE__, __LINE__);
62
63         // Entry found?
64         if (SQL_NUMROWS($result_points) == 1) {
65                 // Load points
66                 list($points) = SQL_FETCHROW($result_points);
67
68                 // Add them to total
69                 $totalPoints += $points;
70         } // END - if
71
72         // Free result
73         SQL_FREERESULT($result_points);
74 }
75
76 // Free memory
77 SQL_FREERESULT($result_depths);
78
79 // Get used points
80 $usedPoints = countSumTotalData(getUserId(), 'user_data', 'used_points');
81
82 // Translate point into comma
83 $totalPoints = ($totalPoints - $usedPoints);
84
85 // Sanity check...
86 if (empty($totalPoints)) $totalPoints = '0.00000';
87
88 if (!isGetRequestElementSet('payout')) {
89         // Load payout types
90         $result = SQL_QUERY_ESC("SELECT id, type, rate, min_points, allow_url
91 FROM `{?_MYSQL_PREFIX?}_payout_types`
92 WHERE %s >= min_points
93 ORDER BY type ASC",
94                 array($totalPoints), __FILE__, __LINE__);
95         if (SQL_NUMROWS($result) > 0) {
96                 // Free memory
97                 SQL_FREERESULT($result);
98
99                 // Check for his payouts
100                 $result_payouts = SQL_QUERY_ESC("SELECT p.id, p.payout_total, p.target_account, p.target_bank, t.type, p.payout_timestamp, p.status, t.allow_url AS allow, p.target_url AS url, p.link_text AS alt, p.banner_url AS banner
101 FROM `{?_MYSQL_PREFIX?}_user_payouts` AS p
102 LEFT JOIN `{?_MYSQL_PREFIX?}_payout_types` AS t
103 ON p.payout_id = t.id
104 WHERE p.userid = %s
105 ORDER BY p.payout_timestamp DESC",
106                         array(getUserId()), __FILE__, __LINE__);
107                 if (SQL_NUMROWS($result_payouts) > 0) {
108                         // List all his requests
109                         $OUT = ''; $SW = 2;
110                         while ($content = SQL_FETCHARRAY($result_payouts)) {
111                                 // Translate status
112                                 $content['status'] = getMessage('PAYOUT_MEMBER_STATUS_'.strtoupper($content['status']).'');
113                                 $content['status'] = "<div class=\"member_failed\">".$content['status']."</div>";
114
115                                 // Nothing entered must be secured in member/what-payputs.php !
116                                 if ($content['allow'] == 'Y') {
117                                         // Banner/Textlink views/clicks request
118                                         if (!empty($content['banner'])) {
119                                                 // Banner
120                                                 $content['target_account'] = "<img src=\"".$content['banner']."\" alt=\"".$content['alt']."\" title=\"".$content['alt']."\" border=\"0\" />";
121                                         } else {
122                                                 // Textlink
123                                                 $content['target_account'] = $content['alt'];
124                                         }
125                                         $content['target_bank'] = "<a href=\"".generateDerefererUrl($content['url'])."\" target=\"_blank\">{--CLICK_HERE--}</a>";
126                                 } else {
127                                         // e-currency payout request
128                                         if (empty($content['target_account'])) $content['target_account'] = '---';
129                                         if (empty($content['target_bank']))    $content['target_bank']    = '---';
130                                 }
131
132                                 // Prepare data for the template
133                                 // @TODO Rewritings: acc->target_account,bank->target_bank in templates
134                                 $content = array(
135                                         'sw'     => $SW,
136                                         'acc'    => $content['target_account'],
137                                         'points' => translateComma($content['payout_total']) . ' ' . $content['type'],
138                                         'bank'   => $content['target_bank'],
139                                         'stamp'  => generateDateTime($content['payout_timestamp'], 2),
140                                         'status' => $content['status']
141                                 );
142
143                                 // Load row template and switch colors
144                                 $OUT .= loadTemplate('member_payout_row', true, $content);
145                                 $SW = 3 - $SW;
146                         }
147
148                         // Load template
149                         loadTemplate('member_payout', false, $OUT);
150                 }
151
152                 // Free memory
153                 SQL_FREERESULT($result_payouts);
154
155                 // Output payout list
156                 outputPayoutList($totalPoints);
157         }
158 } else {
159         // Chedk if he can get paid by selected type
160         $result = SQL_QUERY_ESC("SELECT type, rate, min_points, allow_url AS allow FROM `{?_MYSQL_PREFIX?}_payout_types` WHERE `id`=%s LIMIT 1",
161                 array(bigintval(getRequestElement('payout'))), __FILE__, __LINE__);
162
163         if (SQL_NUMROWS($result) == 1) {
164                 // ID is valid so load the data
165                 $content = SQL_FETCHARRAY($result);
166                 SQL_FREERESULT($result);
167
168                 // Calculate maximum value
169                 $max     = round($totalPoints * $content['rate'] - 0.5);
170                 $PAY_MAX = 0;
171
172                 // Calulcate points from submitted amount
173                 $points = 0;
174                 if (isPostRequestElementSet('payout')) {
175                         $points  = bigintval(postRequestElement('payout')) / $content['rate'];
176                         $PAY_MAX = $max / $content['rate'];
177                 }
178
179                 // Has enougth points to payout?
180                 if ($totalPoints >= $content['min_points']) {
181                         // Ok, he can get be paid
182                         if ((isFormSent()) && ($points <= $PAY_MAX) && ($points >= $content['min_points'])) {
183                                 // Remember points in array
184                                 setRequestPostElement('payout_points', translateComma($points));
185                                 setRequestPostElement('type'         , $content['type']);
186
187                                 // Subtract points from member's account
188                                 subtractPoints('payout', getUserId(), $points);
189
190                                 // Add entry to his tranfer history
191                                 if ($content['allow'] == 'Y') {
192                                         // Banner/textlink ordered
193                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_payouts` (`userid`, `payout_total`, `payout_id`, `payout_timestamp`, `status`, `target_url`, `link_text`, `banner_url`)
194 VALUES (%s,%s,%s, UNIX_TIMESTAMP(), 'NEW','%s','%s','%s')",
195                                         array(
196                                                 getUserId(),
197                                                 bigintval(postRequestElement('payout')),
198                                                 bigintval(getRequestElement('payout')),
199                                                 postRequestElement('turl'),
200                                                 postRequestElement('alt'),
201                                                 postRequestElement('banner')
202                                         ), __FILE__, __LINE__);
203
204                                         // Load templates
205                                         $message_mem = loadEmailTemplate('member_payout_request_banner', postRequestArray(), getUserId());
206                                         if (getExtensionVersion('admins') >= '0.4.1') {
207                                                 $adm_tpl = 'admin_payout_request_banner';
208                                         } else {
209                                                 $message_adm = loadEmailTemplate('admin_payout_request_banner', postRequestArray(), getUserId());
210                                         }
211                                 } else {
212                                         // e-currency payout requested
213                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_payouts` (`userid`, `payout_total`, `target_account`, `target_bank`, `payout_id`, `payout_timestamp`, `status`, `password`)
214 VALUES (%s,%s,%s,'%s',%s, UNIX_TIMESTAMP(), 'NEW','%s')",
215                                         array(
216                                                 getUserId(),
217                                                 bigintval(postRequestElement('payout')),
218                                                 bigintval(postRequestElement('account')),
219                                                 postRequestElement('bank'),
220                                                 bigintval(getRequestElement('payout')),
221                                                 postRequestElement('pass')
222                                         ), __FILE__, __LINE__);
223
224                                         // Load templates
225                                         $message_mem = loadEmailTemplate('member_payout_request', postRequestArray(), getUserId());
226                                         $message_adm = loadEmailTemplate('admin_payout_request', postRequestArray(), getUserId());
227                                         $admin_tpl = '';
228
229                                         // @TODO Rewrite this to a filter
230                                         if (getExtensionVersion('admins') >= '0.4.1') {
231                                                 $admin_tpl = 'admin_payout_request';
232                                         } // END - if
233                                 }
234
235                                 // Generate task
236                                 createNewTask('[payout:] {--PAYOUT_REQUEST_ADMIN--}', $message_adm, 'PAYOUT_REQUEST', getUserId());
237
238                                 // Send out mails
239                                 sendEmail(getUserId(), getMessage('PAYOUT_REQUEST_MEMBER'), $message_mem);
240
241                                 // To admin(s)
242                                 sendAdminNotification(getMessage('PAYOUT_REQUEST_ADMIN'), $admin_tpl, postRequestArray(), getUserId());
243
244                                 // Load template and output it
245                                 loadTemplate('admin_settings_saved', false, getMessage('PAYOUT_REQUEST_SENT'));
246                         } elseif ($content['allow'] == 'Y') {
247                                 // Prepare content
248                                 $content = array(
249                                         'max'    => $max,
250                                         'type'   => $content['type'],
251                                         'payout' => bigintval(getRequestElement('payout'))
252                                 );
253
254                                 // Generate banner order form
255                                 loadTemplate('member_payout_form_banner', false, $content);
256                         } else {
257                                 // Prepare content
258                                 $content = array(
259                                         'max'    => $max,
260                                         'type'   => $content['type'],
261                                         'payout' => bigintval(getRequestElement('payout'))
262                                 );
263
264                                 // Generate normal form
265                                 loadTemplate('member_payout_form', false, $content);
266                         }
267                 } else {
268                         // Not enougth points
269                         loadTemplate('admin_settings_saved', false, getMessage('PAYOUT_POINTS_NOT_ENOUGTH'));
270                 }
271         } else {
272                 // ID is invalid
273                 loadTemplate('admin_settings_saved', false, getMessage('PAYOUT_ID_INVALID'));
274         }
275 }
276
277 // [EOF]
278 ?>