]> git.mxchange.org Git - mailer.git/blobdiff - inc/functions.php
Renamed function, used more "pool functions":
[mailer.git] / inc / functions.php
index 74305d4701e40bf233a83baddfb2e9a5c6340288..857d2c41b2f14cb955a368691463ee88f9e9651f 100644 (file)
@@ -85,7 +85,7 @@ function getTotalFatalErrors () {
 }
 
 // Generate a password in a specified length or use default password length
-function generatePassword ($length = '0', $exclude =  array()) {
+function generatePassword ($length = '0', $exclude = array()) {
        // Auto-fix invalid length of zero
        if ($length == '0') {
                $length = getPassLen();
@@ -194,6 +194,26 @@ function translateYesNo ($yn) {
        return $GLOBALS[__FUNCTION__][$yn];
 }
 
+// "Translates" Y/N into "de-/active"
+function translateActivationStatus ($status) {
+       // Is it cached?
+       if (!isset($GLOBALS[__FUNCTION__][$status])) {
+               // Default
+               $GLOBALS[__FUNCTION__][$status] = '??? (' . $status . ')';
+               switch ($status) {
+                       case 'Y': $GLOBALS[__FUNCTION__][$status] = '{--ACTIVATED--}'; break;
+                       case 'N': $GLOBALS[__FUNCTION__][$status] = '{--DEACTIVATED--}'; break;
+                       default:
+                               // Log unknown value
+                               logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $status));
+                               break;
+               } // END - switch
+       } // END - if
+
+       // Return it
+       return $GLOBALS[__FUNCTION__][$status];
+}
+
 // Translates the american decimal dot into a german comma
 // OPPOMENT: convertCommaToDot()
 function translateComma ($dotted, $cut = TRUE, $max = '0') {
@@ -480,7 +500,7 @@ function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums
                                } elseif ($key != $key2) {
                                        // Sort numbers (E.g.: 9 < 10)
                                        if (($temporaryArray[$a_sort[$primary_key]][$key] < $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = TRUE;
-                                       if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order == 1))  $match = TRUE;
+                                       if (($temporaryArray[$a_sort[$primary_key]][$key] > $temporaryArray[$a_sort[$primary_key]][$key2]) && ($order ==  1)) $match = TRUE;
                                }
 
                                if ($match) {
@@ -607,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
 
@@ -615,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;
@@ -908,7 +933,7 @@ function encodeHashForCookie ($passHash) {
 
                        $mod = substr($mod, 0, 2);
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'idx=' . $idx . ',part1=' . $part1 . '/part2=' . $part2 . '/mod=' . $mod . '(' . strlen($mod) . ')');
-                       $mod = str_pad($mod, 2, '0', STR_PAD_LEFT);
+                       $mod = padLeftZero($mod);
                        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*');
                        $start += 2;
                        $newHash .= $mod;
@@ -1103,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);
@@ -1429,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
 
@@ -1464,12 +1482,12 @@ function convertCommaToDot ($str) {
                        $str = str_replace('.', '', $str);
 
                        // Replace german commata with decimal dot and cast it
-                       $float = sprintf('%01.5f', str_replace(',', '.', $str));
+                       $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str));
                        break;
 
                default: // US and so on
                        // Remove thousand commatas first and cast
-                       $float = sprintf('%01.5f', str_replace(',', '', $str));
+                       $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str));
                        break;
        } // END - switch
 
@@ -1603,16 +1621,7 @@ 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;
@@ -1621,6 +1630,33 @@ function doHourly () {
        runFilterChain('hourly');
 }
 
