Filters for configurable userid exclusion added:
[mailer.git] / inc / libs / refback_functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 09/28/2008 *
4  * ===================                          Last change: 09/28/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : refback_functions.php                            *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for refback extension                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer Refback-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 - 2012 by Mailer Developer Team                   *
20  * For more information visit: http://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 // Payback refback for refid and reduce it for current user
44 function addRefbackPoints ($userid, $ref, $points, $ref_points) {
45         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . $ref . ',points=' . $points . ',ref_points=' . $ref_points . ' - ENTERED!');
46         // Back ref depths
47         $GLOBALS['refback_depth'][$userid][$ref] = $GLOBALS['ref_level'];
48
49         // Init points
50         $return = $ref_points;
51
52         // Get all ref levels
53         $result_refs = SQL_QUERY('SELECT `level`, `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level` > 0 ORDER BY `level` ASC',
54                 __FUNCTION__, __LINE__);
55
56         // "Walk" through all level
57         while ($content = SQL_FETCHARRAY($result_refs)) {
58                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'level=' . $content['level'] . ',percents=' . $content['percents'] . ' - LOOP START!');
59                 // Reset ref depths
60                 initReferralSystem();
61
62                 // Init array
63                 $refids = getArrayFromRefbackLevel($userid, $content['level']);
64
65                 // "Walk" through all refids
66                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . $ref . ',level=' . $content['level'] . ',percents=' . $content['percents'] . ',points=' . $points . ' - LOOP START!');
67                 foreach ($refids as $refid) {
68                         /*
69                          * Get refback percents, do not swap $refid and $userid by the next
70                          * call. If you do so, you will check the wrong direction, $userid
71                          * is always bigger than $refid.
72                          */
73                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero($refid) . ' - CALLING getRefbackPercents()');
74                         $content['refback_percents'] = getRefbackPercents($refid, $userid);
75                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero($refid) . ',refback_percents=' . $content['refback_percents']);
76
77                         // Some percents given?
78                         if ($content['refback_percents'] > 0) {
79                                 // Calculate points for refback
80                                 $refbackPoints = $points * ($content['percents'] / 100) * ($content['refback_percents'] / 100);
81                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',percents=' . $content['percents'] . ',refback_percents=' . $content['refback_percents'] . ',level=' . $content['level'] . ',refback_points=' . $refbackPoints);
82
83                                 // Update refback table ('refid' and 'userid' must be exchanged!)
84                                 SQL_QUERY_ESC('UPDATE
85         `{?_MYSQL_PREFIX?}_user_refs`
86 SET
87         `refback_points`=`refback_points`+%s
88 WHERE
89         `userid`=%s AND
90         `refid`=%s
91 LIMIT 1',
92                                         array(
93                                                 $refbackPoints,
94                                                 $refid,
95                                                 $userid
96                                         ), __FUNCTION__, __LINE__);
97
98                                 // Something must have been updated
99                                 if (SQL_HASZEROAFFECTED()) {
100                                         // Please report this bug
101                                         reportBug(__FUNCTION__, __LINE__, 'Nothing has been updated in user_refs,userid=' . $userid . ',refid=' . convertNullToZero($refid) . ',refbackPoints=' . $refbackPoints);
102                                 } // END - if
103
104                                 // Add points again, but only directly
105                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refbackPoints=' . $refbackPoints . ',userid=' . $userid . ',ref=' . $ref . ',refid=' . convertNullToZero($refid) . ' - REFBACK-UPDATE! (' . SQL_AFFECTEDROWS() . ')');
106                                 addPointsThroughReferralSystem(sprintf("refback:%s", $refid), $userid, $refbackPoints);
107
108                                 // Reduce points if refid is found
109                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . $refid . ',ref=' . $ref . ' - REDUCING?');
110                                 if ($refid == $ref) {
111                                         // Reduce points here!
112                                         $return = $points * ($content['percents'] / 100) - $refbackPoints;
113                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'return=' . $return . ' - REDUCED!');
114                                 } // END - if
115                         } // END - if
116                 } // END foreach
117         } // END - while
118
119         // Free result
120         SQL_FREERESULT($result_refs);
121
122         // Restore ref depth
123         $GLOBALS['ref_level'] = $GLOBALS['refback_depth'][$userid][$ref];
124
125         // Return them
126         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . $ref . ',points=' . $points . ',ref_points=' . $ref_points . ',return=' . $return . ' - EXIT!');
127         return $return;
128 }
129
130 /**
131  * "Getter" for refback percents
132  *
133  * @param       $userid         "Current" user's userid
134  * @param       $refid          $userid has this userid as referral
135  * @return      $percents       Refback percents $userid has given to $refid
136  */
137 function getRefbackPercents ($userid, $refid) {
138         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . $refid . ' - ENTERED!');
139         if ((!isValidId($userid)) || (!isValidId($refid))) {
140                 // userid and/or refid is invalid
141                 reportBug(__FUNCTION__, __LINE__, 'userid=' . convertNullToZero($userid) . ', refid=' . convertNullToZero($refid) . ' - Both must be > 0');
142         } elseif ($userid == $refid) {
143                 // Skip identical ids
144                 return 0;
145         } // END - if
146
147         // Is it cached?
148         if (!isset($GLOBALS['refback_percents'][$userid][$refid])) {
149                 // Default is zero
150                 $GLOBALS['refback_percents'][$userid][$refid] = '0';
151
152                 // Get percents from database
153                 $result = SQL_QUERY_ESC("SELECT `refback_percents` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `userid`=%s AND `refid`=%s LIMIT 1",
154                         array($userid, $refid), __FUNCTION__, __LINE__);
155
156                 // Entry found? (Should be!)
157                 if (SQL_NUMROWS($result) == 1) {
158                         // Fetch percents
159                         list($GLOBALS['refback_percents'][$userid][$refid]) = SQL_FETCHROW($result);
160                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . $refid . ',percents=' . $GLOBALS['refback_percents'][$userid][$refid]);
161                 } else {
162                         // Please report all findings
163                         reportBug(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . $refid . ' - No entry found. :-(');
164                 }
165
166                 // Free result
167                 SQL_FREERESULT($result);
168         } // END - if
169
170         // Return percents
171         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . $refid . ',refback_percents=' . $GLOBALS['refback_percents'][$userid][$refid] . ' - EXIT!');
172         return $GLOBALS['refback_percents'][$userid][$refid];
173 }
174
175 // "Getter" for userid array which will return only one entry
176 function getArrayFromRefbackLevel ($refid, $level) {
177         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . convertNullToZero($refid) . ',level=' . $level . ' - ENTERED!');
178         // Init userids
179         $userIds = array();
180
181         // Look for all
182         $result = SQL_QUERY_ESC("SELECT
183         `userid`
184 FROM
185         `{?_MYSQL_PREFIX?}_user_refs`
186 WHERE
187         `refid`=%s AND
188         `level`=%s
189 ORDER BY
190         `userid` ASC",
191                 array($refid, $level), __FUNCTION__, __LINE__);
192
193         // Entries found?
194         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'numRows=' . SQL_NUMROWS($result));
195         if (!SQL_HASZERONUMS($result)) {
196                 // Add all
197                 while ($content = SQL_FETCHARRAY($result)) {
198                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . convertNullToZero($refid) . ',level=' . $level . ',userid=' . $content['userid']);
199                         array_push($userIds, $content['userid']);
200                 } // END - while
201         } // END - if
202
203         // Free result
204         SQL_FREERESULT($result);
205
206         // Return array
207         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . convertNullToZero($refid) . ',userIds()=' . count($userIds) . ' - EXIT!');
208         return $userIds;
209 }
210
211 // "Getter" for array for user refs in given level
212 function getArrayFromRefbackUserRefs ($userid, $level) {
213         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - ENTERED!');
214         // Default is no refs and no nickname
215         $refs = array();
216
217         // Get refs from database
218         $result = SQL_QUERY_ESC("SELECT
219         `r`.`id`,
220         `r`.`refid`,
221         `r`.`refback_percents`,
222         `r`.`refback_points`,
223         `d`.`status`,
224         `d`.`joined`,
225         `d`.`mails_confirmed`,
226         `d`.`emails_received`,
227         `d`.`refid` AS `level_refid`
228 FROM
229         `{?_MYSQL_PREFIX?}_user_refs` AS `r`
230 LEFT JOIN
231         `{?_MYSQL_PREFIX?}_user_data` AS `d`
232 ON
233         `r`.`refid`=`d`.`userid`
234 WHERE
235         `r`.`userid`=%s AND
236         `r`.`level`=%s
237 ORDER BY
238         `r`.`refid` ASC",
239                 array(bigintval($userid), bigintval($level)), __FUNCTION__, __LINE__);
240
241         // Are there some entries?
242         if (!SQL_HASZERONUMS($result)) {
243                 // Fetch all entries
244                 while ($row = SQL_FETCHARRAY($result)) {
245                         // Init click rate
246                         $row['click_rate'] = '0';
247
248                         // Does he have received some mails?
249                         if ($row['emails_received'] > 0) {
250                                 // Calculate click rate
251                                 $row['click_rate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
252                         } // END - if
253
254                         // Add row
255                         $refs[$row['id']] = $row;
256                 } // END - while
257         } // END - if
258
259         // Free result
260         SQL_FREERESULT($result);
261
262         // Return result
263         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refs()=' . count($refs) . ' - EXIT!');
264         return $refs;
265 }
266
267 // "Getter" for refback entry
268 function getArrayFromUserRefbackData ($id) {
269         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ' - ENTERED!');
270         // Default data is nothing
271         $data = array();
272
273         // Secure id number
274         $id = bigintval($id);
275
276         // Get entry from database
277         $result = SQL_QUERY_ESC("SELECT `id`, `userid`, `refid`, `refback_percents`, `level`, `refback_points` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `id`=%s AND `userid`=%s LIMIT 1",
278                 array($id, getMemberId()), __FUNCTION__, __LINE__);
279
280         // Is there an entry?
281         if (SQL_NUMROWS($result) == 1) {
282                 // Fetch data
283                 $data = SQL_FETCHARRAY($result);
284         } // END - if
285
286         // Free result
287         SQL_FREERESULT($result);
288
289         // Return entry
290         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',data()=' . count($data) . ' - EXIT!');
291         return $data;
292 }
293
294 // Update refback percents (but with some sanity-checks!
295 function updateMemberRefbackPercents ($id, $percents, $note) {
296         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',percents=' . $percents . ' - ENTERED!');
297         // Default status is failed
298         $status['message'] = 'MEMBER_REFBACK_ERROR_GENERAL';
299
300         // Do some sanity-checks
301         if (!isMember()) {
302                 // No member!
303                 $status['message'] = 'MEMBER_REFBACK_ERROR_NO_MEMBER';
304                 return $status;
305         } elseif (''.$id.'' != ''.($id + 0).'') {
306                 // No number!
307                 $status['message'] = 'MEMBER_REFBACK_ERROR_INVALID_ID_NUMBER';
308                 return $status;
309         } elseif (($percents < 0) || ($percents > 100)) {
310                 // Percentage is not valid!
311                 $status['message'] = 'MEMBER_REFBACK_ERROR_INVALID_PERCENTAGE';
312                 return $status;
313         }
314
315         // Get ref entry
316         $content = getArrayFromUserRefbackData($id);
317
318         // Is this valid?
319         if (count($content) == 0) {
320                 // id does not belong to user!
321                 $status['message'] = 'MEMBER_REFBACK_ERROR_ID_MISMATCH';
322                 return $status;
323         } // END - if
324
325         // Revert german commata
326         $percents = convertCommaToDot($percents);
327
328         // Update entry
329         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_refs` SET `refback_percents`='%s' WHERE `id`=%s AND `userid`=%s LIMIT 1",
330                 array(
331                         $percents,
332                         $id,
333                         getMemberId()
334                 ), __FUNCTION__, __LINE__);
335
336         // Entry updated?
337         if (SQL_HASZEROAFFECTED()) {
338                 // Entry not updated!
339                 $status['message'] = 'MEMBER_REFBACK_ERROR_NOT_UPDATED';
340                 return $status;
341         } // END - if
342
343         // Prepare email content
344         $content['refback_percents'] = $percents;
345         $content['refback_notice']     = $note;
346
347         // Load member email template
348         $mail = loadEmailTemplate('member_refback', $content, $content['refid']);
349
350         // Send email to user
351         sendEmail($content['refid'], '{--MEMBER_REFBACK_SUBJECT--}', $mail);
352
353         // Send admin notification
354         sendAdminNotification('{--ADMIN_REFBACK_SUBJECT--}', 'admin_refback', $content, $content['refid']);
355
356         // All fine!
357         $status['ok'] = TRUE;
358
359         // Return status array
360         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',percents=' . $percents . ' - EXIT!');
361         return $status;
362 }
363
364 // ----------------------------------------------------------------------------
365 //                 Wrapper functions for configuration entries
366 // ----------------------------------------------------------------------------
367
368 // Getter for refback_enabled
369 function getRefbackEnabled () {
370         // Is there cache?
371         if (!isset($GLOBALS[__FUNCTION__])) {
372                 // Determine it
373                 $GLOBALS[__FUNCTION__] = getConfig('refback_enabled');
374         } // END - if
375
376         // Return cache
377         return $GLOBALS[__FUNCTION__];
378 }
379
380 // Checks whether refback is enabled
381 function isRefbackEnabled () {
382         // Is there cache?
383         if (!isset($GLOBALS[__FUNCTION__])) {
384                 // Determine it
385                 $GLOBALS[__FUNCTION__] = (getRefbackEnabled() == 'Y');
386         } // END - if
387
388         // Return cache
389         return $GLOBALS[__FUNCTION__];
390 }
391
392 // Getter for refback_max_perc
393 function getRefbackMaxPerc () {
394         // Is there cache?
395         if (!isset($GLOBALS[__FUNCTION__])) {
396                 // Determine it
397                 $GLOBALS[__FUNCTION__] = getConfig('refback_max_perc');
398         } // END - if
399
400         // Return cache
401         return $GLOBALS[__FUNCTION__];
402 }
403
404 // Getter for refback_min_perc
405 function getRefbackMinPerc () {
406         // Is there cache?
407         if (!isset($GLOBALS[__FUNCTION__])) {
408                 // Determine it
409                 $GLOBALS[__FUNCTION__] = getConfig('refback_min_perc');
410         } // END - if
411
412         // Return cache
413         return $GLOBALS[__FUNCTION__];
414 }
415
416 // [EOF]
417 ?>