debug_report_bug() should be used as a replacement for app_die() calls
[mailer.git] / inc / libs / bonus_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 11/10/2004 *
4  * ===================                          Last change: 03/18/2005 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : bonus_functions.php                              *
8  * -------------------------------------------------------------------- *
9  * Short description : Special functions for bonus extension            *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Spezielle Funktion fuer bonus-Erweiterung        *
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  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
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.                                  *
28  *                                                                      *
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.                         *
33  *                                                                      *
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,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // This function must be run *BEFORE* a link is removed from table 'mxchange_user_links' !
46 function addTurboBonus ($mid, $userid, $type) {
47         // Shall we add bonus points?
48         if (getConfig('bonus_active') != 'Y') return false;
49
50         // Init variables
51         $sql = ''; $bonus = '0'; $mail = '0'; $column = '';
52
53         // Select SQL command
54         switch ($type) {
55                 case 'bonusid':
56                         $column = 'bonus_id';
57                         $bonus = $mid;
58                         break;
59
60                 case 'mailid' :
61                         $column = 'mail_id';
62                         $mail = $mid;
63                         break;
64
65                 default:
66                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid type %s detected.", $type));
67                         break;
68         }
69
70         // Is a column name set?
71         if (empty($column)) {
72                 // No, then abort here
73                 return false;
74         } // END - if
75
76         // Check for entry
77         $rank = countSumTotalData($mid, 'bonus_turbo', 'id', $column, true) + 1;
78
79         // Which rank?
80         if ($rank == 1) {
81                 // First rank!
82                 $points = getConfig('turbo_bonus');
83         } else {
84                 // Anything else so let's explode all entered rank points
85                 $test = explode(';', getConfig('turbo_rates'));
86                 if (!empty($test[$rank - 2])) {
87                         // Level found
88                         $points = $test[$rank - 2];
89                 } else {
90                         // Level not found!
91                         $points = '0.00000';
92                 }
93         }
94
95         // Add points to his account directly
96         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `turbo_bonus`=`turbo_bonus`+%s WHERE `userid`=%s LIMIT 1",
97                 array(
98                         bigintval($userid),
99                         $points
100                 ), __FUNCTION__, __LINE__);
101
102         // Rember this whole data for displaying ranking list
103         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_bonus_turbo` (`userid`, `mail_id`, `bonus_id`, `level`, `points`, `timemark`) VALUES (%s, %s, %s, %s, %s, UNIX_TIMESTAMP())",
104                 array(
105                         bigintval($userid),
106                         bigintval($mail),
107                         bigintval($bonus),
108                         $rank,
109                         $points
110                 ), __FUNCTION__, __LINE__);
111
112         if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getConfig('bonus_mode') != 'ADD') && ($points > 0)) handleBonusPoints($points);
113 }
114
115 //
116 function addBonusRanks ($data, $type, $userid) {
117         // Init variables
118         $self = false; $OUT = ''; $GLOBALS['ranking_content'] = array();
119
120         // Clear rankings by default
121         $GLOBALS['ranking_content']['rankings'] = '';
122
123         // How many ranks do we have?
124         $ranks = count(explode(';', getConfig('turbo_rates'))) + 1;
125
126         // Load current user's data
127         $result = SQL_QUERY_ESC("SELECT `level`, `points`, `timemark` FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE `%s`=%s AND `userid`=%s LIMIT 1",
128                 array(
129                         $type,
130                         $data,
131                         $userid
132                 ), __FUNCTION__, __LINE__);
133
134         // Entry found?
135         if (SQL_NUMROWS($result) == 1) {
136                 // Load data
137                 $GLOBALS['ranking_content'] = merge_array($GLOBALS['ranking_content'], SQL_FETCHARRAY($result));
138
139                 // Remember all values for later use
140                 $self  = true;
141
142                 // Transfer data to template
143                 $GLOBALS['ranking_content']['yr_level']  = $GLOBALS['ranking_content']['level'];
144                 $GLOBALS['ranking_content']['yr_points'] = translateComma($GLOBALS['ranking_content']['points']);
145                 $GLOBALS['ranking_content']['yr_tmark']  = generateDateTime($GLOBALS['ranking_content']['timemark'], 1);
146
147                 // Load template
148                 $GLOBALS['ranking_content']['own'] = loadTemplate('show_bonus_yr', true, $GLOBALS['ranking_content']);
149         } // END - if
150
151         // Load rankings
152         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE %s=%s ORDER BY `level` ASC LIMIT {?bonus_lines?}",
153                 array($type, $data), __FUNCTION__, __LINE__);
154         if (SQL_NUMROWS($result) > 0) {
155                 // Start generating the ranking list
156                 $max = SQL_NUMROWS($result);
157
158                 // Init variables
159                 $SW = 2;
160
161                 // Output all ranks (levels)
162                 for ($rank = 1; $rank <= $max; $rank++) {
163                         // Load data
164                         $result_users = SQL_QUERY_ESC("SELECT
165         `userid`, `points`
166 FROM
167         `{?_MYSQL_PREFIX?}_bonus_turbo`
168 WHERE
169         `%s`=%s AND
170         `level`=%s
171 LIMIT 1",
172                                 array($type, $data, $rank), __FUNCTION__, __LINE__);
173
174                         // Nothing found by default
175                         $rows['userid'] = '---';
176                         $rows['points'] = '---';
177
178                         // Are you one of them?
179                         if (SQL_NUMROWS($result_users) == 1) {
180                                 // Load data
181                                 $rows = merge_array($rows, SQL_FETCHARRAY($result_users));
182
183                                 // Is ext-nickname active?
184                                 if (isExtensionActive('nickname')) {
185                                         // Then get the nickname
186                                         $nick = getNickname($rows['userid']);
187
188                                         // Is it not empty? Then use it
189                                         if (!empty($nick)) $rows['userid'] = $nick;
190                                 } // END - if
191                         } // END - if
192
193                         // Free result
194                         SQL_FREERESULT($result_users);
195
196                         // Add more
197                         $rows['rank'] = $rank;
198                         $rows['sw']   = $SW;
199
200                         // Output row
201                         $OUT .= "<tr>
202   <td class=\"bonus_rank_".$rows['rank']." bottom switch_sw".$rows['sw']."\">".$rows['rank'].".</td>
203   <td class=\"bonus_rank_".$rows['rank']." bottom switch_sw".$rows['sw']."\" align=\"center\">".$rows['userid']."</td>
204   <td class=\"bonus_rank_".$rows['rank']." bottom switch_sw".$rows['sw']."\" align=\"center\">{%pipe,translateComma=".$rows['points']."%}</td>
205 </tr>\n";
206
207                         // Switch color
208                         $SW = 3 - $SW;
209                 } // END - for
210
211                 if ($self === false) {
212                         // If current user was not found set constant
213                         // @TODO Try to find a way for rewriting this constant
214                         $GLOBALS['ranking_content']['rankings'] = getMessage('BONUS_RANK_YOU_ARE_404');
215                 } // END - if
216         } else {
217                 // No entries found!
218                 $OUT = "<tr>
219   <td colspan=\"3\" align=\"center\" height=\"30\" class=\"bottom\">
220     <div class=\"guest_failed\">".getMaskedMessage('BONUS_NO_RANKS', $data)."</div>
221   </td>
222 </tr>\n";
223         }
224
225         // Retutn content
226         return $OUT;
227 }
228
229 //
230 function handleBonusPoints ($mode) {
231         // Shall we add bonus points?
232         if (getConfig('bonus_active') != 'Y') return;
233
234         // Switch to jackpot-mode when no UID is supplied but userid-mode is selected
235         if ((getConfig('bonus_mode') == 'UID') && (getConfig('bonus_userid') == '0') && (isExtensionActive('jackpot'))) {
236                 // Update database & config
237                 updateConfiguration('bonus_mode', 'JACKPOT');
238         } // END - if
239
240         if ($mode == 'login_bonus') {
241                 // Login bonus detected
242                 $points = getConfig('login_bonus');
243         } else {
244                 // Direct points supplied
245                 $points = $mode;
246         }
247
248         // Check his amount first
249         $total = countSumTotalData(getConfig('bonus_userid'), 'user_points', 'points') - countSumTotalData(getConfig('bonus_userid'), 'user_data', 'used_points');
250
251         // Subtract points from...
252         switch (getConfig('bonus_mode')) {
253                 case 'JACKPOT': // ... jackpot
254                         if ((isExtensionActive('jackpot')) && (subtractPointsFromJackpot($points) == -1) && (getConfig('bonus_userid') > 0)) {
255                                 if ($total >= $points) {
256                                         // Subtract points from userid's account
257                                         subtractPointsFromJackpot('bonus_payout_jackpot', getConfig('bonus_userid'), $points);
258                                 } // END - if
259                         } // END - if
260                         break;
261
262                 case 'UID': // ... userid's account
263                         if ($total >= $points) {
264                                 // Subtract points from userid's account
265                                 subtractPoints('bonus_payout_userid', getConfig('bonus_userid'), $points);
266                         } elseif (isExtensionActive('jackpot')) {
267                                 // Try to subtract from jackpot
268                                 $dummy = subtractPointsFromJackpot($points);
269                         }
270                         break;
271         } // END - switch
272 }
273
274 // Purges expired fast-click bonus entries
275 function purgeExpiredTurboBonus() {
276         // Remove entries
277         $result = SQL_QUERY("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE `timemark` < (UNIX_TIMESTAMP() - {?bonus_timeout?})", __FUNCTION__, __LINE__);
278
279         if (SQL_AFFECTEDROWS() > 0) {
280                 // Send out email to admin
281                 sendAdminNotification(getMessage('AUTOPURGE_ADMIN_TURBO_SUBJECT'), 'admin_autopurge_turbo', SQL_AFFECTEDROWS());
282         } // END - if
283 }
284
285 ///////////////////////////////////////////////////////////////////////////////
286 //                              Only filter functions
287 ///////////////////////////////////////////////////////////////////////////////
288
289 // Filter for adding login bonus to the user's account
290 function FILTER_ADD_LOGIN_BONUS () {
291         // Is the user data valid?
292         if (!isMember()) {
293                 // Do only run for logged in members
294                 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
295         } // END - if
296
297         // Bonus is not given by default ;-)
298         $bonus = false;
299         if ((isExtensionInstalledAndNewer('sql_patches', '0.2.8')) && (getConfig('bonus_active') == 'Y') && (getConfig('bonus_login_yn') == 'Y')) {
300                 // Update last login if far enougth away
301                 // @TODO This query isn't right, it will only update if the user was for a longer time away!
302                 SQL_QUERY_ESC("UPDATE
303         `{?_MYSQL_PREFIX?}_user_data`
304 SET
305         `last_login`=UNIX_TIMESTAMP()
306 WHERE
307         `userid`=%s AND
308         `last_login` < (UNIX_TIMESTAMP() - {?login_timeout?})
309 LIMIT 1",
310                         array(
311                                 getMemberId()
312                         ), __FUNCTION__, __LINE__
313                 );
314
315                 // Updated entry?
316                 $bonus = (SQL_AFFECTEDROWS() == 1);
317         } // END - if
318
319         if (($bonus === true) && (getRequestParameter('mode') == 'bonus')) {
320                 // Output message with added points
321                 $GLOBALS['message'] .= '<div class="tiny">{--BONUS_LOGIN_BONUS_ADDED--}</div>';
322         } elseif (isExtensionActive('bonus')) {
323                 // No login bonus added!
324                 $GLOBALS['message'] .= '<div class="member_failed">{--BONUS_LOGIN_BONUS_NOT_ADDED--}</div>';
325         }
326 }
327
328 // [EOF]
329 ?>