mailer project continued:
[mailer.git] / inc / referral-functions.php
index 39302c95b4a3b9cf72a4f23edd5103267a18f894..6078e378fa309f9a80c15a0ec5968dc2a60aa8cd 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2011 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -109,29 +109,29 @@ function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NU
        setCurrentUserId($userid);
 
        // Check user account
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',points=' . $points . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify));
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',points=' . $points . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify));
        if (fetchUserData($userid)) {
-               // Determine wether the user has some mails to click before he/she gets the points
-               $locked = ifUserPointsLocked($userid);
+               // Determine whether the user has some mails to click before he/she gets the points
+               $isLocked = ifUserPointsLocked($userid);
 
                // Detect database column
-               $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $locked);
+               $pointsColumn = determinePointsColumnFromSubjectLocked($subject, $isLocked);
 
                // Get percents
-               $per = getReferralLevelPercents($GLOBALS['ref_level']);
-               //* 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'));
+               $percents = getReferralLevelPercents($GLOBALS['ref_level']);
+               //* 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'));
 
                // Some percents found?
-               if ($per > 0) {
+               if ($percents > 0) {
                        // Calculate new points
-                       $ref_points = $points * $per / 100;
+                       $ref_points = $points * $percents / 100;
 
                        // Pay refback here if level > 0 and in ref-mode
-                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',paymentMethod=' . $paymentMethod);
-                       if (($userid != $refid) && ($paymentMethod == 'REFERRAL') && (isValidUserId(getUserData('refid'))) && (isExtensionActive('refback'))) {
-                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - BEFORE!');
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',paymentMethod=' . $paymentMethod);
+                       if (($userid != $refid) && (substr($subject, 0, 8) != 'refback:') &&($paymentMethod == 'REFERRAL') && (isValidUserId(getUserData('refid'))) && (isExtensionActive('refback'))) {
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - BEFORE!');
                                $ref_points = addRefbackPoints($userid, getUserData('refid'), $points, $ref_points);
-                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - AFTER!');
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',ref_points=' . $ref_points . ',depth=' . convertNullToZero($GLOBALS['ref_level']) . ' - AFTER!');
                        } // END - if
 
                        // Update points...
@@ -183,7 +183,7 @@ function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NU
                                'column'      => $pointsColumn,
                                'notify'      => $sendNotify,
                                'refid'       => $refid,
-                               'locked'      => $locked,
+                               'locked'      => $isLocked,
                                'points_mode' => 'add',
                                'add_mode'    => $paymentMethod,
                                'added'       => $added
@@ -196,13 +196,26 @@ function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NU
                        $added = $filterData['added'];
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'added=' . intval($added) . ' - AFTER FILTER');
 
