Required fix for NULL vs. 0 in user_points
[mailer.git] / inc / functions.php
index dbb38836ce3805886a5b7280f30b48474b2d9714..333de57fec72d155269ce177afa46889ae7a78b7 100644 (file)
@@ -85,23 +85,21 @@ function getTotalFatalErrors () {
 // Send mail out to an email address
 function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '') {
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'toEmail=' . $toEmail . ',subject=' . $subject . ',isHtml=' . $isHtml);
+       // Empty parameters should be avoided, so we need to find them
+       if (empty($isHtml)) {
+               // isHtml is empty
+               debug_report_bug(__FUNCTION__, __LINE__, 'isHtml is empty.');
+       } // END - if
 
        // Set from header
        if ((!isInStringIgnoreCase('@', $toEmail)) && ($toEmail > 0)) {
-               // Value detected, is the message extension installed?
-               // @TODO Extension 'msg' does not exist
-               if (isExtensionActive('msg')) {
-                       ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $isHtml);
-                       return;
+               // Does the user exist?
+               if ((isExtensionActive('user')) && (fetchUserData($toEmail))) {
+                       // Get the email
+                       $toEmail = getUserData('email');
                } else {
-                       // Does the user exist?
-                       if (fetchUserData($toEmail)) {
-                               // Get the email
-                               $toEmail = getUserData('email');
-                       } else {
-                               // Set webmaster
-                               $toEmail = getWebmaster();
-                       }
+                       // Set webmaster
+                       $toEmail = getWebmaster();
                }
        } elseif ($toEmail == '0') {
                // Is the webmaster!
@@ -130,11 +128,6 @@ function sendEmail ($toEmail, $subject, $message, $isHtml = 'N', $mailHeader = '
                }
        } // END - if
 
