X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=inc%2Ffunctions.php;h=2d1db00eaec4fdbc81942671c27c0254883e1133;hb=8da353fa4bb729bb3299d247803c23833a52a327;hp=c72f7eb7f65de7009edeb2cfd41a98b544e8eb43;hpb=34200254d76999df3ed2ced0f49758285bc82e7e;p=mailer.git diff --git a/inc/functions.php b/inc/functions.php index c72f7eb7f6..2d1db00eae 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -70,20 +70,22 @@ function addFatalMessage ($F, $L, $message, $extra = '') { // Getter for total fatal message count function getTotalFatalErrors () { // Init count - $count = '0'; + $count = 0; // Is there at least the first entry? if (!empty($GLOBALS['fatal_messages'][0])) { // Get total count $count = count($GLOBALS['fatal_messages']); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - FROM ARRAY'); } // END - if // Return value + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'count=' . $count . ' - EXIT!'); return $count; } // 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(); @@ -192,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') { @@ -478,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) { @@ -648,7 +670,7 @@ function createFancyTime ($stamp) { } // END - foreach // Is something there? - if (strlen($ret) > 0) { + if (!empty($ret)) { // Remove leading commata and space $ret = substr($ret, 2); } else { @@ -799,7 +821,9 @@ function scrambleString ($str) { } // Compare both lengths and abort if different - if (strlen($str) != count($scrambleNums)) return $str; + if (strlen($str) != count($scrambleNums)) { + return $str; + } // END - if // Scramble string here //* DEBUG: */ debugOutput('***Original=' . $str.'***
'); @@ -904,7 +928,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_repeat('0', (2 - strlen($mod))) . $mod; + $mod = padLeftZero($mod); //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mod(' . ($idx * 2) . ')=' . $mod . '*'); $start += 2; $newHash .= $mod; @@ -1207,7 +1231,7 @@ function isUrlValidSimple ($url) { // Wtites data to a config.php-style file // @TODO Rewrite this function to use readFromFile() and writeToFile() -function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0) { +function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek = 0) { // Initialize some variables $done = FALSE; $seek++; @@ -1235,7 +1259,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0 // Start reading while (!feof($fp)) { // Read from source file - $line = fgets ($fp, 1024); + $line = fgets($fp, 1024); if (isInString($search, $line)) { $next = '0'; @@ -1245,7 +1269,7 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0 if ($next > -1) { if ($next === $seek) { $next = -1; - $line = $prefix . $inserted . $suffix . chr(10); + $line = $prefix . $inserted . $suffix . PHP_EOL; } else { $next++; } @@ -1266,18 +1290,22 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $inserted, $seek=0 fclose($fp); if (($done === TRUE) && ($found === TRUE)) { - // Copy back tmp file and delete tmp :-) + // Copy back temporary->FQFN file and ... copyFileVerified($tmp, $FQFN, 0644); + + // ... delete temporay file :-) return removeFile($tmp); } elseif ($found === FALSE) { - outputHtml('CHANGE: 404!'); + // Entry not found + logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - 404!'); } else { - outputHtml('TMP: UNDONE!'); + // Temporary file not fully written + logDebugMessage(__FUNCTION__, __LINE__, 'File ' . basename($FQFN) . ' cannot be changed: comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek . ' - Temporary file unfinished!'); } } } else { // File not found, not readable or writeable - reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN)); + reportBug(__FUNCTION__, __LINE__, 'File not readable/writeable. file=' . basename($FQFN) . ',comment=' . $comment . ',prefix=' . $prefix . ',inserted=' . $inserted . ',seek=' . $seek); } // An error was detected! @@ -1289,10 +1317,10 @@ function logDebugMessage ($funcFile, $line, $message, $force=true) { // Is debug mode enabled? if ((isDebugModeEnabled()) || ($force === TRUE)) { // Remove CRLF - $message = str_replace(array(chr(13), chr(10)), array('', ''), $message); + $message = str_replace(array(chr(13), PHP_EOL), array('', ''), $message); // Log this message away - appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . '|' . basename($funcFile) . '|' . $line . '|' . $message); + appendLineToFile(getPath() . getCachePath() . 'debug.log', generateDateTime(time(), '4') . '|' . getModule(FALSE) . ':' . getExtraModule() . '|' . basename($funcFile) . '|' . $line . '|' . $message); } // END - if } @@ -1343,19 +1371,22 @@ function handleExtraValues ($filterFunction, $value, $extraValue) { } // Tries to determine if call-back functions and/or extra values shall be parsed -function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search) { - // Debug message - /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE)); +function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $userIdColumn, $search, $id = NULL) { + // Debug mode enabled? + if (isDebugModeEnabled()) { + // Debug message + /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'key=' . $key . ',entries=' . $entries . ',userIdColumn=' . $userIdColumn[0] . ',search=' . $search . ',filterFunctions=' . print_r($filterFunctions, TRUE) . ',extraValues=' . print_r($extraValues, TRUE)); + } // END - if // Send data through the filter function if found - if ($key == $userIdColumn[0]) { + if ($key === $userIdColumn[0]) { // Is the userid, we have to process it with convertZeroToNull() $entries = convertZeroToNull($entries); } elseif ((!empty($filterFunctions[$key])) && (isset($extraValues[$key]))) { // Debug mode enabled? if (isDebugModeEnabled()) { // Then log it - /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!'); + /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!'); } // END - if // Filter function + extra value set @@ -1364,8 +1395,26 @@ function doHandleExtraValues ($filterFunctions, $extraValues, $key, $entries, $u // Debug mode enabled? if (isDebugModeEnabled()) { // Then log it - /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!'); + /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$key] . ',extraValues=' . $extraValues[$key] . ',key=' . $key . ',id=' . $id . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!'); } // END - if + } elseif ((!empty($filterFunctions[$search])) && (!empty($extraValues[$search]))) { + // Debug mode enabled? + if (isDebugModeEnabled()) { + // Then log it + /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - BEFORE!'); + } // END - if + + // Handle extra values + $entries = handleExtraValues($filterFunctions[$search], $entries, $extraValues[$search]); + + // Debug mode enabled? + if (isDebugModeEnabled()) { + // Then log it + /* NOISY-DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'search=' . $search . ',filterFunctions=' . $filterFunctions[$search] . ',key=' . $key . ',search=' . $search . ',entries[' . gettype($entries) . ']=' . $entries . ' - AFTER!'); + } // END - if + + // Make sure entries is not bool, then something went wrong + assert(!is_bool($entries)); } elseif (!empty($filterFunctions[$search])) { // Debug mode enabled? if (isDebugModeEnabled()) { @@ -1435,12 +1484,12 @@ function convertCommaToDot ($str) { $str = str_replace('.', '', $str); // Replace german commata with decimal dot and cast it - $float = (float) str_replace(',', '.', $str); + $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '.', $str)); break; default: // US and so on // Remove thousand commatas first and cast - $float = (float) str_replace(',', '', $str); + $float = sprintf(getConfig('FLOAT_MASK'), str_replace(',', '', $str)); break; } // END - switch @@ -1597,8 +1646,8 @@ function doShutdown () { // Call the filter chain 'shutdown' runFilterChain('shutdown', NULL); - // Check if not in installation phase and the link is up - if ((!isInstallationPhase()) && (SQL_IS_LINK_UP())) { + // Check if link is up + if (SQL_IS_LINK_UP()) { // Close link SQL_CLOSE(__FUNCTION__, __LINE__); } elseif (!isInstallationPhase()) { @@ -1616,29 +1665,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 @@ -1805,7 +1854,6 @@ function mapModuleToTable ($moduleName) { case 'login': // ... and 'login' the member's menu $moduleName = 'member'; break; - // Anything else will not be mapped, silently. } // END - switch @@ -1925,7 +1973,7 @@ function encodeUrl ($url, $outputMode = '0') { } // END - if // Is there a valid session? - if (((!isset($GLOBALS['valid_session'])) || ($GLOBALS['valid_session'] === FALSE) || (!isset($_COOKIE[session_name()]))) && (isSpider() === FALSE)) { + if ((!isSessionValid()) && (!isSpider())) { // Determine right separator $separator = '&'; if (!isInString('?', $url)) { @@ -1933,11 +1981,8 @@ function encodeUrl ($url, $outputMode = '0') { $separator = '?'; } // END - if - // Is the session id set? - if (session_id() != '') { - // Then add it to URL - $url .= $separator . session_name() . '=' . session_id(); - } // END - if + // Then add it to URL + $url .= $separator . session_name() . '=' . session_id(); } // END - if // Add {?URL?} ? @@ -1950,7 +1995,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); @@ -2057,16 +2102,13 @@ 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 > 0)) { - // Always secure it - $number = bigintval($number); - } else { + if ((is_null($number)) || (empty($number)) || ($number < 1)) { // Is not valid or zero $number = '0'; - } + } // END - if // Return it return $number; @@ -2098,7 +2140,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 = ''; @@ -2110,11 +2152,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; @@ -2181,7 +2223,7 @@ function isHexadecimal ($hex) { } /** - * Replace chr(13) with "[r]" and chr(10) with "[n]" and add a final new-line to make + * Replace chr(13) with "[r]" and PHP_EOL with "[n]" and add a final new-line to make * them visible to the developer. Use this function to debug e.g. buggy HTTP * response handler functions. * @@ -2301,7 +2343,7 @@ function convertStringToBoolean ($str) { } // END - if // Determine it - $GLOBALS[__FUNCTION__][$str] = (($strTrimmed == 'true') ? true : false); + $GLOBALS[__FUNCTION__][$str] = ($strTrimmed == 'true'); } // END - if // Return cache @@ -2374,7 +2416,7 @@ function memberAddEntries ($tableName, $columns = array(), $filterFunctions = ar } // 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()) { +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(), $content = array()) { // $tableName must be an array if ((!is_array($tableName)) || (count($tableName) != 1)) { // No tableName specified @@ -2408,12 +2450,12 @@ function memberEditEntriesConfirm ($tableName, $columns = array(), $filterFuncti } } else { // List for editing - memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn); + memberListBuilder('edit', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content); } } // 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()) { +function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunctions = array(), $extraValues = array(), $deleteNow = array(FALSE), $idColumn = array('id'), $userIdColumn = array('userid'), $rawUserId = array('userid'), $cacheFiles = array(), $content = array()) { // Do this only for members assert(isMember()); @@ -2450,17 +2492,18 @@ function memberDeleteEntriesConfirm ($tableName, $columns = array(), $filterFunc } } else { // List for deletion confirmation - memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn); + memberListBuilder('delete', $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUSerId, $content); } } // Build a special template list -function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid')) { +// @TODO cacheFiles is not yet supported +function memberListBuilder ($listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId = array('userid'), $content = array()) { // Do this only for logged in member assert(isMember()); // Call inner (general) function - doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId); + doGenericListBuilder('member', $listType, $tableName, $columns, $filterFunctions, $extraValues, $idColumn, $userIdColumn, $rawUserId, $content); } // Checks whether given address is IPv4 @@ -2490,12 +2533,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 @@ -2506,10 +2656,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)) {