Allow to find files where file extension is not important
[mailer.git] / inc / functions.php
index 2d1db00eaec4fdbc81942671c27c0254883e1133..c227a23925e6d5069a84a1108ea06b4c353727d4 100644 (file)
@@ -16,7 +16,7 @@
  * $Author::                                                          $ *
  * -------------------------------------------------------------------- *
  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
- * Copyright (c) 2009 - 2012 by Mailer Developer Team                   *
+ * Copyright (c) 2009 - 2013 by Mailer Developer Team                   *
  * For more information visit: http://mxchange.org                      *
  *                                                                      *
  * This program is free software; you can redistribute it and/or modify *
@@ -51,7 +51,7 @@ function getFatalArray () {
 }
 
 // Add a fatal error message to the queue array
-function addFatalMessage ($F, $L, $message, $extra = '') {
+function addFatalMessage ($file, $line, $message, $extra = '') {
        if (is_array($extra)) {
                // Multiple extras for a message with masks
                $message = call_user_func_array('sprintf', $extra);
@@ -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: ' . compileCode($message));
+       logDebugMessage($file, $line, 'Fatal error message: ' . compileCode($message));
 }
 
 // Getter for total fatal message count
@@ -627,7 +627,8 @@ function createEpocheTimeFromSelections ($prefix, $postData) {
        $M1   = getMonth();
 
        // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
-       if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02'))  {
+       // 01     2     2         1    1           1    123     4                          43    3                                 32    233    4                          43    3                                 3210
+       if ((floor($TEST) == $TEST) && ($M1 == '02') && (((isset($postData[$prefix . '_mo'])) && ($postData[$prefix . '_mo'] > '02')) || ((isset($postData[$prefix . '_mn'])) && ($postData[$prefix . '_mn'] > '02')))) {
                $SWITCH = getOneDay();
        } // END - if
 
@@ -635,7 +636,11 @@ function createEpocheTimeFromSelections ($prefix, $postData) {
        $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH);
 
        // Next months...
-       $ret += $postData[$prefix . '_mo'] * 2628000;
+       if (isset($postData[$prefix . '_mo'])) {
+               $ret += $postData[$prefix . '_mo'] * 2628000;
+       } elseif (isset($postData[$prefix . '_mn'])) {
+               $ret += $postData[$prefix . '_mn'] * 2628000;
+       }
 
        // Next weeks
        $ret += $postData[$prefix . '_we'] * 604800;
@@ -1123,15 +1128,8 @@ function getMessageFromErrorCode ($code) {
                        break;
 
                case getCode('URL_TIME_LOCK'):
-                       // @TODO Move this SQL code into a function, let's say 'getTimestampFromPoolId($id) ?
-                       $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
-                               array(bigintval(getRequestElement('id'))), __FUNCTION__, __LINE__);
-
                        // Load timestamp from last order
-                       $content = SQL_FETCHARRAY($result);
-
-                       // Free memory
-                       SQL_FREERESULT($result);
+                       $content = getPoolDataFromId(getRequestElement('id'));
 
                        // Translate it for templates
                        $content['timestamp'] = generateDateTime($content['timestamp'], 1);
@@ -1449,17 +1447,17 @@ function convertSelectionsToEpocheTime (array &$postData, array &$content, &$id,
        $test = substr($id, -3);
 
        // Improved way of checking! :-)
-       if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
+       if (in_array($test, array('_ye', '_mo', '_mn', '_we', '_da', '_ho', '_mi', '_se'))) {
                // Found a multi-selection for timings?
                $test = substr($id, 0, -3);
-               if ((isset($postData[$test . '_ye'])) && (isset($postData[$test . '_mo'])) && (isset($postData[$test . '_we'])) && (isset($postData[$test . '_da'])) && (isset($postData[$test . '_ho'])) && (isset($postData[$test . '_mi'])) && (isset($postData[$test . '_se'])) && ($test != $test2)) {
+               if ((isset($postData[$test . '_ye'])) && ((isset($postData[$test . '_mo'])) || (isset($postData[$test . '_mn']))) && (isset($postData[$test . '_we'])) && (isset($postData[$test . '_da'])) && (isset($postData[$test . '_ho'])) && (isset($postData[$test . '_mi'])) && (isset($postData[$test . '_se'])) && ($test != $test2)) {
                        // Generate timestamp
                        $postData[$test] = createEpocheTimeFromSelections($test, $postData);
                        array_push($content, sprintf("`%s`='%s'", $test, $postData[$test]));
                        $GLOBALS['skip_config'][$test] = TRUE;
 
                        // Remove data from array
-                       foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
+                       foreach (array('ye', 'mo', 'mn', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
                                unset($postData[$test . '_' . $rem]);
                        } // END - foreach
 
@@ -1534,6 +1532,7 @@ function rebuildCache ($cache, $inc = '', $force = FALSE) {
        // Shall I remove the cache file?
        if ((isExtensionInstalled('cache')) && (isCacheInstanceValid()) && (isHtmlOutputMode())) {
                // Rebuild cache only in HTML output-mode
+               // @TODO This should be rewritten not to load the cache file for just checking if it is there for save removal.
                if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
                        // Destroy it
                        $GLOBALS['cache_instance']->removeCacheFile($force);
@@ -1623,22 +1622,64 @@ function addNewBonusMail ($data, $mode = '', $output = TRUE) {
        }
 }
 
-// Enables the reset mode and runs it
-function doReset () {
-       // Enable the reset mode
-       $GLOBALS['reset_enabled'] = TRUE;
-
-       // Run filters
-       runFilterChain('reset');
-}
-
-// Enables the reset mode (hourly, weekly and monthly) and runs it
+// Enables the hourly reset mode and runs it
 function doHourly () {
        // Enable the hourly reset mode
        $GLOBALS['hourly_enabled'] = TRUE;
 
        // Run filters (one always!)
        runFilterChain('hourly');
+
+       // Do not update in hourly debug mode
+       if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
+               // Update database
+               updateConfiguration('last_hourly', getHour());
+       } // END - if
+}
+
+// Enables the daily reset mode and runs it
+function doDaily () {
+       // Enable the reset mode
+       $GLOBALS['daily_enabled'] = TRUE;
+
+       // Run filters
+       runFilterChain('daily');
+
+       // Do not update in daily debug mode
+       if ((!isConfigEntrySet('DEBUG_DAILY')) || (!isDebugDailyEnabled())) {
+               // Update database
+               updateConfiguration('last_daily', getDay());
+       } // END - if
+}
+
+// Enables the weekly reset mode and runs it
+function doWeekly () {
+       // Enable the reset mode
+       $GLOBALS['weekly_enabled'] = TRUE;
+
+       // Run filters
+       runFilterChain('weekly');
+
+       // Do not update in weekly debug mode
+       if ((!isConfigEntrySet('DEBUG_WEEKLY')) || (!isDebugWeeklyEnabled())) {
+               // Update database
+               updateConfiguration('last_weekly', getWeek());
+       } // END - if
+}
+
+// Enables the monthly reset mode and runs it
+function doMonthly () {
+       // Enable the reset mode
+       $GLOBALS['monthly_enabled'] = TRUE;
+
+       // Run filters
+       runFilterChain('monthly');
+
+       // Do not update in monthly debug mode
+       if ((!isConfigEntrySet('DEBUG_MONTHLY')) || (!isDebugMonthlyEnabled())) {
+               // Update database
+               updateConfiguration('last_monthly', getMonth());
+       } // END - if
 }
 
 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
@@ -1647,9 +1688,9 @@ function doShutdown () {
        runFilterChain('shutdown', NULL);
 
        // Check if link is up
-       if (SQL_IS_LINK_UP()) {
+       if (isSqlLinkUp()) {
                // Close link
-               SQL_CLOSE(__FUNCTION__, __LINE__);
+               sqlCloseLink(__FUNCTION__, __LINE__);
        } elseif (!isInstallationPhase()) {
                // No database link
                reportBug(__FUNCTION__, __LINE__, 'Database link is already down, while shutdown is running.');
@@ -1731,9 +1772,10 @@ function isExtraTitleSet () {
  * @param      $excludePattern         Regular expression to exclude more files (preg_match())
  * @param      $recursive                      whether to scan recursively
  * @param      $suffix                         Suffix for positive matches ($extension will be appended, too)
+ * @param      $withPrefixSuffix       Whether to include prefix/suffix in found entries
  * @return     $foundMatches           All found positive matches for above criteria
  */
-function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '') {
+function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $addBaseDir = TRUE, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = TRUE, $suffix = '', $withPrefixSuffix = TRUE) {
        // Add default entries we should always exclude
        array_unshift($excludeArray, '.', '..', '.svn', '.htaccess');
 
@@ -1812,6 +1854,9 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $ad
                                if ($addBaseDir === TRUE) {
                                        // With base path
                                        array_push($foundMatches, $fileName);
+                               } elseif ($withPrefixSuffix === FALSE) {
+                                       // No prefix/suffix
+                                       array_push($foundMatches, substr($baseFile, strlen($prefix), -strlen($suffix . $extension)));
                                } else {
                                        // No base path
                                        array_push($foundMatches, $baseFile);
@@ -1820,7 +1865,7 @@ function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = FALSE, $ad
                                // We found .php file but should not search for them, why?
                                reportBug(__FUNCTION__, __LINE__, 'We should find files with extension=' . $extension . ', but we found a PHP script. (baseFile=' . $baseFile . ')');
                        }
-               } elseif ($fileExtension == $extension) {
+               } elseif (($fileExtension == $extension) || (empty($extension))) {
                        // Other, generic file found
                        array_push($foundMatches, $fileName);
                }
@@ -1848,7 +1893,7 @@ function mapModuleToTable ($moduleName) {
        // Map only these, still lame code...
        switch ($moduleName) {
                case 'index': // 'index' is the guest's menu
-                       $moduleName = 'guest'; 
+                       $moduleName = 'guest';
                        break;
 
                case 'login': // ... and 'login' the member's menu
@@ -1862,35 +1907,35 @@ function mapModuleToTable ($moduleName) {
 }
 
 // Add SQL debug data to array for later output
-function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
+function addSqlToDebug ($result, $sqlString, $timing, $file, $line) {
        // Is there cache?
        if (!isset($GLOBALS['debug_sql_available'])) {
                // Check it and cache it in $GLOBALS
                $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isDisplayDebugSqlEnabled()));
        } // END - if
-       
+
        // Don't execute anything here if we don't need or ext-other is missing
        if ($GLOBALS['debug_sql_available'] === FALSE) {
                return;
        } // END - if
 
        // Already executed?
-       if (isset($GLOBALS['debug_sqls'][$F][$L][$sqlString])) {
+       if (isset($GLOBALS['debug_sqls'][$file][$line][$sqlString])) {
                // Then abort here, we don't need to profile a query twice
                return;
        } // END - if
 
        // Remeber this as profiled (or not, but we don't care here)
-       $GLOBALS['debug_sqls'][$F][$L][$sqlString] = TRUE;
+       $GLOBALS['debug_sqls'][$file][$line][$sqlString] = TRUE;
 
        // Generate record
        $record = array(
-               'num_rows' => SQL_NUMROWS($result),
-               'affected' => SQL_AFFECTEDROWS(),
+               'num_rows' => sqlNumRows($result),
+               'affected' => sqlAffectedRows(),
                'sql_str'  => $sqlString,
                'timing'   => $timing,
-               'file'     => basename($F),
-               'line'     => $L
+               'file'     => basename($file),
+               'line'     => $line
        );
 
        // Add it
@@ -2169,7 +2214,7 @@ function generateAdminMailLinks ($mailType, $mailId) {
        // Is the mail type supported?
        if (!empty($table)) {
                // Query for the mail
-               $result = SQL_QUERY_ESC("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
+               $result = sqlQueryEscaped("SELECT `id`, `%s` AS `mail_status` FROM `{?_MYSQL_PREFIX?}_%s` WHERE `id`=%s LIMIT 1",
                        array(
                                $statusColumn,
                                $table,
@@ -2177,9 +2222,9 @@ function generateAdminMailLinks ($mailType, $mailId) {
                        ), __FILE__, __LINE__);
 
                // Is there one entry there?
-               if (SQL_NUMROWS($result) == 1) {
+               if (sqlNumRows($result) == 1) {
                        // Load the entry
-                       $content = SQL_FETCHARRAY($result);
+                       $content = sqlFetchArray($result);
 
                        // Add output and type
                        $content['type']     = $mailType;
@@ -2193,7 +2238,7 @@ function generateAdminMailLinks ($mailType, $mailId) {
                } // END - if
 
                // Free result
-               SQL_FREERESULT($result);
+               sqlFreeResult($result);
        } // END - if
 
        // Return generated HTML code
@@ -2406,7 +2451,7 @@ function memberAddEntries ($tableName, $columns = array(), $filterFunctions = ar
        doGenericAddEntries($tableName, $columns, $filterFunctions, $extraValues, $timeColumns, $columnIndex);
 
        // Entry has been added?
-       if ((!SQL_HASZEROAFFECTED()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
+       if ((!ifSqlHasZeroAffectedRows()) && ($GLOBALS['__XML_PARSE_RESULT'] === TRUE)) {
                // Display success message
                displayMessage('{--MEMBER_ENTRY_ADDED--}');
        } else {
@@ -2488,7 +2533,7 @@ function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunc
                        displayMessage('{--MEMBER_ALL_ENTRIES_REMOVED--}');
                } else {
                        // Some are still there :(
-                       displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), SQL_AFFECTEDROWS(), countPostSelection($idColumn[0])));
+                       displayMessage(sprintf(getMessage('MEMBER_SOME_ENTRIES_NOT_DELETED'), sqlAffectedRows(), countPostSelection($idColumn[0])));
                }
        } else {
                // List for deletion confirmation
@@ -2594,7 +2639,7 @@ function getArrayFromArrayIndex ($array, $key) {
 
 /**
  * Compress given data and encodes it into BASE64 to be stored in database with
- * SQL_QUERY_ESC()
+ * sqlQueryEscaped()
  *
  * @param      $data   Data to be compressed and encoded
  * @return     $data   Compressed+encoded data
@@ -2722,9 +2767,18 @@ function translateTaskType ($taskType) {
        return translateGeneric('ADMIN_TASK_TYPE', $taskType);
 }
 
-//-----------------------------------------------------------------------------
-// Automatically re-created functions, all taken from user comments on www.php.net
-//-----------------------------------------------------------------------------
+// "Translates" task status to a human-readable version
+function translateTaskStatus ($taskStatus) {
+       // Return it
+       return translateGeneric('ADMIN_TASK_STATUS', $taskStatus);
+}
+
+/*
+ *-----------------------------------------------------------------------------
+ * Automatically re-created functions, all taken from user comments on
+ * www.php.net
+ *-----------------------------------------------------------------------------
+ */
 if (!function_exists('html_entity_decode')) {
        // Taken from documentation on www.php.net
        function html_entity_decode ($string) {