-                       // Points updated, maybe I shall send him an email?
-                       if (($sendNotify === true) && (isValidUserId(getUserData('refid'))) && ($locked === false)) {
+                       // Debug message
+                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',userid=' . $userid . ',refid=' . $refid . ',paymentMethod=' . $paymentMethod . ',sendNotify=' . intval($sendNotify) . ',isLocked=' . intval($isLocked));
+
+                       // Send "referral confirmed" mails out?
+                       if ((isValidUserid($refid)) && ($refid != $userid) && ($sendNotify === true)) {
+                               // Calculate the referral's points and percents
+                               $percentsReferral = getReferralLevelPercents($GLOBALS['ref_level'] + 1);
+
+                               // Calculate new points
+                               $ref_points = $ref_points * $percentsReferral / 100;
+
                                // Prepare content
                                $content = array(
-                                       'percents' => $per,
-                                       'level'    => bigintval($GLOBALS['ref_level']),
-                                       'points'   => $ref_points,
+                                       'userid'         => bigintval($userid),
+                                       'refid'          => $refid,
+                                       'level'          => bigintval($GLOBALS['ref_level'] + 1),
+                                       'percents'       => $percentsReferral,
+                                       'points'         => ($paymentMethod == 'REFERRAL' ? $ref_points : '0'),
+                                       'payment_method' => $paymentMethod,
+                                       'subject'        => $subject,
                                );
 
                                // Load email template
@@ -210,24 +223,44 @@ function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NU
 
                                // Send email
                                sendEmail($userid, '{--THANX_REFERRAL_ONE_SUBJECT--}', $message);
-                       } elseif (($sendNotify === true) && (!isValidUserId(getUserData('refid'))) && ($locked === false) && ($paymentMethod == 'DIRECT')) {
-                               // Prepare content
+                       } // END - if
+
+                       // Points updated, maybe I shall send him an email?
+                       if (($sendNotify === true) && ($isLocked === false)) {
+                               // "Explode" subject
+                               $subjectArray = explode(':', $subject);
+                               $subjectUserid = (isset($subjectArray[1])) ? $subjectArray[1] : '0';
+
+                               // Generic delivery of mails, so prepare data
                                $content = array(
-                                       'reason'  => '{--REASON_DIRECT_PAYMENT--}',
-                                       'subject' => $subject,
-                                       'points'  => $ref_points
+                                       'userid'         => $userid,
+                                       'percents'       => $percents,
+                                       'level'          => bigintval($GLOBALS['ref_level']),
+                                       'points'         => $ref_points,
+                                       'column'         => $pointsColumn,
+                                       'subject'        => $subjectArray[0],
+                                       'subject_userid' => $subjectUserid,
+                                       'payment_method' => $paymentMethod,
                                );
 
-                               // Load message
-                               $message = loadEmailTemplate('member_add_points', $content, $userid);
+                               // Load email template
+                               $message = loadEmailTemplate('member_' . $subjectArray[0] . '_' . strtolower($paymentMethod), $content, $userid);
 
-                               // And sent it away
-                               sendEmail($userid, '{--DIRECT_PAYMENT_SUBJECT--}', $message);
-                               if (!isGetRequestElementSet('mid')) {
-                                       // Output message to admin
-                                       displayMessage('{--ADMIN_POINTS_ADDED--}');
-                               } // END - if
-                       }
+                               // Send email
+                               sendEmail($userid, '{%message,MEMBER_' . $paymentMethod . '_' . strtoupper($subjectArray[0]) . '_SUBJECT=' . $subjectUserid . '%}', $message);
+
+                               // Also send admin notification
+                               sendAdminNotification(
+                                       // Subject
+                                       '{%message,ADMIN_' . $paymentMethod . '_' . strtoupper($subjectArray[0]) . '_SUBJECT=' . $subjectUserid . '%}',
+                                       // Template name
+                                       'admin_' . $subjectArray[0] . '_' . strtolower($paymentMethod),
+                                       // Template content (data array)
+                                       $content,
+                                       // User id
+                                       $userid
+                               );
+                       } // END - if
 
                        // Increase referral level, if payment method is REFERRAL
                        if ($paymentMethod == 'REFERRAL') {
@@ -239,11 +272,20 @@ function addPointsThroughReferralSystem ($subject, $userid, $points, $refid = NU
                                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Referral level *NOT* increased, ref_level=' . convertNullToZero($GLOBALS['ref_level']) . ',points=' . $points . ',refid=' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
                        }
 
+                       // Remove any :x
+                       $subject = removeDoubleDotFromSubject($subject);
+
                        // Maybe there's another ref?
-                       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'points=' . $points . ',refid(var|data)=' . convertNullToZero($refid) . '|' . convertNullToZero(getUserData('refid')) . ',userid=' . $userid . ',paymentMethod=' . $paymentMethod);
+                       //* 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']);
                        if ((isValidUserId(getUserData('refid'))) && ($points > 0) && (getUserData('refid') != $userid) && ($paymentMethod == 'REFERRAL')) {
+                               // Is _ref there?
+                               if (substr($subject, -4, 4) == '_ref') {
+                                       // Then remove it, no double _ref suffix!
+                                       $subject = substr($subject, 0, -4);
+                               } // END - if
+
                                // Then let's credit him here...
-                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',refid=' . convertNullToZero(getUserData('refid')) . ',points=' . $points . ',ref_points=' . $ref_points . ',added[' . gettype($added) . ']=' . intval($added) . ' - ADVANCE!');
+                               //* 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!');
                                $added = ($added && addPointsThroughReferralSystem(sprintf("%s_ref:%s", $subject, $GLOBALS['ref_level']), getUserData('refid'), $points, getFetchedUserData('userid', getUserData('refid'), 'refid')));
                        } // END - if
                } // END - if
@@ -414,16 +456,20 @@ function getPointsDataArrayFromSubject ($subject) {
        // Extension ext-sql_patches must be up-to-date
        if (isExtensionInstalledAndOlder('sql_patches', '0.8.2')) {
                // Please update ext-sql_patches
-               debug_report_bug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
-       } // END - if
+               reportBug(__FUNCTION__, __LINE__, 'sql_patches is out-dated. Please update to at least 0.8.2 to continue. subject=' . $subject);
+       } elseif (substr($subject, -8, 8) == '_ref_ref') {
+               // Please report ALL finiding
+               reportBug(__FUNCTION__, __LINE__, 'subject=' . $subject . ' contains invalid double-suffix _ref.');
+       }
 
        // Remove any double-dot from it
