Hotfix
[mailer.git] / inc / referral-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 07/12/2011 *
4  * ===================                          Last change: 07/12/2011 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : referral-functions.php                           *
8  * -------------------------------------------------------------------- *
9  * Short description : All referral system functions                    *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Alle zum Referral-System gehoerenden Funktionen  *
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 - 2011 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 // Initializes the referral system
44 function initReferralSystem () {
45         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' Referral system initialized!');
46         $GLOBALS['ref_level']  = NULL;
47         $GLOBALS['ref_system'] = true;
48 }
49
50 // Getter fro ref level percents
51 function getReferralLevelPercents ($level) {
52         // Default is zero
53         $data['percents'] = '0';
54
55         // Do we have cache?
56         if ((isset($GLOBALS['cache_array']['refdepths']['level'])) && (isExtensionActive('cache'))) {
57                 // First look for level
58                 $key = array_search($level, $GLOBALS['cache_array']['refdepths']['level']);
59                 if ($key !== false) {
60                         // Entry found
61                         $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
62
63                         // Count cache hit
64                         incrementStatsEntry('cache_hits');
65                 } // END - if
66         } elseif (!isExtensionActive('cache')) {
67                 // Get referral data
68                 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`=%s LIMIT 1",
69                         array(bigintval($level)), __FUNCTION__, __LINE__);
70
71                 // Entry found?
72                 if (SQL_NUMROWS($result_level) == 1) {
73                         // Get percents
74                         $data = SQL_FETCHARRAY($result_level);
75                 } // END - if
76
77                 // Free result
78                 SQL_FREERESULT($result_level);
79         }
80
81         // Return percent
82         return $data['percents'];
83 }
84
85 /**
86  * Dynamic referral and points system, can also send mails!
87  *
88  * subject       = Subject line, write in lower-case letters and underscore is allowed
89  * userid        = Referral id wich should receive...
90  * points        = ... xxx points
91  * refid         = inc/modules/guest/what-confirm.php need this
92  */
93 function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NULL) {
94         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',refid=' . convertNullToZero($refid) . ' - ENTERED!');
95         // By default nothing has been added
96         $added = false;
97
98         // Determine payment method and notification
99         $paymentMethod = strtoupper(getPaymentMethodFromSubject($subject));
100         $sendNotify    = isPaymentRecipientNotificationEnabled($subject);
101
102         // When $userid is NULL add points to jackpot
103         if ((!isValidUserId($userid)) && ($paymentMethod == 'DIRECT') && (isExtensionActive('jackpot'))) {
104                 // Add points to jackpot only in DIRECT mode
105                 return addPointsToJackpot($points);
106         } // END - if
107
108         // Set userid as current
109         setCurrentUserId($userid);
110
111         // Check user account
112         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',points=' . $points . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify));
113         if (fetchUserData($userid)) {
114                 // Determine wether the user has some mails to click before he/she gets the points
115                 $locked = ifUserPointsLocked($userid);
116
117                 // Detect database column
118                 $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $locked);
119
120                 // Get percents
121                 $per = getReferralLevelPercents($GLOBALS['ref_level']);
122                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',points=' . $points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ',per=' . $per . ',mode=' . $paymentMethod . ',pointsColumn=' . $pointsColumn . ',locked=' . intval($locked) . ',refid=' . getUserData('refid'));
123
124                 // Some percents found?
125                 if ($per > 0) {
126                         // Calculate new points
127                         $ref_points = $points * $per / 100;
128
129                         // Pay refback here if level > 0 and in ref-mode
130                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',paymentMethod=' . $paymentMethod);
131                         if (($userid != $refid) && ($paymentMethod == 'REFERRAL') && (isValidUserId(getUserData('refid'))) && (isExtensionActive('refback'))) {
132                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - BEFORE!');
133                                 $ref_points = addRefbackPoints($userid, getUserData('refid'), $points, $ref_points);
134                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - AFTER!');
135                         } // END - if
136
137                         // Update points...
138                         if (is_null($GLOBALS['ref_level'])) {
139                                 // Level NULL (self)
140                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth` IS NULL LIMIT 1",
141                                         array(
142                                                 $pointsColumn,
143                                                 $pointsColumn,
144                                                 $ref_points,
145                                                 bigintval($userid)
146                                         ), __FUNCTION__, __LINE__);
147                         } else {
148                                 // Level 1+
149                                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
150                                         array(
151                                                 $pointsColumn,
152                                                 $pointsColumn,
153                                                 $ref_points,
154                                                 bigintval($userid),
155                                                 bigintval($GLOBALS['ref_level'])
156                                         ), __FUNCTION__, __LINE__);
157                         }
158                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'pointsColumn='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.convertNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - UPDATE! ('.SQL_AFFECTEDROWS().')');
159
160                         // No entry updated?
161                         if (SQL_HASZEROAFFECTED()) {
162                                 // First ref in this level! :-)
163                                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`,`ref_depth`,`%s`) VALUES (%s, %s, %s)",
164                                         array(
165                                                 $pointsColumn,
166                                                 bigintval($userid),
167                                                 convertZeroToNull($GLOBALS['ref_level']),
168                                                 $ref_points
169                                         ), __FUNCTION__, __LINE__);
170                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.convertNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - INSERTED! ('.SQL_AFFECTEDROWS().')');
171                         } // END - if
172
173                         // Check affected rows
174                         $added = (SQL_AFFECTEDROWS() == 1);
175                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - BEFORE FILTER');
176
177                         // Prepare data for the filter
178                         $filterData = array(
179                                 'subject'     => $subject,
180                                 'userid'      => $userid,
181                                 'points'      => $points,
182                                 'ref_points'  => $ref_points,
183                                 'column'      => $pointsColumn,
184                                 'notify'      => $sendNotify,
185                                 'refid'       => $refid,
186                                 'locked'      => $locked,
187                                 'points_mode' => 'add',
188                                 'add_mode'    => $paymentMethod,
189                                 'added'       => $added
190                         );
191
192                         // Filter it now
193                         $filterData = runFilterChain('post_add_points', $filterData);
194
195                         // Extract $added
196                         $added = $filterData['added'];
197                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - AFTER FILTER');
198
199                         // Points updated, maybe I shall send him an email?
200                         if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
201                                 // Prepare content
202                                 $content = array(
203                                         'percents' => $per,
204                                         'level'    => bigintval($GLOBALS['ref_level']),
205                                         'points'   => $ref_points,
206                                 );
207
208                                 // Load email template
209                                 $message = loadEmailTemplate('guest_user_confirmed_referral', $content, bigintval($userid));
210
211                                 // Send email
212                                 sendEmail($userid, '{--THANX_REFERRAL_ONE_SUBJECT--}', $message);
213                         } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($paymentMethod == 'DIRECT')) {
214                                 // Prepare content
215                                 $content = array(
216                                         'reason'  => '{--REASON_DIRECT_PAYMENT--}',
217                                         'subject' => $subject,
218                                         'points'  => $ref_points
219                                 );
220
221                                 // Load message
222                                 $message = loadEmailTemplate('member_add_points', $content, $userid);
223
224                                 // And sent it away
225                                 sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
226                                 if (!isGetRequestElementSet('mid')) {
227                                         // Output message to admin
228                                         displayMessage('{--ADMIN_POINTS_ADDED--}');
229                                 } // END - if
230                         }
231
232                         // Increase referral level, if payment method is REFERRAL
233                         if ($paymentMethod == 'REFERRAL') {
234                                 // Increase it
235                                 $GLOBALS['ref_level']++;
236                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
237                         } elseif (isDebugModeEnabled()) {
238                                 // Not increasing referral level, DIRECT payment method
239                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level *NOT* increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
240                         }
241
242                         // Maybe there's another ref?
243                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',refid(var|data)=' . convertNullToZero($refid) . '|' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
244                         if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($paymentMethod == 'REFERRAL')) {
245                                 // Then let's credit him here...
246                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',ref_points=' . $ref_points . ',added[' . gettype($added) . ']=' . intval($added) . ' - ADVANCE!');
247                                 $added = ($added && addPointsThroughReferralSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, getFetchedUserData('userid', getUserData('refid'), 'refid')));
248                         } // END - if
249                 } // END - if
250         } // END - if
251
252         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',sendNotify=' . intval($sendNotify) . ',refid=' . convertNullToZero($refid) . ',paymentMethod=' . $paymentMethod . ' - EXIT!');
253         return $added;
254 }
255
256 // Updates the referral counter
257 function updateReferralCounter ($userid) {
258         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
259         // Init referral id
260         $ref = NULL;
261
262         // Check for his referral
263         if (fetchUserData($userid)) {
264                 // Get it
265                 $ref = getUserData('refid');
266                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . convertZeroToNull($ref) . ' - FETCHED!');
267         } // END - if
268
269         // Init entries
270         if (empty($GLOBALS['cache_array']['ref_level'][$userid])) {
271                 $GLOBALS['cache_array']['ref_level'][$userid] = NULL;
272         } // END - if
273         if (empty($GLOBALS['cache_array']['ref_level'][$ref])) {
274                 $GLOBALS['cache_array']['ref_level'][$ref] = NULL;
275         } // END - if
276
277         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . convertZeroToNull($ref));
278
279         // When he has a referral...
280         if (($ref > 0) && ($ref != $userid)) {
281                 // Move to next referral level and count his counter one up
282                 $GLOBALS['cache_array']['ref_level'][$ref] = $GLOBALS['cache_array']['ref_level'][$userid] + 1;
283                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref(' . $ref . ')=' . $GLOBALS['cache_array']['ref_level'][$ref] . ' - ADVANCED!');
284
285                 // Update counter
286                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`=%s LIMIT 1",
287                         array(
288                                 bigintval($ref),
289                                 bigintval($GLOBALS['cache_array']['ref_level'][$ref])
290                         ), __FUNCTION__, __LINE__);
291
292                 // When no entry was updated then we have to create it here
293                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . $ref . ',level=' . $GLOBALS['cache_array']['ref_level'][$ref] . ',updated=' . SQL_AFFECTEDROWS());
294                 if (SQL_HASZEROAFFECTED()) {
295                         // First count!
296                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`,`level`,`counter`) VALUES (%s,%s,1)",
297                                 array(
298                                         bigintval($ref),
299                                         convertZeroToNull($GLOBALS['cache_array']['ref_level'][$ref])
300                                 ), __FUNCTION__, __LINE__);
301                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . $ref . ',level=' . $GLOBALS['cache_array']['ref_level'][$ref] . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS());
302                 } // END - if
303
304                 // Advance to next level
305                 updateReferralCounter($ref);
306         } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
307                 // Remove cache here
308                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . convertZeroToNull($ref) . ' - CACHE!');
309                 rebuildCache('refsystem', 'refsystem');
310         }
311
312         // Update the referral table
313         updateReferralTable($userid);
314
315         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . convertZeroToNull($ref) . ',level=' . convertZeroToNull($GLOBALS['cache_array']['ref_level'][$ref]) . ' - EXIT!');
316 }
317
318 // Subtract points from database and mediadata cache
319 function subtractPoints ($subject, $userid, $points) {
320         // Add points to used points
321         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
322                 array(
323                         $points,
324                         bigintval($userid)
325                 ), __FUNCTION__, __LINE__);
326
327         // Prepare filter data
328         $filterData = array(
329                 'subject'     => $subject,
330                 'userid'      => $userid,
331                 'points'      => $points,
332                 'points_mode' => 'sub',
333                 'added'       => (!SQL_HASZEROAFFECTED())
334         );
335
336         // Insert booking record
337         $filterData = runFilterChain('post_sub_points', $filterData);
338
339         // Return result
340         return $filterData['added'];
341 }
342 // "Getter" for array for user refs and points in given level
343 function getUserReferralPoints ($userid, $level) {
344         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - ENTERED!');
345         // Default is no refs and no nickname
346         $refs = array();
347
348         // Get refs from database
349         $result = SQL_QUERY_ESC("SELECT
350         ur.`id`, ur.`refid`, ud.`status`, ud.`last_online`, ud.`mails_confirmed`, ud.`emails_received`
351 FROM
352         `{?_MYSQL_PREFIX?}_user_refs` AS `ur`
353 LEFT JOIN
354         `{?_MYSQL_PREFIX?}_user_points` AS `up`
355 ON
356         ur.`refid`=up.`userid` AND
357         (ur.`level`=0 OR ur.`level` IS NULL)
358 LEFT JOIN
359         `{?_MYSQL_PREFIX?}_user_data` AS `ud`
360 ON
361         ur.`refid`=ud.`userid`
362 WHERE
363         ur.`userid`=%s AND
364         ur.`level`=%s
365 ORDER BY
366         ur.`refid` ASC",
367                 array(
368                         bigintval($userid),
369                         bigintval($level)
370                 ), __FUNCTION__, __LINE__);
371
372         // Are there some entries?
373         if (!SQL_HASZERONUMS($result)) {
374                 // Fetch all entries
375                 while ($row = SQL_FETCHARRAY($result)) {
376                         // Init click rate with zero
377                         $row['click_rate'] = '0';
378
379                         // Is at least one mail received?
380                         if ($row['emails_received'] > 0) {
381                                 // Calculate click rate
382                                 $row['click_rate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
383                         } // END - if
384
385                         // Activity is 'active' by default because if ext-autopurge is not installed
386                         $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
387
388                         // Is autopurge installed and the user inactive?
389                         if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online']))  {
390                                 // Inactive user!
391                                 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
392                         } // END - if
393
394                         // Remove some entries
395                         unset($row['mails_confirmed']);
396                         unset($row['emails_received']);
397                         unset($row['last_online']);
398
399                         // Add row
400                         $refs[$row['id']] = $row;
401                 } // END - while
402         } // END - if
403
404         // Free result
405         SQL_FREERESULT($result);
406
407         // Return result
408         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
409         return $refs;
410 }
411
412 // Get points data for given subject
413 function getPointsDataArrayFromSubject ($subject) {
414         // Extension ext-sql_patches must be up-to-date
415         if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
416                 // Please update ext-sql_patches
417                 debug_report_bug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
418         } // END - if
419
420         // Remove any double-dot from it
421         $subjectArray = explode(':', $subject);
422         $subject = $subjectArray[0];
423         unset($subjectArray);
424
425         // If we have cache, shortcut it here
426         if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
427                 // Return it
428                 return $GLOBALS['cache_array']['points_data'][$subject];
429         } // END - if
430
431         // Now checkout the entry in database table
432         $result = SQL_QUERY_ESC("SELECT `id`,`subject`,`column_name`,`locked_mode`,`payment_method`,`notify_recipient` FROM `{?_MYSQL_PREFIX?}_points_data` WHERE `subject`='%s' LIMIT 1",
433                 array($subject), __FUNCTION__, __LINE__);
434
435         // Do we have an entry?
436         if (SQL_NUMROWS($result) == 1) {
437                 // Then load it
438                 $pointsData = SQL_FETCHARRAY($result);
439
440                 // Add all entries to our cache array
441                 foreach ($pointsData as $key => $value) {
442                         $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
443                 } // END - foreach
444         } else {
445                 // Register this automatically
446                 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`,`notify_recipient`) VALUES ('%s','points','LOCKED','REFERRAL','N')",
447                         array($subject), __FUNCTION__, __LINE__);
448
449                 // Re-request it
450                 return getPointsDataArrayFromSubject($subject);
451         }
452
453         // Free result
454         SQL_FREERESULT($result);
455
456         // Return it
457         return $GLOBALS['cache_array']['points_data'][$subject];
458 }
459
460 // Determines the right points column name for given subject and 'locked'
461 function getPointsColumnNameFromSubjectLocked ($subject, $isLocked) {
462         // Get the points_data entry
463         $pointsData = getPointsDataArrayFromSubject($subject);
464
465         // Regular points by default
466         $columnName = $pointsData['column_name'];
467
468         // Are the points locked?
469         if (($isLocked === true) && ($pointsData['locked_mode'] == 'LOCKED')) {
470                 // Locked points, so prefix it
471                 $columnName = 'locked_' . $pointsData['column_name'];
472         } // END - if
473
474         // Return the result
475         return $columnName;
476 }
477
478 // Determines the payment method for given extension and 'locked'
479 function getPaymentMethodFromSubject ($subject) {
480         // Get the points_data entry
481         $pointsData = getPointsDataArrayFromSubject($subject);
482
483         // Regular points by default
484         $paymentMethod = $pointsData['payment_method'];
485
486         // Return the result
487         return $paymentMethod;
488 }
489
490 // Checks wether notification of points recipient is enabled
491 function isPaymentRecipientNotificationEnabled ($subject) {
492         // Get the points_data entry
493         $pointsData = getPointsDataArrayFromSubject($subject);
494
495         // Is it enabled?
496         $isEnabled = ($pointsData['notify_recipient'] == 'Y');
497
498         // Return the result
499         return $isEnabled;
500 }
501
502 // Update "referral table"
503 function updateReferralTable ($userid) {
504         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
505         // Load all referrals
506         loadReferralTable($userid);
507
508         // Add missing level > 1
509         addMissingReferralLevels($userid);
510
511         // The last step is to flush all userid's entries to the database
512         flushReferralTableToDatabase($userid);
513
514         // Rebuild cache
515         rebuildCache('refsystem', 'refsystem');
516
517         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
518 }
519
520 // Loads all referrals for given userid
521 function loadReferralTable ($userid) {
522         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
523         // Init array
524         $GLOBALS['referral_refid'][$userid] = array();
525
526         // Get all level entries from the refsystem table
527         $result = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
528                 array($userid), __FUNCTION__, __LINE__);
529
530         // Do we have entries?
531         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($result));
532         if (SQL_NUMROWS($result) > 0) {
533                 // Then walk through all levels
534                 while (list($level) = SQL_FETCHROW($result)) {
535                         // Init array
536                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
537                         $GLOBALS['referral_refid'][$userid][$level] = array();
538
539                         // Level is = 1?
540                         if ($level == 1) {
541                                 // Load all referrals of this user
542                                 $result_refs = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
543                                         array($userid), __FUNCTION__, __LINE__);
544
545                                 // Do we have entries?
546                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($result_refs));
547                                 if (SQL_NUMROWS($result_refs) > 0) {
548                                         // Then again walk through all
549                                         while (list($refid) = SQL_FETCHROW($result_refs)) {
550                                                 // Add this refid
551                                                 $GLOBALS['referral_refid'][$userid][$level][] = $refid;
552                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
553                                                 // Load the refid's array as well
554                                                 loadReferralTable($refid);
555                                         } // END - while
556                                 } // END - if
557
558                                 // Free result
559                                 SQL_FREERESULT($result_refs);
560                         } // END - if
561                 } // END - while
562         } // END - if
563
564         // Free result
565         SQL_FREERESULT($result);
566         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
567 }
568
569 // Adds missing referral levels to the array
570 function addMissingReferralLevels ($userid) {
571         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
572         // If the array is gone, you have called this function without calling loadReferralTable()
573         if (!isset($GLOBALS['referral_refid'][$userid])) {
574                 // Please fix your code
575                 debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
576         } // END - if
577         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
578
579         // Now walk through the array, first levels
580         foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
581                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
582                 // Next are the users
583                 foreach ($levelArray as $refid) {
584                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
585                         // Does the refid have an array?
586                         if (isset($GLOBALS['referral_refid'][$refid])) {
587                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',count()=' . count($GLOBALS['referral_refid'][$refid]));
588                                 // Okay, then walk through here, too
589                                 foreach ($GLOBALS['referral_refid'][$refid] as $refLevel => $refArray) {
590                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',count()=' . count($refArray));
591                                         // Also walk through this one
592                                         foreach ($refArray as $refRefid) {
593                                                 // Calculate new level
594                                                 $newLevel =  $level + $refLevel;
595                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',refRefid=' . $refRefid . ',newLevel=' . $newLevel);
596                                                 // Is the refRefid not in?
597                                                 if ((!isset($GLOBALS['referral_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referral_refid'][$userid][$newLevel]))) {
598                                                         // Then we must add this ref's refid to the userid's next level
599                                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
600                                                         $GLOBALS['referral_refid'][$userid][$newLevel][] = $refRefid;
601                                                 } // END - if
602                                         } // END - foreach
603                                 } // END - foreach
604                         } // END - foreach
605                 } // END - foreach
606         } // END - foreach
607         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
608 }
609
610 // Flush all entries for given userid to database
611 function flushReferralTableToDatabase ($userid) {
612         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
613         // If the array is gone, you have called this function without calling loadReferralTable()
614         if (!isset($GLOBALS['referral_refid'][$userid])) {
615                 // Please fix your code
616                 debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
617         } // END - if
618         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
619
620         // If no entries are there, skip this whole step
621         if (count($GLOBALS['referral_refid'][$userid]) == 0) {
622                 // No entries found
623                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
624                 return;
625         } // END - if
626
627         // Prepare SQL
628         $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES ';
629         $executeSql = false;
630
631         // Now walk through the array, first levels
632         foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
633                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
634                 // Next are the users
635                 foreach ($levelArray as $refid) {
636                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
637                         // Query the user_refs table
638                         list($count) = SQL_FETCHROW(SQL_QUERY_ESC('SELECT COUNT(`id`) AS `count` FROM `{?_MYSQL_PREFIX?}_user_refs` WHERE `userid`=%s AND `level`=%s AND `refid`=%s LIMIT 1',
639                                 array(
640                                         $userid,
641                                         $level,
642                                         $refid
643                                 ), __FUNCTION__, __LINE__));
644
645                         // Do we have no entry?
646                         if ($count == 0) {
647                                 // Then add it to the SQL
648                                 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
649
650                                 // Some has been added, so execute the query
651                                 $executeSql = true;
652                         } // END - if
653                 } // END - foreach
654         } // END - foreach
655
656         // Remove last comma from SQL
657         $SQL = substr($SQL, 0, -1);
658
659         // And run it
660         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
661         if ($executeSql === true) {
662                 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
663         } // END - if
664
665         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
666 }
667
668 // [EOF]
669 ?>