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 - 2013 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 = sqlQueryEscaped("SELECT `percents` FROM `{?_MYSQL_PREFIX?}_refdepths` WHERE `level`=%s LIMIT 1",
69 array(bigintval($level)), __FUNCTION__, __LINE__);
72 if (sqlNumRows($result_level) == 1) {
74 $data = sqlFetchArray($result_level);
78 sqlFreeResult($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=' . convertNullToZero($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 ((!isValidId($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__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify));
113 if (fetchUserData($userid)) {
114 // Determine whether the user has some mails to click before he/she gets the points
115 $isLocked = ifUserPointsLocked($userid);
117 // Detect database column
118 $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $isLocked);
121 $percents = getReferralLevelPercents($GLOBALS['ref_level']);
122 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ',percents=' . $percents . ',mode=' . $paymentMethod . ',pointsColumn=' . $pointsColumn . ',isLocked=' . intval($isLocked) . ',refid=' . getUserData('refid'));
124 // Some percents found?
126 // Calculate new points
127 $ref_points = $points * $percents / 100;
129 // Pay refback here if level > 0 and in ref-mode
130 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',paymentMethod=' . $paymentMethod);
131 if (($userid != $refid) && (substr($subject, 0, 8) != 'refback:') &&($paymentMethod == 'REFERRAL') && (isValidId(getUserData('refid'))) && (isExtensionActive('refback'))) {
132 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',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__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - AFTER!');
138 if (is_null($GLOBALS['ref_level'])) {
140 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_points` SET `%s`=`%s`+%s WHERE `userid`=%s AND `ref_depth` IS NULL LIMIT 1",
146 ), __FUNCTION__, __LINE__);
149 sqlQueryEscaped("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='.convertNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - UPDATE! ('.sqlAffectedRows().')');
161 if (ifSqlHasZeroAffectedRows()) {
162 // First ref in this level! :-)
163 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_user_points` (`userid`, `ref_depth`, `%s`) VALUES (%s, %s, %s)",
167 convertZeroToNull($GLOBALS['ref_level']),
169 ), __FUNCTION__, __LINE__);
170 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'data='.$pointsColumn.',ref_points='.$ref_points.',userid='.$userid.',depth='.convertNullToZero($GLOBALS['ref_level']).',mode='.$paymentMethod.' - INSERTED! ('.sqlAffectedRows().')');
173 // Check affected rows
174 $added = (sqlAffectedRows() == 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,
186 'locked' => $isLocked,
187 'points_mode' => 'add',
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');
200 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . $refid . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify) . ',isLocked=' . intval($isLocked));
202 // Send "referral confirmed" mails out?
203 if ((isValidId($refid)) && ($refid != $userid) && ($sendNotify === TRUE)) {
204 // Calculate the referral's points and percents
205 $percentsReferral = getReferralLevelPercents($GLOBALS['ref_level'] + 1);
207 // Calculate new points
208 $ref_points = $ref_points * $percentsReferral / 100;
212 'userid' => bigintval($userid),
214 'level' => bigintval($GLOBALS['ref_level'] + 1),
215 'percents' => $percentsReferral,
216 'points' => ($paymentMethod == 'REFERRAL' ? $ref_points : '0'),
217 'payment_method' => $paymentMethod,
218 'subject' => $subject,
221 // Load email template
222 $message = loadEmailTemplate('guest_user_confirmed_referral', $content, bigintval($userid));
225 sendEmail($userid, '{--THANKS_REFERRAL_ONE_SUBJECT--}', $message);
228 // Points updated, maybe I shall send him an email?
229 if (($sendNotify === TRUE) && ($isLocked === FALSE)) {
231 $subjectArray = explode(':', $subject);
232 $subjectUserid = (isset($subjectArray[1])) ? $subjectArray[1] : '0';
234 // Generic delivery of mails, so prepare data
237 'percents' => $percents,
238 'level' => bigintval($GLOBALS['ref_level']),
239 'points' => $ref_points,
240 'column' => $pointsColumn,
241 'subject' => $subjectArray[0],
242 'subject_userid' => $subjectUserid,
243 'payment_method' => $paymentMethod,
246 // Load email template
247 $message = loadEmailTemplate('member_' . $subjectArray[0] . '_' . strtolower($paymentMethod), $content, $userid);
250 sendEmail($userid, '{%message,MEMBER_' . $paymentMethod . '_' . strtoupper($subjectArray[0]) . '_SUBJECT=' . $subjectUserid . '%}', $message);
252 // Also send admin notification
253 sendAdminNotification(
255 '{%message,ADMIN_' . $paymentMethod . '_' . strtoupper($subjectArray[0]) . '_SUBJECT=' . $subjectUserid . '%}',
257 'admin_' . $subjectArray[0] . '_' . strtolower($paymentMethod),
258 // Template content (data array)
265 // Increase referral level, if payment method is 'REFERRAL'
266 if ($paymentMethod == 'REFERRAL') {
268 $GLOBALS['ref_level']++;
269 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
270 } elseif (isDebugModeEnabled()) {
271 // Not increasing referral level, DIRECT payment method
272 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level *NOT* increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
276 $subject = removeDoubleDotFromSubject($subject);
278 // Maybe there's another ref?
279 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',refid(var|data)=' . convertNullToZero($refid) . '|' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod . ',subject=' . $subject . ',ref_level=' . $GLOBALS['ref_level']);
280 if (($paymentMethod == 'REFERRAL') && (isValidId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid)) {
282 if (ifSubjectHasReferralSuffix($subject)) {
283 // Then remove it, no double _ref suffix!
284 $subject = substr($subject, 0, -4);
287 // Then let's credit him here...
288 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',ref_points=' . $ref_points . ',added[' . gettype($added) . ']=' . intval($added) . ',ref_level=' . $GLOBALS['ref_level'] . ' - ADVANCE!');
289 $added = ($added && addPointsThroughReferralSystem(sprintf('%s_ref:%s', $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, getFetchedUserData('userid', getUserData('refid'), 'refid')));
294 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',sendNotify=' . intval($sendNotify) . ',refid=' . convertNullToZero($refid) . ',paymentMethod=' . $paymentMethod . ' - EXIT!');
298 // Updates the referral counter
299 function updateReferralCounter ($userid) {
300 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
304 // Check for his referral
305 if (fetchUserData($userid)) {
307 $refid = getUserData('refid');
308 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertZeroToNull($refid) . ' - FETCHED!');
312 if (empty($GLOBALS['cache_array']['ref_level'][$userid])) {
313 $GLOBALS['cache_array']['ref_level'][$userid] = NULL;
315 if (empty($GLOBALS['cache_array']['ref_level'][$refid])) {
316 $GLOBALS['cache_array']['ref_level'][$refid] = NULL;
319 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertZeroToNull($refid));
321 // When he has a referral...
322 if ((isValidId($refid)) && ($refid != $userid)) {
323 // Move to next referral level and count his counter one up
324 $GLOBALS['cache_array']['ref_level'][$refid] = $GLOBALS['cache_array']['ref_level'][$userid] + 1;
325 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid(' . $refid . ')=' . $GLOBALS['cache_array']['ref_level'][$refid] . ' - ADVANCED!');
328 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_refsystem` SET `counter`=`counter`+1 WHERE `userid`=%s AND `level`=%s LIMIT 1",
331 bigintval($GLOBALS['cache_array']['ref_level'][$refid])
332 ), __FUNCTION__, __LINE__);
334 // When no entry was updated then we have to create it here
335 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ',level=' . $GLOBALS['cache_array']['ref_level'][$refid] . ',updated=' . sqlAffectedRows());
336 if (ifSqlHasZeroAffectedRows()) {
338 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_refsystem` (`userid`, `level`, `counter`) VALUES (%s,%s,1)",
341 convertZeroToNull($GLOBALS['cache_array']['ref_level'][$refid])
342 ), __FUNCTION__, __LINE__);
343 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . $refid . ',level=' . $GLOBALS['cache_array']['ref_level'][$refid] . ',sqlAffectedRows()=' . sqlAffectedRows());
346 // Advance to next level
347 updateReferralCounter($refid);
348 } elseif ((($refid == $userid) || (!isValidId($refid))) && (isExtensionInstalledAndNewer('cache', '0.1.2'))) {
350 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'refid=' . convertZeroToNull($refid) . ' - CACHE!');
351 rebuildCache('refsystem', 'refsystem');
354 // Update the referral table
355 updateReferralTable($userid);
357 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertZeroToNull($refid) . ',level=' . convertZeroToNull($GLOBALS['cache_array']['ref_level'][$refid]) . ' - EXIT!');
360 // Subtract points from database and mediadata cache
361 function subtractPoints ($subject, $userid, $points) {
362 // Add points to used points
363 sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `used_points`=`used_points`+%s WHERE `userid`=%s LIMIT 1",
367 ), __FUNCTION__, __LINE__);
369 // Prepare filter data
371 'subject' => $subject,
374 'points_mode' => 'sub',
375 'column' => 'used_points',
376 'added' => (!ifSqlHasZeroAffectedRows())
379 // Insert booking record
380 $filterData = runFilterChain('post_sub_points', $filterData);
383 return $filterData['added'];
385 // "Getter" for array for user refs and points in given level
386 function getUserReferralPoints ($userid, $level) {
387 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - ENTERED!');
388 // Default is no refs and no nickname
391 // Get refs from database
392 $result = sqlQueryEscaped('SELECT
397 `ud`.`mails_confirmed`,
398 `ud`.`emails_received`,
401 `{?_MYSQL_PREFIX?}_user_refs` AS `ur`
403 `{?_MYSQL_PREFIX?}_user_points` AS `up`
405 `ur`.`refid`=`up`.`userid` AND
406 (`ur`.`level`=0 OR `ur`.`level` IS NULL)
408 `{?_MYSQL_PREFIX?}_user_data` AS `ud`
410 `ur`.`refid`=`ud`.`userid`
419 ), __FUNCTION__, __LINE__);
421 // Are there some entries?
422 if (!ifSqlHasZeroNums($result)) {
424 while ($row = sqlFetchArray($result)) {
425 // Init click rate with zero
426 $row['click_rate'] = calculatePercentageRate($row['mails_confirmed'], $row['emails_received']);
428 // Activity is 'active' by default because if ext-autopurge is not installed
429 $row['activity'] = '{--MEMBER_ACTIVITY_ACTIVE--}';
431 // Is autopurge installed and the user inactive?
432 if ((isExtensionActive('autopurge')) && ((time() - getApInactiveSince()) >= $row['last_online'])) {
434 $row['activity'] = '{--MEMBER_ACTIVITY_INACTIVE--}';
437 // Remove some entries
438 unset($row['mails_confirmed']);
439 unset($row['emails_received']);
440 unset($row['last_online']);
443 $refs[$row['id']] = $row;
448 sqlFreeResult($result);
451 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ' - EXIT!');
455 // Get points data for given subject
456 function getPointsDataArrayFromSubject ($subject) {
457 // Extension ext-sql_patches must be up-to-date
458 if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
459 // Please update ext-sql_patches
460 reportBug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
461 } elseif (substr($subject, -8, 8) == '_ref_ref') {
462 // Please report ALL finiding
463 reportBug(__FUNCTION__, __LINE__, 'subject=' . $subject . ' contains invalid double-suffix _ref.');
466 // Remove any double-dot from it
467 $subject = removeDoubleDotFromSubject($subject);
469 // If we have cache, shortcut it here
470 if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
472 incrementStatsEntry('cache_hits');
475 return $GLOBALS['cache_array']['points_data'][$subject];
478 // Now checkout the entry in database table
479 $result = sqlQueryEscaped("SELECT
487 `{?_MYSQL_PREFIX?}_points_data`
493 ), __FUNCTION__, __LINE__
496 // Is there an entry?
497 if (sqlNumRows($result) == 1) {
499 $pointsData = sqlFetchArray($result);
501 // Add all entries to our cache array
502 foreach ($pointsData as $key => $value) {
503 $GLOBALS['cache_array']['points_data'][$subject][$key] = $value;
506 // Register this automatically
507 sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_points_data` (`subject`, `column_name`, `locked_mode`, `payment_method`, `notify_recipient`) VALUES ('%s','points','LOCKED','REFERRAL','N')",
508 array($subject), __FUNCTION__, __LINE__);
511 return getPointsDataArrayFromSubject($subject);
515 sqlFreeResult($result);
518 return $GLOBALS['cache_array']['points_data'][$subject];
521 // Determines the right points column name for given subject and 'locked'
522 function getPointsColumnNameFromSubjectLocked ($subject, $isLocked) {
523 // Get the points_data entry
524 $pointsData = getPointsDataArrayFromSubject($subject);
526 // Regular points by default
527 $columnName = $pointsData['column_name'];
529 // Are the points locked?
530 if (($isLocked === TRUE) && ($pointsData['locked_mode'] == 'LOCKED')) {
531 // Locked points, so prefix it
532 $columnName = 'locked_' . $pointsData['column_name'];
539 // Determines the payment method for given extension and 'locked'
540 function getPaymentMethodFromSubject ($subject) {
541 // Get the points_data entry
542 $pointsData = getPointsDataArrayFromSubject($subject);
544 // Regular points by default
545 $paymentMethod = $pointsData['payment_method'];
548 return $paymentMethod;
551 // Checks whether notification of points recipient is enabled
552 function isPaymentRecipientNotificationEnabled ($subject) {
553 // Get the points_data entry
554 $pointsData = getPointsDataArrayFromSubject($subject);
557 $isEnabled = ($pointsData['notify_recipient'] == 'Y');
563 // Update "referral table"
564 function updateReferralTable ($userid) {
565 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
566 // Load all referrals
567 loadReferralTable($userid);
569 // Add missing level > 1
570 addMissingReferralLevels($userid);
572 // The last step is to flush all userid's entries to the database
573 flushReferralTableToDatabase($userid);
576 rebuildCache('refsystem', 'refsystem');
578 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
581 // Loads all referrals for given userid
582 function loadReferralTable ($userid) {
583 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
585 $GLOBALS['referral_refid'][$userid] = array();
587 // Get all level entries from the refsystem table
588 $GLOBALS['referral_result'][$userid] = sqlQueryEscaped('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
589 array($userid), __FUNCTION__, __LINE__);
591 // Are there entries?
592 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',sqlNumRows()=' . sqlNumRows($GLOBALS['referral_result'][$userid]));
593 if (sqlNumRows($GLOBALS['referral_result'][$userid]) > 0) {
594 // Then walk through all levels
595 while (list($level) = sqlFetchRow($GLOBALS['referral_result'][$userid])) {
597 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
598 $GLOBALS['referral_refid'][$userid][$level] = array();
602 // Load all referrals of this user
603 $GLOBALS['referral_result_refs'][$userid] = sqlQueryEscaped('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
604 array($userid), __FUNCTION__, __LINE__);
606 // Are there entries?
607 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',sqlNumRows()=' . sqlNumRows($GLOBALS['referral_result_refs'][$userid]));
608 if (sqlNumRows($GLOBALS['referral_result_refs'][$userid]) > 0) {
609 // Then again walk through all
610 while (list($refid) = sqlFetchRow($GLOBALS['referral_result_refs'][$userid])) {
612 array_push($GLOBALS['referral_refid'][$userid][$level], $refid);
613 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid . ' - ADDED!');
615 // Load the refid's array as well
616 loadReferralTable($refid);
621 sqlFreeResult($GLOBALS['referral_result_refs'][$userid]);
627 sqlFreeResult($GLOBALS['referral_result'][$userid]);
628 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
631 // Adds missing referral levels to the array
632 function addMissingReferralLevels ($userid) {
633 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
634 // If the array is gone, you have called this function without calling loadReferralTable()
635 if (!isset($GLOBALS['referral_refid'][$userid])) {
636 // Please fix your code
637 reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
639 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
641 // Sort the array reversed
642 krsort($GLOBALS['referral_refid']);
644 // Now walk through the array, first levels
645 foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
646 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
647 // Next are the users
648 foreach ($levelArray as $refid) {
649 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
650 // Does the refid have an array?
651 if (isset($GLOBALS['referral_refid'][$refid])) {
652 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',count()=' . count($GLOBALS['referral_refid'][$refid]));
653 // Add also this user's (maybe) missing levels
654 addMissingReferralLevels($refid);
656 // Okay, then walk through here, too
657 foreach ($GLOBALS['referral_refid'][$refid] as $refLevel => $refArray) {
658 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',count()=' . count($refArray));
659 // Also walk through this one
660 foreach ($refArray as $refRefid) {
661 // Calculate new level
662 $newLevel = $level + $refLevel;
663 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . convertNullToZero($refid) . ',refLevel=' . $refLevel . ',refRefid=' . $refRefid . ',newLevel=' . $newLevel);
664 // Is the refRefid not in?
665 if ((!isset($GLOBALS['referral_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referral_refid'][$userid][$newLevel]))) {
666 // Then we must add this ref's refid to the userid's next level
667 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
668 array_push($GLOBALS['referral_refid'][$userid][$newLevel], $refRefid);
670 // Add also this user's (maybe) missing levels
671 addMissingReferralLevels($refRefid);
678 //die('<pre>'.print_r($GLOBALS['referral_refid'][$userid],TRUE).'</pre>');
679 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
682 // Flush all entries for given userid to database
683 function flushReferralTableToDatabase ($userid) {
684 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ENTERED!');
685 // If the array is gone, you have called this function without calling loadReferralTable()
686 if (!isset($GLOBALS['referral_refid'][$userid])) {
687 // Please fix your code
688 reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
690 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
692 // If no entries are there, skip this whole step
693 if (!isFilledArray($GLOBALS['referral_refid'][$userid])) {
695 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - ABORTING...');
700 $SQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_user_refs` (`userid`, `level`, `refid`) VALUES ';
703 // Now walk through the array, first levels
704 foreach ($GLOBALS['referral_refid'][$userid] as $level => $levelArray) {
705 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',count()=' . count($levelArray));
706 // Next are the users
707 foreach ($levelArray as $refid) {
708 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
709 // Query the user_refs table
710 $count = countSumTotalData(bigintval($userid), 'user_refs', 'id', 'userid', TRUE, ' AND `level`=' . bigintval($level) . ' AND `refid`=' . bigintval($refid));
712 // Is there no entry?
714 // Then add it to the SQL
715 $SQL .= '(' . $userid . ',' . $level . ',' . $refid . '),';
717 // Some has been added, so execute the query
723 // Remove last comma from SQL
724 $SQL = substr($SQL, 0, -1);
727 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL=' . $SQL);
728 if ($executeSql === TRUE) {
729 sqlQuery($SQL, __FUNCTION__, __LINE__);
732 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
735 // Generator (somewhat getter) for points_data, locked_mode
736 function generatePointsLockedModeOptions ($lockedMode = NULL) {
738 if (!isset($GLOBALS[__FUNCTION__][$lockedMode])) {
739 // Generate output and cache it
740 $GLOBALS[__FUNCTION__][$lockedMode] = generateOptions(
750 'translatePointsLockedMode'
755 return $GLOBALS[__FUNCTION__][$lockedMode];
758 // Generator (somewhat getter) for points_data, payment_method
759 function generatePointsPaymentMethodOptions ($paymentMethod = NULL) {
761 if (!isset($GLOBALS[__FUNCTION__][$paymentMethod])) {
762 // Generate output and cache it
763 $GLOBALS[__FUNCTION__][$paymentMethod] = generateOptions(
773 'translatePointsPaymentMethod'
778 return $GLOBALS[__FUNCTION__][$paymentMethod];
781 // Generator (somewhat getter) for points_data, notify_recipient
782 function generatePointsNotifyRecipientOptions ($notifyRecipient = NULL) {
784 if (!isset($GLOBALS[__FUNCTION__][$notifyRecipient])) {
785 // Generate output and cache it
786 $GLOBALS[__FUNCTION__][$notifyRecipient] = generateOptions(
796 'translatePointsNotifyRecipient'
801 return $GLOBALS[__FUNCTION__][$notifyRecipient];
804 // Setter for referral id (no bigintval, or nicknames will fail!)
805 function setReferralId ($refid) {
806 $GLOBALS['__refid'] = $refid;
809 // Checks if 'refid' is valid
810 function isValidReferralId () {
811 return ((isset($GLOBALS['__refid'])) && (isValidId(getReferralId())));
814 // Getter for referral id
815 function getReferralId () {
816 return $GLOBALS['__refid'];
819 // Determines referral id and sets it
820 function determineReferralId () {
821 // Is it already detected?
822 if (isValidReferralId()) {
823 // Do not determine it, just return it
824 return getReferralId();
825 } elseif ((!isHtmlOutputMode()) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) {
826 // Skip this in non-html-mode and outside ref.php
830 // Check if refid is set
831 if (isValidReferralId()) {
833 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from GLOBALS (' . getReferralId() . ')');
834 } elseif (isPostRequestElementSet('refid')) {
835 // Get referral id from POST element refid
836 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from POST data (' . postRequestElement('refid') . ')');
837 setReferralId(secureString(postRequestElement('refid')));
838 } elseif (isGetRequestElementSet('refid')) {
839 // Get referral id from GET parameter refid
840 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from GET data (' . getRequestElement('refid') . ')');
841 setReferralId(getRequestElement('refid'));
842 } elseif (isGetRequestElementSet('ref')) {
843 // Set refid=ref (the referral link uses such variable)
844 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using ref from GET data (' . getRequestElement('ref') . ')');
845 setReferralId(getRequestElement('ref'));
846 } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
847 // The variable user comes from click.php
848 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using user from GET data (' . getRequestElement('user') . ')');
849 setReferralId(bigintval(getRequestElement('user')));
850 } elseif ((isSessionVariableSet('refid')) && (isValidId(getSession('refid')))) {
851 // Set session refid as global
852 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from SESSION data (' . getSession('refid') . ')');
853 setReferralId(bigintval(getSession('refid')));
854 } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (isRandomReferralIdEnabled())) {
855 // Select a random user which has confirmed enougth mails
856 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Checking random referral id');
857 setReferralId(determineRandomReferralId());
858 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidId(getDefRefid()))) {
859 // Set default refid as refid in URL
860 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using default refid (' . getDefRefid() . ')');
861 setReferralId(getDefRefid());
863 // No default id when ext-sql_patches is not installed or none set
864 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using NULL as refid');
868 // Set cookie when default refid > 0
869 if ((!isSessionVariableSet('refid')) || (!isValidId(getReferralId())) || ((!isValidId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidId(getDefRefid())))) {
870 // Default is not found
873 // Is there nickname or userid set?
874 if ((isExtensionActive('nickname')) && (isNicknameUsed(getReferralId()))) {
875 // Nickname in URL, so load the id
876 $found = fetchUserData(getReferralId(), 'nickname');
878 // If we found it, use the userid as referral id
879 if ($found === TRUE) {
880 // Set the userid as 'refid'
881 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using refid from user account by nickname (' . getUserData('userid') . ')');
882 setReferralId(getUserData('userid'));
884 } elseif (isValidId(getReferralId())) {
885 // Direct userid entered
886 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using direct userid (' . getReferralId() . ')');
887 $found = fetchUserData(getReferralId());
890 // Is the record valid?
891 if ((($found === FALSE) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
892 // No, then reset referral id
893 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Using default refid (' . getDefRefid() . ')');
894 setReferralId(getDefRefid());
898 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Saving refid to session (' . getReferralId() . ') #1');
899 setSession('refid', getReferralId());
900 } elseif ((!isValidReferralId()) || (!fetchUserData(getReferralId()))) {
902 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Not valid referral id (' . getReferralId() . '), setting NULL in session');
904 setSession('refid', NULL);
906 // Set it from GLOBALS array in session
907 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Saving refid to session (' . getReferralId() . ') #2');
908 setSession('refid', getReferralId());
911 // Run post validation filter chain
912 runFilterChain('post_refid_validation');
914 // Return determined refid
915 return getReferralId();