X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=inc%2Ffunctions.php;h=a941932a6ca5d471dbe8008484b418f6c5802fbd;hb=386367490d9c77419c3bce89cee2864118ba2f42;hp=2c0f1b4480a1a8ccd117faf283f6eb9dac6e3fe5;hpb=9aea37564ade675024cc31d7593ead0c89038920;p=mailer.git
diff --git a/inc/functions.php b/inc/functions.php
index 2c0f1b4480..a941932a6c 100644
--- a/inc/functions.php
+++ b/inc/functions.php
@@ -16,8 +16,8 @@
* $Author:: $ *
* -------------------------------------------------------------------- *
* Copyright (c) 2003 - 2009 by Roland Haeder *
- * Copyright (c) 2009 - 2011 by Mailer Developer Team *
- * For more information visit: http://www.mxchange.org *
+ * Copyright (c) 2009 - 2012 by Mailer Developer Team *
+ * For more information visit: http://mxchange.org *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
@@ -61,10 +61,10 @@ function addFatalMessage ($F, $L, $message, $extra = '') {
}
// Add message to $GLOBALS['fatal_messages']
- $GLOBALS['fatal_messages'][] = $message;
+ 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']);
@@ -82,172 +82,19 @@ function getTotalFatalErrors () {
return $count;
}
-// 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);
-
- // 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;
- } else {
- // Does the user exist?
- if (fetchUserData($toEmail)) {
- // Get the email
- $toEmail = getUserData('email');
- } else {
- // Set webmaster
- $toEmail = getWebmaster();
- }
- }
- } elseif ($toEmail == '0') {
- // Is the webmaster!
- $toEmail = getWebmaster();
- }
- //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "TO={$toEmail}
");
-
- // Check for PHPMailer or debug-mode
- if ((!checkPhpMailerUsage()) || (isDebugModeEnabled())) {
- // Prefix is '' for text mails
- $prefix = '';
-
- // Is HTML?
- if ($isHtml == 'Y') {
- // Set prefix
- $prefix = 'html_';
- } // END - if
-
- // Not in PHPMailer-Mode
- if (empty($mailHeader)) {
- // Load email header template
- $mailHeader = loadEmailTemplate($prefix . 'header');
- } else {
- // Append header
- $mailHeader .= loadEmailTemplate($prefix . 'header');
- }
- } // 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
- outputHtml('
-Headers : ' . htmlentities(utf8_decode(trim($mailHeader))) . ' -To : ' . htmlentities(utf8_decode($toEmail)) . ' -Subject : ' . htmlentities(utf8_decode($subject)) . ' -Message : ' . htmlentities(utf8_decode($message)) . ' -'); - - // This is always fine - return true; - } elseif (!empty($toEmail)) { - // Send Mail away - return sendRawEmail($toEmail, $subject, $message, $mailHeader); - } elseif ($isHtml != 'Y') { - // Problem detected while sending a mail, forward it to admin - return sendRawEmail(getWebmaster(), '[PROBLEM:]' . $subject, $message, $mailHeader); - } - - // Why did we end up here? This should not happen - debug_report_bug(__FUNCTION__, __LINE__, 'Ending up: template=' . $template); -} - -// Check to use wether legacy mail() command or PHPMailer class -// @TODO Rewrite this to an extension 'smtp' -// @private -function checkPhpMailerUsage() { - return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != '')); -} - -// Send out a raw email with PHPMailer class or legacy mail() command -function sendRawEmail ($toEmail, $subject, $message, $headers) { - // Just compile all to put out all configs, etc. - $eval = '$toEmail = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($toEmail), false)) . '"); '; - $eval .= '$subject = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($subject), false)) . '"); '; - $eval .= '$headers = decodeEntities("' . escapeQuotes(doFinalCompilation(compileRawCode($headers), false)) . '"); '; - - // Do not decode entities in the message because we also send HTML mails through this function - $eval .= '$message = "' . escapeQuotes(doFinalCompilation(compileRawCode($message), false)) . '";'; - - // Run the final eval() command - eval($eval); - - // Shall we use PHPMailer class or legacy mode? - if (checkPhpMailerUsage()) { - // Use PHPMailer class with SMTP enabled - loadIncludeOnce('inc/phpmailer/class.phpmailer.php'); - loadIncludeOnce('inc/phpmailer/class.smtp.php'); - - // get new instance - $mail = new PHPMailer(); - - // Set charset to UTF-8 - $mail->CharSet = 'UTF-8'; - - // Path for PHPMailer - $mail->PluginDir = sprintf("%sinc/phpmailer/", getPath()); - - $mail->IsSMTP(); - $mail->SMTPAuth = true; - $mail->Host = getConfig('SMTP_HOSTNAME'); - $mail->Port = 25; - $mail->Username = getConfig('SMTP_USER'); - $mail->Password = getConfig('SMTP_PASSWORD'); - if (empty($headers)) { - $mail->From = getWebmaster(); - } else { - $mail->From = $headers; - } - $mail->FromName = getMainTitle(); - $mail->Subject = $subject; - if ((isExtensionActive('html_mail')) && (secureString($message) != $message)) { - $mail->Body = $message; - $mail->AltBody = 'Your mail program required HTML support to read this mail!'; - $mail->WordWrap = 70; - $mail->IsHTML(true); - } else { - $mail->Body = decodeEntities($message); - } - - $mail->AddAddress($toEmail, ''); - $mail->AddReplyTo(getWebmaster(), getMainTitle()); - $mail->AddCustomHeader('Errors-To:' . getWebmaster()); - $mail->AddCustomHeader('X-Loop:' . getWebmaster()); - $mail->AddCustomHeader('Bounces-To:' . getWebmaster()); - $mail->Send(); - - // Has an error occured? - if (!empty($mail->ErrorInfo)) { - // Log message - logDebugMessage(__FUNCTION__, __LINE__, 'Error while sending mail: ' . $mail->ErrorInfo); - - // Raise an error - return false; - } else { - // All fine! - return true; - } - } else { - // Use legacy mail() command - return mail($toEmail, $subject, decodeEntities($message), $headers); - } -} - // Generate a password in a specified length or use default password length -function generatePassword ($length = '0') { +function generatePassword ($length = '0', $exclude = array()) { // Auto-fix invalid length of zero - if ($length == '0') $length = getPassLen(); + if ($length == '0') { + $length = getPassLen(); + } // END - if // Initialize array with all allowed chars $ABC = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/,.'); + // Exclude some entries + $ABC = array_diff($ABC, $exclude); + // Start creating password $PASS = ''; for ($i = '0'; $i < $length; $i++) { @@ -267,47 +114,49 @@ function generatePassword ($length = '0') { // Generates a human-readable timestamp from the Uni* stamp function generateDateTime ($time, $mode = '0') { + // Is there cache? + if (isset($GLOBALS[__FUNCTION__][$time][$mode])) { + // Return it instead + return $GLOBALS[__FUNCTION__][$time][$mode]; + } // END - if + // 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 // Filter out numbers - $time = bigintval($time); - - // Is it cached? - if (isset($GLOBALS[__FUNCTION__][$time][$mode])) { - // Then use it - return $GLOBALS[__FUNCTION__][$time][$mode]; - } // END - if + $timeSecured = bigintval($time); // Detect language switch (getLanguage()) { case 'de': // German date / time format switch ($mode) { - case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break; - case '1': $ret = strtolower(date('d.m.Y - H:i', $time)); break; - case '2': $ret = date('d.m.Y|H:i', $time); break; - case '3': $ret = date('d.m.Y', $time); break; - case '4': $ret = date('d.m.Y|H:i:s', $time); break; - case '5': $ret = date('d-m-Y (l-F-T)', $time); break; - case '6': $ret = date('Ymd', $time); break; + case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $timeSecured); break; + case '1': $ret = strtolower(date('d.m.Y - H:i', $timeSecured)); break; + case '2': $ret = date('d.m.Y|H:i', $timeSecured); break; + case '3': $ret = date('d.m.Y', $timeSecured); break; + case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break; + case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break; + case '6': $ret = date('Ymd', $timeSecured); break; + case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP default: logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode)); break; - } + } // END - switch break; default: // Default is the US date / time format! switch ($mode) { - case '0': $ret = date('r', $time); break; - case '1': $ret = strtolower(date('Y-m-d - g:i A', $time)); break; - case '2': $ret = date('y-m-d|H:i', $time); break; - case '3': $ret = date('y-m-d', $time); break; - case '4': $ret = date('d.m.Y|H:i:s', $time); break; - case '5': $ret = date('d-m-Y (l-F-T)', $time); break; - case '6': $ret = date('Ymd', $time); break; + case '0': $ret = date('r', $timeSecured); break; + case '1': $ret = strtolower(date('Y-m-d - g:i A', $timeSecured)); break; + case '2': $ret = date('y-m-d|H:i', $timeSecured); break; + case '3': $ret = date('y-m-d', $timeSecured); break; + case '4': $ret = date('d.m.Y|H:i:s', $timeSecured); break; + case '5': $ret = date('d-m-Y (l-F-T)', $timeSecured); break; + case '6': $ret = date('Ymd', $timeSecured); break; + case '7': $ret = date('Y-m-d H:i:s', $timeSecured); break; // Compatible with MySQL TIMESTAMP default: logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode)); break; @@ -332,7 +181,7 @@ function translateYesNo ($yn) { case 'N': $GLOBALS[__FUNCTION__][$yn] = '{--NO--}'; break; default: // Log unknown value - logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn)); + logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected: Y/N", $yn)); break; } // END - switch } // END - if @@ -342,21 +191,26 @@ function translateYesNo ($yn) { } // Translates the american decimal dot into a german comma -function translateComma ($dotted, $cut = true, $max = '0') { +// OPPOMENT: convertCommaToDot() +function translateComma ($dotted, $cut = TRUE, $max = '0') { // First, cast all to double, due to PHP changes $dotted = (double) $dotted; - // Default is 3 you can change this in admin area "Misc -> Misc Options" - if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', 3); + // Default is 3 you can change this in admin area "Settings -> Misc Options" + if (!isConfigEntrySet('max_comma')) { + setConfigEntry('max_comma', 3); + } // END - if // Use from config is default $maxComma = getConfig('max_comma'); // Use from parameter? - if ($max > 0) $maxComma = $max; + if ($max > 0) { + $maxComma = $max; + } // END - if // Cut zeros off? - if (($cut === true) && ($max == '0')) { + if (($cut === TRUE) && ($max == '0')) { // Test for commata if in cut-mode $com = explode('.', $dotted); if (count($com) < 2) { @@ -394,12 +248,13 @@ function translateGender ($gender) { case 'M': // Male case 'F': // Female case 'C': // Company - $ret = sprintf("{--GENDER_%s--}", $gender); + // Use generic function + $ret = translateGeneric('GENDER', $gender); break; default: // Please report bugs on unknown genders - debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender)); + reportBug(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender)); break; } // END - switch @@ -417,17 +272,17 @@ function translateUserStatus ($status) { case 'UNCONFIRMED': case 'CONFIRMED': case 'LOCKED': - $ret = sprintf("{--ACCOUNT_STATUS_%s--}", $status); + // Use generic function for all "normal" cases" + $ret = translateGeneric('ACCOUNT_STATUS', $status); break; - case '': - case null: + case '': // Account deleted + case NULL: // Account deleted $ret = '{--ACCOUNT_STATUS_DELETED--}'; break; - default: - // Please report all unknown status - debug_report_bug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status))); + default: // Please report all unknown status + reportBug(__FUNCTION__, __LINE__, sprintf("Unknown status %s(%s) detected.", $status, gettype($status))); break; } // END - switch @@ -442,23 +297,31 @@ function translateMenuVisibleLocked ($content, $prefix = '') { // Translate 'visible' and keep an eye on the prefix switch ($content['visible']) { - // Should be visible - case 'Y': $content['visible_css'] = $prefix . 'menu_visible' ; break; - case 'N': $content['visible_css'] = $prefix . 'menu_invisible'; break; - default: - // Please report this - debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=
' . print_r($content, true) . ''); + case 'Y': // Should be visible + $content['visible_css'] = $prefix . 'menu_visible'; + break; + + case 'N': // Is invisible + $content['visible_css'] = $prefix . 'menu_invisible'; + break; + + default: // Please report this + reportBug(__FUNCTION__, __LINE__, 'Unsupported visible value detected. content=
' . print_r($content, TRUE) . ''); break; } // END - switch // Translate 'locked' and keep an eye on the prefix switch ($content['locked']) { - // Should be locked - case 'Y': $content['locked_css'] = $prefix . 'menu_locked' ; break; - case 'N': $content['locked_css'] = $prefix . 'menu_unlocked'; break; - default: - // Please report this - debug_report_bug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=
' . print_r($content, true) . ''); + case 'Y': // Should be locked, only admins can call this + $content['locked_css'] = $prefix . 'menu_locked'; + break; + + case 'N': // Is unlocked and visible to members/guests/sponsors + $content['locked_css'] = $prefix . 'menu_unlocked'; + break; + + default: // Please report this + reportBug(__FUNCTION__, __LINE__, 'Unsupported locked value detected. content=
' . print_r($content, TRUE) . ''); break; } // END - switch @@ -467,22 +330,28 @@ 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)) . '%}'; + if (substr($url, 0, strlen(getUrl())) != getUrl()) { + // 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 - 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 @@ -494,7 +363,7 @@ function countSelection ($array) { // Integrity check if (!is_array($array)) { // Not an array! - debug_report_bug(__FUNCTION__, __LINE__, 'No array provided.'); + reportBug(__FUNCTION__, __LINE__, 'No array provided.'); } // END - if // Init count @@ -503,7 +372,10 @@ function countSelection ($array) { // Count all entries foreach ($array as $key => $selected) { // Is it checked? - if (!empty($selected)) $ret++; + if (!empty($selected)) { + // Yes, then count it + $ret++; + } // END - if } // END - foreach // Return counted selections @@ -529,55 +401,48 @@ 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) { + // Is the output mode -2? + if (isAjaxOutputMode()) { + // This is always (!) an AJAX request and shall not be redirected + return; + } // END - if + // 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()) { + // Is there internal or external URL? + 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); - - // Simple probe for bots/spiders from search engines - if ((isSpider()) && ($allowSpider === true)) { - // Set HTTP-Status - setHttpStatus('200 OK'); - - // Set content-type here to fix a missing array element - setContentType('text/html'); - - // Output new location link as anchor - outputHtml('' . secureString($URL) . ''); - } elseif (!headers_sent()) { - // Clear output buffer - clearOutputBuffer(); - - // Clear own output buffer - $GLOBALS['output'] = ''; + //* DEBUG: */ reportBug(__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()) { // 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'); } // Shut the mailer down here - shutdown(); + doShutdown(); } /************************************************************************ @@ -587,36 +452,36 @@ function redirectToUrl ($URL, $allowSpider = true) { * * * $array - Das 3-dimensionale Array, das paralell sortiert werden soll * * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben * - * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird * + * $primary_key - Primaerschl.ssel aus $a_sort, nach dem sortiert wird * * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a * - * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren * + * $nums - TRUE = Als Zahlen sortieren, FALSE = Als Zeichen sortieren * * * * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array * * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen * * Sie, dass es doch nicht so schwer ist! :-) * * * ************************************************************************/ -function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = false) { - $dummy = $array; +function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums = FALSE) { + $temporaryArray = $array; while ($primary_key < count($a_sort)) { - foreach ($dummy[$a_sort[$primary_key]] as $key => $value) { - foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) { - $match = false; - if ($nums === false) { + foreach ($temporaryArray[$a_sort[$primary_key]] as $key => $value) { + foreach ($temporaryArray[$a_sort[$primary_key]] as $key2 => $value2) { + $match = FALSE; + if ($nums === FALSE) { // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10") - if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true; + if (($key != $key2) && (strcmp(strtolower($temporaryArray[$a_sort[$primary_key]][$key]), strtolower($temporaryArray[$a_sort[$primary_key]][$key2])) == $order)) $match = TRUE; } elseif ($key != $key2) { // Sort numbers (E.g.: 9 < 10) - if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true; - if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$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) { // We have found two different values, so let's sort whole array - foreach ($dummy as $sort_key => $sort_val) { - $t = $dummy[$sort_key][$key]; - $dummy[$sort_key][$key] = $dummy[$sort_key][$key2]; - $dummy[$sort_key][$key2] = $t; + foreach ($temporaryArray as $sort_key => $sort_val) { + $t = $temporaryArray[$sort_key][$key]; + $temporaryArray[$sort_key][$key] = $temporaryArray[$sort_key][$key2]; + $temporaryArray[$sort_key][$key2] = $t; unset($t); } // END - foreach } // END - if @@ -628,111 +493,116 @@ function array_pk_sort (&$array, $a_sort, $primary_key = '0', $order = -1, $nums } // END - while // Write back sorted array - $array = $dummy; + $array = $temporaryArray; } // // Deprecated : $length (still has one reference in this function) -// Optional : $DATA +// Optional : $extraData // -function generateRandomCode ($length, $code, $userid, $DATA = '') { +function generateRandomCode ($length, $code, $userid, $extraData = '') { // Build server string - $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr(); + $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr(); // Build key string - $keys = getSiteKey() . getEncryptSeperator() . getDateKey(); + $keys = getSiteKey() . getEncryptSeparator() . getDateKey(); if (isConfigEntrySet('secret_key')) { - $keys .= getEncryptSeperator().getSecretKey(); + $keys .= getEncryptSeparator() . getSecretKey(); } // END - if if (isConfigEntrySet('file_hash')) { - $keys .= getEncryptSeperator().getFileHash(); + $keys .= getEncryptSeparator() . getFileHash(); } // END - if - $keys .= getEncryptSeperator() . getDateFromPatchTime(); + $keys .= getEncryptSeparator() . getDateFromRepository(); if (isConfigEntrySet('master_salt')) { - $keys .= getEncryptSeperator().getMasterSalt(); + $keys .= getEncryptSeparator() . getMasterSalt(); } // END - if // Build string from misc data - $data = $code . getEncryptSeperator() . $userid . getEncryptSeperator() . $DATA; + $data = $code . getEncryptSeparator() . $userid . getEncryptSeparator() . $extraData; // Add more additional data if (isSessionVariableSet('u_hash')) { - $data .= getEncryptSeperator() . getSession('u_hash'); + $data .= getEncryptSeparator() . getSession('u_hash'); } // END - if - // Add referal id, language, theme and userid - $data .= getEncryptSeperator() . determineReferalId(); - $data .= getEncryptSeperator() . getLanguage(); - $data .= getEncryptSeperator() . getCurrentTheme(); - $data .= getEncryptSeperator() . getMemberId(); + // Add referral id, language, theme and userid + $data .= getEncryptSeparator() . determineReferralId(); + $data .= getEncryptSeparator() . getLanguage(); + $data .= getEncryptSeparator() . getCurrentTheme(); + $data .= getEncryptSeparator() . getMemberId(); // Calculate number for generating the code $a = $code + getConfig('_ADD') - 1; if (isConfigEntrySet('master_salt')) { // Generate hash with master salt from modula of number with the prime number and other data - $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, getMasterSalt()); - - // Create number from hash - $rcode = hexdec(substr($saltedHash, strlen(getMasterSalt()), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi(); + $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, getMasterSalt()); } else { // Generate hash with "hash of site key" from modula of number with the prime number and other data - $saltedHash = generateHash(($a % getPrime()) . getEncryptSeperator() . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength())); - - // Create number from hash - $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi(); + $saltedHash = generateHash(($a % getPrime()) . getEncryptSeparator() . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a, substr(sha1(getSiteKey()), 0, getSaltLength())); } + // Create number from hash + $rcode = hexdec(substr($saltedHash, getSaltLength(), 9)) / abs(getRandNo() - $a + sqrt(getConfig('_ADD'))) / pi(); + // At least 10 numbers shall be secure enought! - $len = getCodeLength(); - if ($len == '0') { + if (isExtensionActive('other')) { + $len = getCodeLength(); + } else { $len = $length; } // END - if - if ($len == '0') { + + // Smaller 1 is not okay + if ($len < 1) { + // Fix it to 10 $len = 10; } // END - if - // Cut off requested counts of number - $return = substr(str_replace('.', '', $rcode), 0, $len); + // Cut off requested counts of number, but skip first digit (which is mostly a zero) + $return = substr($rcode, (strpos($rcode, '.') + 1), $len); // Done building code return $return; } // Does only allow numbers -function bigintval ($num, $castValue = true, $abortOnMismatch = true) { - // Filter all numbers out +function bigintval ($num, $castValue = TRUE, $abortOnMismatch = TRUE) { + //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ' - ENTERED!'); + // Filter all non-number chars out, so only number chars will remain $ret = preg_replace('/[^0123456789]/', '', $num); // Shall we cast? - if ($castValue === true) { + if ($castValue === TRUE) { // Cast to biggest numeric type $ret = (double) $ret; } // END - if // Has the whole value changed? - if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === true) && (!is_null($num))) { + if (('' . $ret . '' != '' . $num . '') && ($abortOnMismatch === TRUE) && (!is_null($num))) { // Log the values - debug_report_bug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num); + reportBug(__FUNCTION__, __LINE__, 'Problem with number found. ret[' . gettype($ret) . ']=' . $ret . ', num[' . gettype($num) . ']='. $num); } // END - if // Return result + //* DEBUG: */ debugOutput('[' . __FUNCTION__ . ':' . __LINE__ . '] ' . 'num=' . $num . ',castValue=' . intval($castValue) . ',abortOnMismatch=' . intval($abortOnMismatch) . ',ret=' . $ret . ' - EXIT!'); return $ret; } // Creates a Uni* timestamp from given selection data and prefix -function createTimestampFromSelections ($prefix, $postData) { +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(); // 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')) $SWITCH = getOneDay(); + if ((floor($TEST) == $TEST) && ($M1 == '02') && ($postData[$prefix . '_mo'] > '02')) { + $SWITCH = getOneDay(); + } // END - if // First add years... $ret += $postData[$prefix . '_ye'] * (31536000 + $SWITCH); @@ -762,114 +632,88 @@ function createTimestampFromSelections ($prefix, $postData) { // Creates a 'fancy' human-readable timestamp from a Uni* stamp function createFancyTime ($stamp) { // Get data array with years/months/weeks/days/... - $data = createTimeSelections($stamp, '', '', '', true); + $data = createTimeSelections($stamp, '', '', '', TRUE); $ret = ''; foreach ($data as $k => $v) { if ($v > 0) { // Value is greater than 0 "eval" data to return string - $ret .= ', ' . $v . ' {--_' . strtoupper($k) . '--}'; + $ret .= ', ' . $v . ' {%pipe,translateTimeUnit=' . $k . '%}'; break; } // 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); } else { // Zero seconds - $ret = '0 {--_SECONDS--}'; + $ret = '0 {--TIME_UNIT_SECOND--}'; } // Return fancy time string return $ret; } -// Extract host from script name -function extractHostnameFromUrl (&$script) { - // Use default SERVER_URL by default... ;) So? - $url = getServerUrl(); +// Taken from www.php.net isInStringIgnoreCase() user comments +function isEmailValid ($email) { + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ' - ENTERED!'); - // Is this URL valid? - if (substr($script, 0, 7) == 'http://') { - // Use the hostname from script URL as new hostname - $url = substr($script, 7); - $extract = explode('/', $url); - $url = $extract[0]; - // Done extracting the URL :) - } // END - if + // Is there cache? + if (!isset($GLOBALS[__FUNCTION__][$email])) { + // Check first part of email address + $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*'; - // Extract host name - $host = str_replace('http://', '', $url); - if (isInString('/', $host)) { - $host = substr($host, 0, strpos($host, '/')); - } // END - if + // Check domain + $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+'; - // Generate relative URL - //* DEBUG: */ debugOutput('SCRIPT=' . $script); - if (substr(strtolower($script), 0, 7) == 'http://') { - // But only if http:// is in front! - $script = substr($script, (strlen($url) + 7)); - } elseif (substr(strtolower($script), 0, 8) == 'https://') { - // Does this work?! - $script = substr($script, (strlen($url) + 8)); - } + // Generate pattern + $regex = '@^' . $first . '\@' . $domain . '$@iU'; - //* DEBUG: */ debugOutput('SCRIPT=' . $script); - if (substr($script, 0, 1) == '/') { - $script = substr($script, 1); + // Determine it + $GLOBALS[__FUNCTION__][$email] = (($email != getMessage('DEFAULT_WEBMASTER')) && (preg_match($regex, $email))); } // END - if - // Return host name - return $host; -} - -// Taken from www.php.net isInStringIgnoreCase() user comments -function isEmailValid ($email) { - // Check first part of email address - $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*'; - - // Check domain - $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+'; - - // Generate pattern - $regex = '@^' . $first . '\@' . $domain . '$@iU'; - // Return check result - return preg_match($regex, $email); + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'email=' . $email . ',isValid=' . intval($GLOBALS[__FUNCTION__][$email]) . ' - EXIT!'); + return $GLOBALS[__FUNCTION__][$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); + /* + * 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); } // Generate a hash for extra-security for all passwords -function generateHash ($plainText, $salt = '', $hash = true) { +function generateHash ($plainText, $salt = '', $hash = TRUE) { // Debug output //* DEBUG: */ debugOutput('plainText('.strlen($plainText).')=' . $plainText . ',salt('.strlen($salt).')=' . $salt . ',hash=' . intval($hash)); // Is the required extension 'sql_patches' there and a salt is not given? // 123 4 43 3 4 432 2 3 32 2 3 32 2 3 3 21 if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) && (empty($salt))) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5')) || (strlen($salt) == 32)) { - // Extension sql_patches is missing/outdated so we hash the plain text with MD5 - if ($hash === true) { + // Extension ext-sql_patches is missing/outdated so we hash the plain text with MD5 + if ($hash === TRUE) { // Is plain password return md5($plainText); } else { @@ -878,28 +722,28 @@ 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 - debug_report_bug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.'); + reportBug(__FUNCTION__, __LINE__, 'Missing file_hash in ' . __FUNCTION__ . '.'); } // END - if // When the salt is empty build a new one, else use the first x configured characters as the salt if (empty($salt)) { // Build server string for more entropy - $server = $_SERVER['PHP_SELF'] . getEncryptSeperator() . detectUserAgent() . getEncryptSeperator() . getenv('SERVER_SOFTWARE') . getEncryptSeperator() . detectRealIpAddress() . getEncryptSeperator() . detectRemoteAddr(); + $server = $_SERVER['PHP_SELF'] . getEncryptSeparator() . detectUserAgent() . getEncryptSeparator() . getenv('SERVER_SOFTWARE') . getEncryptSeparator() . detectRealIpAddress() . getEncryptSeparator() . detectRemoteAddr(); // Build key string - $keys = getSiteKey() . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . getSecretKey() . getEncryptSeperator() . getFileHash() . getEncryptSeperator() . getDateFromPatchTime() . getEncryptSeperator() . getMasterSalt(); + $keys = getSiteKey() . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . getSecretKey() . getEncryptSeparator() . getFileHash() . getEncryptSeparator() . getDateFromRepository() . getEncryptSeparator() . getMasterSalt(); // Additional data - $data = $plainText . getEncryptSeperator() . uniqid(mt_rand(), true) . getEncryptSeperator() . time(); + $data = $plainText . getEncryptSeparator() . uniqid(mt_rand(), TRUE) . getEncryptSeparator() . time(); // Calculate number for generating the code $a = time() + getConfig('_ADD') - 1; // Generate SHA1 sum from modula of number and the prime number - $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeperator() . $keys . getEncryptSeperator() . $data . getEncryptSeperator() . getDateKey() . getEncryptSeperator() . $a); + $sha1 = sha1(($a % getPrime()) . $server . getEncryptSeparator() . $keys . getEncryptSeparator() . $data . getEncryptSeparator() . getDateKey() . getEncryptSeparator() . $a); //* DEBUG: */ debugOutput('SHA1=' . $sha1.' ('.strlen($sha1).')
'.print_r($content, true).''); + + // Add output and type + $content['type'] = $mailType; + $content['__output'] = ''; + + // Filter all data + $content = runFilterChain('generate_admin_mail_links', $content); + + // Get output back + $OUT = $content['__output']; } // END - if // Free result @@ -2230,7 +2094,7 @@ function generateAdminMailLinks ($mailType, $mailId) { /** - * determine if a string can represent a number in hexadecimal + * Determine if a string can represent a number in hexadecimal * * @param $hex A string to check if it is hex-encoded * @return $foo True if the string is a hex, otherwise false @@ -2250,12 +2114,16 @@ function isHexadecimal ($hex) { return ($hex == dechex(hexdec($hex))); } -// Replace "\r" with "[r]" and "\n" 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. +/** + * Replace chr(13) with "[r]" and chr(10) 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. + * + * @param $str String to overwork + * @return $str Overworked string + */ function replaceReturnNewLine ($str) { - return str_replace("\r", '[r]', str_replace("\n", '[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 @@ -2267,7 +2135,7 @@ function stringToArray ($delimiter, $string) { // "Walk" through all entries foreach (explode($delimiter, $string) as $split) { // Append the delimiter and add it to the array - $strArray[] = $split . $delimiter; + array_push($strArray, $split . $delimiter); } // END - foreach // Return array @@ -2280,7 +2148,7 @@ function detectMultiBytePrefix ($str) { $mbPrefix = ''; // Detect multi-byte (strictly) - if (mb_detect_encoding($str, 'auto', true) !== false) { + if (mb_detect_encoding($str, 'auto', TRUE) !== FALSE) { // With multi-byte encoded string $mbPrefix = 'mb_'; } // END - if @@ -2289,18 +2157,18 @@ function detectMultiBytePrefix ($str) { return $mbPrefix; } -// Searches the given array for a sub-string match and returns all found keys in an array -function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) { +// Searches given array for a sub-string match and returns all found keys in an array +function getArrayKeysFromSubStrArray ($heystack, $needles, $offset = 0) { // Init array for all found keys $keys = array(); // 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) { + if (strpos($heystack, $needle, $offset) !== FALSE) { // Add the found key - $keys[] = $key; + array_push($keys, $key); } // END - if } // END - foreach @@ -2308,6 +2176,336 @@ function getArrayKeysFromSubStrArray ($heystack, array $needles, $offset = 0) { return $keys; } +// Determines database column name from given subject and locked +function determinePointsColumnFromSubjectLocked ($subject, $locked) { + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ' - ENTERED!'); + // 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 + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'subject=' . $subject . ',locked=' . intval($locked) . ',pointsColumn=' . $pointsColumn . ' - EXIT!'); + return $pointsColumn; +} + +// 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" 'true' to true and 'false' to false +function convertStringToBoolean ($str) { + // Debug message (to measure how often this function is called) + //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'str=' . $str); + + // Is there cache? + if (!isset($GLOBALS[__FUNCTION__][$str])) { + // Trim it lower-case for validation + $strTrimmed = trim(strtolower($str)); + + // Is it valid? + if (!in_array($strTrimmed, array('true', 'false'))) { + // Not valid! + reportBug(__FUNCTION__, __LINE__, 'str=' . $str . '(' . $strTrimmed . ') is not true/false'); + } // END - if + + // Determine it + $GLOBALS[__FUNCTION__][$str] = (($strTrimmed == 'true') ? true : false); + } // END - if + + // Return cache + return $GLOBALS[__FUNCTION__][$str]; +} + +/** + * "Makes" a variable in given string parseable, this function will throw an + * error if the first character is not a dollar sign. + * + * @param $varString String which contains a variable + * @return $return String with added single quotes for better parsing + */ +function makeParseableVariable ($varString) { + // The first character must be a dollar sign + if (substr($varString, 0, 1) != '$') { + // Please report this + reportBug(__FUNCTION__, __LINE__, 'varString=' . $varString . ' - No dollar sign detected, will not parse it.'); + } // END - if + + // Is there cache? + if (!isset($GLOBALS[__FUNCTION__][$varString])) { + // Snap them in, if [,] are there + $GLOBALS[__FUNCTION__][$varString] = str_replace(array('[', ']'), array("['", "']"), $varString); + } // END - if + + // Return cache + return $GLOBALS[__FUNCTION__][$varString]; +} + +// "Getter" for random TAN +function getRandomTan () { + // Generate one + return mt_rand(0, 99999); +} + +// Removes any : from subject +function removeDoubleDotFromSubject ($subject) { + // Remove it + $subjectArray = explode(':', $subject); + $subject = $subjectArray[0]; + unset($subjectArray); + + // Return it + 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, 'mem_edit'); + + // 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, 'mem_delete'); + + // 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]; +} + +// Returns the string if not empty or FALSE if empty +function validateIsEmpty ($str) { + // Trim it + $trimmed = trim($str); + + // Is the string empty? + if (empty($trimmed)) { + // Then set FALSE + $str = FALSE; + } // END - if + + // Return it + return $str; +} + +// ---------------------------------------------------------------------------- +// "Translatation" functions for points_data table +// ---------------------------------------------------------------------------- + +// Translates generically some data into a target string +function translateGeneric ($messagePrefix, $data) { + // Is the method null or empty? + if (is_null($data)) { + // Is NULL + $data = 'NULL'; + } elseif (empty($data)) { + // Is empty (string) + $data = 'EMPTY'; + } // END - if + + // Default column name is unknown + $return = '{%message,' . $messagePrefix . '_UNKNOWN=' . strtoupper($data) . '%}'; + + // Construct message id + $messageId = $messagePrefix . '_' . strtoupper($data); + + // Is it there? + if (isMessageIdValid($messageId)) { + // Then use it as message string + $return = '{--' . $messageId . '--}'; + } // END - if + + // Return the column name + return $return; +} + +// Translates points subject to human-readable +function translatePointsSubject ($subject) { + // Remove any :x + $subject = removeDoubleDotFromSubject($subject); + + // Return it + return translateGeneric('POINTS_SUBJECT', $subject); +} + +// "Translates" given points account type +function translatePointsAccountType ($accountType) { + // Return it + return translateGeneric('POINTS_ACCOUNT_TYPE', $accountType); +} + +// "Translates" given points "locked mode" +function translatePointsLockedMode ($lockedMode) { + // Return it + return translateGeneric('POINTS_LOCKED_MODE', $lockedMode); +} + +// "Translates" given points payment method +function translatePointsPaymentMethod ($paymentMethod) { + // Return it + return translateGeneric('POINTS_PAYMENT_METHOD', $paymentMethod); +} + +// "Translates" given points account provider +function translatePointsAccountProvider ($accountProvider) { + // Return it + return translateGeneric('POINTS_ACCOUNT_PROVIDER', $accountProvider); +} + +// "Translates" given points notify recipient +function translatePointsNotifyRecipient ($notifyRecipient) { + // Return it + return translateGeneric('POINTS_NOTIFY_RECIPIENT', $notifyRecipient); +} + +// "Translates" given mode to a human-readable version +function translatePointsMode ($pointsMode) { + // Return it + return translateGeneric('POINTS_MODE', $pointsMode); +} + +// "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 //-----------------------------------------------------------------------------