Fix for inserted codes while registering of extensions, many rewrites/cleanups:
[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 (!isBonusRallyeActive()) 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         } // END - switch
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                         bigintval($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']['timemark'] = generateDateTime($GLOBALS['ranking_content']['timemark'], 1);
144
145                 // Load template
146                 $GLOBALS['ranking_content']['own'] = loadTemplate('show_bonus_yr', true, $GLOBALS['ranking_content']);
147         } // END - if
148
149         // Load rankings
150         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE `%s`=%s ORDER BY `level` ASC LIMIT {?bonus_lines?}",
151                 array($type, $data), __FUNCTION__, __LINE__);
152         if (!SQL_HASZERONUMS($result)) {
153                 // Start generating the ranking list
154                 $max = SQL_NUMROWS($result);
155
156                 // Output all ranks (levels)
157                 for ($rank = 1; $rank <= $max; $rank++) {
158                         // Load data
159                         $result_users = SQL_QUERY_ESC("SELECT
160         `userid`, `points`
161 FROM
162         `{?_MYSQL_PREFIX?}_bonus_turbo`
163 WHERE
164         `%s`=%s AND
165         `level`=%s
166 LIMIT 1",
167                                 array($type, $data, $rank), __FUNCTION__, __LINE__);
168
169                         // Nothing found by default
170                         $rows['userid'] = '---';
171                         $rows['points'] = '---';
172
173                         // Are you one of them?
174                         if (SQL_NUMROWS($result_users) == 1) {
175                                 // Load data
176                                 $rows = merge_array($rows, SQL_FETCHARRAY($result_users));
177
178                                 // Is ext-nickname active?
179                                 if (isExtensionActive('nickname')) {
180                                         // Then get the nickname
181                                         $nick = getNickname($rows['userid']);
182
183                                         // Is it not empty? Then use it
184                                         if (!empty($nick)) $rows['userid'] = $nick;
185                                 } // END - if
186                         } // END - if
187
188                         // Free result
189                         SQL_FREERESULT($result_users);
190
191                         // Add more
192                         $rows['rank'] = $rank;
193
194                         // Load row template
195                         $OUT .= loadTemplate('member_bonus_turbo_row', true, $rows);
196                 } // END - for
197
198                 if ($self === false) {
199                         // If current user was not found set constant
200                         $GLOBALS['ranking_content']['rankings'] = '{--BONUS_RANK_YOU_ARE_404--}';
201                 } // END - if
202         } else {
203                 // No entries found!
204                 // @TODO Move this HTML to a template
205                 $OUT = '<tr>
206   <td colspan="3" align="center" height="30" class="bottom">
207     <div class="guest_failed">' . getMaskedMessage('BONUS_NO_RANKS', $data) . '</div>
208   </td>
209 </tr>';
210         }
211
212         // Retutn content
213         return $OUT;
214 }
215
216 //
217 function handleBonusPoints ($mode) {
218         // Shall we add bonus points?
219         if (!isBonusRallyeActive()) return;
220
221         // Switch to jackpot-mode when no UID is supplied but userid-mode is selected
222         if ((getConfig('bonus_mode') == 'UID') && (getBonusUserId() == '0') && (isExtensionActive('jackpot'))) {
223                 // Update database & config
224                 updateConfiguration('bonus_mode', 'JACKPOT');
225         } // END - if
226
227         if ($mode == 'login_bonus') {
228                 // Login bonus detected
229                 $points = getConfig('login_bonus');
230         } else {
231                 // Direct points supplied
232                 $points = $mode;
233         }
234
235         // Check his amount first
236         $total = getTotalPoints(getBonusUserId());
237
238         // Subtract points from...
239         switch (getConfig('bonus_mode')) {
240                 case 'JACKPOT': // ... jackpot
241                         if ((isExtensionActive('jackpot')) && (subtractPointsFromJackpot($points) == -1) && (isValidUserId(getBonusUserId()))) {
242                                 if ($total >= $points) {
243                                         // Subtract points from userid's account
244                                         subtractPointsFromJackpot('bonus_payout_jackpot', getBonusUserId(), $points);
245                                 } // END - if
246                         } // END - if
247                         break;
248
249                 case 'UID': // ... userid's account
250                         if ($total >= $points) {
251                                 // Subtract points from userid's account
252                                 subtractPoints('bonus_payout_userid', getBonusUserId(), $points);
253                         } elseif (isExtensionActive('jackpot')) {
254                                 // Try to subtract from jackpot
255                                 $dummy = subtractPointsFromJackpot($points);
256                         }
257                         break;
258         } // END - switch
259 }
260
261 // Purges expired fast-click bonus entries
262 function purgeExpiredTurboBonus() {
263         // Remove entries
264         $result = SQL_QUERY('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE `timemark` < (UNIX_TIMESTAMP() - {?bonus_timeout?})', __FUNCTION__, __LINE__);
265
266         if (SQL_AFFECTEDROWS() > 0) {
267                 // Send out email to admin
268                 sendAdminNotification('{--ADMIN_AUTOPURGE_TURBO_SUBJECT--}', 'admin_autopurge_turbo', SQL_AFFECTEDROWS());
269         } // END - if
270 }
271
272 ///////////////////////////////////////////////////////////////////////////////
273 //                              Only filter functions
274 ///////////////////////////////////////////////////////////////////////////////
275
276 // Filter for adding login bonus to the user's account
277 function FILTER_ADD_LOGIN_BONUS () {
278         // Is the user data valid?
279         if (!isMember()) {
280                 // Do only run for logged in members
281                 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
282         } // END - if
283
284         // Bonus is not given by default ;-)
285         $bonus = false;
286         if ((isExtensionInstalledAndNewer('sql_patches', '0.2.8')) && (isBonusRallyeActive()) && (getConfig('bonus_login_yn') == 'Y')) {
287                 // Update last login if far enougth away
288                 // @TODO This query isn't right, it will only update if the user was for a longer time away!
289                 SQL_QUERY_ESC('UPDATE
290         `{?_MYSQL_PREFIX?}_user_data`
291 SET
292         `last_login`=UNIX_TIMESTAMP()
293 WHERE
294         `userid`=%s AND
295         `last_login` < (UNIX_TIMESTAMP() - {?login_timeout?})
296 LIMIT 1',
297                         array(
298                                 getMemberId()
299                         ), __FUNCTION__, __LINE__
300                 );
301
302                 // Updated entry?
303                 $bonus = (SQL_AFFECTEDROWS() == 1);
304         } // END - if
305
306         if (($bonus === true) && (getRequestParameter('mode') == 'bonus')) {
307                 // Output message with added points
308                 $GLOBALS['message'] .= '<div class="tiny">{--BONUS_LOGIN_BONUS_ADDED--}</div>';
309         } elseif (isExtensionActive('bonus')) {
310                 // No login bonus added!
311                 $GLOBALS['message'] .= '<div class="member_failed">{--BONUS_LOGIN_BONUS_NOT_ADDED--}</div>';
312         }
313 }
314
315 ///////////////////////////////////////////////////////////////////////////////
316 //                             Wrapper functions                             //
317 ///////////////////////////////////////////////////////////////////////////////
318
319 // Determines wether the "bonus rallye" is active
320 function isBonusRallyeActive () {
321         // Do we have cache?
322         if (!isset($GLOBALS['bonus_rallye_active'])) {
323                 // Just determine it
324                 $GLOBALS['bonus_rallye_active'] = (getConfig('bonus_active') == 'Y');
325         } // END - if
326
327         // Return cache
328         return $GLOBALS['bonus_rallye_active'];
329 }
330
331 // Determines wether the "bonus new_member_notify" is active
332 function isBonusNewMemberNotifyEnabled () {
333         // Do we have cache?
334         if (!isset($GLOBALS['bonus_new_member_notify_active'])) {
335                 // Just determine it
336                 $GLOBALS['bonus_new_member_notify_active'] = (getConfig('bonus_new_member_notify') == 'Y');
337         } // END - if
338
339         // Return cache
340         return $GLOBALS['bonus_new_member_notify_active'];
341 }
342
343 // [EOF]
344 ?>