2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 07/12/2011 *
4 * =================== Last change: 07/12/2011 *
6 * -------------------------------------------------------------------- *
7 * File : referal-functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : All referal system functions *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Alle zum Referal-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://www.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 referal system
44 function initReferalSystem () {
45 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ' Referal system initialized!');
46 $GLOBALS['ref_level'] = NULL;
47 $GLOBALS['ref_system'] = true;
50 // Getter fro ref level percents
51 function getReferalLevelPercents ($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 referal and points system, can also send mails!
88 * subject = Subject line, write in lower-case letters and underscore is allowed
89 * userid = Referal id wich should receive...
90 * points = ... xxx points
91 * refid = inc/modules/guest/what-confirm.php need this
93 function addPointsThroughReferalSystem ($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 = getReferalLevelPercents($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 == 'REFERAL') && (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_referal', $content, bigintval($userid));
212 sendEmail($userid, '{--THANX_REFERAL_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 (!isGetRequestParameterSet('mid')) {
227 // Output message to admin
228 displayMessage('{--ADMIN_POINTS_ADDED--}');
232 // Increase referal level, if payment method is REFERAL
233 if ($paymentMethod == 'REFERAL') {
235 $GLOBALS['ref_level']++;
236 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referal level increased, ref_level=' . makeNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . makeNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
237 } elseif (isDebugModeEnabled()) {
238 // Not increasing referal level, DIRECT payment method
239 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referal 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 == 'REFERAL')) {
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 && addPointsThroughReferalSystem(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 referal counter
257 function updateReferalCounter ($userid) {
258 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
262 // Check for his referal
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 referal...
280 if (($ref > 0) && ($ref != $userid)) {
281 // Move to next referal 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 updateReferalCounter($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 referal table
313 updateReferalTable($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 getUserReferalPoints ($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 // Get total points of this user
377 $row['points'] = getTotalPoints($row['refid']);
379 // Get unconfirmed mails
380 $row['unconfirmed'] = getTotalUnconfirmedMails($row['refid']);
382 // Init click rate with zero
383 $row['click_rate'] = '0';
385 // Is at least one mail received?
386 if ($row['emails_received'] > 0) {
387 // Calculate click rate
388 $row['click_rate'] = ($row['mails_confirmed'] / $row['emails_received'] * 100);
391 // Activity is 'active' by default because if autopurge is not installed
392 $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
394 // Is autopurge installed and the user inactive?
395 if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online'])) {
397 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
400 // Remove some entries
401 unset($row['mails_confirmed']);
402 unset($row['emails_received']);
403 unset($row['last_online']);
406 $refs[$row['id']] = $row;
411 SQL_FREERESULT($result);
414 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
418 // Get points data for given subject
419 function getPointsDataArrayFromSubject ($subject) {
420 // Extension ext-sql_patches must be up-to-date
421 if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
422 // Please update ext-sql_patches
423 debug_report_bug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
426 // Remove any double-dot from it
427 $subjectArray = explode(':', $subject);
428 $subject = $subjectArray[0];
429 unset($subjectArray);
431 // If we have cache, shortcut it here
432 if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
434 return $GLOBALS['cache_array']['points_data'][$subject];
437 // Now checkout the entry in database table
438 $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",
439 array($subject), __FUNCTION__, __LINE__);
441 // Do we have an entry?
442 if (SQL_NUMROWS($result) == 1) {
444 $pointsData = SQL_FETCHARRAY($result);
446 // Add all entries to our cache array
447 foreach ($pointsData as $key=>$value) {
448 $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
451 // Register this automatically
452 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`,`column_name`,`locked_mode`,`payment_method`,`notify_recipient`) VALUES ('%s','points','LOCKED','REFERAL','N')",
453 array($subject), __FUNCTION__, __LINE__);
456 return getPointsDataArrayFromSubject($subject);
460 SQL_FREERESULT($result);
463 return $GLOBALS['cache_array']['points_data'][$subject];
466 // Determines the right points column name for given subject and 'locked'
467 function getPointsColumnNameFromSubjectLocked ($subject, $isLocked) {
468 // Get the points_data entry
469 $pointsData = getPointsDataArrayFromSubject($subject);
471 // Regular points by default
472 $columnName = $pointsData['column_name'];
474 // Are the points locked?
475 if (($isLocked === true) && ($pointsData['locked_mode'] == 'LOCKED')) {
476 // Locked points, so prefix it
477 $columnName = 'locked_' . $pointsData['column_name'];
484 // Determines the payment method for given extension and 'locked'
485 function getPaymentMethodFromSubject ($subject) {
486 // Get the points_data entry
487 $pointsData = getPointsDataArrayFromSubject($subject);
489 // Regular points by default
490 $paymentMethod = $pointsData['payment_method'];
493 return $paymentMethod;
496 // Checks wether notification of points recipient is enabled
497 function isPaymentRecipientNotificationEnabled ($subject) {
498 // Get the points_data entry
499 $pointsData = getPointsDataArrayFromSubject($subject);
502 $isEnabled = ($pointsData['notify_recipient'] == 'Y');
508 // Update "referal table"
509 function updateReferalTable ($userid) {
510 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
512 loadReferalTable($userid);
514 // Add missing level > 1
515 addMissingReferalLevels($userid);
517 // The last step is to flush all userid's entries to the database
518 flushReferalTableToDatabase($userid);
521 rebuildCache('refsystem', 'refsystem');
523 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
526 // Loads all referals for given userid
527 function loadReferalTable ($userid) {
528 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
530 $GLOBALS['referal_refid'][$userid] = array();
532 // Get all level entries from the refsystem table
533 $result = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
534 array($userid), __FUNCTION__, __LINE__);
536 // Do we have entries?
537 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($result));
538 if (SQL_NUMROWS($result) > 0) {
539 // Then walk through all levels
540 while (list($level) = SQL_FETCHROW($result)) {
542 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
543 $GLOBALS['referal_refid'][$userid][$level] = array();
547 // Load all referals of this user
548 $result_refs = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
549 array($userid), __FUNCTION__, __LINE__);
551 // Do we have entries?
552 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($result_refs));
553 if (SQL_NUMROWS($result_refs) > 0) {
554 // Then again walk through all
555 while (list($refid) = SQL_FETCHROW($result_refs)) {
557 $GLOBALS['referal_refid'][$userid][$level][] = $refid;
558 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
559 // Load the refid's array as well
560 loadReferalTable($refid);
565 SQL_FREERESULT($result_refs);
571 SQL_FREERESULT($result);
572 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
575 // Adds missing referal levels to the array
576 function addMissingReferalLevels ($userid) {
577 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
578 // If the array is gone, you have called this function without calling loadReferalTable()
579 if (!isset($GLOBALS['referal_refid'][$userid])) {
580 // Please fix your code
581 debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferalTable() before! userid=' . $userid);
583 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referal_refid'][$userid]));
585 // Now walk through the array, first levels
586 foreach ($GLOBALS['referal_refid'][$userid] as $level=>$levelArray) {
587 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
588 // Next are the users
589 foreach ($levelArray as $refid) {
590 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
591 // Does the refid have an array?
592 if (isset($GLOBALS['referal_refid'][$refid])) {
593 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . makeNullToZero($refid) . ',count()=' . count($GLOBALS['referal_refid'][$refid]));
594 // Okay, then walk through here, too
595 foreach ($GLOBALS['referal_refid'][$refid] as $refLevel=>$refArray) {
596 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . makeNullToZero($refid) . ',refLevel=' . $refLevel . ',count()=' . count($refArray));
597 // Also walk through this one
598 foreach ($refArray as $refRefid) {
599 // Calculate new level
600 $newLevel = $level + $refLevel;
601 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . makeNullToZero($refid) . ',refLevel=' . $refLevel . ',refRefid=' . $refRefid . ',newLevel=' . $newLevel);
602 // Is the refRefid not in?
603 if ((!isset($GLOBALS['referal_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referal_refid'][$userid][$newLevel]))) {
604 // Then we must add this ref's refid to the userid's next level
605 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
606 $GLOBALS['referal_refid'][$userid][$newLevel][] = $refRefid;
613 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
616 // Flush all entries for given userid to database
617 function flushReferalTableToDatabase ($userid) {
618 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
619 // If the array is gone, you have called this function without calling loadReferalTable()
620 if (!isset($GLOBALS['referal_refid'][$userid])) {
621 // Please fix your code
622 debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferalTable() before! userid=' . $userid);
624 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referal_refid'][$userid]));
626 // If no entries are there, skip this whole step
627 if (count($GLOBALS['referal_refid'][$userid]) == 0) {
629 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
634 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`,`level`,`refid`) VALUES ';
637 // Now walk through the array, first levels
638 foreach ($GLOBALS['referal_refid'][$userid] as $level=>$levelArray) {
639 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
640 // Next are the users
641 foreach ($levelArray as $refid) {
642 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
643 // Query the user_refs table
644 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',
649 ), __FUNCTION__, __LINE__));
651 // Do we have no entry?
653 // Then add it to the SQL
654 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
656 // Some has been added, so execute the query
662 // Remove last comma from SQL
663 $SQL = substr($SQL, 0, -1);
666 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
667 if ($executeSql === true) {
668 SQL_QUERY($SQL, __FUNCTION__, __LINE__);
671 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');