Missing bonus mode 'ADD' added
[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  * -------------------------------------------------------------------- *
18  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
19  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
20  * For more information visit: http://www.mxchange.org                  *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // This function must be run *BEFORE* a link is removed from table 'mxchange_user_links' !
44 function addTurboBonus ($mid, $userid, $type) {
45         // Shall we add bonus points?
46         if (!isBonusRallyeActive()) return false;
47
48         // Init variables
49         $sql = ''; $bonus = '0'; $mail = '0'; $column = '';
50
51         // Select SQL command
52         switch ($type) {
53                 case 'bonusid':
54                         $column = 'bonus_id';
55                         $bonus = $mid;
56                         break;
57
58                 case 'mailid' :
59                         $column = 'mail_id';
60                         $mail = $mid;
61                         break;
62
63                 default:
64                         logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid type %s detected.", $type));
65                         break;
66         } // END - switch
67
68         // Is a column name set?
69         if (empty($column)) {
70                 // No, then abort here
71                 return false;
72         } // END - if
73
74         // Check for entry
75         $rank = countSumTotalData($mid, 'bonus_turbo', 'id', $column, true) + 1;
76
77         // Which rank?
78         if ($rank == 1) {
79                 // First rank!
80                 $points = getConfig('turbo_bonus');
81         } else {
82                 // Anything else so let's explode all entered rank points
83                 $test = explode(';', getConfig('turbo_rates'));
84                 if (!empty($test[$rank - 2])) {
85                         // Level found
86                         $points = $test[$rank - 2];
87                 } else {
88                         // Level not found!
89                         $points = '0.00000';
90                 }
91         }
92
93         // Add points to his account directly
94         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `turbo_bonus`=`turbo_bonus`+%s WHERE `userid`=%s LIMIT 1",
95                 array(
96                         bigintval($userid),
97                         $points
98                 ), __FUNCTION__, __LINE__);
99
100         // Rember this whole data for displaying ranking list
101         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())",
102                 array(
103                         bigintval($userid),
104                         bigintval($mail),
105                         bigintval($bonus),
106                         $rank,
107                         $points
108                 ), __FUNCTION__, __LINE__);
109
110         if ((isExtensionInstalledAndNewer('bonus', '0.3.5')) && (getBonusMode() != 'ADD') && ($points > 0)) {
111                 handleBonusPoints($points);
112         } // END - if
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                 // Output all ranks (levels)
154                 for ($rank = 1; $rank <= SQL_NUMROWS($result); $rank++) {
155                         // Load data
156                         $result_users = SQL_QUERY_ESC("SELECT
157         `userid`, `points`
158 FROM
159         `{?_MYSQL_PREFIX?}_bonus_turbo`
160 WHERE
161         `%s`=%s AND
162         `level`=%s
163 LIMIT 1",
164                                 array($type, $data, $rank), __FUNCTION__, __LINE__);
165
166                         // Nothing found by default
167                         $rows['userid'] = '---';
168                         $rows['points'] = '---';
169
170                         // Are you one of them?
171                         if (SQL_NUMROWS($result_users) == 1) {
172                                 // Load data
173                                 $rows = merge_array($rows, SQL_FETCHARRAY($result_users));
174
175                                 // Is ext-nickname active?
176                                 if (isExtensionActive('nickname')) {
177                                         // Then get the nickname
178                                         $nick = getNickname($rows['userid']);
179
180                                         // Is it not empty? Then use it
181                                         if (!empty($nick)) $rows['userid'] = $nick;
182                                 } // END - if
183                         } // END - if
184
185                         // Free result
186                         SQL_FREERESULT($result_users);
187
188                         // Add more
189                         $rows['rank'] = $rank;
190
191                         // Load row template
192                         $OUT .= loadTemplate('member_bonus_turbo_row', true, $rows);
193                 } // END - for
194
195                 if ($self === false) {
196                         // If current user was not found set constant
197                         $GLOBALS['ranking_content']['rankings'] = '{--MEMBER_BONUS_RANK_YOU_ARE_404--}';
198                 } // END - if
199         } else {
200                 // No entries found!
201                 // @TODO Move this HTML to a template
202                 $OUT = '<tr>
203   <td colspan="3" align="center" height="30" class="bottom">
204     <div class="notice">' . getMaskedMessage('MEMBER_BONUS_NO_RANKS', $data) . '</div>
205   </td>
206 </tr>';
207         }
208
209         // Retutn content
210         return $OUT;
211 }
212
213 //
214 function handleBonusPoints ($mode) {
215         // Shall we add bonus points?
216         if (!isBonusRallyeActive()) return;
217
218         // Switch to jackpot-mode when no UID is supplied but userid-mode is selected
219         if ((getBonusMode() == 'UID') && (getBonusUserId() == '0') && (isExtensionActive('jackpot'))) {
220                 // Update database & config
221                 updateConfiguration('bonus_mode', 'JACKPOT');
222         } // END - if
223
224         if ($mode == 'login_bonus') {
225                 // Login bonus detected
226                 $points = getConfig('login_bonus');
227         } else {
228                 // Direct points supplied
229                 $points = $mode;
230         }
231
232         // Check his amount first
233         $total = getTotalPoints(getBonusUserId());
234
235         // Subtract points from...
236         switch (getBonusMode()) {
237                 case 'ADD': // Only add them (no subtraction)
238                         // Ignored
239                         break;
240
241                 case 'JACKPOT': // ... jackpot
242                         if ((isExtensionActive('jackpot')) && (subtractPointsFromJackpot($points) == -1) && (isValidUserId(getBonusUserId()))) {
243                                 if ($total >= $points) {
244                                         // Subtract points from userid's account
245                                         subtractPointsFromJackpot('bonus_payout_jackpot', getBonusUserId(), $points);
246                                 } // END - if
247                         } // END - if
248                         break;
249
250                 case 'UID': // ... userid's account
251                         if ($total >= $points) {
252                                 // Subtract points from userid's account
253                                 subtractPoints('bonus_payout_userid', getBonusUserId(), $points);
254                         } elseif (isExtensionActive('jackpot')) {
255                                 // Try to subtract from jackpot
256                                 $dummy = subtractPointsFromJackpot($points);
257                         }
258                         break;
259
260                 default: // This should not happen
261                         debug_report_bug(__FUNCTION__, __LINE__, 'Invalid bonus-mode ' . getBonusMode() . ' detected.');
262                         break;
263         } // END - switch
264 }
265
266 // Purges expired fast-click bonus entries
267 function purgeExpiredTurboBonus() {
268         // Remove entries
269         $result = SQL_QUERY('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE `timemark` < (UNIX_TIMESTAMP() - {?bonus_timeout?})', __FUNCTION__, __LINE__);
270
271         if (!SQL_HASZEROAFFECTED()) {
272                 // Send out email to admin
273                 sendAdminNotification('{--ADMIN_AUTOPURGE_TURBO_SUBJECT--}', 'admin_autopurge_turbo', SQL_AFFECTEDROWS());
274         } // END - if
275 }
276
277 //-----------------------------------------------------------------------------
278 //                                Filter Functions
279 //-----------------------------------------------------------------------------
280
281 // Filter for adding login bonus to the user's account
282 function FILTER_ADD_LOGIN_BONUS () {
283         // Is the user data valid?
284         if (!isMember()) {
285                 // Do only run for logged in members
286                 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
287         } // END - if
288
289         // Bonus is not given by default ;-)
290         $bonus = false;
291         if ((isExtensionInstalledAndNewer('sql_patches', '0.2.8')) && (isBonusRallyeActive()) && (getConfig('bonus_login_yn') == 'Y')) {
292                 // Update last login if far enougth away
293                 // @TODO This query isn't right, it will only update if the user was for a longer time away!
294                 SQL_QUERY_ESC('UPDATE
295         `{?_MYSQL_PREFIX?}_user_data`
296 SET
297         `last_login`=UNIX_TIMESTAMP()
298 WHERE
299         `userid`=%s AND
300         `last_login` < (UNIX_TIMESTAMP() - {?login_timeout?})
301 LIMIT 1',
302                         array(
303                                 getMemberId()
304                         ), __FUNCTION__, __LINE__
305                 );
306
307                 // Updated entry?
308                 $bonus = (!SQL_HASZEROAFFECTED());
309         } // END - if
310
311         if (($bonus === true) && (getRequestParameter('mode') == 'bonus')) {
312                 // Output message with added points
313                 $GLOBALS['message'] .= '<div class="tiny">{--MEMBER_BONUS_LOGIN_BONUS_ADDED--}</div>';
314         } elseif (isExtensionActive('bonus')) {
315                 // No login bonus added!
316                 $GLOBALS['message'] .= '<div class="notice">{--MEMBER_BONUS_LOGIN_BONUS_NOT_ADDED--}</div>';
317         }
318 }
319
320 //-----------------------------------------------------------------------------
321 //                             Wrapper Functions
322 //-----------------------------------------------------------------------------
323
324 // Determines wether the "bonus rallye" is active
325 function isBonusRallyeActive () {
326         // Do we have cache?
327         if (!isset($GLOBALS['bonus_rallye_active'])) {
328                 // Just determine it
329                 $GLOBALS['bonus_rallye_active'] = (getConfig('bonus_active') == 'Y');
330         } // END - if
331
332         // Return cache
333         return $GLOBALS['bonus_rallye_active'];
334 }
335
336 // Determines wether the "bonus new_member_notify" is active
337 function isBonusNewMemberNotifyEnabled () {
338         // Do we have cache?
339         if (!isset($GLOBALS['bonus_new_member_notify_active'])) {
340                 // Just determine it
341                 $GLOBALS['bonus_new_member_notify_active'] = (getConfig('bonus_new_member_notify') == 'Y');
342         } // END - if
343
344         // Return cache
345         return $GLOBALS['bonus_new_member_notify_active'];
346 }
347
348 // Getter for bonus_timeout
349 function getBonusTimeout () {
350         // Do we have cache?
351         if (!isset($GLOBALS[__FUNCTION__])) {
352                 // Determine it
353                 $GLOBALS[__FUNCTION__] = getConfig('bonus_timeout');
354         } // END - if
355
356         // Return cache
357         return $GLOBALS[__FUNCTION__];
358 }
359
360 // Getter for bonus_mode
361 function getBonusMode () {
362         // Do we have cache?
363         if (!isset($GLOBALS[__FUNCTION__])) {
364                 // Determine it
365                 $GLOBALS[__FUNCTION__] = getConfig('bonus_mode');
366         } // END - if
367
368         // Return cache
369         return $GLOBALS[__FUNCTION__];
370 }
371
372 // Getter for bonus_ranks
373 function getBonusRanks () {
374         // Do we have cache?
375         if (!isset($GLOBALS[__FUNCTION__])) {
376                 // Determine it
377                 $GLOBALS[__FUNCTION__] = getConfig('bonus_ranks');
378         } // END - if
379
380         // Return cache
381         return $GLOBALS[__FUNCTION__];
382 }
383
384 // [EOF]
385 ?>