2 /************************************************************************
3 * MXChange v0.2.1 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 * For more information visit: http://www.mxchange.org *
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. *
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. *
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, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
42 } elseif (!isMember()) {
43 redirectToIndexMemberOnlyModule();
46 // Add description as navigation point
47 addMenuDescription('member', __FILE__);
49 if ((!isExtensionActive('transfer')) && (!isAdmin())) {
50 loadTemplate('admin_settings_saved', false, generateExtensionInactiveNotInstalledMessage('transfer'));
55 if (!fetchUserData(getMemberId())) {
56 // Something really bad happened
57 debug_report_bug('No user account ' . getMemberId() . ' found.');
60 // Check for mode in GET
62 if (isGetRequestElementSet('mode')) $mode = getRequestElement('mode');
65 if ((getUserData('opt_in') != 'Y') && ($mode == 'new')) $mode = '';
68 case 'new': // Start new transfer
69 // Get total points and subtract the balance amount from it = maximum transferable points
70 $total = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
72 // Remember maximum value for template
73 $content['max_transferable'] = round($total - getConfig('transfer_balance') - 0.5);
77 if (getConfig('transfer_code') > 0) {
79 $code = generateRandomCode(getConfig('transfer_code'), postRequestElement('code_chk'), getMemberId(), $content['max_transferable']);
80 $valid_code = ($code == postRequestElement('code'));
82 // Zero length (= disabled) is always valid!
87 $valid_pass = ($pass == generateHash(postRequestElement('password'), $pass));
89 // Test transfer amount
90 $valid_amount = ((isPostRequestElementSet('points')) && (postRequestElement('points') <= $content['max_transferable']));
92 // Test reason for transfer
93 $valid_reason = (isPostRequestElementSet('reason'));
95 // Test if a recipient is selected
96 $valid_recipient = (postRequestElement('to_userid') > 0);
98 // Check for nickname extension and set additional data
99 // @TODO Rewrite this to a filter
101 if (isExtensionActive('nickname')) {
102 $add = ', `nickname`';
105 // Re-check receivers and own personal data
106 $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",
109 bigintval(postRequestElement('to_userid'))
110 ), __FILE__, __LINE__);
112 // Do we have two entries?
113 $valid_data = (SQL_NUMROWS($result) == 2);
115 // Final check if all is fine
116 if ($valid_code && $valid_data && $valid_pass && $valid_amount && $valid_reason && $valid_recipient) {
117 // Let's start the transfer and load user data
118 $content['sender'] = SQL_FETCHARRAY($result);
119 $content['recipient'] = SQL_FETCHARRAY($result);
121 // Is the nickname extension not installed?
122 if (!isExtensionActive('nickname')) {
123 // Fix empty nicknames
124 $content['sender']['nickname'] = '';
125 $content['recipient']['nickname'] = '';
128 // Translate some data
129 $content['sender']['gender'] = translateGender($content['sender']['gender']);
130 $content['recipient']['gender'] = translateGender($content['recipient']['gender']);
132 // Prepare variables for testing
133 $TEST_NICK_SENDER = $content['sender']['nickname'];
134 $TEST_NICK_REC = $content['recipient']['nickname'];
136 // Default is userids for subject line
137 $SENDER = getMemberId();
138 $RECIPIENT = bigintval(postRequestElement('to_userid'));
140 // If nickname is installed we can set the nickname
141 // @TODO Rewrite this to a filter
142 if (isExtensionActive('nickname')) {
143 if (($TEST_NICK_SENDER != getMemberId()) && (!empty($TEST_NICK_SENDER))) {
144 $SENDER = $content['sender']['nickname'];
147 if (($TEST_NICK_REC != postRequestElement('to_userid')) && (!empty($TEST_NICK_REC))) {
148 $RECIPIENT = $content['recipient']['nickname'];
152 // Remember transfer reason and fancy date/time in constants
153 $content['reason'] = secureString(postRequestElement('reason'));
154 $content['expires'] = createFancyTime(getConfig('transfer_age'));
156 // Generate tranafer id
157 $content['trans_id'] = bigintval(generateRandomCode('10', mt_rand(0, 99999), getMemberId(), postRequestElement('reason')));
159 // Add entries to both tables
160 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')",
161 array(bigintval(postRequestElement('to_userid')), getMemberId(), bigintval(postRequestElement('points')), postRequestElement('reason'), $content['trans_id']), __FILE__, __LINE__);
162 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')",
163 array(getMemberId(), bigintval(postRequestElement('to_userid')), bigintval(postRequestElement('points')), postRequestElement('reason'), $content['trans_id']), __FILE__, __LINE__);
165 // Add points to account *directly* ...
166 addPointsDirectly('member_transfer', bigintval(postRequestElement('to_userid')), bigintval(postRequestElement('points')));
168 // ... and add it to current user's used points
169 subtractPoints('transfer', getMemberId(), postRequestElement('points'));
171 // First send email to recipient
172 $message = loadEmailTemplate('member_transfer_recipient', $content, postRequestElement('to_userid'));
173 sendEmail($content['recipient']['email'], getMessage('TRANSFER_MEMBER_RECIPIENT_SUBJ') . ': ' . $SENDER, $message);
175 // Second send email to sender
176 $message = loadEmailTemplate('member_transfer_sender', $content, getMemberId());
177 sendEmail($content['sender']['email'], getMessage('TRANSFER_MEMBER_SENDER_SUBJ') . ': ' . $RECIPIENT, $message);
179 // At last send admin mail(s)
180 $ADMIN_SUBJ = sprintf("%s (%s->%s)", getMessage('TRANSFER_ADMIN_SUBJECT'), $SENDER, $RECIPIENT);
181 sendAdminNotification($ADMIN_SUBJ, 'admin_transfer_points', $content);
183 // Transfer is completed
184 loadTemplate('admin_settings_saved', false, getMessage('TRANSFER_COMPLETED') . "<br /><a href=\"{?URL?}/modules.php?module=login&what=transfer\">{--TRANSFER_CONTINUE_OVERVIEW--}</a>");
185 } elseif ($valid_code === false) {
186 // Invalid Touring code!
187 loadTemplate('admin_settings_saved', false, "<div class=\"member_note\">{--TRANSFER_INVALID_CODE--}</div>");
188 unsetPostRequestElement('ok');
189 } elseif ($valid_pass === false) {
190 // Wrong password entered
191 loadTemplate('admin_settings_saved', false, "<div class=\"member_note\">{--TRANSFER_INVALID_PASSWORD--}</div>");
192 unsetPostRequestElement('ok');
193 } elseif ($valid_amount === false) {
194 // Too much points entered
195 loadTemplate('admin_settings_saved', false, "<div class=\"member_note\">{--TRANSFER_INVALID_POINTS--}</div>");
196 unsetPostRequestElement('ok');
197 } elseif ($valid_reason === false) {
198 // No transfer reason entered
199 loadTemplate('admin_settings_saved', false, "<div class=\"member_note\">{--TRANSFER_INVALID_REASON--}</div>");
200 unsetPostRequestElement('ok');
201 } elseif ($valid_recipient === false) {
202 // No recipient selected
203 loadTemplate('admin_settings_saved', false, "<div class=\"member_note\">{--TRANSFER_INVALID_RECIPIENT--}</div>");
204 unsetPostRequestElement('ok');
205 } elseif ($valid_data === false) {
206 // No recipient/sender selected
207 loadTemplate('admin_settings_saved', false, "<div class=\"member_note\">{--TRANSFER_INVALID_DATA--}</div>");
208 unsetPostRequestElement('ok');
212 SQL_FREERESULT($result);
217 if (isExtensionActive('nickname')) {
218 // Load userid and nickname
219 $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",
220 array(getMemberId()), __FILE__, __LINE__);
223 $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",
224 array(getMemberId()), __FILE__, __LINE__);
227 if (SQL_NUMROWS($result) > 0) {
229 $OUT = "<select name=\"to_userid\" size=\"1\" class=\"member_select\">
230 <option value=\"0\">{--SELECT_NONE--}</option>\n";
231 // @TODO Try to rewrite his to $content = SQL_FETCHARRAY(), see some lines above for two different queries
232 while (list($userid, $nick) = SQL_FETCHROW($result)) {
233 $OUT .= " <option value=\"".$userid."\"";
234 if ((isPostRequestElementSet(('to_userid'))) && (postRequestElement('to_userid') == $userid)) $OUT .= ' selected="selected"';
236 if (($nick != $userid) && (!empty($nick))) {
243 $OUT .= "</option>\n";
245 $OUT .= "</select>\n";
246 $content['to_disabled'] = '';
249 SQL_FREERESULT($result);
251 // No one else is opt-in
252 $OUT = loadTemplate('admin_settings_saved', true, getMessage('TRANSFER_NO_ONE_ELSE_OPT_IN'));
253 $content['to_disabled'] = ' disabled="disabled"';
256 // Transfer output to constant for the template
257 $content['userid_selection'] = $OUT;
260 if (getConfig('transfer_code') > 0) {
261 $rand = mt_rand(0, 99999);
262 $code = generateRandomCode(getConfig('transfer_code'), $rand, getMemberId(), $content['max_transferable']);
263 $img = generateImageOrCode($code, false);
264 $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;
267 $content['captcha_code'] = loadTemplate('admin_settings_saved', true, getMessage('TRANSFER_NO_CODE'));
270 // Init points/reason
271 $content['points'] = '';
272 $content['reason'] = '';
274 // Transfer maybe already entered valued'
275 if (isGetRequestElementSet('ok')) {
276 // Get values from form
277 $content['points'] = bigintval(postRequestElement('points'));
278 $content['reason'] = secureString(postRequestElement('reason'));
281 // Translate some array elements for template
282 $content['max_transferable'] = translateComma($content['max_transferable']);
285 loadTemplate('member_transfer_new', false, $content);
289 case 'list_in': // List only incoming transactions
290 case 'list_out': // List only outgoing transactions
291 // 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
292 $nothingMessage = '';
295 $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 ".getConfig('transfer_max');
296 $nothingMessage = getMessage('TRANSFER_NO_INCOMING_TRANSFERS');
297 $content['balance'] = getMessage('TRANSFER_TOTAL_INCOMING');
298 $content['title'] = getMessage('TRANSFER_LIST_INCOMING');
302 $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 ".getConfig('transfer_max');
303 $nothingMessage = getMessage('TRANSFER_NO_OUTGOING_TRANSFERS');
304 $content['balance'] = getMessage('TRANSFER_TOTAL_OUTGOING');
305 $content['title'] = getMessage('TRANSFER_LIST_OUTGOING');
309 // Run the SQL command and set total points to zero
311 $result = SQL_QUERY_ESC($sql, array(getMemberId()), __FILE__, __LINE__);
313 // Do we have entries?
314 if (SQL_NUMROWS($result) > 0) {
316 // @TODO This should be somehow rewritten to $row = SQL_FETCHARRAY(), see switch() block above for SQL queries
317 while (list($tid, $userid, $points, $reason, $stamp) = SQL_FETCHROW($result)) {
319 if ($type == 'OUT') $points = $points . '-';
321 // Prepare content for template
322 // @TODO Rewrite: tid->trans_id,stamp->time_trans
326 'stamp' => generateDateTime($stamp, 3),
329 'points' => translateComma($points)
333 $OUT .= loadTemplate('member_transfer_row2', true, $row);
335 // Add points and switch color
336 $totalPoints += $points;
341 SQL_FREERESULT($result);
343 // Nothing for in or out
345 <td colspan=\"5\" align=\"center\" class=\"bottom2\" height=\"70\">
346 ".loadTemplate('admin_settings_saved', true, $nothingMessage)."
351 // ... and add them to a constant for the template
352 $content['rows'] = $OUT;
354 // Remeber total amount
355 $content['total'] = translateComma($totalPoints);
357 // Load final template
358 loadTemplate('member_transfer_list', false, $content);
361 case 'list_all': // List all transactions
362 // We fill a temporary table with data from both tables. This is much easier
363 // to code and unstand by you as sub-SELECT queries. I know this is not the
364 // fastest way but it shall be fine for now.
366 // First of all create the temporary table
367 $result = SQL_QUERY("CREATE TEMPORARY TABLE `{?_MYSQL_PREFIX?}_transfers_tmp` (
368 `trans_id` VARCHAR(12) NOT NULL DEFAULT '',
369 `party_userid` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
370 `points` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
371 `reason` VARCHAR(255) NOT NULL DEFAULT '',
372 `time_trans` VARCHAR(10) NOT NULL DEFAULT 0,
373 `trans_type` ENUM('IN','OUT') NOT NULL DEFAULT 'IN',
375 ) TYPE=HEAP", __FILE__, __LINE__);
377 // Let's begin with the incoming list
378 $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?}",
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);
389 // As the last table transfer data from outgoing table to temporary
390 $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?}",
391 array(getMemberId()), __FILE__, __LINE__);
392 while ($DATA = SQL_FETCHROW($result)) {
394 $DATA = implode("','", $DATA);
395 $res_temp = SQL_QUERY("INSERT INTO `{?_MYSQL_PREFIX?}_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('".$DATA."')", __FILE__, __LINE__);
399 SQL_FREERESULT($result);
402 if (SQL_NUMROWS($result) > 0) {
403 // Search for entries
404 $result = SQL_QUERY("SELECT `party_userid`, `trans_id`, `points`, `reason`, `time_trans`, `trans_type` FROM `{?_MYSQL_PREFIX?}_transfers_tmp` ORDER BY `time_trans` DESC",
409 while ($content = SQL_FETCHARRAY($result)) {
411 if ($content['trans_type'] == 'OUT') $content['points'] = '-'.$content['points']."";
413 // Prepare content for template
414 $content['sw'] = $SW;
415 $content['time'] = generateDateTime($content['time_trans'], 3);
416 $content['points'] = translateComma($content['points']);
419 $OUT .= loadTemplate('member_transfer_row', true, $content);
421 // Add points and switch color
422 $total += $content['points'];
427 SQL_FREERESULT($result);
429 // Nothing for in and out
431 <td colspan=\"5\" align=\"center\" class=\"bottom2\" height=\"70\">
432 ".loadTemplate('admin_settings_saved', true, getMessage('TRANSFER_NO_INOUT_TRANSFERS'))."
437 // ... and add them to a constant for the template
438 $content['rows'] = $OUT;
440 // Remeber total amount
441 $content['total'] = translateComma($total);
444 $content['title'] = getMessage('TRANSFER_LIST_ALL');
446 // Set "balance" word
447 $content['balance'] = getMessage('TRANSFER_TOTAL_BALANCE');
449 // At the end we don't need a temporary table in memory
450 $result = SQL_QUERY("DROP TABLE IF EXISTS `{?_MYSQL_PREFIX?}_transfers_tmp`", __FILE__, __LINE__);
452 // Load final template
453 loadTemplate('member_transfer_list', false, $content);
455 // Free some memory...
456 SQL_FREERESULT($result);
459 default: // Overview page
460 // Check incoming transfers
461 $total = countSumTotalData(getMemberId(), 'user_transfers_in', 'id', 'userid', true);
462 $content['in_link'] = $total;
464 $content['in_link'] = "<a href=\"{?URL?}/modules.php?module=login&what=transfer&mode=list_in\">".$total."</a>";
467 // Check outgoing transfers
468 $dmy = countSumTotalData(getMemberId(), 'user_transfers_out', 'id', 'userid', true);
470 // Add to total amount
473 $content['out_link'] = $dmy;
475 $content['out_link'] = "<a href=\"{?URL?}/modules.php?module=login&what=transfer&mode=list_out\">".$dmy."</a>";
478 // Total transactions
479 $content['all_link'] = $total;
481 $content['all_link'] = "<a href=\"{?URL?}/modules.php?module=login&what=transfer&mode=list_all\">".$total."</a>";
486 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `opt_in`='%s' WHERE `userid`=%s LIMIT 1",
487 array(postRequestElement('opt_in'), getMemberId()), __FILE__, __LINE__);
489 // Rember for next switch() command
490 getUserData('opt_in') = substr(postRequestElement('opt_in'), 0, 1);
492 // "Settings saved..."
493 loadTemplate('admin_settings_saved', false, "<div class=\"member_done\">{--SETTINGS_SAVED--}</div>");
497 foreach (array('allow_y','allow_n') as $entry) {
498 $content[$entry] = '';
501 // Set current selection
502 $content['allow_' . strtolower(getUserData('opt_in'))] = ' checked="checked"';
504 // Set 'new transfer' link according to above option
505 switch (getUserData('opt_in')) {
507 $content['new_link'] = "<a href=\"{?URL?}/modules.php?module=login&what=transfer&mode=new\">{--TRANSFER_NOW_LINK--}</a>";
511 $content['new_link'] = getMessage('TRANSFER_PLEASE_ALLOW_OPT_IN');
515 // Check for latest out-transfers
516 $result = SQL_QUERY_ESC("SELECT
519 `{?_MYSQL_PREFIX?}_user_transfers_out`
521 `time_trans` > (UNIX_TIMESTAMP() - %s) AND `userid`=%s
526 getConfig('transfer_timeout'),
528 ), __FILE__, __LINE__);
530 // Do we have an entry?
531 if (SQL_NUMROWS($result) == 1) {
532 // Load newest transaction
533 list($newest) = SQL_FETCHROW($result);
534 $content['settings'] = sprintf(getMessage('TRANSFER_LATEST_IS'), generateDateTime($newest, 3));
537 $content['settings'] = loadTemplate('member_transfer_settings', true, $content);
541 SQL_FREERESULT($result);
544 loadTemplate('member_transfer_overview', false, $content);