+// Enables the daily reset mode and runs it
+function doDaily () {
+       // Enable the reset mode
+       $GLOBALS['daily_enabled'] = TRUE;
+
+       // Run filters
+       runFilterChain('daily');
+}
+
+// Enables the weekly reset mode and runs it
+function doWeekly () {
+       // Enable the reset mode
+       $GLOBALS['weekly_enabled'] = TRUE;
+
+       // Run filters
+       runFilterChain('weekly');
+}
+
+// Enables the monthly reset mode and runs it
+function doMonthly () {
+       // Enable the reset mode
+       $GLOBALS['monthly_enabled'] = TRUE;
+
+       // Run filters
+       runFilterChain('monthly');
+}
+
 // Shuts down the mailer (e.g. closing database link, flushing output/filters, etc.)
 function doShutdown () {
        // Call the filter chain 'shutdown'
@@ -1645,29 +1681,29 @@ function initMemberId () {
 }
 
 // Setter for member id
-function setMemberId ($memberid) {
+function setMemberId ($memberId) {
        // We should not set member id to zero
-       if ($memberid == '0') {
+       if (!isValidId($memberId)) {
                reportBug(__FUNCTION__, __LINE__, 'Userid should not be set zero.');
        } // END - if
 
        // Set it secured
-       $GLOBALS['member_id'] = bigintval($memberid);
+       $GLOBALS['member_id'] = bigintval($memberId);
 }
 
 // Getter for member id or returns zero
 function getMemberId () {
        // Default member id
-       $memberid = '0';
+       $memberId = '0';
 
        // Is the member id set?
        if (isMemberIdSet()) {
                // Then use it
-               $memberid = $GLOBALS['member_id'];
+               $memberId = $GLOBALS['member_id'];
        } // END - if
 
        // Return it
-       return $memberid;
+       return $memberId;
 }
 
 // Checks ether the member id is set
@@ -1975,7 +2011,7 @@ function encodeUrl ($url, $outputMode = '0') {
        //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ',isHtmlOutputMode()=' . intval(isHtmlOutputMode()) . ',outputMode=' . $outputMode);
 
        // Is there to decode entities?
-       if ((!isHtmlOutputMode()) || ($outputMode != '0')) {
+       if (!isHtmlOutputMode()) {
                //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'url=' . $url . ' - BEFORE DECODING');
                // Decode them for e.g. JavaScript parts
                $url = decodeEntities($url);
@@ -2082,7 +2118,7 @@ function convertZeroToNull ($number) {
        return $number;
 }
 
-// Converts a NULL to zero
+// Converts a NULL|empty string|< 1 to zero
 function convertNullToZero ($number) {
        // Is it a valid username?
        if ((is_null($number)) || (empty($number)) || ($number < 1)) {
@@ -2120,7 +2156,7 @@ function capitalizeUnderscoreString ($str) {
 }
 
 // Generate admin links for mail order
-// mailType can be: 'mid' or 'bid'
+// mailType can be: 'normal' or 'bonus'
 function generateAdminMailLinks ($mailType, $mailId) {
        // Init variables
        $OUT = '';
@@ -2132,11 +2168,11 @@ function generateAdminMailLinks ($mailType, $mailId) {
 
        // Which mail do we have?
        switch ($mailType) {
-               case 'bid': // Bonus mail
+               case 'bonus': // Bonus mail
                        $table = 'bonus';
                        break;
 
-               case 'mid': // Member mail
+               case 'normal': // Member mail
                        $table = 'pool';
                        break;
 
@@ -2211,7 +2247,7 @@ function isHexadecimal ($hex) {
  * @return     $str    Overworked string
  */
 function replaceReturnNewLine ($str) {
-       return str_replace(array(chr(13), PHP_EOL), array('[r]', '[n]'), $str);
+       return str_replace(array(chr(13), chr(10)), array('[r]', '[n]'), $str);
 }
 
 // Converts a given string by splitting it up with given delimiter similar to
@@ -2513,12 +2549,119 @@ function validateIsEmpty ($str) {
        return $str;
 }
 
+// "Getter" for seconds from given time unit
+function getSecondsFromTimeUnit ($timeUnit) {
+       // Default is not found
+       $seconds = NULL;
+
+       // "Detect" it
+       switch ($timeUnit) {
+               case 's': // Seconds = 1
+                       $seconds = 1;
+                       break;
+
+               case 'm': // Minutes
+                       $seconds = 60;
+                       break;
+
+               case 'h': // Hours
+                       $seconds = 60*60;
+                       break;
+
+               case 'D': // Days
+                       $seconds = 60*60*24;
+                       break;
+
+               case 'W': // Weeks
+                       $seconds = 60*60*24*7;
+                       break;
+
+               default: // Unsupported
+                       reportBug(__FUNCTION__, __LINE__, 'Unsupported time unit ' . $timeUnit . ' detected.');
+                       break;
+       } // END - switch
+
+       // Return value
+       return $seconds;
+}
+
+// Calulates value for given seconds and time unit
+function caluculateTimeUnitValue ($seconds, $timeUnit) {
+       // Calculate it
+       return ($seconds / getSecondsFromTimeUnit($timeUnit));
+}
+
+// "Getter" for an array from given one but only one index of it
+function getArrayFromArrayIndex ($array, $key) {
+       // Some simple validation
+       assert(isset($array[0][$key]));
+
+       // Init new array
+       $newArray = array();
+
+       // "Walk" through all elements
+       foreach ($array as $element) {
+               $newArray[] = $element[$key];
+       } // END - if
+
+       // Return it
+       return $newArray;
+}
+
+/**
+ * Compress given data and encodes it into BASE64 to be stored in database with
+ * SQL_QUERY_ESC()
+ *
+ * @param      $data   Data to be compressed and encoded
+ * @return     $data   Compressed+encoded data
+ */
+function compress ($data) {
+       // Compress it
+       return base64_encode(gzcompress($data));
+}
+
+/**
+ * Decompress given data previously compressed with compress().
+ *
+ * @param      $data   Data compressed with compress()
+ * @reurn      $data   Uncompressed data
+ */
+function decompress ($data) {
+       // Decompress it
+       return gzuncompress(base64_decode($data));
+}
+
+/**
+ * Converts given charset in given string to UTF-8 if not UTF-8. This function
+ * is currently limited to iconv().
+ *
+ * @param      $str            String to convert charset in
+ * @param      $charset        Charset to convert from
+ * @return     $str            Converted string
+ */
+function convertCharsetToUtf8 ($str, $charset) {
+       // Is iconv() available?
+       if (!function_exists('iconv')) {
+               // Please make it sure
+               reportBug(__FUNCTION__, __LINE__, 'PHP function iconv() is currently required to do charset convertion.');
+       } // END - if
+
+       // Is the charset not UTF-8?
+       if (strtoupper($charset) != 'UTF-8') {
+               // Convert it to UTF-8
+               $str = iconv(strtoupper($charset), 'UTF-8//TRANSLIT', $str);
+       } // END - if
+
+       // Return converted string
+       return $str;
+}
+
 // ----------------------------------------------------------------------------
 //              "Translatation" functions for points_data table
 // ----------------------------------------------------------------------------
 
 // Translates generically some data into a target string
-function translateGeneric ($messagePrefix, $data) {
+function translateGeneric ($messagePrefix, $data, $messageSuffix = '') {
        // Is the method null or empty?
        if (is_null($data)) {
                // Is NULL
@@ -2529,10 +2672,10 @@ function translateGeneric ($messagePrefix, $data) {
        } // END - if
 
        // Default column name is unknown
-       $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}';
+       $return = '{%message,' . $messagePrefix . '_UNKNOWN' . $messageSuffix . '=' . strtoupper($data) . '%}';
 
        // Construct message id
-       $messageId = $messagePrefix . '_' . strtoupper($data);
+       $messageId = $messagePrefix . '_' . strtoupper($data) . $messageSuffix;
 
        // Is it there?
        if (isMessageIdValid($messageId)) {
@@ -2595,9 +2738,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) {