50676cfff821c2c80de8e8bcf1e60488dff51292
[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 - 2015 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 = sqlQuery('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 = sqlFetchArray($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                                 sqlQueryEscaped('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 (ifSqlHasZeroAffectedRows()) {
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! (' . sqlAffectedRows() . ')');
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         sqlFreeResult($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 = sqlQueryEscaped("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 (sqlNumRows($result) == 1) {
158                         // Fetch percents
159                         list($GLOBALS['refback_percents'][$userid][$refid]) = sqlFetchRow($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                 sqlFreeResult($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 = sqlQueryEscaped("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=' . sqlNumRows($result));
195         if (!ifSqlHasZeroNums($result)) {
196                 // Add all
197                 while ($content = sqlFetchArray($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         sqlFreeResult($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 = sqlQueryEscaped("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 (!ifSqlHasZeroNums($result)) {
243                 // Fetch all entries
244                 while ($row = sqlFetchArray($result)) {
245                         // Calculate click rate
246                         $row['click_rate'] = calculatePercentageRate($row['mails_confirmed'], $row['emails_received']);
247
248                         // Add row
249                         $refs[$row['id']] = $row;
250                 } // END - while
251         } // END - if
252
253         // Free result
254         sqlFreeResult($result);
255
256         // Return result
257         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refs()=' . count($refs) . ' - EXIT!');
258         return $refs;
259 }
260
261 // "Getter" for refback entry
262 function getArrayFromUserRefbackData ($id) {
263         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ' - ENTERED!');
264         // Default data is nothing
265         $data = array();
266
267         // Secure id number
268         $id = bigintval($id);
269
270         // Get entry from database
271         $result = sqlQueryEscaped("SELECT `id`, `userid`, `refid`, `refback_percents`, `level`, `refback_points` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `id`=%s AND `userid`=%s LIMIT 1",
272                 array($id, getMemberId()), __FUNCTION__, __LINE__);
273
274         // Is there an entry?
275         if (sqlNumRows($result) == 1) {
276                 // Fetch data
277                 $data = sqlFetchArray($result);
278         } // END - if
279
280         // Free result
281         sqlFreeResult($result);
282
283         // Return entry
284         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',data()=' . count($data) . ' - EXIT!');
285         return $data;
286 }
287
288 // Update refback percents (but with some sanity-checks!
289 function updateMemberRefbackPercents ($id, $percents, $note) {
290         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',percents=' . $percents . ' - ENTERED!');
291         // Default status is failed
292         $status['message'] = 'MEMBER_REFBACK_ERROR_GENERAL';
293
294         // Do some sanity-checks
295         if (!isMember()) {
296                 // No member!
297                 $status['message'] = 'MEMBER_REFBACK_ERROR_NO_MEMBER';
298                 return $status;
299         } elseif (''.$id.'' != ''.($id + 0).'') {
300                 // No number!
301                 $status['message'] = 'MEMBER_REFBACK_ERROR_INVALID_ID_NUMBER';
302                 return $status;
303         } elseif (($percents < 0) || ($percents > 100)) {
304                 // Percentage is not valid!
305                 $status['message'] = 'MEMBER_REFBACK_ERROR_INVALID_PERCENTAGE';
306                 return $status;
307         }
308
309         // Get ref entry
310         $content = getArrayFromUserRefbackData($id);
311
312         // Is this valid?
313         if (!isFilledArray($content)) {
314                 // id does not belong to user!
315                 $status['message'] = 'MEMBER_REFBACK_ERROR_ID_MISMATCH';
316                 return $status;
317         } // END - if
318
319         // Revert german commata
320         $percents = convertCommaToDot($percents);
321
322         // Update entry
323         sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_refs` SET `refback_percents`='%s' WHERE `id`=%s AND `userid`=%s LIMIT 1",
324                 array(
325                         $percents,
326                         $id,
327                         getMemberId()
328                 ), __FUNCTION__, __LINE__);
329
330         // Entry updated?
331         if (ifSqlHasZeroAffectedRows()) {
332                 // Entry not updated!
333                 $status['message'] = 'MEMBER_REFBACK_ERROR_NOT_UPDATED';
334                 return $status;
335         } // END - if
336
337         // Prepare email content
338         $content['refback_percents'] = $percents;
339         $content['refback_notice']     = $note;
340
341         // Load member email template
342         $mail = loadEmailTemplate('member_refback', $content, $content['refid']);
343
344         // Send email to user
345         sendEmail($content['refid'], '{--MEMBER_REFBACK_SUBJECT--}', $mail);
346
347         // Send admin notification
348         sendAdminNotification('{--ADMIN_REFBACK_SUBJECT--}', 'admin_refback', $content, $content['refid']);
349
350         // All fine!
351         $status['ok'] = TRUE;
352
353         // Return status array
354         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'id=' . $id . ',percents=' . $percents . ' - EXIT!');
355         return $status;
356 }
357
358 // ----------------------------------------------------------------------------
359 //                 Wrapper functions for configuration entries
360 // ----------------------------------------------------------------------------
361
362 // Getter for refback_enabled
363 function getRefbackEnabled () {
364         // Is there cache?
365         if (!isset($GLOBALS[__FUNCTION__])) {
366                 // Determine it
367                 $GLOBALS[__FUNCTION__] = getConfig('refback_enabled');
368         } // END - if
369
370         // Return cache
371         return $GLOBALS[__FUNCTION__];
372 }
373
374 // Checks whether refback is enabled
375 function isRefbackEnabled () {
376         // Is there cache?
377         if (!isset($GLOBALS[__FUNCTION__])) {
378                 // Determine it
379                 $GLOBALS[__FUNCTION__] = (getRefbackEnabled() == 'Y');
380         } // END - if
381
382         // Return cache
383         return $GLOBALS[__FUNCTION__];
384 }
385
386 // Getter for refback_max_perc
387 function getRefbackMaxPerc () {
388         // Is there cache?
389         if (!isset($GLOBALS[__FUNCTION__])) {
390                 // Determine it
391                 $GLOBALS[__FUNCTION__] = getConfig('refback_max_perc');
392         } // END - if
393
394         // Return cache
395         return $GLOBALS[__FUNCTION__];
396 }
397
398 // Getter for refback_min_perc
399 function getRefbackMinPerc () {
400         // Is there cache?
401         if (!isset($GLOBALS[__FUNCTION__])) {
402                 // Determine it
403                 $GLOBALS[__FUNCTION__] = getConfig('refback_min_perc');
404         } // END - if
405
406         // Return cache
407         return $GLOBALS[__FUNCTION__];
408 }
409
410 // [EOF]
411 ?>