-       $subjectArray = explode(':', $subject);
-       $subject = $subjectArray[0];
-       unset($subjectArray);
+       $subject = removeDoubleDotFromSubject($subject);
 
        // If we have cache, shortcut it here
        if (isset($GLOBALS['cache_array']['points_data'][$subject])) {
+               // Count cache hit
+               incrementStatsEntry('cache_hits');
+
                // Return it
                return $GLOBALS['cache_array']['points_data'][$subject];
        } // END - if
@@ -487,7 +533,7 @@ function getPaymentMethodFromSubject ($subject) {
        return $paymentMethod;
 }
 
-// Checks wether notification of points recipient is enabled
+// Checks whether notification of points recipient is enabled
 function isPaymentRecipientNotificationEnabled ($subject) {
        // Get the points_data entry
        $pointsData = getPointsDataArrayFromSubject($subject);
@@ -524,14 +570,14 @@ function loadReferralTable ($userid) {
        $GLOBALS['referral_refid'][$userid] = array();
 
        // Get all level entries from the refsystem table
-       $result = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
+       $GLOBALS['referral_result'][$userid] = SQL_QUERY_ESC('SELECT `level` FROM `{?_MYSQL_PREFIX?}_refsystem` WHERE `userid`=%s ORDER BY `level` ASC',
                array($userid), __FUNCTION__, __LINE__);
 
        // Do we have entries?
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($result));
-       if (SQL_NUMROWS($result) > 0) {
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',SQL_NUMROWS()=' . SQL_NUMROWS($GLOBALS['referral_result'][$userid]));
+       if (SQL_NUMROWS($GLOBALS['referral_result'][$userid]) > 0) {
                // Then walk through all levels
-               while (list($level) = SQL_FETCHROW($result)) {
+               while (list($level) = SQL_FETCHROW($GLOBALS['referral_result'][$userid])) {
                        // Init array
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level);
                        $GLOBALS['referral_refid'][$userid][$level] = array();
@@ -539,30 +585,31 @@ function loadReferralTable ($userid) {
                        // Level is = 1?
                        if ($level == 1) {
                                // Load all referrals of this user
-                               $result_refs = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
+                               $GLOBALS['referral_result_refs'][$userid] = SQL_QUERY_ESC('SELECT `userid` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `refid`=%s ORDER BY `userid` ASC',
                                        array($userid), __FUNCTION__, __LINE__);
 
                                // Do we have entries?
-                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($result_refs));
-                               if (SQL_NUMROWS($result_refs) > 0) {
+                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',SQL_NUMROWS()=' . SQL_NUMROWS($GLOBALS['referral_result_refs'][$userid]));
+                               if (SQL_NUMROWS($GLOBALS['referral_result_refs'][$userid]) > 0) {
                                        // Then again walk through all
-                                       while (list($refid) = SQL_FETCHROW($result_refs)) {
+                                       while (list($refid) = SQL_FETCHROW($GLOBALS['referral_result_refs'][$userid])) {
                                                // Add this refid
-                                               $GLOBALS['referral_refid'][$userid][$level][] = $refid;
-                                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid);
+                                               array_push($GLOBALS['referral_refid'][$userid][$level], $refid);
+                                               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',level=' . $level . ',refid=' . $refid . ' - ADDED!');
+
                                                // Load the refid's array as well
                                                loadReferralTable($refid);
                                        } // END - while
                                } // END - if
 
                                // Free result
-                               SQL_FREERESULT($result_refs);
+                               SQL_FREERESULT($GLOBALS['referral_result_refs'][$userid]);
                        } // END - if
                } // END - while
        } // END - if
 
        // Free result
-       SQL_FREERESULT($result);
+       SQL_FREERESULT($GLOBALS['referral_result'][$userid]);
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
 }
 
