Caching of XML/email templates finished:
[mailer.git] / inc / functions.php
index 2afef01eabf53df9410f4f2497abf5c523f16a08..c37b570c973521bd1b26183a87f88e4754da0972 100644 (file)
@@ -64,7 +64,7 @@ function addFatalMessage ($F, $L, $message, $extra = '') {
        array_push($GLOBALS['fatal_messages'], $message);
 
        // Log fatal messages away
-       logDebugMessage($F, $L, 'Fatal error message: ' . $message);
+       logDebugMessage($F, $L, 'Fatal error message: ' . compileCode($message));
 }
 
 // Getter for total fatal message count
@@ -72,7 +72,7 @@ function getTotalFatalErrors () {
        // Init count
        $count = '0';
 
-       // Do we have at least the first entry?
+       // Is there at least the first entry?
        if (!empty($GLOBALS['fatal_messages'][0])) {
                // Get total count
                $count = count($GLOBALS['fatal_messages']);
@@ -330,11 +330,17 @@ function translateMenuVisibleLocked ($content, $prefix = '') {
 }
 
 // Generates an URL for the dereferer
-function generateDerefererUrl ($url) {
+function generateDereferrerUrl ($url) {
        // Don't de-refer our own links!
        if (substr($url, 0, strlen(getUrl())) != getUrl()) {
-               // De-refer this link
-               $url = '{%url=modules.php?module=loader&url=' . encodeString(compileUriCode($url)) . '%}';
+               // Encode URL
+               $encodedUrl = encodeString(compileUriCode($url));
+
+               // Log plain URL
+               //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url);
+
+               // De-refer this URL
+               $url = '{%url=modules.php?module=loader&url=' . $encodedUrl . '&hash=' . encodeHashForCookie(generateHash($url)) . '%}';
        } // END - if
 
        // Return link
@@ -413,7 +419,7 @@ function redirectToUrl ($url, $allowSpider = true) {
        // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
        $rel = ' rel="external"';
 
-       // Do we have internal or external URL?
+       // Is there internal or external URL?
        if (substr($url, 0, strlen(getUrl())) == getUrl()) {
                // Own (=internal) URL
                $rel = '';
@@ -547,7 +553,9 @@ function generateRandomCode ($length, $code, $userid, $extraData = '') {
                $len = $length;
        } // END - if
 
-       if ($len == '0') {
+       // Smaller 1 is not okay
+       if ($len < 1) {
+               // Fix it to 10
                $len = 10;
        } // END - if
 
@@ -586,7 +594,7 @@ function createEpocheTimeFromSelections ($prefix, $postData) {
        // Initial return value
        $ret = '0';
 
-       // Do we have a leap year?
+       // Is there a leap year?
        $SWITCH = '0';
        $TEST = getYear() / 4;
        $M1   = getMonth();
@@ -634,7 +642,7 @@ function createFancyTime ($stamp) {
                } // END - if
        } // END - foreach
 
-       // Do we have something there?
+       // Is something there?
        if (strlen($ret) > 0) {
                // Remove leading commata and space
                $ret = substr($ret, 2);
@@ -714,7 +722,7 @@ function generateHash ($plainText, $salt = '', $hash = true) {
                }
        } // END - if
 
-       // Do we miss an arry element here?
+       // Is an arry element missing here?
        if (!isConfigEntrySet('file_hash')) {
                // Stop here
                reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.');
@@ -925,7 +933,7 @@ function getCurrentTheme () {
        // The default theme is 'default'... ;-)
        $ret = 'default';
 
-       // Do we have ext-theme installed and active or is 'theme' in URL or POST data?
+       // Is there ext-theme installed and active or is 'theme' in URL or POST data?
        if (isExtensionActive('theme')) {
                // Call inner method
                $ret = getActualTheme();
@@ -1281,11 +1289,11 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
        // Default is the value itself
        $ret = $value;
 
-       // Do we have a special filter function?
+       // Is there a special filter function?
        if (!empty($filterFunction)) {
                // Does the filter function exist?
                if (function_exists($filterFunction)) {
-                       // Do we have extra parameters here?
+                       // Is there extra parameters here?
                        if (!empty($extraValue)) {
                                // Put both parameters in one new array by default
                                $args = array($value, $extraValue);
@@ -1298,9 +1306,21 @@ function handleExtraValues ($filterFunction, $value, $extraValue) {
 
                                // Call the multi-parameter call-back
                                $ret = call_user_func_array($filterFunction, $args);
+
+                               // Is $ret 'true'?
+                               if ($ret === true) {
+                                       // Test passed, so write direct value
+                                       $ret = $args;
+                               } // END - if
                        } else {
                                // One parameter call
                                $ret = call_user_func($filterFunction, $value);
+
+                               // Is $ret 'true'?
+                               if ($ret === true) {
+                                       // Test passed, so write direct value
+                                       $ret = $value;
+                               } // END - if
                        }
                } // END - if
        } // END - if
@@ -1354,12 +1374,12 @@ function convertCommaToDot ($str) {
                        $str = str_replace('.', '', $str);
 
                        // Replace german commata with decimal dot and cast it
-                       $float = (float)str_replace(',', '.', $str);
+                       $float = (float) str_replace(',', '.', $str);
                        break;
 
                default: // US and so on
                        // Remove thousand commatas first and cast
-                       $float = (float)str_replace(',', '', $str);
+                       $float = (float) str_replace(',', '', $str);
                        break;
        } // END - switch
 
@@ -1402,7 +1422,7 @@ function rebuildCache ($cache, $inc = '', $force = false) {
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
 
        // Shall I remove the cache file?
-       if (isCacheInstanceValid()) {
+       if ((isExtensionInstalled('cache')) && (isCacheInstanceValid())) {
                // Rebuild cache
                if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
                        // Destroy it
@@ -1734,7 +1754,7 @@ function mapModuleToTable ($moduleName) {
 
 // Add SQL debug data to array for later output
 function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
-       // Do we have cache?
+       // Is there cache?
        if (!isset($GLOBALS['debug_sql_available'])) {
                // Check it and cache it in $GLOBALS
                $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
@@ -1837,13 +1857,13 @@ function getModuleFromFileName ($file, $accessLevel) {
 
 // Encodes an URL for adding session id, etc.
 function encodeUrl ($url, $outputMode = '0') {
-       // Do we have already have a PHPSESSID inside or view.php is called? Then abort here
+       // Is there already have a PHPSESSID inside or view.php is called? Then abort here
        if ((isInStringIgnoreCase(session_name(), $url)) || (isRawOutputMode())) {
                // Raw output mode detected or session_name() found in URL
                return $url;
        } // END - if
 
-       // Do we have a valid session?
+       // Is there a valid session?
        if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === false) || (!isset($_COOKIE[session_name()]))) && (isSpider() === false)) {
                // Determine right separator
                $separator = '&amp;';
@@ -1864,7 +1884,7 @@ function encodeUrl ($url, $outputMode = '0') {
                $url = '{?URL?}/' . $url;
        } // END - if
 
-       // Do we have to decode entities?
+       // Is there to decode entities?
        if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
                // Decode them for e.g. JavaScript parts
                $url = decodeEntities($url);
@@ -1988,7 +2008,7 @@ function convertNullToZero ($number) {
 // Capitalizes a string with underscores, e.g.: some_foo_string will become SomeFooString
 // Note: This function is cached
 function capitalizeUnderscoreString ($str) {
-       // Do we have cache?
+       // Is there cache?
        if (!isset($GLOBALS[__FUNCTION__][$str])) {
                // Init target string
                $capitalized = '';
@@ -2047,7 +2067,7 @@ function generateAdminMailLinks ($mailType, $mailId) {
                                bigintval($mailId)
                        ), __FILE__, __LINE__);
 
-               // Do we have one entry there?
+               // Is there one entry there?
                if (SQL_NUMROWS($result) == 1) {
                        // Load the entry
                        $content = SQL_FETCHARRAY($result);
@@ -2143,7 +2163,7 @@ function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) {
 
        // Now check all entries
        foreach ($needles as $key => $needle) {
-               // Do we have found a partial string?
+               // Is there found a partial string?
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'heystack='.$heystack.',key='.$key.',needle='.$needle.',offset='.$offset);
                if (strpos($heystack, $needle, $offset) !== false) {
                        // Add the found key
@@ -2202,7 +2222,7 @@ function convertStringToBoolean ($str) {
        // Debug message (to measure how often this function is called)
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str);
 
-       // Do we have cache?
+       // Is there cache?
        if (!isset($GLOBALS[__FUNCTION__][$str])) {
                // Trim it lower-case for validation
                $strTrimmed = trim(strtolower($str));
@@ -2235,7 +2255,7 @@ function makeParseableVariable ($varString) {
                reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.');
        } // END - if
 
-       // Do we have cache?
+       // Is there cache?
        if (!isset($GLOBALS[__FUNCTION__][$varString])) {
                // Snap them in, if [,] are there
                $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString);
@@ -2262,6 +2282,136 @@ function removeDoubleDotFromSubject ($subject) {
        return $subject;
 }
 
+// Adds a given entry to the database
+function memberAddEntries ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $columnIndex = NULL) {
+       // Is it a member?
+       if (!isMember()) {
+               // Then abort here
+               return false;
+       } // END - if
+
+       // Set POST data generic userid
+       setPostRequestElement('userid', getMemberId());
+
+       // Call inner function
+       doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
+
+       // Entry has been added?
+       if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === true)) {
+               // Display success message
+               displayMessage('{--MEMBER_ENTRY_ADDED--}');
+       } else {
+               // Display failed message
+               displayMessage('{--MEMBER_ENTRY_NOT_ADDED--}');
+       }
+}
+
+// Edit rows by given id numbers
+function memberEditEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $timeColumns = array(), $editNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
+       // $tableName must be an array
+       if ((!is_array($tableName)) || (count($tableName) != 1)) {
+               // No tableName specified
+               reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
+       } elseif (!is_array($idColumn)) {
+               // $idColumn is no array
+               reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
+       } elseif (!is_array($userIdColumn)) {
+               // $userIdColumn is no array
+               reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
+       } elseif (!is_array($editNow)) {
+               // $editNow is no array
+               reportBug(__FUNCTION__, __LINE__, 'editNow[]=' . gettype($editNow) . '!=array: userIdColumn=' . $userIdColumn);
+       } // END - if
+
+       // Shall we change here or list for editing?
+       if ($editNow[0] === true) {
+               // Add generic userid field
+               setPostRequestElement('userid', getMemberId());
+
+               // Call generic change method
+               $affected = doGenericEditEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $editNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
+
+               // Was this fine?
+               if ($affected == countPostSelection($idColumn[0])) {
+                       // All deleted
+                       displayMessage('{--MEMBER_ALL_ENTRIES_EDITED--}');
+               } else {
+                       // Some are still there :(
+                       displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_EDITED'), $affected, countPostSelection($idColumn[0])));
+               }
+       } else {
+               // List for editing
+               memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
+       }
+}
+
+// Delete rows by given id numbers
+function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(false), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array()) {
+       // Do this only for members
+       assert(isMember());
+
+       // $tableName must be an array
+       if ((!is_array($tableName)) || (count($tableName) != 1)) {
+               // No tableName specified
+               reportBug(__FUNCTION__, __LINE__, 'tableName is not given. Please fix your XML,tableName[]=' . gettype($tableName) . '!=array: userIdColumn=' . $userIdColumn);
+       } elseif (!is_array($idColumn)) {
+               // $idColumn is no array
+               reportBug(__FUNCTION__, __LINE__, 'idColumn[]=' . gettype($idColumn) . '!=array: userIdColumn=' . $userIdColumn);
+       } elseif (!is_array($userIdColumn)) {
+               // $userIdColumn is no array
+               reportBug(__FUNCTION__, __LINE__, 'userIdColumn[]=' . gettype($userIdColumn) . '!=array: userIdColumn=' . $userIdColumn);
+       } elseif (!is_array($deleteNow)) {
+               // $deleteNow is no array
+               reportBug(__FUNCTION__, __LINE__, 'deleteNow[]=' . gettype($deleteNow) . '!=array: userIdColumn=' . $userIdColumn);
+       } // END - if
+
+       // Shall we delete here or list for deletion?
+       if ($deleteNow[0] === true) {
+               // Add generic userid field
+               setPostRequestElement('userid', getMemberId());
+
+               // Call generic function
+               $affected = doGenericDeleteEntriesConfirm($tableName, $columns, $filterFunctions, $extraValues, $deleteNow, $idColumn, $userIdColumn, $rawUserId, $cacheFiles);
+
+               // Was this fine?
+               if ($affected == countPostSelection($idColumn[0])) {
+                       // All deleted
+                       displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
+               } else {
+                       // Some are still there :(
+                       displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
+               }
+       } else {
+               // List for deletion confirmation
+               memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn);
+       }
+}
+
+// Build a special template list
+function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) {
+       // Do this only for logged in member
+       assert(isMember());
+
+       // Call inner (general) function
+       doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId);
+}
+
+// Checks whether given address is IPv4
+function isIp4AddressValid ($address) {
+       // Is there cache?
+       if (!isset($GLOBALS[__FUNCTION__][$address])) {
+               // Determine it ...
+               $GLOBALS[__FUNCTION__][$address] = preg_match('/((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9]))/', $address);
+       } // END - if
+
+       // Return cache
+       return $GLOBALS[__FUNCTION__][$address];
+}
+
+// ----------------------------------------------------------------------------
+//              "Translatation" functions for points_data table
+// ----------------------------------------------------------------------------
+
 // Translates generically some data into a target string
 function translateGeneric ($messagePrefix, $data) {
        // Is the method null or empty?
@@ -2289,16 +2439,6 @@ function translateGeneric ($messagePrefix, $data) {
        return $return;
 }
 
-// Translates task type to a human-readable version
-function translateTaskType ($taskType) {
-       // Return it
-       return translateGeneric('ADMIN_TASK_TYPE', $taskType);
-}
-
-// ----------------------------------------------------------------------------
-//              "Translatation" functions for points_data table
-// ----------------------------------------------------------------------------
-
 // Translates points subject to human-readable
 function translatePointsSubject ($subject) {
        // Remove any :x
@@ -2338,6 +2478,12 @@ function translatePointsNotifyRecipient ($notifyRecipient) {
        return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient);
 }
 
+// Translates task type to a human-readable version
+function translateTaskType ($taskType) {
+       // Return it
+       return translateGeneric('ADMIN_TASK_TYPE', $taskType);
+}
+
 //-----------------------------------------------------------------------------
 // Automatically re-created functions, all taken from user comments on www.php.net
 //-----------------------------------------------------------------------------