0cba632fea12a6f5a6fea5a721e110d65e91f18c
[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                 // 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="guest_failed">' . 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 ((getConfig('bonus_mode') == '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 (getConfig('bonus_mode')) {
237                 case 'JACKPOT': // ... jackpot
238                         if ((isExtensionActive('jackpot')) && (subtractPointsFromJackpot($points) == -1) && (isValidUserId(getBonusUserId()))) {
239                                 if ($total >= $points) {
240                                         // Subtract points from userid's account
241                                         subtractPointsFromJackpot('bonus_payout_jackpot', getBonusUserId(), $points);
242                                 } // END - if
243                         } // END - if
244                         break;
245
246                 case 'UID': // ... userid's account
247                         if ($total >= $points) {
248                                 // Subtract points from userid's account
249                                 subtractPoints('bonus_payout_userid', getBonusUserId(), $points);
250                         } elseif (isExtensionActive('jackpot')) {
251                                 // Try to subtract from jackpot
252                                 $dummy = subtractPointsFromJackpot($points);
253                         }
254                         break;
255         } // END - switch
256 }
257
258 // Purges expired fast-click bonus entries
259 function purgeExpiredTurboBonus() {
260         // Remove entries
261         $result = SQL_QUERY('DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_bonus_turbo` WHERE `timemark` < (UNIX_TIMESTAMP() - {?bonus_timeout?})', __FUNCTION__, __LINE__);
262
263         if (SQL_AFFECTEDROWS() > 0) {
264                 // Send out email to admin
265                 sendAdminNotification('{--ADMIN_AUTOPURGE_TURBO_SUBJECT--}', 'admin_autopurge_turbo', SQL_AFFECTEDROWS());
266         } // END - if
267 }
268
269 //-----------------------------------------------------------------------------
270 //                                Filter Functions
271 //-----------------------------------------------------------------------------
272
273 // Filter for adding login bonus to the user's account
274 function FILTER_ADD_LOGIN_BONUS () {
275         // Is the user data valid?
276         if (!isMember()) {
277                 // Do only run for logged in members
278                 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
279         } // END - if
280
281         // Bonus is not given by default ;-)
282         $bonus = false;
283         if ((isExtensionInstalledAndNewer('sql_patches', '0.2.8')) && (isBonusRallyeActive()) && (getConfig('bonus_login_yn') == 'Y')) {
284                 // Update last login if far enougth away
285                 // @TODO This query isn't right, it will only update if the user was for a longer time away!
286                 SQL_QUERY_ESC('UPDATE
287         `{?_MYSQL_PREFIX?}_user_data`
288 SET
289         `last_login`=UNIX_TIMESTAMP()
290 WHERE
291         `userid`=%s AND
292         `last_login` < (UNIX_TIMESTAMP() - {?login_timeout?})
293 LIMIT 1',
294                         array(
295                                 getMemberId()
296                         ), __FUNCTION__, __LINE__
297                 );
298
299                 // Updated entry?
300                 $bonus = (SQL_AFFECTEDROWS() == 1);
301         } // END - if
302
303         if (($bonus === true) && (getRequestParameter('mode') == 'bonus')) {
304                 // Output message with added points
305                 $GLOBALS['message'] .= '<div class="tiny">{--MEMBER_BONUS_LOGIN_BONUS_ADDED--}</div>';
306         } elseif (isExtensionActive('bonus')) {
307                 // No login bonus added!
308                 $GLOBALS['message'] .= '<div class="member_failed">{--MEMBER_BONUS_LOGIN_BONUS_NOT_ADDED--}</div>';
309         }
310 }
311
312 //-----------------------------------------------------------------------------
313 //                             Wrapper Functions
314 //-----------------------------------------------------------------------------
315
316 // Determines wether the "bonus rallye" is active
317 function isBonusRallyeActive () {
318         // Do we have cache?
319         if (!isset($GLOBALS['bonus_rallye_active'])) {
320                 // Just determine it
321                 $GLOBALS['bonus_rallye_active'] = (getConfig('bonus_active') == 'Y');
322         } // END - if
323
324         // Return cache
325         return $GLOBALS['bonus_rallye_active'];
326 }
327
328 // Determines wether the "bonus new_member_notify" is active
329 function isBonusNewMemberNotifyEnabled () {
330         // Do we have cache?
331         if (!isset($GLOBALS['bonus_new_member_notify_active'])) {
332                 // Just determine it
333                 $GLOBALS['bonus_new_member_notify_active'] = (getConfig('bonus_new_member_notify') == 'Y');
334         } // END - if
335
336         // Return cache
337         return $GLOBALS['bonus_new_member_notify_active'];
338 }
339
340 // Getter for bonus_timeout
341 function getBonusTimeout () {
342         // Do we have cache?
343         if (!isset($GLOBALS[__FUNCTION__])) {
344                 // Determine it
345                 $GLOBALS[__FUNCTION__] = getConfig('bonus_timeout');
346         } // END - if
347
348         // Return cache
349         return $GLOBALS[__FUNCTION__];
350 }
351
352 // [EOF]
353 ?>