@@ -572,7 +619,7 @@ function addMissingReferralLevels ($userid) {
        // If the array is gone, you have called this function without calling loadReferralTable()
        if (!isset($GLOBALS['referral_refid'][$userid])) {
                // Please fix your code
-               debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
+               reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
        } // END - if
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
 
@@ -603,7 +650,7 @@ function addMissingReferralLevels ($userid) {
                                                if ((!isset($GLOBALS['referral_refid'][$userid][$newLevel])) || (!in_array($refRefid, $GLOBALS['referral_refid'][$userid][$newLevel]))) {
                                                        // Then we must add this ref's refid to the userid's next level
                                                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',newLevel=' . $newLevel . ',refRefid=' . $refRefid . ' - ADDED!');
-                                                       $GLOBALS['referral_refid'][$userid][$newLevel][] = $refRefid;
+                                                       array_push($GLOBALS['referral_refid'][$userid][$newLevel], $refRefid);
 
                                                        // Add also this user's (maybe) missing levels
                                                        addMissingReferralLevels($refRefid);
@@ -613,6 +660,7 @@ function addMissingReferralLevels ($userid) {
                        } // END - foreach
                } // END - foreach
        } // END - foreach
+       //die('<pre>'.print_r($GLOBALS['referral_refid'][$userid],true).'</pre>');
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
 }
 
@@ -622,7 +670,7 @@ function flushReferralTableToDatabase ($userid) {
        // If the array is gone, you have called this function without calling loadReferralTable()
        if (!isset($GLOBALS['referral_refid'][$userid])) {
                // Please fix your code
-               debug_report_bug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
+               reportBug(__FUNCTION__, __LINE__, 'Called without calling loadReferralTable() before! userid=' . $userid);
        } // END - if
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ',count()=' . count($GLOBALS['referral_refid'][$userid]));
 
@@ -674,5 +722,89 @@ function flushReferralTableToDatabase ($userid) {
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'userid=' . $userid . ' - EXIT!');
 }
 
+// Generator (somewhat getter) for points_data, locked_mode
+function generatePointsLockedModeOptions ($lockedMode =  NULL) {
+       // Is this cached?
+       if (!isset($GLOBALS[__FUNCTION__][$lockedMode])) {
+               // Generate output and cache it
+               $GLOBALS[__FUNCTION__][$lockedMode] = generateOptions(
+                       '/ARRAY/',
+                       array(
+                               'LOCKED',
+                               'UNLOCKED'
+                       ),
+                       array(),
+                       $lockedMode,
+                       '', '',
+                       array(),
+                       'translatePointsLockedMode'
+               );
+       } // END - if
+
+       // Return content
+       return $GLOBALS[__FUNCTION__][$lockedMode];
+}
+
+// Generator (somewhat getter) for points_data, payment_method
+function generatePointsPaymentMethodOptions ($paymentMethod =  NULL) {
+       // Is this cached?
+       if (!isset($GLOBALS[__FUNCTION__][$paymentMethod])) {
+               // Generate output and cache it
+               $GLOBALS[__FUNCTION__][$paymentMethod] = generateOptions(
+                       '/ARRAY/',
+                       array(
+                               'DIRECT',
+                               'REFERRAL'
+                       ),
+                       array(),
+                       $paymentMethod,
+                       '', '',
+                       array(),
+                       'translatePointsPaymentMethod'
+               );
+       } // END - if
+
+       // Return content
+       return $GLOBALS[__FUNCTION__][$paymentMethod];
+}
+
+// Generator (somewhat getter) for points_data, notify_recipient
+function generatePointsNotifyRecipientOptions ($notifyRecipient =  NULL) {
+       // Is this cached?
+       if (!isset($GLOBALS[__FUNCTION__][$notifyRecipient])) {
+               // Generate output and cache it
+               $GLOBALS[__FUNCTION__][$notifyRecipient] = generateOptions(
+                       '/ARRAY/',
+                       array(
+                               'Y',
+                               'N'
+                       ),
+                       array(),
+                       $notifyRecipient,
+                       '', '',
+                       array(),
+                       'translatePointsNotifyRecipient'
+               );
+       } // END - if
+
+       // Return content
+       return $GLOBALS[__FUNCTION__][$notifyRecipient];
+}
+
+// Setter for referral id (no bigintval, or nicknames will fail!)
+function setReferralId ($refid) {
+       $GLOBALS['__refid'] = $refid;
+}
+
+// Checks if 'refid' is valid
+function isReferralIdValid () {
+       return ((isset($GLOBALS['__refid'])) && (getReferralId() !== NULL) && (getReferralId() > 0));
+}
+
+// Getter for referral id
+function getReferralId () {
+       return $GLOBALS['__refid'];
+}
+
 // [EOF]
 ?>