2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 10/07/2004 *
4 * =================== Last change: 10/07/2004 *
6 * -------------------------------------------------------------------- *
7 * File : what-transfer.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Point transfers *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Punktetransfers *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2013 by Mailer Developer Team *
20 * For more information visit: http://mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
41 } elseif (!isMember()) {
42 redirectToIndexMemberOnlyModule();
45 // Add description as navigation point
46 addYouAreHereLink('member', __FILE__);
48 // Extension ext-transfer must be avtive
49 if ((!isExtensionActive('transfer')) && (!isAdmin())) {
50 displayMessage('{%pipe,generateExtensionInactiveNotInstalledMessage=transfer%}');
54 // Check for mode in GET
56 if (isGetRequestElementSet('do')) {
57 $mode = getRequestElement('do');
61 if ((getUserData('opt_in') != 'Y') && ($mode == 'new')) {
66 case 'new': // Start new transfer
67 // Get total points and subtract the balance amount from it = maximum transferable points
68 $total = getTotalPoints(getMemberId());
70 // Remember maximum value for template
71 $content['max_transferable'] = round($total - getConfig('transfer_balance') - 0.5);
75 if (getTransferCode() > 0) {
77 $code = generateRandomCode(getTransferCode(), postRequestElement('code_chk'), getMemberId(), $content['max_transferable']);
78 $valid_code = ($code == postRequestElement('code'));
80 // Zero length (= disabled) is always valid!
85 $valid_pass = ($pass == generateHash(postRequestElement('password'), $pass));
87 // Test transfer amount
88 $valid_amount = ((isPostRequestElementSet('points')) && (postRequestElement('points') <= $content['max_transferable']));
90 // Test reason for transfer
91 $valid_reason = (isPostRequestElementSet('reason'));
93 // Test if a recipient is selected
94 $valid_recipient = isValidId(postRequestElement('to_userid'));
96 // Re-check receivers and own personal data
97 $result = sqlQueryEscaped("SELECT `userid`, `gender`, `surname`, `family`, `email` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid` IN ('%s','%s') AND `status`='CONFIRMED'" . runFilterChain('user_exclusion_sql', ' ') . " LIMIT 2",
100 bigintval(postRequestElement('to_userid'))
101 ), __FILE__, __LINE__);
103 // Is there two entries?
104 $valid_data = (sqlNumRows($result) == 2);
106 // Final check if all is fine
107 if ($valid_code && $valid_data && $valid_pass && $valid_amount && $valid_reason && $valid_recipient) {
108 // Let's start the transfer and load user data
109 $content['sender'] = sqlFetchArray($result);
110 $content['recipient'] = sqlFetchArray($result);
112 // Is the nickname extension not installed?
113 if (!isExtensionActive('nickname')) {
114 // Fix empty nicknames
115 $content['sender']['nickname'] = '';
116 $content['recipient']['nickname'] = '';
119 // Prepare variables for testing
120 $TEST_NICK_SENDER = $content['sender']['nickname'];
121 $TEST_NICK_REC = $content['recipient']['nickname'];
123 // Default is userids for subject line
124 $SENDER = getMemberId();
125 $RECIPIENT = bigintval(postRequestElement('to_userid'));
127 // If nickname is installed we can set the nickname
128 // @TODO Rewrite this to a filter
129 if (isExtensionActive('nickname')) {
130 if (($TEST_NICK_SENDER != getMemberId()) && (!empty($TEST_NICK_SENDER))) {
131 $SENDER = $content['sender']['nickname'];
134 if (($TEST_NICK_REC != postRequestElement('to_userid')) && (!empty($TEST_NICK_REC))) {
135 $RECIPIENT = $content['recipient']['nickname'];
139 // Remember transfer reason
140 $content['reason'] = postRequestElement('reason');
142 // Generate tranafer id
143 $content['trans_id'] = bigintval(generateRandomCode('10', getRandomTan(), getMemberId(), postRequestElement('reason')));
145 // Add entries to both tables
146 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_user_transfers_in` (`userid`, `from_userid`, `points`, `reason`, `time_trans`, `trans_id`) VALUES (%s,%s,%s,'%s', UNIX_TIMESTAMP(),%s)",
148 bigintval(postRequestElement('to_userid')),
150 bigintval(postRequestElement('points')),
151 postRequestElement('reason'),
153 ), __FILE__, __LINE__);
154 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_user_transfers_out` (`userid`, `to_userid`, `points`, `reason`, `time_trans`, `trans_id`) VALUES (%s,%s,%s,'%s', UNIX_TIMESTAMP(),%s)",
157 bigintval(postRequestElement('to_userid')),
158 bigintval(postRequestElement('points')),
159 postRequestElement('reason'),
161 ), __FILE__, __LINE__);
163 // Add points to account *directly* ...
164 initReferralSystem();
165 addPointsThroughReferralSystem('transfer', bigintval(postRequestElement('to_userid')), bigintval(postRequestElement('points')));
167 // ... and add it to current user's used points and ignore return status
168 subtractPoints('transfer', getMemberId(), postRequestElement('points'));
170 // First send email to recipient
171 $message = loadEmailTemplate('member_transfer_recipient', $content, postRequestElement('to_userid'));
172 sendEmail($content['recipient']['userid'], '{--TRANSFER_MEMBER_RECIPIENT_SUBJECT--}' . ': ' . $SENDER, $message);
174 // Second send email to sender
175 $message = loadEmailTemplate('member_transfer_sender', $content, getMemberId());
176 sendEmail($content['sender']['userid'], '{--TRANSFER_MEMBER_SENDER_SUBJECT--}' . ': ' . $RECIPIENT, $message);
178 // At last send admin mail(s)
179 $adminSubject = sprintf('%s (%s->%s)', '{--ADMIN_TRANSFER_SUBJECT--}', $SENDER, $RECIPIENT);
180 sendAdminNotification($adminSubject, 'admin_transfer_points', $content);
182 // Transfer is completed
183 displayMessage('<div>{--MEMBER_TRANSFER_COMPLETED--}' . '</div><div><a href="{%url=modules.php?module=login&what=transfer%}">{--MEMBER_TRANSFER_CONTINUE_OVERVIEW--}</a></div>');
184 } elseif ($valid_code === FALSE) {
185 // Invalid Touring code!
186 displayErrorMessage('{--MEMBER_TRANSFER_INVALID_CODE--}');
187 unsetPostRequestElement('ok');
188 } elseif ($valid_pass === FALSE) {
189 // Wrong password entered
190 displayErrorMessage('{--MEMBER_TRANSFER_INVALID_PASSWORD--}');
191 unsetPostRequestElement('ok');
192 } elseif ($valid_amount === FALSE) {
193 // Too much points entered
194 displayErrorMessage('{--MEMBER_TRANSFER_INVALID_POINTS--}');
195 unsetPostRequestElement('ok');
196 } elseif ($valid_reason === FALSE) {
197 // No transfer reason entered
198 displayErrorMessage('{--MEMBER_TRANSFER_INVALID_REASON--}');
199 unsetPostRequestElement('ok');
200 } elseif ($valid_recipient === FALSE) {
201 // No recipient selected
202 displayErrorMessage('{--MEMBER_TRANSFER_INVALID_RECIPIENT--}');
203 unsetPostRequestElement('ok');
204 } elseif ($valid_data === FALSE) {
205 // No recipient/sender selected
206 displayErrorMessage('{--MEMBER_TRANSFER_INVALID_DATA--}');
207 unsetPostRequestElement('ok');
211 sqlFreeResult($result);
216 $result = sqlQueryEscaped("SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `status`='CONFIRMED'" . runFilterChain('user_exclusion_sql', ' ') . " AND `opt_in`='Y' AND `userid` != '%s' ORDER BY `userid` ASC",
217 array(getMemberId()), __FILE__, __LINE__);
219 if (!ifSqlHasZeroNums($result)) {
221 $OUT = '<select name="to_userid" size="1" class="form_select">
222 <option value="0">{--SELECT_NONE--}</option>';
223 while (list($userid) = sqlFetchRow($result)) {
224 $OUT .= ' <option value="' . $userid . '"';
225 if ((isPostRequestElementSet('to_userid')) && (postRequestElement('to_userid') == $userid)) {
226 $OUT .= ' selected="selected"';
228 $OUT .= '>{%template,DisplayUsername=' . $userid . '%}</option>';
231 $content['to_disabled'] = '';
234 sqlFreeResult($result);
236 // No one else is opt-in
237 $OUT = returnMessage('{--MEMBER_TRANSFER_NO_ONE_ELSE_OPT_IN--}');
238 $content['to_disabled'] = ' disabled="disabled"';
241 // Transfer output to constant for the template
242 $content['userid_selection'] = $OUT;
245 if (getTransferCode() > 0) {
246 // Generate random number
247 $rand = getRandomTan();
249 // Generate CAPTCHA code
250 $code = generateRandomCode(getTransferCode(), $rand, getMemberId(), $content['max_transferable']);
252 // Generate image (HTML code)
253 $img = generateImageOrCode($code, FALSE);
255 // Add all and hidden field
256 $content['captcha_code'] = '<input type="hidden" name="code_chk" value="' . $rand . '" /><input type="text" name="code" class="form_field" size="5" maxlength="7"' . $content['to_disabled'] . ' /> ' . $img;
259 $content['captcha_code'] = returnMessage('{--MEMBER_TRANSFER_NO_CODE--}');
262 // Init points/reason
263 $content['points'] = '';
264 $content['reason'] = '';
266 // Transfer maybe already entered valued'
267 if (isPostRequestElementSet('ok')) {
268 // Get values from form
269 $content['points'] = postRequestElement('points');
270 $content['reason'] = postRequestElement('reason');
274 loadTemplate('member_transfer_new', FALSE, $content);
278 case 'list_in': // List only incoming transactions
279 case 'list_out': // List only outgoing transactions
280 // As you can see I put list_in and list_out together. I now do a switch() again on it for the right SQL command
281 $nothingMessage = '';
284 $sql = 'SELECT `trans_id`, `from_userid` AS `party_userid`, `points`, `reason`, `time_trans` FROM `{?_MYSQL_PREFIX?}_user_transfers_in` WHERE `userid`=%s ORDER BY `time_trans` DESC LIMIT {?transfer_max?}';
285 $nothingMessage = '{--MEMBER_TRANSFER_NO_INCOMING_TRANSFERS--}';
286 $content['balance'] = '{--MEMBER_TRANSFER_TOTAL_INCOMING--}';
287 $content['title'] = '{--MEMBER_LIST_INCOMING_TRANSFER_TITLE--}';
291 $sql = 'SELECT `trans_id`, `to_userid` AS `party_userid`, `points`, `reason`, `time_trans` FROM `{?_MYSQL_PREFIX?}_user_transfers_out` WHERE `userid`=%s ORDER BY `time_trans` DESC LIMIT {?transfer_max?}';
292 $nothingMessage = '{--MEMBER_TRANSFER_NO_OUTGOING_TRANSFERS--}';
293 $content['balance'] = '{--TRANSFER_TOTAL_OUTGOING--}';
294 $content['title'] = '{--MEMBER_LIST_OUTGOING_TRANSFER_TITLE--}';
298 // Run the SQL command and set total points to zero
300 $result = sqlQueryEscaped($sql, array(getMemberId()), __FILE__, __LINE__);
302 // Are there entries?
303 if (!ifSqlHasZeroNums($result)) {
305 while ($content = sqlFetchArray($result)) {
306 // Rewrite points, out is subtracted
307 if ($type == 'OUT') {
308 $content['points'] = $content['points'] * -1;
311 // Prepare content for template
312 $$content['time_trans'] = generateDateTime($content['time_trans'], 3);
315 $OUT .= loadTemplate('member_transfer_row2', TRUE, $content);
317 // Add points and switch color
318 $totalPoints += $content['points'];
322 sqlFreeResult($result);
324 // Nothing for in or out
326 <td colspan="5" align="center" class="bottom">
327 ' . displayMessage($nothingMessage, TRUE) . '
332 // ... and add them to a constant for the template
333 $content['rows'] = $OUT;
335 // Remeber total amount
336 $content['total_points'] = $totalPoints;
338 // Load final template
339 loadTemplate('member_transfer_list', FALSE, $content);
342 case 'list_all': // List all transactions
344 * Fill a temporary table with data from both tables. This is much
345 * easier to code and unstandable by you as sub-SELECT queries. I know
346 * this is not the fastest way but it shall be fine for now.
349 // First of all create the per-user temporary table
350 $result = sqlQueryEscaped("CREATE TEMPORARY TABLE `{?_MYSQL_PREFIX?}_%s_transfers_tmp` (
351 `trans_id` VARCHAR(12) NOT NULL DEFAULT '',
352 `party_userid` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
353 `points` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
354 `reason` VARCHAR(255) NOT NULL DEFAULT '',
355 `time_trans` VARCHAR(10) NOT NULL DEFAULT 0,
356 `trans_type` ENUM('IN','OUT') NOT NULL DEFAULT 'IN',
357 INDEX (`party_userid`)
358 ) ENGINE = HEAP COMMENT = 'Temporary transfer table'", array(getMemberId()), __FILE__, __LINE__);
360 // Let's begin with the incoming list
361 $result = sqlQueryEscaped("SELECT `trans_id`, `from_userid`, `points`, `reason`, `time_trans` FROM `{?_MYSQL_PREFIX?}_user_transfers_in` WHERE `userid`=%s ORDER BY `id` ASC LIMIT {?transfer_max?}",
362 array(getMemberId()), __FILE__, __LINE__);
363 while ($content = sqlFetchRow($result)) {
364 array_push($content, 'IN');
365 $content = implode("','", $content);
366 $res_temp = sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_%s_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('" . $content . "')", array(getMemberId()), __FILE__, __LINE__);
370 sqlFreeResult($result);
372 // As the last table transfer data from outgoing table to temporary
373 $result = sqlQueryEscaped("SELECT `trans_id`, `to_userid`, `points`, `reason`, `time_trans` FROM `{?_MYSQL_PREFIX?}_user_transfers_out` WHERE `userid`=%s ORDER BY `id` LIMIT {?transfer_max?}",
374 array(getMemberId()), __FILE__, __LINE__);
375 while ($content = sqlFetchRow($result)) {
376 array_push($content, 'OUT');
377 $content = implode("','", $content);
378 $res_temp = sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_%s_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('" . $content . "')", array(getMemberId()), __FILE__, __LINE__);
382 sqlFreeResult($result);
384 // Search for entries
385 $result = sqlQueryEscaped("SELECT `party_userid`, `trans_id`, `points`, `reason`, `time_trans`, `trans_type` FROM `{?_MYSQL_PREFIX?}_%s_transfers_tmp` ORDER BY `time_trans` DESC",
386 array(getMemberId()), __FILE__, __LINE__);
389 if (!ifSqlHasZeroNums($result)) {
392 while ($content = sqlFetchArray($result)) {
393 // Rewrite points if OUT
394 if ($content['trans_type'] == 'OUT') {
395 $content['points'] = $content['points'] * -1;
398 // Prepare content for template
399 $content['time'] = generateDateTime($content['time_trans'], 3);
402 $OUT .= loadTemplate('member_transfer_row', TRUE, $content);
404 // Add points and switch color
405 $total += $content['points'];
408 // Nothing for in and out
410 <td colspan="5" align="center" class="bottom">
411 ' . displayMessage('{--TRANSFER_NO_INOUT_TRANSFERS--}', TRUE) . '
417 sqlFreeResult($result);
419 // ... and add them to a constant for the template
420 $content['rows'] = $OUT;
422 // Remeber total amount
423 $content['total_points'] = $total;
426 $content['title'] = '{--TRANSFER_LIST_ALL--}';
428 // Set "balance" word
429 $content['balance'] = '{--TRANSFER_TOTAL_BALANCE--}';
431 // At the end we don't need a temporary table in memory
432 $result = sqlQueryEscaped("DROP TABLE IF EXISTS `{?_MYSQL_PREFIX?}_%s_transfers_tmp`", array(getMemberId()), __FILE__, __LINE__);
434 // Load final template
435 loadTemplate('member_transfer_list', FALSE, $content);
437 // Free some memory...
438 sqlFreeResult($result);
441 default: // Overview page
442 // Check incoming transfers
443 $totalIn = countSumTotalData(getMemberId(), 'user_transfers_in', 'id', 'userid', TRUE);
444 $content['in_link'] = $totalIn;
446 $content['in_link'] = '<a href="{%url=modules.php?module=login&what=transfer&do=list_in%}">' . $totalIn . '</a>';
449 // Check outgoing transfers
450 $totalOut = countSumTotalData(getMemberId(), 'user_transfers_out', 'id', 'userid', TRUE);
452 $content['out_link'] = $totalOut;
454 $content['out_link'] = '<a href="{%url=modules.php?module=login&what=transfer&do=list_out%}">' . $totalOut . '</a>';
457 // Add all to total amount
458 $total = $totalIn + $totalOut;
460 // Total transactions
461 $content['all_link'] = $total;
463 $content['all_link'] = '<a href="{%url=modules.php?module=login&what=transfer&do=list_all%}">{%pipe,translateComma=' . $total . '%}</a>';
468 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `opt_in`='%s' WHERE `userid`=%s LIMIT 1",
469 array(postRequestElement('opt_in'), getMemberId()), __FILE__, __LINE__);
471 // "Settings saved..."
472 displayMessage('{--SETTINGS_SAVED--}');
476 foreach (array('allow_y','allow_n') as $entry) {
477 $content[$entry] = '';
480 // Set current selection
481 $content['allow_' . strtolower(getUserData('opt_in'))] = ' checked="checked"';
483 // Set 'new transfer' link according to above option
484 switch (getUserData('opt_in')) {
486 $content['new_link'] = '<a href="{%url=modules.php?module=login&what=transfer&do=new%}" title="{--MEMBER_TRANSFER_NOW_LINK_TITLE--}">{--MEMBER_TRANSFER_NOW_LINK--}</a>';
490 $content['new_link'] = '{--MEMBER_PLEASE_ALLOW_TRANSFER_RECEIVE--}';
494 // Check for latest out-transfers
495 $result = sqlQueryEscaped("SELECT
498 `{?_MYSQL_PREFIX?}_user_transfers_out`
500 (UNIX_TIMESTAMP() - `time_trans`) >= {?transfer_timeout?} AND
507 ), __FILE__, __LINE__);
509 // Is there an entry?
510 if (sqlNumRows($result) == 1) {
511 // Load newest transaction
512 list($newest) = sqlFetchRow($result);
513 $content['settings'] = '{%message,MEMBER_TRANSFER_LATEST_IS=' . generateDateTime($newest, '3') . '%}';
516 $content['settings'] = loadTemplate('member_transfer_settings', TRUE, $content);
520 sqlFreeResult($result);
523 loadTemplate('member_transfer_overview', FALSE, $content);