-       // Fix HTML parameter (default is no!)
-       if (empty($isHtml)) {
-               $isHtml = 'N';
-       } // END - if
-
        // Debug mode enabled?
        if (isDebugModeEnabled()) {
                // In debug mode we want to display the mail instead of sending it away so we can debug this part
@@ -273,7 +266,7 @@ function generatePassword ($length = '0', $exclude =  array()) {
 // Generates a human-readable timestamp from the Uni* stamp
 function generateDateTime ($time, $mode = '0') {
        // If the stamp is zero it mostly didn't "happen"
-       if ($time == '0') {
+       if (($time == '0') || (is_null($time))) {
                // Never happend
                return '{--NEVER_HAPPENED--}';
        } // END - if
@@ -478,22 +471,22 @@ function translateMenuVisibleLocked ($content, $prefix = '') {
 }
 
 // Generates an URL for the dereferer
-function generateDerefererUrl ($URL) {
+function generateDerefererUrl ($url) {
        // Don't de-refer our own links!
-       if (substr($URL, 0, strlen(getUrl())) != getUrl()) {
+       if (substr($url, 0, strlen(getUrl())) != getUrl()) {
                // De-refer this link
-               $URL = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($URL)) . '%}';
+               $url = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($url)) . '%}';
        } // END - if
 
        // Return link
-       return $URL;
+       return $url;
 }
 
 // Generates an URL for the frametester
-function generateFrametesterUrl ($URL) {
+function generateFrametesterUrl ($url) {
        // Prepare frametester URL
        $frametesterUrl = sprintf("{%%url=modules.php?module=frametester&url=%s%%}",
-               encodeString(compileUriCode($URL))
+               encodeString(compileUriCode($url))
        );
 
        // Return the new URL
@@ -540,26 +533,28 @@ function makeTime ($hours, $minutes, $seconds, $stamp) {
 }
 
 // Redirects to an URL and if neccessarry extends it with own base URL
-function redirectToUrl ($URL, $allowSpider = true) {
+function redirectToUrl ($url, $allowSpider = true) {
        // Remove {%url=
-       if (substr($URL, 0, 6) == '{%url=') $URL = substr($URL, 6, -2);
+       if (substr($url, 0, 6) == '{%url=') {
+               $url = substr($url, 6, -2);
+       } // END - if
 
        // Compile out codes
-       eval('$URL = "' . compileRawCode(encodeUrl($URL)) . '";');
+       eval('$url = "' . compileRawCode(encodeUrl($url)) . '";');
 
        // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
        $rel = ' rel="external"';
 
        // Do we have internal or external URL?
-       if (substr($URL, 0, strlen(getUrl())) == getUrl()) {
+       if (substr($url, 0, strlen(getUrl())) == getUrl()) {
                // Own (=internal) URL
                $rel = '';
        } // END - if
 
        // Three different ways to debug...
-       //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $URL);
-       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $URL);
-       //* DEBUG: */ die($URL);
+       //* DEBUG: */ debug_report_bug(__FUNCTION__, __LINE__, 'URL=' . $url);
+       //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'URL=' . $url);
+       //* DEBUG: */ die($url);
 
        // We should not sent a redirect if headers are already sent
        if (!headers_sent()) {
@@ -570,11 +565,11 @@ function redirectToUrl ($URL, $allowSpider = true) {
                $GLOBALS['output'] = '';
 
                // Load URL when headers are not sent
-               sendRawRedirect(doFinalCompilation(str_replace('&', '&', $URL), false));
+               sendRawRedirect(doFinalCompilation(str_replace('&', '&', $url), false));
        } else {
                // Output error message
                loadInclude('inc/header.php');
-               loadTemplate('redirect_url', false, str_replace('&', '&', $URL));
+               loadTemplate('redirect_url', false, str_replace('&', '&', $url));
                loadInclude('inc/footer.php');
        }
 
@@ -844,24 +839,26 @@ function isEmailValid ($email) {
 }
 
 // Function taken from user comments on www.php.net / function isInStringIgnoreCase()
-function isUrlValid ($URL, $compile=true) {
+function isUrlValid ($url, $compile=true) {
        // Trim URL a little
-       $URL = trim(urldecode($URL));
-       //* DEBUG: */ debugOutput($URL);
+       $url = trim(urldecode($url));
+       //* DEBUG: */ debugOutput($url);
 
        // Compile some chars out...
-       if ($compile === true) $URL = compileUriCode($URL, false, false, false);
-       //* DEBUG: */ debugOutput($URL);
+       if ($compile === true) {
+               $url = compileUriCode($url, false, false, false);
+       } // END - if
+       //* DEBUG: */ debugOutput($url);
 
        // Check for the extension filter
        if (isExtensionActive('filter')) {
                // Use the extension's filter set
-               return FILTER_VALIDATE_URL($URL, false);
+               return FILTER_VALIDATE_URL($url, false);
        } // END - if
 
        // If not installed, perform a simple test. Just make it sure there is always a http:// or
        // https:// in front of the URLs
-       return isUrlValidSimple($URL);
+       return isUrlValidSimple($url);
 }
 
 // Generate a hash for extra-security for all passwords
@@ -922,7 +919,7 @@ function generateHash ($plainText, $salt = '', $hash = true) {
                // Sanity check on salt
                if (strlen($salt) != getSaltLength()) {
                        // Not the same!
-                       debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! ('.strlen($salt).'/'.getSaltLength().')');
+                       debug_report_bug(__FUNCTION__, __LINE__, 'salt length mismatch! (' . strlen($salt) . '/' . getSaltLength() . ')');
                } // END - if
        }
 
@@ -941,7 +938,7 @@ function scrambleString ($str) {
        // Init
        $scrambled = '';
 
-       // Final check, in case of failture it will return unscrambled string
+       // Final check, in case of failure it will return unscrambled string
        if (strlen($str) > 40) {
                // The string is to long
                return $str;
@@ -1187,7 +1184,7 @@ function getMessageFromErrorCode ($code) {
                case getCode('ACCOUNT_LOCKED')     : $message = '{--LOGIN_STATUS_LOCKED--}'; break;
                case getCode('ACCOUNT_UNCONFIRMED'): $message = '{--LOGIN_STATUS_UNCONFIRMED--}'; break;
                case getCode('COOKIES_DISABLED')   : $message = '{--LOGIN_COOKIES_DISABLED--}'; break;
-               case getCode('BEG_SAME_AS_OWN')    : $message = '{--BEG_SAME_UID_AS_OWN--}'; break;
+               case getCode('BEG_SAME_AS_OWN')    : $message = '{--BEG_SAME_USERID_AS_OWN--}'; break;
                case getCode('LOGIN_FAILED')       : $message = '{--GUEST_LOGIN_FAILED_GENERAL--}'; break;
                case getCode('MODULE_MEMBER_ONLY') : $message = getMaskedMessage('MODULE_MEMBER_ONLY', getRequestParameter('mod')); break;
                case getCode('OVERLENGTH')         : $message = '{--MEMBER_TEXT_OVERLENGTH--}'; break;
@@ -1654,60 +1651,69 @@ function determineReferalId () {
        } // END - if
 
        // Check if refid is set
-       if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
+       if (isReferalIdValid()) {
                // This is fine...
        } elseif (isPostRequestParameterSet('refid')) {
                // Get referal id from POST element refid
-               $GLOBALS['refid'] = secureString(postRequestParameter('refid'));
+               setReferalId(secureString(postRequestParameter('refid')));
        } elseif (isGetRequestParameterSet('refid')) {
                // Get referal id from GET parameter refid
-               $GLOBALS['refid'] = secureString(getRequestParameter('refid'));
+               setReferalId(secureString(getRequestParameter('refid')));
        } elseif (isGetRequestParameterSet('ref')) {
                // Set refid=ref (the referal link uses such variable)
-               $GLOBALS['refid'] = secureString(getRequestParameter('ref'));
+               setReferalId(secureString(getRequestParameter('ref')));
        } elseif ((isGetRequestParameterSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
                // The variable user comes from  click.php
-               $GLOBALS['refid'] = bigintval(getRequestParameter('user'));
+               setReferalId(bigintval(getRequestParameter('user')));
        } elseif ((isSessionVariableSet('refid')) && (isValidUserId(getSession('refid')))) {
                // Set session refid als global
-               $GLOBALS['refid'] = bigintval(getSession('refid'));
+               setReferalId(bigintval(getSession('refid')));
        } elseif (isRandomReferalIdEnabled()) {
                // Select a random user which has confirmed enougth mails
-               $GLOBALS['refid'] = determineRandomReferalId();
+               setReferalId(determineRandomReferalId());
        } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid()))) {
                // Set default refid as refid in URL
-               $GLOBALS['refid'] = getDefRefid();
+               setReferalId(getDefRefid());
        } else {
                // No default id when sql_patches is not installed or none set
-               $GLOBALS['refid'] = null;
+               setReferalId(null);
        }
 
        // Set cookie when default refid > 0
-       if (!isSessionVariableSet('refid') || (isValidUserId($GLOBALS['refid'])) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
+       if (!isSessionVariableSet('refid') || (!isValidUserId(getReferalId())) || ((!isValidUserId(getSession('refid'))) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2')) && (isValidUserId(getDefRefid())))) {
                // Default is not found
                $found = false;
 
                // Do we have nickname or userid set?
-               if ((isExtensionActive('nickname')) && (isNicknameUsed($GLOBALS['refid']))) {
+               if ((isExtensionActive('nickname')) && (isNicknameUsed(getReferalId()))) {
                        // Nickname in URL, so load the id
-                       $found = fetchUserData($GLOBALS['refid'], 'nickname');
-               } elseif (isValidUserId($GLOBALS['refid'])) {
+                       $found = fetchUserData(getReferalId(), 'nickname');
+
+                       // If we found it, use the userid as referal id
+                       if ($found === true) {
+                               // Set the userid as 'refid'
+                               setReferalId(getUserData('userid'));
+                       } // END - if
+               } elseif (isValidUserId(getReferalId())) {
                        // Direct userid entered
-                       $found = fetchUserData($GLOBALS['refid']);
+                       $found = fetchUserData(getReferalId());
                }
 
                // Is the record valid?
                if ((($found === false) || (!isUserDataValid())) && (isExtensionInstalledAndNewer('sql_patches', '0.1.2'))) {
                        // No, then reset referal id
-                       $GLOBALS['refid'] = getDefRefid();
+                       setReferalId(getDefRefid());
                } // END - if
 
                // Set cookie
-               setSession('refid', $GLOBALS['refid']);
-       } // END - if
+               setSession('refid', getReferalId());
+       } elseif (!isReferalIdValid()) {
+               // Not valid!
+               setSession('refid', 0);
+       }
 
        // Return determined refid
-       return $GLOBALS['refid'];
+       return getReferalId();
 }
 
 // Enables the reset mode and runs it
@@ -2145,18 +2151,18 @@ function handleFieldWithBraces ($field) {
 }
 
 // Converts a userid so it can be used in SQL queries
-function makeDatabaseUserId ($userid) {
+function makeZeroToNull ($number) {
        // Is it a valid username?
-       if (isValidUserId($userid)) {
+       if ((!is_null($number)) && ($number > 0)) {
                // Always secure it
-               $userid = bigintval($userid);
+               $number = bigintval($number);
        } else {
                // Is not valid or zero
-               $userid = 'NULL';
+               $number = 'NULL';
        }
 
        // Return it
-       return $userid;
+       return $number;
 }
 
 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
@@ -2312,6 +2318,79 @@ function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) {
        return $keys;
 }
 
+// Determines database column name from given subject and locked
+function determinePointsColumnFromSubjectLocked ($subject, $locked) {
+       // Default is 'normal' points
+       $pointsColumn = 'points';
+
+       // Which points, locked or normal?
+       if ($locked === true) {
+               $pointsColumn = 'locked_points';
+       } // END - if
+
+       // Prepare array for filter
+       $filterData = array(
+               'subject' => $subject,
+               'locked'  => $locked,
+               'column'  => $pointsColumn
+       );
+
+       // Run the filter
+       $filterData = runFilterChain('determine_points_column_name', $filterData);
+
+       // Extract column name from array
+       $pointsColumn = $filterData['column'];
+
+       // Return it
+       return $pointsColumn;
+}
+
+// Setter for referal id (no bigintval, or nicknames will fail!)
+function setReferalId ($refid) {
+       $GLOBALS['refid'] = $refid;
+}
+
+// Checks if 'refid' is valid
+function isReferalIdValid () {
+       return ((isset($GLOBALS['refid'])) && (getReferalId() !== NULL) && (getReferalId() > 0));
+}
+
+// Getter for referal id
+function getReferalId () {
+       return $GLOBALS['refid'];
+}
+
+// Converts a boolean variable into 'Y' for true and 'N' for false
+function convertBooleanToYesNo ($boolean) {
+       // Default is 'N'
+       $converted = 'N';
+       if ($boolean === true) {
+               // Set 'Y'
+               $converted = 'Y';
+       } // END - if
+
+       // Return it
+       return $converted;
+}
+
+// Translates task type to a human-readable version
+function translateTaskType ($taskType) {
+       // Construct message id
+       $messageId = 'ADMIN_TASK_TYPE_' . strtoupper($taskType) . '';
+
+       // Is the message id there?
+       if (isMessageIdValid($messageId)) {
+               // Then construct message
+               $message = '{--' . $messageId . '--}';
+       } else {
+               // Else it is an unknown task type
+               $message = '{%message,ADMIN_TASK_TYPE_UNKNOWN=' . $taskType . '%}';
+       } // END - if
+
+       // Return message
+       return $message;
+}
+
 //-----------------------------------------------------------------------------
 // Automatically re-created functions, all taken from user comments on www.php.net
 //-----------------------------------------------------------------------------