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 * 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'));
54 // Check for mode in GET
56 if (isGetRequestElementSet('mode')) $mode = getRequestElement('mode');
59 if ((getUserData('opt_in') != 'Y') && ($mode == 'new')) $mode = '';
62 case 'new': // Start new transfer
63 // Get total points and subtract the balance amount from it = maximum transferable points
64 $total = countSumTotalData(getMemberId(), 'user_points', 'points') - countSumTotalData(getMemberId(), 'user_data', 'used_points');
66 // Remember maximum value for template
67 $content['max_transferable'] = round($total - getConfig('transfer_balance') - 0.5);
71 if (getConfig('transfer_code') > 0) {
73 $code = generateRandomCode(getConfig('transfer_code'), postRequestElement('code_chk'), getMemberId(), $content['max_transferable']);
74 $valid_code = ($code == postRequestElement('code'));
76 // Zero length (= disabled) is always valid!
81 $valid_pass = ($pass == generateHash(postRequestElement('password'), $pass));
83 // Test transfer amount
84 $valid_amount = ((isPostRequestElementSet('points')) && (postRequestElement('points') <= $content['max_transferable']));
86 // Test reason for transfer
87 $valid_reason = (isPostRequestElementSet('reason'));
89 // Test if a recipient is selected
90 $valid_recipient = (postRequestElement('to_userid') > 0);
92 // Check for nickname extension and set additional data
93 // @TODO Rewrite this to a filter
95 if (isExtensionActive('nickname')) {
96 $add = ', `nickname`';
99 // Re-check receivers and own personal data
100 $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",
103 bigintval(postRequestElement('to_userid'))
104 ), __FILE__, __LINE__);
106 // Do we have two entries?
107 $valid_data = (SQL_NUMROWS($result) == 2);
109 // Final check if all is fine
110 if ($valid_code && $valid_data && $valid_pass && $valid_amount && $valid_reason && $valid_recipient) {
111 // Let's start the transfer and load user data
112 $content['sender'] = SQL_FETCHARRAY($result);
113 $content['recipient'] = SQL_FETCHARRAY($result);
115 // Is the nickname extension not installed?
116 if (!isExtensionActive('nickname')) {
117 // Fix empty nicknames
118 $content['sender']['nickname'] = '';
119 $content['recipient']['nickname'] = '';
122 // Translate some data
123 $content['sender']['gender'] = translateGender($content['sender']['gender']);
124 $content['recipient']['gender'] = translateGender($content['recipient']['gender']);
126 // Prepare variables for testing
127 $TEST_NICK_SENDER = $content['sender']['nickname'];
128 $TEST_NICK_REC = $content['recipient']['nickname'];
130 // Default is userids for subject line
131 $SENDER = getMemberId();
132 $RECIPIENT = bigintval(postRequestElement('to_userid'));
134 // If nickname is installed we can set the nickname
135 // @TODO Rewrite this to a filter
136 if (isExtensionActive('nickname')) {
137 if (($TEST_NICK_SENDER != getMemberId()) && (!empty($TEST_NICK_SENDER))) {
138 $SENDER = $content['sender']['nickname'];
141 if (($TEST_NICK_REC != postRequestElement('to_userid')) && (!empty($TEST_NICK_REC))) {
142 $RECIPIENT = $content['recipient']['nickname'];
146 // Remember transfer reason and fancy date/time in constants
147 $content['reason'] = secureString(postRequestElement('reason'));
148 $content['expires'] = createFancyTime(getConfig('transfer_age'));
150 // Generate tranafer id
151 $content['trans_id'] = bigintval(generateRandomCode('10', mt_rand(0, 99999), getMemberId(), postRequestElement('reason')));
153 // Add entries to both tables
154 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')",
155 array(bigintval(postRequestElement('to_userid')), getMemberId(), bigintval(postRequestElement('points')), postRequestElement('reason'), $content['trans_id']), __FILE__, __LINE__);
156 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')",
157 array(getMemberId(), bigintval(postRequestElement('to_userid')), bigintval(postRequestElement('points')), postRequestElement('reason'), $content['trans_id']), __FILE__, __LINE__);
159 // Add points to account *directly* ...
160 addPointsDirectly('member_transfer', bigintval(postRequestElement('to_userid')), bigintval(postRequestElement('points')));
162 // ... and add it to current user's used points
163 subtractPoints('transfer', getMemberId(), postRequestElement('points'));
165 // First send email to recipient
166 $message = loadEmailTemplate('member_transfer_recipient', $content, postRequestElement('to_userid'));
167 sendEmail($content['recipient']['email'], getMessage('TRANSFER_MEMBER_RECIPIENT_SUBJ') . ': ' . $SENDER, $message);
169 // Second send email to sender
170 $message = loadEmailTemplate('member_transfer_sender', $content, getMemberId());
171 sendEmail($content['sender']['email'], getMessage('TRANSFER_MEMBER_SENDER_SUBJ') . ': ' . $RECIPIENT, $message);
173 // At last send admin mail(s)
174 $adminSubject = sprintf("%s (%s->%s)", getMessage('TRANSFER_ADMIN_SUBJECT'), $SENDER, $RECIPIENT);
175 sendAdminNotification($adminSubject, 'admin_transfer_points', $content);
177 // Transfer is completed
178 loadTemplate('admin_settings_saved', false, getMessage('TRANSFER_COMPLETED') . "<br /><a href=\"{%url=modules.php?module=login&what=transfer%}\">{--TRANSFER_CONTINUE_OVERVIEW--}</a>");
179 } elseif ($valid_code === false) {
180 // Invalid Touring code!
181 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_CODE--}</div>');
182 unsetPostRequestElement('ok');
183 } elseif ($valid_pass === false) {
184 // Wrong password entered
185 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_PASSWORD--}</div>');
186 unsetPostRequestElement('ok');
187 } elseif ($valid_amount === false) {
188 // Too much points entered
189 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_POINTS--}</div>');
190 unsetPostRequestElement('ok');
191 } elseif ($valid_reason === false) {
192 // No transfer reason entered
193 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_REASON--}</div>');
194 unsetPostRequestElement('ok');
195 } elseif ($valid_recipient === false) {
196 // No recipient selected
197 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_RECIPIENT--}</div>');
198 unsetPostRequestElement('ok');
199 } elseif ($valid_data === false) {
200 // No recipient/sender selected
201 loadTemplate('admin_settings_saved', false, '<div class="member_note">{--TRANSFER_INVALID_DATA--}</div>');
202 unsetPostRequestElement('ok');
206 SQL_FREERESULT($result);
211 if (isExtensionActive('nickname')) {
212 // Load userid and nickname
213 $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",
214 array(getMemberId()), __FILE__, __LINE__);
217 $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",
218 array(getMemberId()), __FILE__, __LINE__);
221 if (SQL_NUMROWS($result) > 0) {
223 $OUT = "<select name=\"to_userid\" size=\"1\" class=\"member_select\">
224 <option value=\"0\">{--SELECT_NONE--}</option>\n";
225 // @TODO Try to rewrite his to $content = SQL_FETCHARRAY(), see some lines above for two different queries
226 while (list($userid, $nick) = SQL_FETCHROW($result)) {
227 $OUT .= " <option value=\"".$userid."\"";
228 if ((isPostRequestElementSet(('to_userid'))) && (postRequestElement('to_userid') == $userid)) $OUT .= ' selected="selected"';
230 if (($nick != $userid) && (!empty($nick))) {
237 $OUT .= "</option>\n";
239 $OUT .= "</select>\n";
240 $content['to_disabled'] = '';
243 SQL_FREERESULT($result);
245 // No one else is opt-in
246 $OUT = loadTemplate('admin_settings_saved', true, getMessage('TRANSFER_NO_ONE_ELSE_OPT_IN'));
247 $content['to_disabled'] = ' disabled="disabled"';
250 // Transfer output to constant for the template
251 $content['userid_selection'] = $OUT;
254 if (getConfig('transfer_code') > 0) {
255 $rand = mt_rand(0, 99999);
256 $code = generateRandomCode(getConfig('transfer_code'), $rand, getMemberId(), $content['max_transferable']);
257 $img = generateImageOrCode($code, false);
258 $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;
261 $content['captcha_code'] = loadTemplate('admin_settings_saved', true, getMessage('TRANSFER_NO_CODE'));
264 // Init points/reason
265 $content['points'] = '';
266 $content['reason'] = '';
268 // Transfer maybe already entered valued'
269 if (isGetRequestElementSet('ok')) {
270 // Get values from form
271 $content['points'] = bigintval(postRequestElement('points'));
272 $content['reason'] = secureString(postRequestElement('reason'));
275 // Translate some array elements for template
276 $content['max_transferable'] = translateComma($content['max_transferable']);
279 loadTemplate('member_transfer_new', false, $content);
283 case 'list_in': // List only incoming transactions
284 case 'list_out': // List only outgoing transactions
285 // 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
286 $nothingMessage = '';
289 $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');
290 $nothingMessage = getMessage('TRANSFER_NO_INCOMING_TRANSFERS');
291 $content['balance'] = getMessage('TRANSFER_TOTAL_INCOMING');
292 $content['title'] = getMessage('TRANSFER_LIST_INCOMING');
296 $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');
297 $nothingMessage = getMessage('TRANSFER_NO_OUTGOING_TRANSFERS');
298 $content['balance'] = getMessage('TRANSFER_TOTAL_OUTGOING');
299 $content['title'] = getMessage('TRANSFER_LIST_OUTGOING');
303 // Run the SQL command and set total points to zero
305 $result = SQL_QUERY_ESC($sql, array(getMemberId()), __FILE__, __LINE__);
307 // Do we have entries?
308 if (SQL_NUMROWS($result) > 0) {
310 // @TODO This should be somehow rewritten to $row = SQL_FETCHARRAY(), see switch() block above for SQL queries
311 while (list($tid, $userid, $points, $reason, $stamp) = SQL_FETCHROW($result)) {
313 if ($type == 'OUT') $points = $points . '-';
315 // Prepare content for template
316 // @TODO Rewrite: tid->trans_id,stamp->time_trans
320 'stamp' => generateDateTime($stamp, 3),
323 'points' => translateComma($points)
327 $OUT .= loadTemplate('member_transfer_row2', true, $row);
329 // Add points and switch color
330 $totalPoints += $points;
335 SQL_FREERESULT($result);
337 // Nothing for in or out
339 <td colspan=\"5\" align=\"center\" class=\"bottom\">
340 ".loadTemplate('admin_settings_saved', true, $nothingMessage)."
345 // ... and add them to a constant for the template
346 $content['rows'] = $OUT;
348 // Remeber total amount
349 $content['total'] = translateComma($totalPoints);
351 // Load final template
352 loadTemplate('member_transfer_list', false, $content);
355 case 'list_all': // List all transactions
356 // We fill a temporary table with data from both tables. This is much easier
357 // to code and unstand by you as sub-SELECT queries. I know this is not the
358 // fastest way but it shall be fine for now.
360 // First of all create the temporary table
361 $result = SQL_QUERY("CREATE TEMPORARY TABLE `{?_MYSQL_PREFIX?}_transfers_tmp` (
362 `trans_id` VARCHAR(12) NOT NULL DEFAULT '',
363 `party_userid` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
364 `points` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
365 `reason` VARCHAR(255) NOT NULL DEFAULT '',
366 `time_trans` VARCHAR(10) NOT NULL DEFAULT 0,
367 `trans_type` ENUM('IN','OUT') NOT NULL DEFAULT 'IN',
369 ) TYPE=HEAP", __FILE__, __LINE__);
371 // Let's begin with the incoming list
372 $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?}",
373 array(getMemberId()), __FILE__, __LINE__);
374 while ($DATA = SQL_FETCHROW($result)) {
376 $DATA = implode("','", $DATA);
377 $res_temp = SQL_QUERY("INSERT INTO `{?_MYSQL_PREFIX?}_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('".$DATA."')", __FILE__, __LINE__);
381 SQL_FREERESULT($result);
383 // As the last table transfer data from outgoing table to temporary
384 $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?}",
385 array(getMemberId()), __FILE__, __LINE__);
386 while ($DATA = SQL_FETCHROW($result)) {
388 $DATA = implode("','", $DATA);
389 $res_temp = SQL_QUERY("INSERT INTO `{?_MYSQL_PREFIX?}_transfers_tmp` (`trans_id`, `party_userid`, `points`, `reason`, `time_trans`, `trans_type`) VALUES ('".$DATA."')", __FILE__, __LINE__);
393 SQL_FREERESULT($result);
396 if (SQL_NUMROWS($result) > 0) {
397 // Search for entries
398 $result = SQL_QUERY("SELECT `party_userid`, `trans_id`, `points`, `reason`, `time_trans`, `trans_type` FROM `{?_MYSQL_PREFIX?}_transfers_tmp` ORDER BY `time_trans` DESC",
403 while ($content = SQL_FETCHARRAY($result)) {
405 if ($content['trans_type'] == 'OUT') $content['points'] = '-'.$content['points']."";
407 // Prepare content for template
408 $content['sw'] = $SW;
409 $content['time'] = generateDateTime($content['time_trans'], 3);
410 $content['points'] = translateComma($content['points']);
413 $OUT .= loadTemplate('member_transfer_row', true, $content);
415 // Add points and switch color
416 $total += $content['points'];
421 SQL_FREERESULT($result);
423 // Nothing for in and out
425 <td colspan=\"5\" align=\"center\" class=\"bottom\">
426 ".loadTemplate('admin_settings_saved', true, getMessage('TRANSFER_NO_INOUT_TRANSFERS'))."
431 // ... and add them to a constant for the template
432 $content['rows'] = $OUT;
434 // Remeber total amount
435 $content['total'] = translateComma($total);
438 $content['title'] = getMessage('TRANSFER_LIST_ALL');
440 // Set "balance" word
441 $content['balance'] = getMessage('TRANSFER_TOTAL_BALANCE');
443 // At the end we don't need a temporary table in memory
444 $result = SQL_QUERY("DROP TABLE IF EXISTS `{?_MYSQL_PREFIX?}_transfers_tmp`", __FILE__, __LINE__);
446 // Load final template
447 loadTemplate('member_transfer_list', false, $content);
449 // Free some memory...
450 SQL_FREERESULT($result);
453 default: // Overview page
454 // Check incoming transfers
455 $total = countSumTotalData(getMemberId(), 'user_transfers_in', 'id', 'userid', true);
456 $content['in_link'] = $total;
458 $content['in_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=list_in%}">' . $total . '</a>';
461 // Check outgoing transfers
462 $dmy = countSumTotalData(getMemberId(), 'user_transfers_out', 'id', 'userid', true);
464 // Add to total amount
467 $content['out_link'] = $dmy;
469 $content['out_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=list_out%}">' . $dmy . '</a>';
472 // Total transactions
473 $content['all_link'] = $total;
475 $content['all_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=list_all%}">' . $total . '</a>';
480 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `opt_in`='%s' WHERE `userid`=%s LIMIT 1",
481 array(postRequestElement('opt_in'), getMemberId()), __FILE__, __LINE__);
483 // Rember for next switch() command
484 getUserData('opt_in') = substr(postRequestElement('opt_in'), 0, 1);
486 // "Settings saved..."
487 loadTemplate('admin_settings_saved', false, '<div class="member_done">{--SETTINGS_SAVED--}</div>');
491 foreach (array('allow_y','allow_n') as $entry) {
492 $content[$entry] = '';
495 // Set current selection
496 $content['allow_' . strtolower(getUserData('opt_in'))] = ' checked="checked"';
498 // Set 'new transfer' link according to above option
499 switch (getUserData('opt_in')) {
501 $content['new_link'] = '<a href="{%url=modules.php?module=login&what=transfer&mode=new%}" title="{--TRANSFER_NOW_TITLE--}">{--TRANSFER_NOW_LINK--}</a>';
505 $content['new_link'] = getMessage('TRANSFER_PLEASE_ALLOW_OPT_IN');
509 // Check for latest out-transfers
510 $result = SQL_QUERY_ESC("SELECT
513 `{?_MYSQL_PREFIX?}_user_transfers_out`
515 `time_trans` > (UNIX_TIMESTAMP() - %s) AND `userid`=%s
520 getConfig('transfer_timeout'),
522 ), __FILE__, __LINE__);
524 // Do we have an entry?
525 if (SQL_NUMROWS($result) == 1) {
526 // Load newest transaction
527 list($newest) = SQL_FETCHROW($result);
528 $content['settings'] = getMaskedMessage('TRANSFER_LATEST_IS', generateDateTime($newest, 3));
531 $content['settings'] = loadTemplate('member_transfer_settings', true, $content);
535 SQL_FREERESULT($result);
538 loadTemplate('member_transfer_overview', false, $content);