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 * 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 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
43 } elseif (!isMember()) {
44 redirectToIndexMemberOnlyModule();
47 // Add description as navigation point
48 addMenuDescription('member', __FILE__);
50 if ((!isExtensionActive('transfer')) && (!isAdmin())) {
51 loadTemplate('admin_settings_saved', false, generateExtensionInactiveNotInstalledMessage('transfer'));
55 // Check for mode in GET
57 if (isGetRequestParameterSet('mode')) $mode = getRequestParameter('mode');
60 if ((getUserData('opt_in') != 'Y') && ($mode == 'new')) $mode = '';
63 case 'new': // Start new transfer
64 // Get total points and subtract the balance amount from it = maximum transferable points
65 $total = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
67 // Remember maximum value for template
68 $content['max_transferable'] = round($total - getConfig('transfer_balance') - 0.5);
72 if (getConfig('transfer_code') > 0) {
74 $code = generateRandomCode(getConfig('transfer_code'), postRequestParameter('code_chk'), getMemberId(), $content['max_transferable']);
75 $valid_code = ($code == postRequestParameter('code'));
77 // Zero length (= disabled) is always valid!
82 $valid_pass = ($pass == generateHash(postRequestParameter('password'), $pass));
84 // Test transfer amount
85 $valid_amount = ((isPostRequestParameterSet('points')) && (postRequestParameter('points') <= $content['max_transferable']));
87 // Test reason for transfer
88 $valid_reason = (isPostRequestParameterSet('reason'));
90 // Test if a recipient is selected
91 $valid_recipient = (postRequestParameter('to_userid') > 0);
93 // Check for nickname extension and set additional data
94 // @TODO Rewrite this to a filter
96 if (isExtensionActive('nickname')) {
97 $add = ', `nickname`';
100 // Re-check receivers and own personal data
101 $result = SQL_QUERY_ESC("SELECT `userid`, `gender`, `surname`, `family`, `email`".$add." FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid` IN ('%s','%s') AND `status`='CONFIRMED' LIMIT 2",
104 bigintval(postRequestParameter('to_userid'))
105 ), __FILE__, __LINE__);
107 // Do we have two entries?
108 $valid_data = (SQL_NUMROWS($result) == 2);
110 // Final check if all is fine
111 if ($valid_code && $valid_data && $valid_pass && $valid_amount && $valid_reason && $valid_recipient) {
112 // Let's start the transfer and load user data
113 $content['sender'] = SQL_FETCHARRAY($result);
114 $content['recipient'] = SQL_FETCHARRAY($result);
116 // Is the nickname extension not installed?
117 if (!isExtensionActive('nickname')) {
118 // Fix empty nicknames
119 $content['sender']['nickname'] = '';
120 $content['recipient']['nickname'] = '';
123 // Prepare variables for testing
124 $TEST_NICK_SENDER = $content['sender']['nickname'];
125 $TEST_NICK_REC = $content['recipient']['nickname'];
127 // Default is userids for subject line
128 $SENDER = getMemberId();
129 $RECIPIENT = bigintval(postRequestParameter('to_userid'));
131 // If nickname is installed we can set the nickname
132 // @TODO Rewrite this to a filter
133 if (isExtensionActive('nickname')) {
134 if (($TEST_NICK_SENDER != getMemberId()) && (!empty($TEST_NICK_SENDER))) {
135 $SENDER = $content['sender']['nickname'];
138 if (($TEST_NICK_REC != postRequestParameter('to_userid')) && (!empty($TEST_NICK_REC))) {
139 $RECIPIENT = $content['recipient']['nickname'];
143 // Remember transfer reason and fancy date/time in constants
144 $content['reason'] = secureString(postRequestParameter('reason'));
145 $content['expires'] = createFancyTime(getConfig('transfer_age'));
147 // Generate tranafer id
148 $content['trans_id'] = bigintval(generateRandomCode('10', mt_rand(0, 99999), getMemberId(), postRequestParameter('reason')));
150 // Add entries to both tables
151 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_transfers_in` (`userid`, `from_userid`, `points`, `reason`, `time_trans`, `trans_id`) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP(),'%s')",
152 array(bigintval(postRequestParameter('to_userid')), getMemberId(), bigintval(postRequestParameter('points')), postRequestParameter('reason'), $content['trans_id']), __FILE__, __LINE__);
153 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_transfers_out` (`userid`, `to_userid`, `points`, `reason`, `time_trans`, `trans_id`) VALUES ('%s','%s','%s','%s', UNIX_TIMESTAMP(),'%s')",
154 array(getMemberId(), bigintval(postRequestParameter('to_userid')), bigintval(postRequestParameter('points')), postRequestParameter('reason'), $content['trans_id']), __FILE__, __LINE__);
156 // Add points to account *directly* ...
157 addPointsDirectly('member_transfer', bigintval(postRequestParameter('to_userid')), bigintval(postRequestParameter('points')));
159 // ... and add it to current user's used points
160 subtractPoints('transfer', getMemberId(), postRequestParameter('points'));
162 // First send email to recipient
163 $message = loadEmailTemplate('member_transfer_recipient', $content, postRequestParameter('to_userid'));
164 sendEmail($content['recipient']['email'], getMessage('TRANSFER_MEMBER_RECIPIENT_SUBJ') . ': ' . $SENDER, $message);
166 // Second send email to sender
167 $message = loadEmailTemplate('member_transfer_sender', $content, getMemberId());
168 sendEmail($content['sender']['email'], getMessage('TRANSFER_MEMBER_SENDER_SUBJ') . ': ' . $RECIPIENT, $message);
170 // At last send admin mail(s)
171 $adminSubject = sprintf("%s (%s->%s)", getMessage('TRANSFER_ADMIN_SUBJECT'), $SENDER, $RECIPIENT);
172 sendAdminNotification($adminSubject, 'admin_transfer_points', $content);
174 // Transfer is completed
175 loadTemplate('admin_settings_saved', false, '{--TRANSFER_COMPLETED--}' . '<br /><a href="{%url=modules.php?module=login&what=transfer%}">{--TRANSFER_CONTINUE_OVERVIEW--}</a>');
176 } elseif ($valid_code === false) {
177 // Invalid Touring code!
178 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_CODE--}</div>');
179 unsetPostRequestParameter('ok');
180 } elseif ($valid_pass === false) {
181 // Wrong password entered
182 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_PASSWORD--}</div>');
183 unsetPostRequestParameter('ok');
184 } elseif ($valid_amount === false) {
185 // Too much points entered
186 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_POINTS--}</div>');
187 unsetPostRequestParameter('ok');
188 } elseif ($valid_reason === false) {
189 // No transfer reason entered
190 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_REASON--}</div>');
191 unsetPostRequestParameter('ok');
192 } elseif ($valid_recipient === false) {
193 // No recipient selected
194 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_RECIPIENT--}</div>');
195 unsetPostRequestParameter('ok');
196 } elseif ($valid_data === false) {
197 // No recipient/sender selected
198 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_DATA--}</div>');
199 unsetPostRequestParameter('ok');
203 SQL_FREERESULT($result);
208 if (isExtensionActive('nickname')) {
209 // Load userid and nickname
210 $result = SQL_QUERY_ESC("SELECT `userid`, `nickname` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `status`='CONFIRMED' AND `opt_in`='Y' AND `userid` != '%s' ORDER BY `userid` ASC",
211 array(getMemberId()), __FILE__, __LINE__);
214 $result = SQL_QUERY_ESC("SELECT `userid`, `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `status`='CONFIRMED' AND `opt_in`='Y' AND `userid` != '%s' ORDER BY `userid` ASC",
215 array(getMemberId()), __FILE__, __LINE__);
218 if (SQL_NUMROWS($result) > 0) {
220 $OUT = "<select name=\"to_userid\" size=\"1\" class=\"member_select\">
221 <option value=\"0\">{--SELECT_NONE--}</option>\n";
222 // @TODO Try to rewrite his to $content = SQL_FETCHARRAY(), see some lines above for two different queries
223 while (list($userid, $nick) = SQL_FETCHROW($result)) {
224 $OUT .= " <option value=\"".$userid."\"";
225 if ((isPostRequestParameterSet(('to_userid'))) && (postRequestParameter('to_userid') == $userid)) $OUT .= ' selected="selected"';
227 if (($nick != $userid) && (!empty($nick))) {
234 $OUT .= "</option>\n";
236 $OUT .= "</select>\n";
237 $content['to_disabled'] = '';
240 SQL_FREERESULT($result);
242 // No one else is opt-in
243 $OUT = loadTemplate('admin_settings_saved', true, '{--TRANSFER_NO_ONE_ELSE_OPT_IN--}');
244 $content['to_disabled'] = ' disabled="disabled"';
247 // Transfer output to constant for the template
248 $content['userid_selection'] = $OUT;
251 if (getConfig('transfer_code') > 0) {
252 $rand = mt_rand(0, 99999);
253 $code = generateRandomCode(getConfig('transfer_code'), $rand, getMemberId(), $content['max_transferable']);
254 $img = generateImageOrCode($code, false);
255 $content['captcha_code'] = '<input type="hidden" name="code_chk" value="' . $rand . '" /><input type="text" name="code" class="member_normal" size="5" maxlength="7"' . $content['to_disabled'] . ' /> ' . $img;
258 $content['captcha_code'] = loadTemplate('admin_settings_saved', true, '{--TRANSFER_NO_CODE--}');
261 // Init points/reason
262 $content['points'] = '';
263 $content['reason'] = '';
265 // Transfer maybe already entered valued'
266 if (isPostRequestParameterSet('ok')) {
267 // Get values from form
268 $content['points'] = postRequestParameter('points');
269 $content['reason'] = postRequestParameter('reason');
273 loadTemplate('member_transfer_new', false, $content);
277 case 'list_in': // List only incoming transactions
278 case 'list_out': // List only outgoing transactions
279 // 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
280 $nothingMessage = '';
283 $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?}";
284 $nothingMessage = getMessage('TRANSFER_NO_INCOMING_TRANSFERS');
285 $content['balance'] = getMessage('TRANSFER_TOTAL_INCOMING');
286 $content['title'] = getMessage('TRANSFER_LIST_INCOMING');
290 $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?}";
291 $nothingMessage = getMessage('TRANSFER_NO_OUTGOING_TRANSFERS');
292 $content['balance'] = getMessage('TRANSFER_TOTAL_OUTGOING');
293 $content['title'] = getMessage('TRANSFER_LIST_OUTGOING');
297 // Run the SQL command and set total points to zero
299 $result = SQL_QUERY_ESC($sql, array(getMemberId()), __FILE__, __LINE__);
301 // Do we have entries?
302 if (SQL_NUMROWS($result) > 0) {
304 // @TODO This should be somehow rewritten to $row = SQL_FETCHARRAY(), see switch() block above for SQL queries
305 while (list($tid, $userid, $points, $reason, $stamp) = SQL_FETCHROW($result)) {
307 if ($type == 'OUT') $points = $points . '-';
309 // Prepare content for template
310 // @TODO Rewrite: tid->trans_id,stamp->time_trans
314 'stamp' => generateDateTime($stamp, 3),
321 $OUT .= loadTemplate('member_transfer_row2', true, $row);
323 // Add points and switch color
324 $totalPoints += $points;
329 SQL_FREERESULT($result);
331 // Nothing for in or out
333 <td colspan=\"5\" align=\"center\" class=\"bottom\">
334 ".loadTemplate('admin_settings_saved', true, $nothingMessage)."
339 // ... and add them to a constant for the template
340 $content['rows'] = $OUT;
342 // Remeber total amount
343 $content['total'] = translateComma($totalPoints);
345 // Load final template
346 loadTemplate('member_transfer_list', false, $content);
349 case 'list_all': // List all transactions
350 // We fill a temporary table with data from both tables. This is much easier
351 // to code and unstand by you as sub-SELECT queries. I know this is not the
352 // fastest way but it shall be fine for now.
354 // First of all create the temporary table
355 $result = SQL_QUERY("CREATE TEMPORARY TABLE `{?_MYSQL_PREFIX?}_transfers_tmp` (
356 `trans_id` VARCHAR(12) NOT NULL DEFAULT '',
357 `party_userid` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
358 `points` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
359 `reason` VARCHAR(255) NOT NULL DEFAULT '',
360 `time_trans` VARCHAR(10) NOT NULL DEFAULT 0,
361 `trans_type` ENUM('IN','OUT') NOT NULL DEFAULT 'IN',
363 ) TYPE=HEAP", __FILE__, __LINE__);
365 // Let's begin with the incoming list
366 $result = SQL_QUERY_ESC("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?}",
367 array(getMemberId()), __FILE__, __LINE__);
368 while ($DATA = SQL_FETCHROW($result)) {
370 $DATA = implode("','", $DATA);
371 $res_temp = SQL_QUERY("INSERT INTO `{?_MYSQL_PREFIX?}_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('" . $DATA . "')", __FILE__, __LINE__);
375 SQL_FREERESULT($result);
377 // As the last table transfer data from outgoing table to temporary
378 $result = SQL_QUERY_ESC("SELECT `trans_id`, `to_userid`, `points`, `reason`, `time_trans` FROM `{?_MYSQL_PREFIX?}_user_transfers_out` WHERE `userid`=%s ORDER BY `id` LIMIT {?transfer_max?}",
379 array(getMemberId()), __FILE__, __LINE__);
380 while ($DATA = SQL_FETCHROW($result)) {
382 $DATA = implode("','", $DATA);
383 $res_temp = SQL_QUERY("INSERT INTO `{?_MYSQL_PREFIX?}_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('" . $DATA . "')", __FILE__, __LINE__);
387 SQL_FREERESULT($result);
390 if (SQL_NUMROWS($result) > 0) {
391 // Search for entries
392 $result = SQL_QUERY("SELECT `party_userid`, `trans_id`, `points`, `reason`, `time_trans`, `trans_type` FROM `{?_MYSQL_PREFIX?}_transfers_tmp` ORDER BY `time_trans` DESC",
397 while ($content = SQL_FETCHARRAY($result)) {
399 if ($content['trans_type'] == 'OUT') $content['points'] = '-'.$content['points']."";
401 // Prepare content for template
402 $content['sw'] = $SW;
403 $content['time'] = generateDateTime($content['time_trans'], 3);
404 $content['points'] = translateComma($content['points']);
407 $OUT .= loadTemplate('member_transfer_row', true, $content);
409 // Add points and switch color
410 $total += $content['points'];
415 SQL_FREERESULT($result);
417 // Nothing for in and out
419 <td colspan="5" align="center" class="bottom">
420 ' . loadTemplate('admin_settings_saved', true, '{--TRANSFER_NO_INOUT_TRANSFERS--}') . '
425 // ... and add them to a constant for the template
426 $content['rows'] = $OUT;
428 // Remeber total amount
429 $content['total'] = translateComma($total);
432 $content['title'] = getMessage('TRANSFER_LIST_ALL');
434 // Set "balance" word
435 $content['balance'] = getMessage('TRANSFER_TOTAL_BALANCE');
437 // At the end we don't need a temporary table in memory
438 $result = SQL_QUERY("DROP TABLE IF EXISTS `{?_MYSQL_PREFIX?}_transfers_tmp`", __FILE__, __LINE__);
440 // Load final template
441 loadTemplate('member_transfer_list', false, $content);
443 // Free some memory...
444 SQL_FREERESULT($result);
447 default: // Overview page
448 // Check incoming transfers
449 $total = countSumTotalData(getMemberId(), 'user_transfers_in', 'id', 'userid', true);
450 $content['in_link'] = $total;
452 $content['in_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=list_in%}">' . $total . '</a>';
455 // Check outgoing transfers
456 $dmy = countSumTotalData(getMemberId(), 'user_transfers_out', 'id', 'userid', true);
458 // Add to total amount
461 $content['out_link'] = $dmy;
463 $content['out_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=list_out%}">' . $dmy . '</a>';
466 // Total transactions
467 $content['all_link'] = $total;
469 $content['all_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=list_all%}">' . $total . '</a>';
474 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `opt_in`='%s' WHERE `userid`=%s LIMIT 1",
475 array(postRequestParameter('opt_in'), getMemberId()), __FILE__, __LINE__);
477 // Rember for next switch() command
478 getUserData('opt_in') = substr(postRequestParameter('opt_in'), 0, 1);
480 // "Settings saved..."
481 loadTemplate('admin_settings_saved', false, '<div class="member_done">{--SETTINGS_SAVED--}</div>');
485 foreach (array('allow_y','allow_n') as $entry) {
486 $content[$entry] = '';
489 // Set current selection
490 $content['allow_' . strtolower(getUserData('opt_in'))] = ' checked="checked"';
492 // Set 'new transfer' link according to above option
493 switch (getUserData('opt_in')) {
495 $content['new_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=new%}" title="{--TRANSFER_NOW_TITLE--}">{--TRANSFER_NOW_LINK--}</a>';
499 $content['new_link'] = getMessage('TRANSFER_PLEASE_ALLOW_OPT_IN');
503 // Check for latest out-transfers
504 $result = SQL_QUERY_ESC("SELECT
507 `{?_MYSQL_PREFIX?}_user_transfers_out`
509 `time_trans` > (UNIX_TIMESTAMP() - %s) AND `userid`=%s
514 getConfig('transfer_timeout'),
516 ), __FILE__, __LINE__);
518 // Do we have an entry?
519 if (SQL_NUMROWS($result) == 1) {
520 // Load newest transaction
521 list($newest) = SQL_FETCHROW($result);
522 $content['settings'] = getMaskedMessage('TRANSFER_LATEST_IS', generateDateTime($newest, 3));
525 $content['settings'] = loadTemplate('member_transfer_settings', true, $content);
529 SQL_FREERESULT($result);
532 loadTemplate('member_transfer_overview', false, $content);