2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 07/12/2011 *
4 * =================== Last change: 07/12/2011 *
6 * -------------------------------------------------------------------- *
7 * File : referral-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : All referral system functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle zum Referral-System gehoerenden Funktionen *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
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 *
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. *
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. *
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, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
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;
50 // Getter fro ref level percents
51 function getReferralLevelPercents ($level) {
53 $data['percents'] = '0';
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']);
61 $data['percents'] = $GLOBALS['cache_array']['refdepths']['percents'][$key];
64 incrementStatsEntry('cache_hits');
66 } elseif (!isExtensionActive('cache')) {
68 $result_level = SQL_QUERY_ESC("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`=%s LIMIT 1",
69 array(bigintval($level)), __FUNCTION__, __LINE__);
72 if (SQL_NUMROWS($result_level) == 1) {
74 $data = SQL_FETCHARRAY($result_level);
78 SQL_FREERESULT($result_level);
82 return $data['percents'];
86 * Dynamic referral and points system, can also send mails!
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
93 function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NULL) {
94 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',refid=' . makeNullToZero($refid) . ' - ENTERED!');
95 // By default nothing has been added
98 // Determine payment method and notification
99 $paymentMethod = strtoupper(getPaymentMethodFromSubject($subject));
100 $sendNotify = isPaymentRecipientNotificationEnabled($subject);
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);
108 // Set userid as current
109 setCurrentUserId($userid);
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);
117 // Detect database column
118 $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $locked);
121 $per = getReferralLevelPercents($GLOBALS['ref_level']);
122 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',points=' . $points . ',depth=' . makeNullToZero($GLOBALS['ref_level']) . ',per=' . $per . ',mode=' . $paymentMethod . ',pointsColumn=' . $pointsColumn . ',locked=' . intval($locked) . ',refid=' . getUserData('refid'));
124 // Some percents found?
126 // Calculate new points
127 $ref_points = $points * $per / 100;
129 // Pay refback here if level > 0 and in ref-mode
130 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . makeNullToZero(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=' . makeNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . makeNullToZero($GLOBALS['ref_level']) . ' - BEFORE!');
133 $ref_points = addRefbackPoints($userid, getUserData('refid'), $points, $ref_points);
134 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . makeNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . makeNullToZero($GLOBALS['ref_level']) . ' - AFTER!');
138 if (is_null($GLOBALS['ref_level'])) {
140 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth` IS NULL LIMIT 1",
146 ), __FUNCTION__, __LINE__);
149 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth`=%s LIMIT 1",
155 bigintval($GLOBALS['ref_level'])
156 ), __FUNCTION__, __LINE__);
158 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'pointsColumn='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.makeNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - UPDATE! ('.SQL_AFFECTEDROWS().')');
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)",
167 makeZeroToNull($GLOBALS['ref_level']),
169 ), __FUNCTION__, __LINE__);
170 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.makeNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - INSERTED! ('.SQL_AFFECTEDROWS().')');
173 // Check affected rows
174 $added = (SQL_AFFECTEDROWS() == 1);
175 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - BEFORE FILTER');
177 // Prepare data for the filter
179 'subject' => $subject,
182 'ref_points' => $ref_points,
183 'column' => $pointsColumn,
184 'notify' => $sendNotify,
188 'add_mode' => $paymentMethod,
193 $filterData = runFilterChain('post_add_points', $filterData);
196 $added = $filterData['added'];
197 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - AFTER FILTER');
199 // Points updated, maybe I shall send him an email?
200 if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
204 'level' => bigintval($GLOBALS['ref_level']),
205 'points' => $ref_points,
208 // Load email template
209 $message = loadEmailTemplate('guest_user_confirmed_referral', $content, bigintval($userid));
212 sendEmail($userid, '{--THANX_REFERRAL_ONE_SUBJECT--}', $message);
213 } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($paymentMethod == 'DIRECT')) {
216 'reason' => '{--REASON_DIRECT_PAYMENT--}',
217 'subject' => $subject,
218 'points' => $ref_points
222 $message = loadEmailTemplate('member_add_points', $content, $userid);
225 sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
226 if (!isGetRequestElementSet('mid')) {
227 // Output message to admin
228 displayMessage('{--ADMIN_POINTS_ADDED--}');
232 // Increase referral level, if payment method is REFERRAL
233 if ($paymentMethod == 'REFERRAL') {
235 $GLOBALS['ref_level']++;
236 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level increased, ref_level=' . makeNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . makeNullToZero(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=' . makeNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . makeNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
242 // Maybe there's another ref?
243 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',refid(var|data)=' . makeNullToZero($refid) . '|' . makeNullToZero(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=' . makeNullToZero(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')));
252 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',sendNotify=' . intval($sendNotify) . ',refid=' . makeNullToZero($refid) . ',paymentMethod=' . $paymentMethod . ' - EXIT!');
256 // Updates the referral counter
257 function updateReferralCounter ($userid) {
258 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
262 // Check for his referral
263 if (fetchUserData($userid)) {
265 $ref = getUserData('refid');
266 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . makeZeroToNull($ref) . ' - FETCHED!');
270 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) {
271 $GLOBALS['cache_array']['ref_level'][$userid] = NULL;
273 if (empty($GLOBALS['cache_array']['ref_level'][$ref])) {
274 $GLOBALS['cache_array']['ref_level'][$ref] = NULL;
277 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . makeZeroToNull($ref));
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!');
286 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`=%s LIMIT 1",
289 bigintval($GLOBALS['cache_array']['ref_level'][$ref])
290 ), __FUNCTION__, __LINE__);
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()) {
296 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`,`level`,`counter`) VALUES (%s,%s,1)",
299 makeZeroToNull($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());
304 // Advance to next level
305 updateReferralCounter($ref);
306 } elseif ((($ref == $userid) || ($ref == '0')) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ref=' . makeZeroToNull($ref) . ' - CACHE!');
309 rebuildCache('refsystem', 'refsystem');
312 // Update the referral table
313 updateReferralTable($userid);
315 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',ref=' . makeZeroToNull($ref) . ',level=' . makeZeroToNull($GLOBALS['cache_array']['ref_level'][$ref]) . ' - EXIT!');
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",
325 ), __FUNCTION__, __LINE__);
327 // Prepare filter data
329 'subject' => $subject,
333 'added' => (!SQL_HASZEROAFFECTED())
336 // Insert booking record
337 $filterData = runFilterChain('post_sub_points', $filterData);
340 return $filterData['added'];
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
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`
352 `{?_MYSQL_PREFIX?}_user_refs` AS `ur`
354 `{?_MYSQL_PREFIX?}_user_points` AS `up`
356 ur.`refid`=up.`userid` AND
357 (ur.`level`=0 OR ur.`level` IS NULL)
359 `{?_MYSQL_PREFIX?}_user_data` AS `ud`
361 ur.`refid`=ud.`userid`
370 ), __FUNCTION__, __LINE__);
372 // Are there some entries?
373 if (!SQL_HASZERONUMS($result)) {
375 while ($row = SQL_FETCHARRAY($result)) {
376 // Init click rate with zero
377 $row['click_rate'] = '0';
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);
385 // Activity is 'active' by default because if ext-autopurge is not installed
386 $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
388 // Is autopurge installed and the user inactive?
389 if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online'])) {
391 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
394 // Remove some entries
395 unset($row['mails_confirmed']);
396 unset($row['emails_received']);
397 unset($row['last_online']);
400 $refs[$row['id']] = $row;
405 SQL_FREERESULT($result);
408 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
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);
420 // Remove any double-dot from it
421 $subjectArray = explode(':', $subject);
422 $subject = $subjectArray[0];
423 unset($subjectArray);
425 // If we have cache, shortcut it here
426 if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
428 return $GLOBALS['cache_array']['points_data'][$subject];
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__);
435 // Do we have an entry?
436 if (SQL_NUMROWS($result) == 1) {
438 $pointsData = SQL_FETCHARRAY($result);
440 // Add all entries to our cache array
441 foreach ($pointsData as $key=>$value) {
442 $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
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__);
450 return getPointsDataArrayFromSubject($subject);
454 SQL_FREERESULT($result);
457 return $GLOBALS['cache_array']['points_data'][$subject];
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);
465 // Regular points by default
466 $columnName = $pointsData['column_name'];
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'];
478 // Determines the payment method for given extension and 'locked'
479 function getPaymentMethodFromSubject ($subject) {
480 // Get the points_data entry
481 $pointsData = getPointsDataArrayFromSubject($subject);
483 // Regular points by default
484 $paymentMethod = $pointsData['payment_method'];
487 return $paymentMethod;
490 // Checks wether notification of points recipient is enabled
491 function isPaymentRecipientNotificationEnabled ($subject) {
492 // Get the points_data entry
493 $pointsData = getPointsDataArrayFromSubject($subject);
496 $isEnabled = ($pointsData['notify_recipient'] == 'Y');
502 // Update "referral table"
503 function updateReferralTable ($userid) {
504 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
505 // Load all referrals
506 loadReferralTable($userid);
508 // Add missing level > 1
509 addMissingReferralLevels($userid);
511 // The last step is to flush all userid's entries to the database
512 flushReferralTableToDatabase($userid);
515 rebuildCache('refsystem', 'refsystem');
517 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
520 // Loads all referrals for given userid
521 function loadReferralTable ($userid) {
522 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
524 $GLOBALS['referral_refid'][$userid] = array();
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__);
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)) {
536 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
537 $GLOBALS['referral_refid'][$userid][$level] = array();
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__);
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)) {
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);
559 SQL_FREERESULT($result_refs);
565 SQL_FREERESULT($result);
566 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
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);
577 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
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=' . makeNullToZero($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=' . makeNullToZero($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=' . makeNullToZero($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;
607 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
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);
618 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
620 // If no entries are there, skip this whole step
621 if (count($GLOBALS['referral_refid'][$userid]) == 0) {
623 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
628 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES ';
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',
643 ), __FUNCTION__, __LINE__));
645 // Do we have no entry?
647 // Then add it to the SQL
648 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
650 // Some has been added, so execute the query
656 // Remove last comma from SQL
657 $SQL = substr($SQL, 0, -1);
660 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
661 if ($executeSql === true) {
662 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
665 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');