\n";
$OUT .= "
\n";
$OUT .= "\n";
@@ -1414,7 +1465,7 @@ function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="ce
$OUT .= " {--_YEARS--}
\n";
}
- if (ereg("M", $display) || (empty($display))) {
+ if (ereg('M', $display) || (empty($display))) {
$OUT .= " {--_MONTHS--}
\n";
}
@@ -1430,7 +1481,7 @@ function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="ce
$OUT .= " {--_HOURS--}
\n";
}
- if (ereg("m", $display) || (empty($display))) {
+ if (ereg('m', $display) || (empty($display))) {
$OUT .= " {--_MINUTES--}
\n";
}
@@ -1443,94 +1494,94 @@ function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="ce
if (ereg('Y', $display) || (empty($display))) {
// Generate year selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 10; $idx++) {
- $OUT .= " \n";
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 10; $idx++) {
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
- if (ereg("M", $display) || (empty($display))) {
+ if (ereg('M', $display) || (empty($display))) {
// Generate month selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 11; $idx++)
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 11; $idx++)
{
- $OUT .= " \n";
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
if (ereg("W", $display) || (empty($display))) {
// Generate week selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 4; $idx++) {
- $OUT .= " \n";
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 4; $idx++) {
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
if (ereg("D", $display) || (empty($display))) {
// Generate day selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 31; $idx++) {
- $OUT .= " \n";
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 31; $idx++) {
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
if (ereg("h", $display) || (empty($display))) {
// Generate hour selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 23; $idx++) {
- $OUT .= " \n";
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 23; $idx++) {
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
- if (ereg("m", $display) || (empty($display))) {
+ if (ereg('m', $display) || (empty($display))) {
// Generate minute selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 59; $idx++) {
- $OUT .= " \n";
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 59; $idx++) {
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
if (ereg("s", $display) || (empty($display))) {
// Generate second selection
- $OUT .= " \n";
- for ($idx = 0; $idx <= 59; $idx++) {
- $OUT .= " \n";
+ $OUT .= " \n";
+ for ($idx = '0'; $idx <= 59; $idx++) {
+ $OUT .= " \n";
}
$OUT .= " \n";
} else {
- $OUT .= " \n";
+ $OUT .= " \n";
}
$OUT .= " \n";
$OUT .= "
\n";
@@ -1541,108 +1592,43 @@ function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="ce
}
//
-function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
+function createTimestampFromSelections ($prefix, $postData) {
// Initial return value
- $ret = 0;
+ $ret = '0';
// Do we have a leap year?
- $SWITCH = 0;
+ $SWITCH = '0';
$TEST = date('Y', time()) / 4;
- $M1 = date("m", time());
+ $M1 = date('m', time());
// 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") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
+ if ((floor($TEST) == $TEST) && ($M1 == "02") && ($postData[$prefix."_mo"] > "02")) $SWITCH = getConfig('ONE_DAY');
// First add years...
- $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
+ $ret += $postData[$prefix."_ye"] * (31536000 + $SWITCH);
// Next months...
- $ret += $POST[$prefix."_mo"] * 2628000;
+ $ret += $postData[$prefix."_mo"] * 2628000;
// Next weeks
- $ret += $POST[$prefix."_we"] * 604800;
+ $ret += $postData[$prefix."_we"] * 604800;
// Next days...
- $ret += $POST[$prefix."_da"] * 86400;
+ $ret += $postData[$prefix."_da"] * 86400;
// Next hours...
- $ret += $POST[$prefix."_ho"] * 3600;
+ $ret += $postData[$prefix."_ho"] * 3600;
// Next minutes..
- $ret += $POST[$prefix."_mi"] * 60;
+ $ret += $postData[$prefix."_mi"] * 60;
// And at last seconds...
- $ret += $POST[$prefix."_se"];
+ $ret += $postData[$prefix."_se"];
// Return calculated value
return $ret;
}
-// Sends out mail to all administrators
-// IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
-function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
- // Trim template name
- $template = trim($template);
-
- // Load email template
- $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
-
- // Check which admin shall receive this mail
- $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
- array($template), __FUNCTION__, __LINE__);
- if (SQL_NUMROWS($result) == 0) {
- // Create new entry (to all admins)
- SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
- array($template), __FUNCTION__, __LINE__);
- } else {
- // Load admin IDs...
- // @TODO This can be, somehow, rewritten
- $adminIds = array();
- while ($content = SQL_FETCHARRAY($result)) {
- $adminIds[] = $content['admin_id'];
- } // END - while
-
- // Free memory
- SQL_FREERESULT($result);
-
- // Init result
- $result = false;
-
- // "implode" IDs and query string
- $aid = implode(",", $adminIds);
- if ($aid == "-1") {
- if (EXT_IS_ACTIVE("events")) {
- // Add line to user events
- EVENTS_ADD_LINE($subj, $msg, $UID);
- } else {
- // Log error for debug
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
- $template,
- $subj,
- $UID
- ));
- }
- } elseif ($aid == "0") {
- // Select all email adresses
- $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
- __FUNCTION__, __LINE__);
- } else {
- // If Admin-ID is not "to-all" select
- $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
- array($aid), __FUNCTION__, __LINE__);
- }
- }
-
- // Load email addresses and send away
- while ($content = SQL_FETCHARRAY($result)) {
- SEND_EMAIL($content['email'], $subj, $msg);
- } // END - while
-
- // Free memory
- SQL_FREERESULT($result);
-}
-
-//
-function CREATE_FANCY_TIME ($stamp) {
+// Creates a 'fancy' human-readable timestamp from a Uni* stamp
+function createFancyTime ($stamp) {
// Get data array with years/months/weeks/days/...
- $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
- $ret = "";
+ $data = createTimeSelections($stamp, '', '', '', true);
+ $ret = '';
foreach($data as $k => $v) {
if ($v > 0) {
// Value is greater than 0 "eval" data to return string
- $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
- eval($eval);
+ eval("\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";");
break;
} // END - if
} // END - foreach
@@ -1660,84 +1646,82 @@ function CREATE_FANCY_TIME ($stamp) {
return $ret;
}
-//
-function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
- $SEP = ""; $TOP = "";
- if (!$show_form) {
+// Generates a navigation row for listing emails
+function addEmailNavigation ($PAGES, $offset, $show_form, $colspan, $return=false) {
+ $SEP = ''; $TOP = '';
+ if ($show_form === false) {
$TOP = " top2";
- $SEP = "
";
+ $SEP = "
";
}
- $NAV = "";
+ $NAV = '';
for ($page = 1; $page <= $PAGES; $page++) {
// Is the page currently selected or shall we generate a link to it?
- if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
+ if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
// Is currently selected, so only highlight it
- $NAV .= "
-";
+ $NAV .= '-';
} else {
// Open anchor tag and add base URL
- $NAV .= " 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
+ if ((isGetRequestElementSet('userid')) && (bigintval(getRequestElement('userid')) > 0)) $NAV .= '&userid=' . bigintval(getRequestElement('userid'));
// Close open anchor tag
- $NAV .= "\">";
+ $NAV .= '">';
}
$NAV .= $page;
- if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
+ if (($page == getRequestElement('page')) || ((!isGetRequestElementSet('page')) && ($page == 1))) {
// Is currently selected, so only highlight it
- $NAV .= "- ";
+ $NAV .= '- ';
} else {
// Close anchor tag
- $NAV .= "";
+ $NAV .= '';
}
// Add seperator if we have not yet reached total pages
- if ($page < $PAGES) $NAV .= " | ";
- }
+ if ($page < $PAGES) $NAV .= ' | ';
+ } // END - for
// Define constants only once
- if (!defined('__NAV_OUTPUT')) {
- define('__NAV_OUTPUT' , $NAV);
- define('__NAV_COLSPAN', $colspan);
- define('__NAV_TOP' , $TOP);
- define('__NAV_SEP' , $SEP);
- }
+ $content['nav'] = $NAV;
+ $content['span'] = $colspan;
+ $content['top'] = $TOP;
+ $content['sep'] = $SEP;
// Load navigation template
- $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
+ $OUT = loadTemplate('admin_email_nav_row', true, $content);
if ($return === true) {
// Return generated HTML-Code
return $OUT;
} else {
// Output HTML-Code
- OUTPUT_HTML($OUT);
+ outputHtml($OUT);
}
}
// Extract host from script name
-function EXTRACT_HOST (&$script) {
+function extractHostnameFromUrl (&$script) {
// Use default SERVER_URL by default... ;) So?
- $url = constant('SERVER_URL');
+ $url = getConfig('SERVER_URL');
// Is this URL valid?
- if (substr($script, 0, 7) == "http://") {
+ if (substr($script, 0, 7) == 'http://') {
// Use the hostname from script URL as new hostname
$url = substr($script, 7);
- $extract = explode("/", $url);
+ $extract = explode('/', $url);
$url = $extract[0];
// Done extracting the URL :)
} // END - if
// Extract host name
- $host = str_replace("http://", "", $url);
- if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
+ $host = str_replace('http://', '', $url);
+ if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
// Generate relative URL
- //* DEBUG: */ print("SCRIPT=".$script."
\n");
- if (substr(strtolower($script), 0, 7) == "http://") {
+ //* DEBUG: */ print("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://") {
@@ -1745,96 +1729,110 @@ function EXTRACT_HOST (&$script) {
$script = substr($script, (strlen($url) + 8));
}
- //* DEBUG: */ print("SCRIPT=".$script."
\n");
- if (substr($script, 0, 1) == "/") $script = substr($script, 1);
+ //* DEBUG: */ print("SCRIPT=" . $script.'
');
+ if (substr($script, 0, 1) == '/') $script = substr($script, 1);
// Return host name
return $host;
}
// Send a GET request
-function GET_URL ($script) {
- // Compile the script name
- $script = COMPILE_CODE($script);
-
+function sendGetRequest ($script, $data = array()) {
// Extract host name from script
- $host = EXTRACT_HOST($script);
+ $host = extractHostnameFromUrl($script);
+
+ // Add data
+ $scriptData = http_build_query($data, '', '&');
+
+ // Do we have a question-mark in the script?
+ if (strpos($script, '?') === false) {
+ // No, so first char must be question mark
+ $scriptData = '?' . $scriptData;
+ } else {
+ // Ok, add &
+ $scriptData = '&' . $scriptData;
+ }
+
+ // Add script data
+ $script .= $scriptData;
// Generate GET request header
- $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
- $request .= "Host: " . $host . "\r\n";
- $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
- if (defined('FULL_VERSION')) {
- $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
+ $request = 'GET /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
+ $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
+ $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
+ if (isConfigEntrySet('FULL_VERSION')) {
+ $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
} else {
- $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
+ $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('VERSION') . getConfig('HTTP_EOL');
}
- $request .= "Content-Type: text/plain\r\n";
- $request .= "Cache-Control: no-cache\r\n";
- $request .= "Connection: Close\r\n\r\n";
+ $request .= 'Content-Type: text/plain' . getConfig('HTTP_EOL');
+ $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
+ $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
// Send the raw request
- $response = SEND_RAW_REQUEST($host, $request);
+ $response = sendRawRequest($host, $request);
// Return the result to the caller function
return $response;
}
// Send a POST request
-function POST_URL ($script, $postData) {
+function sendPostRequest ($script, $postData) {
// Is postData an array?
if (!is_array($postData)) {
// Abort here
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
- return array("", "", "");
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
+ return array('', '', '');
} // END - if
- // Compile the script name
- $script = COMPILE_CODE($script);
-
// Extract host name from script
- $host = EXTRACT_HOST($script);
+ $host = extractHostnameFromUrl($script);
// Construct request
- $data = http_build_query($postData, '','&');
+ $data = http_build_query($postData, '', '&');
// Generate POST request header
- $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
- $request .= "Host: " . $host . "\r\n";
- $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
- $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
- $request .= "Content-type: application/x-www-form-urlencoded\r\n";
- $request .= "Content-length: " . strlen($data) . "\r\n";
- $request .= "Cache-Control: no-cache\r\n";
- $request .= "Connection: Close\r\n\r\n";
+ $request = 'POST /' . trim($script) . ' HTTP/1.1' . getConfig('HTTP_EOL');
+ $request .= 'Host: ' . $host . getConfig('HTTP_EOL');
+ $request .= 'Referer: ' . getConfig('URL') . '/admin.php' . getConfig('HTTP_EOL');
+ $request .= 'User-Agent: ' . getConfig('TITLE') . '/' . getConfig('FULL_VERSION') . getConfig('HTTP_EOL');
+ $request .= 'Content-Type: application/x-www-form-urlencoded' . getConfig('HTTP_EOL');
+ $request .= 'Content-length: ' . strlen($data) . getConfig('HTTP_EOL');
+ $request .= 'Cache-Control: no-cache' . getConfig('HTTP_EOL');
+ $request .= 'Connection: Close' . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
$request .= $data;
// Send the raw request
- $response = SEND_RAW_REQUEST($host, $request);
+ $response = sendRawRequest($host, $request);
// Return the result to the caller function
return $response;
}
// Sends a raw request to another host
-function SEND_RAW_REQUEST ($host, $request) {
+function sendRawRequest ($host, $request) {
+ // Init errno and errdesc with 'all fine' values
+ $errno = '0'; $errdesc = '';
+
// Initialize array
- $response = array("", "", "");
+ $response = array('', '', '');
// Default is not to use proxy
$useProxy = false;
// Are proxy settins set?
- if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
+ if ((isConfigEntrySet('proxy_host')) && (getConfig('proxy_host') != '') && (isConfigEntrySet('proxy_port')) && (getConfig('proxy_port') > 0)) {
// Then use it
$useProxy = true;
} // END - if
// Open connection
- //* DEBUG: */ die("SCRIPT=".$script."
\n");
- if ($useProxy) {
- $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
+ //* DEBUG: */ die("SCRIPT=" . $script.'
');
+ if ($useProxy === true) {
+ // Connect to host through proxy connection
+ $fp = @fsockopen(compileRawCode(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
} else {
+ // Connect to host directly
$fp = @fsockopen($host, 80, $errno, $errdesc, 30);
}
@@ -1845,21 +1843,21 @@ function SEND_RAW_REQUEST ($host, $request) {
} // END - if
// Do we use proxy?
- if ($useProxy) {
+ if ($useProxy === true) {
// Generate CONNECT request header
- $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
- $proxyTunnel .= "Host: ".$host."\r\n";
+ $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
+ $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
// Use login data to proxy? (username at least!)
- if (getConfig('proxy_username') != "") {
+ if (getConfig('proxy_username') != '') {
// Add it as well
- $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
- $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
+ $encodedAuth = base64_encode(compileRawCode(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . compileRawCode(getConfig('proxy_password')));
+ $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
} // END - if
// Add last new-line
- $proxyTunnel .= "\r\n";
- //* DEBUG: */ print("
proxyTunnel= ".$proxyTunnel." ");
+ $proxyTunnel .= getConfig('HTTP_EOL');
+ //* DEBUG: */ print("
proxyTunnel= " . $proxyTunnel." ");
// Write request
fputs($fp, $proxyTunnel);
@@ -1872,8 +1870,8 @@ function SEND_RAW_REQUEST ($host, $request) {
// Read the first line
$resp = trim(fgets($fp, 10240));
- $respArray = explode(" ", $resp);
- if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
+ $respArray = explode(' ', $resp);
+ if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
// Invalid response!
return $response;
} // END - if
@@ -1909,16 +1907,16 @@ function SEND_RAW_REQUEST ($host, $request) {
//* DEBUG: */ print("
Response: ".print_r($response, true)." ");
// Proxy agent found?
- if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
+ if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
// Proxy header detected, so remove two lines
array_shift($response);
array_shift($response);
} // END - if
// Was the request successfull?
- if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
+ if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
// Not found / access forbidden
- $response = array("", "", "");
+ $response = array('', '', '');
} // END - if
// Return response
@@ -1926,109 +1924,108 @@ function SEND_RAW_REQUEST ($host, $request) {
}
// Taken from www.php.net eregi() user comments
-function VALIDATE_EMAIL ($email) {
- // Compile email
- $email = COMPILE_CODE($email);
-
+function isEmailValid ($email) {
// Check first part of email address
- $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
+ $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
// Check domain
- $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
+ $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
// Generate pattern
- $regex = "^".$first."@".$domain."$";
+ $regex = '@^' . $first . '\@' . $domain . '$@iU';
// Return check result
- return eregi($regex, $email);
+ return preg_match($regex, $email);
}
// Function taken from user comments on www.php.net / function eregi()
-function VALIDATE_URL ($URL, $compile=true) {
+function isUrlValid ($URL, $compile=true) {
// Trim URL a little
$URL = trim(urldecode($URL));
- //* DEBUG: */ echo $URL."
";
+ //* DEBUG: */ outputHtml($URL.'
');
// Compile some chars out...
- if ($compile) $URL = compileUriCode($URL, false, false, false);
- //* DEBUG: */ echo $URL."
";
+ if ($compile === true) $URL = compileUriCode($URL, false, false, false);
+ //* DEBUG: */ outputHtml($URL.'
');
// Check for the extension filter
- if (EXT_IS_ACTIVE("filter")) {
+ if (isExtensionActive('filter')) {
// Use the extension's filter set
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 isUrlValid($URL);
+ return isUrlValidSimple($URL);
}
// Generate a list of administrative links to a given userid
-function MEMBER_ACTION_LINKS ($uid, $status = "") {
+function generateMemberAdminActionLinks ($userid, $status = '') {
+ // Make sure userid is a number
+ if ($userid != bigintval($userid)) debug_report_bug('userid is not a number!');
+
// Define all main targets
- $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
+ $targetArray = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
// Begin of navigation links
- $eval = "\$OUT = \"[ ";
+ $OUT = "[ ";
- foreach ($TARGETS as $tar) {
- $eval .= "
\n";
- if (($tar == "lock_user") && ($status == "LOCKED")) {
+ foreach ($targetArray as $tar) {
+ $OUT .= " ");
+ if (($tar == 'lock_user') && ($status == 'LOCKED')) {
// Locked accounts shall be unlocked
- $eval .= "UNLOCK_USER";
+ $OUT .= 'UNLOCK_USER';
} else {
// All other status is fine
- $eval .= strtoupper($tar);
+ $OUT .= strtoupper($tar);
}
- $eval .= "_TITLE--}\\\">{--ADMIN_";
- if (($tar == "lock_user") && ($status == "LOCKED")) {
+ $OUT .= "_TITLE--}\">{--ADMIN_";
+ if (($tar == 'lock_user') && ($status == 'LOCKED')) {
// Locked accounts shall be unlocked
- $eval .= "UNLOCK_USER";
+ $OUT .= 'UNLOCK_USER';
} else {
// All other status is fine
- $eval .= strtoupper($tar);
+ $OUT .= strtoupper($tar);
}
- $eval .= "--} | ";
+ $OUT .= "--} | ";
}
// Finish navigation link
- $eval = substr($eval, 0, -7)."]\";";
- eval($eval);
+ $OUT = substr($OUT, 0, -7) . ']';
// Return string
return $OUT;
}
// Generate an email link
-function CREATE_EMAIL_LINK ($email, $table = "admins") {
+function generateEmailLink ($email, $table = 'admins') {
// Default email link (INSECURE! Spammer can read this by harvester programs)
- $EMAIL = "mailto:".$email;
+ $EMAIL = 'mailto:' . $email;
// Check for several extensions
- if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
+ if ((isExtensionActive('admins')) && ($table == 'admins')) {
// Create email link for contacting admin in guest area
- $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
- } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
+ $EMAIL = generateAdminEmailLink($email);
+ } elseif ((isExtensionActive('user')) && (getExtensionVersion('user') >= '0.3.3') && ($table == 'user_data')) {
// Create email link for contacting a member within admin area (or later in other areas, too?)
- $EMAIL = USER_CREATE_EMAIL_LINK($email);
- } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
+ $EMAIL = generateUserEmailLink($email, 'admin');
+ } elseif ((isExtensionActive('sponsor')) && ($table == 'sponsor_data')) {
// Create email link to contact sponsor within admin area (or like the link above?)
- $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
+ $EMAIL = generateSponsorEmailLink($email, 'sponsor_data');
}
// Shall I close the link when there is no admin?
- if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
+ if ((!isAdmin()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
// Return email link
return $EMAIL;
}
// Generate a hash for extra-security for all passwords
-function generateHash ($plainText, $salt = "") {
- // Is the required extension "sql_patches" there and a salt is not given?
- if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
+function generateHash ($plainText, $salt = '') {
+ // Is the required extension 'sql_patches' there and a salt is not given?
+ if (((isExtensionInstalledAndOlder('sql_patches', '0.3.6')) || (!isExtensionActive('sql_patches')) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) && (empty($salt))) {
// Extension sql_patches is missing/outdated so we hash the plain text with MD5
return md5($plainText);
} // END - if
@@ -2036,48 +2033,55 @@ function generateHash ($plainText, $salt = "") {
// Do we miss an arry element here?
if (!isConfigEntrySet('file_hash')) {
// Stop here
- debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
+ debug_report_bug('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
- $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
+ // Build server string (inc/databases.php is no longer updated with every commit)
+ $server = $_SERVER['PHP_SELF'] . getConfig('ENCRYPT_SEPERATOR') . detectUserAgent() . getConfig('ENCRYPT_SEPERATOR') . getenv('SERVER_SOFTWARE') . getConfig('ENCRYPT_SEPERATOR') . detectRemoteAddr();
// Build key string
- $keys = constant('SITE_KEY').":".constant('DATE_KEY').":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).":".getConfig('master_salt');
+ $keys = getConfig('SITE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . getConfig('secret_key') . getConfig('ENCRYPT_SEPERATOR') . getConfig('file_hash') . getConfig('ENCRYPT_SEPERATOR') . date('d-m-Y (l-F-T)', getConfig('patch_ctime')) . getConfig('ENCRYPT_SEPERATOR') . getConfig('master_salt');
// Additional data
- $data = $plainText.":".uniqid(mt_rand(), true).":".time();
+ $data = $plainText . getConfig('ENCRYPT_SEPERATOR') . uniqid(mt_rand(), true) . getConfig('ENCRYPT_SEPERATOR') . time();
// Calculate number for generating the code
- $a = time() + constant('_ADD') - 1;
+ $a = time() + getConfig('_ADD') - 1;
// Generate SHA1 sum from modula of number and the prime number
- $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
- //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")
";
+ $sha1 = sha1(($a % getConfig('_PRIME')) . $server . getConfig('ENCRYPT_SEPERATOR') . $keys . getConfig('ENCRYPT_SEPERATOR') . $data . getConfig('ENCRYPT_SEPERATOR') . getConfig('DATE_KEY') . getConfig('ENCRYPT_SEPERATOR') . $a);
+ //* DEBUG: */ outputHtml("SHA1=" . $sha1." (".strlen($sha1).")
");
$sha1 = scrambleString($sha1);
- //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")
";
+ //* DEBUG: */ outputHtml("Scrambled=" . $sha1." (".strlen($sha1).")
");
//* DEBUG: */ $sha1b = descrambleString($sha1);
- //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")
";
+ //* DEBUG: */ outputHtml("Descrambled=" . $sha1b." (".strlen($sha1b).")
");
// Generate the password salt string
$salt = substr($sha1, 0, getConfig('salt_length'));
- //* DEBUG: */ echo $salt." (".strlen($salt).")
";
+ //* DEBUG: */ outputHtml($salt." (".strlen($salt).")
");
} else {
// Use given salt
+ //* DEBUG: */ print 'salt=' . $salt . '
';
$salt = substr($salt, 0, getConfig('salt_length'));
- //* DEBUG: */ echo "GIVEN={$salt}
\n";
+ //* DEBUG: */ print 'salt=' . $salt . '(' . strlen($salt) . '/' . getConfig('salt_length') . ')
';
+
+ // Sanity check on salt
+ if (strlen($salt) != getConfig('salt_length')) {
+ // Not the same!
+ debug_report_bug(__FUNCTION__.': salt length mismatch! ('.strlen($salt).'/'.getConfig('salt_length').')');
+ } // END - if
}
// Return hash
- return $salt.sha1($salt.$plainText);
+ return $salt.sha1($salt . $plainText);
}
// Scramble a string
function scrambleString($str) {
// Init
- $scrambled = "";
+ $scrambled = '';
// Final check, in case of failture it will return unscrambled string
if (strlen($str) > 40) {
@@ -2085,15 +2089,15 @@ function scrambleString($str) {
return $str;
} elseif (strlen($str) == 40) {
// From database
- $scrambleNums = explode(":", getConfig('pass_scramble'));
+ $scrambleNums = explode(':', getConfig('pass_scramble'));
} else {
// Generate new numbers
- $scrambleNums = explode(":", genScrambleString(strlen($str)));
+ $scrambleNums = explode(':', genScrambleString(strlen($str)));
}
// Scramble string here
- //* DEBUG: */ echo "***Original=".$str."***
";
- for ($idx = 0; $idx < strlen($str); $idx++) {
+ //* DEBUG: */ outputHtml("***Original=" . $str."***
");
+ for ($idx = '0'; $idx < strlen($str); $idx++) {
// Get char on scrambled position
$char = substr($str, $scrambleNums[$idx], 1);
@@ -2102,7 +2106,7 @@ function scrambleString($str) {
} // END - for
// Return scrambled string
- //* DEBUG: */ echo "***Scrambled=".$scrambled."***
";
+ //* DEBUG: */ outputHtml("***Scrambled=" . $scrambled."***
");
return $scrambled;
}
@@ -2112,21 +2116,21 @@ function descrambleString($str) {
if (strlen($str) != 40) return $str;
// Load numbers from config
- $scrambleNums = explode(":", getConfig('pass_scramble'));
+ $scrambleNums = explode(':', getConfig('pass_scramble'));
// Validate numbers
if (count($scrambleNums) != 40) return $str;
// Begin descrambling
- $orig = str_repeat(" ", 40);
- //* DEBUG: */ echo "+++Scrambled=".$str."+++
";
- for ($idx = 0; $idx < 40; $idx++) {
+ $orig = str_repeat(' ', 40);
+ //* DEBUG: */ outputHtml("+++Scrambled=" . $str."+++
");
+ for ($idx = '0'; $idx < 40; $idx++) {
$char = substr($str, $idx, 1);
$orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
} // END - for
// Return scrambled string
- //* DEBUG: */ echo "+++Original=".$orig."+++
";
+ //* DEBUG: */ outputHtml("+++Original=" . $orig."+++
");
return $orig;
}
@@ -2136,7 +2140,7 @@ function genScrambleString ($len) {
$scrambleNumbers = array();
// First we need to setup randomized numbers from 0 to 31
- for ($idx = 0; $idx < $len; $idx++) {
+ for ($idx = '0'; $idx < $len; $idx++) {
// Generate number
$rand = mt_rand(0, ($len -1));
@@ -2150,68 +2154,44 @@ function genScrambleString ($len) {
} // END - for
// So let's create the string for storing it in database
- $scrambleString = implode(":", $scrambleNumbers);
+ $scrambleString = implode(':', $scrambleNumbers);
return $scrambleString;
}
-// Append data like session ID or referal ID to the given URL which would
-// normally be stored in cookies
-function ADD_URL_DATA ($URL) {
- // Init add
- $add = "";
-
- // Determine URL binder
- $BIND = "?";
- if (strpos($URL, "?") !== false) $BIND = "&";
-
- if ((!defined('__COOKIES')) || ((!__COOKIES))) {
- // Cookies are not accepted
- if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
- // Cookie found in URL
- $add .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
- } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
- // Not found! So let's set default here
- $add .= $BIND."refid=".getConfig('def_refid');
- }
- } // END - if
-
- // Add all together and return it
- return $URL . $add;
-}
-
// Generate an PGP-like encrypted hash of given hash for e.g. cookies
function generatePassString ($passHash) {
// Return vanilla password hash
$ret = $passHash;
// Is a secret key and master salt already initialized?
- if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
+ if ((isExtensionInstalled('sql_patches')) && (isExtensionInstalledAndNewer('other', '0.2.5')) && (isConfigEntrySet('_PRIME')) && (isConfigEntrySet('secret_key')) && (isConfigEntrySet('master_salt'))) {
// Only calculate when the secret key is generated
- $newHash = ""; $start = 9;
- for ($idx = 0; $idx < 10; $idx++) {
+ $newHash = ''; $start = 9;
+ for ($idx = '0'; $idx < 10; $idx++) {
$part1 = hexdec(substr($passHash, $start, 4));
$part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
$mod = dechex($idx);
if ($part1 > $part2) {
- $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
+ $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
} elseif ($part2 > $part1) {
- $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
+ $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
}
- $mod = substr(round($mod), 0, 4);
- $mod = str_repeat('0', 4-strlen($mod)).$mod;
- //* DEBUG: */ echo "*".$start."=".$mod."*
";
+ $mod = substr($mod, 0, 4);
+ //* DEBUG: */ outputHtml('part1='.$part1.'/part2='.$part2.'/mod=' . $mod . '('.strlen($mod).')
');
+ $mod = str_repeat(0, (4 - strlen($mod))) . $mod;
+ //* DEBUG: */ outputHtml('*' . $start . '=' . $mod . '*
');
$start += 4;
$newHash .= $mod;
} // END - for
- //* DEBUG: */ print($passHash."
".$newHash." (".strlen($newHash).")");
+ //* DEBUG: */ print($passHash.'
' . $newHash." (".strlen($newHash).')
');
$ret = generateHash($newHash, getConfig('master_salt'));
- //* DEBUG: */ print($ret."
\n");
+ //* DEBUG: */ print('ret='.$ret.'
');
} else {
// Hash it simple
- //* DEBUG: */ echo "--".$passHash."--
\n";
+ //* DEBUG: */ outputHtml("--" . $passHash."--
");
$ret = md5($passHash);
- //* DEBUG: */ echo "++".$ret."++
\n";
+ //* DEBUG: */ outputHtml("++" . $ret."++
");
}
// Return result
@@ -2219,39 +2199,48 @@ function generatePassString ($passHash) {
}
// Fix "deleted" cookies
-function FIX_DELETED_COOKIES ($cookies) {
+function fixDeletedCookies ($cookies) {
// Is this an array with entries?
if ((is_array($cookies)) && (count($cookies) > 0)) {
// Then check all cookies if they are marked as deleted!
foreach ($cookies as $cookieName) {
// Is the cookie set to "deleted"?
- if (get_session($cookieName) == "deleted") {
- set_session($cookieName, "");
- }
+ if (getSession($cookieName) == 'deleted') {
+ setSession($cookieName, '');
+ } // END - if
} // END - foreach
} // END - if
}
// Output error messages in a fasioned way and die...
-function app_die ($F, $L, $msg) {
- // Load header
- LOAD_INC_ONCE("inc/header.php");
+function app_die ($F, $L, $message) {
+ // Check if Script is already dieing and not let it kill itself another 1000 times
+ if (!isset($GLOBALS['app_died'])) {
+ // Make sure, that the script realy realy diese here and now
+ $GLOBALS['app_died'] = true;
- // Prepare message for output
- $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
+ // Load header
+ loadIncludeOnce('inc/header.php');
- // Load the message template
- LOAD_TEMPLATE("admin_settings_saved", false, $msg);
+ // Rewrite message for output
+ $message = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $message);
- // Load footer
- LOAD_INC_ONCE("inc/footer.php");
+ // Better log this message away
+ logDebugMessage($F, $L, $message);
- // Exit explicitly
- shutdown();
+ // Load the message template
+ loadTemplate('admin_settings_saved', false, $message);
+
+ // Load footer
+ loadIncludeOnce('inc/footer.php');
+ } else {
+ // Script tried to kill itself twice
+ debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $message . ', file/function=' . $F . ', line=' . $L);
+ }
}
// Display parsing time and number of SQL queries in footer
-function DISPLAY_PARSING_TIME_FOOTER() {
+function displayParsingTime() {
// Is the timer started?
if (!isset($GLOBALS['startTime'])) {
// Abort here
@@ -2262,21 +2251,19 @@ function DISPLAY_PARSING_TIME_FOOTER() {
$endTime = microtime(true);
// "Explode" both times
- $start = explode(" ", $GLOBALS['startTime']);
- $end = explode(" ", $endTime);
+ $start = explode(' ', $GLOBALS['startTime']);
+ $end = explode(' ', $endTime);
$runTime = $end[0] - $start[0];
- if ($runTime < 0) $runTime = 0;
- $runTime = TRANSLATE_COMMA($runTime);
+ if ($runTime < 0) $runTime = '0';
// Prepare output
$content = array(
- 'runtime' => $runTime,
- 'numSQLs' => (getConfig('sql_count') + 1),
- 'numTemplates' => (getConfig('num_templates') + 1)
+ 'runtime' => translateComma($runTime),
+ 'timeSQLs' => translateComma(getConfig('sql_time') * 1000),
);
// Load the template
- LOAD_TEMPLATE("show_timings", false, $content);
+ loadTemplate('show_timings', false, $content);
}
// Check wether a boolean constant is set
@@ -2288,14 +2275,14 @@ function isBooleanConstantAndTrue ($constName) { // : Boolean
// In cache?
if (isset($GLOBALS['cache_array']['const'][$constName])) {
// Use cache
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ): ".$constName."-CACHE!
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ): " . $constName."-CACHE!
");
$res = ($GLOBALS['cache_array']['const'][$constName] === true);
} else {
// Check constant
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ): ".$constName."-RESOLVE!
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ): " . $constName."-RESOLVE!
");
if (defined($constName)) {
// Found!
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ): ".$constName."-FOUND!
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ): " . $constName."-FOUND!
");
$res = (constant($constName) === true);
} // END - if
@@ -2309,97 +2296,72 @@ function isBooleanConstantAndTrue ($constName) { // : Boolean
}
// Checks if a given apache module is loaded
-function IF_APACHE_MODULE_LOADED ($apacheModule) {
+function isApacheModuleLoaded ($apacheModule) {
// Check it and return result
return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
}
-// "Getter" for language strings
-// @TODO Rewrite all language constants to this function.
-function getMessage ($messageId) {
- // Default is not found!
- $return = "!".$messageId."!";
-
- // Is the language string found?
- if (isset($GLOBALS['msg'][strtolower($messageId)])) {
- // Language array element found in small_letters
- $return = $GLOBALS['msg'][$messageId];
- } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
- // @DEPRECATED Language array element found in BIG_LETTERS
- $return = $GLOBALS['msg'][$messageId];
- } elseif (defined($messageId)) {
- // @DEPRECATED Deprecated constant found
- $return = constant($messageId);
- } else {
- // Missing language constant
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
- }
-
- // Return the string
- return $return;
-}
-
// Get current theme name
-function GET_CURR_THEME() {
+function getCurrentTheme () {
// The default theme is 'default'... ;-)
- $ret = "default";
+ $ret = 'default';
// Load default theme if not empty from configuration
- if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
+ if ((isConfigEntrySet('default_theme')) && (getConfig('default_theme') != '')) $ret = getConfig('default_theme');
if (!isSessionVariableSet('mxchange_theme')) {
// Set default theme
- set_session('mxchange_theme', $ret);
- } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
+ setTheme($ret);
+ } elseif ((isSessionVariableSet('mxchange_theme')) && (isExtensionInstalledAndNewer('sql_patches', '0.1.4'))) {
//die("
".print_r($GLOBALS['cache_array']['themes'], true)." ");
// Get theme from cookie
- $ret = get_session('mxchange_theme');
+ $ret = getSession('mxchange_theme');
// Is it valid?
- if (THEME_GET_ID($ret) == 0) {
+ if (getThemeId($ret) == '0') {
// Fix it to default
- $ret = "default";
+ $ret = 'default';
} // END - if
- } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
+ } elseif ((!isInstalled()) && ((isInstalling()) || (getOutputMode() == true)) && ((isGetRequestElementSet('theme')) || (isPostRequestElementSet('theme')))) {
// Prepare FQFN for checking
- $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
+ $theme = sprintf("%stheme/%s/theme.php", getConfig('PATH'), getRequestElement('theme'));
// Installation mode active
- if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
+ if ((isGetRequestElementSet('theme')) && (isFileReadable($theme))) {
// Set cookie from URL data
- set_session('mxchange_theme', REQUEST_GET(('theme')));
- } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
+ setTheme(getRequestElement('theme'));
+ } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", getConfig('PATH'), SQL_ESCAPE(postRequestElement('theme'))))) {
// Set cookie from posted data
- set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
+ setTheme(SQL_ESCAPE(postRequestElement('theme')));
}
// Set return value
- $ret = get_session('mxchange_theme');
+ $ret = getSession('mxchange_theme');
} else {
// Invalid design, reset cookie
- set_session('mxchange_theme', $ret);
+ setTheme($ret);
}
- // Add (maybe) found theme.php file to inclusion list
- $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
-
- // Try to load the requested include file
- if (INCLUDE_READABLE($INC)) ADD_INC_TO_POOL($INC);
-
// Return theme value
return $ret;
}
+// Setter for theme in session
+function setTheme ($newTheme) {
+ setSession('mxchange_theme', $newTheme);
+}
+
// Get id from theme
-function THEME_GET_ID ($name) {
- // Is the extension "theme" installed?
- if (!EXT_IS_ACTIVE("theme")) {
+// @TODO Try to move this to inc/libs/theme_functions.php
+function getThemeId ($name) {
+ // Is the extension 'theme' installed?
+ if (!isExtensionActive('theme')) {
// Then abort here
return 0;
} // END - if
// Default id
- $id = 0;
+ $id = '0';
// Is the cache entry there?
if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
@@ -2407,10 +2369,10 @@ function THEME_GET_ID ($name) {
$id = $GLOBALS['cache_array']['themes']['id'][$name];
// Count up
- incrementConfigEntry('cache_hits');
- } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
+ incrementStatsEntry('cache_hits');
+ } elseif (getExtensionVersion('cache') != '0.1.8') {
// Check if current theme is already imported or not
- $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
+ $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_themes` WHERE `theme_path`='%s' LIMIT 1",
array($name), __FUNCTION__, __LINE__);
// Entry found?
@@ -2427,120 +2389,63 @@ function THEME_GET_ID ($name) {
return $id;
}
-// Read a given file
-function READ_FILE ($FQFN, $sqlPrepare = false) {
- // Load the file
- if (function_exists('file_get_contents')) {
- // Use new function
- $content = file_get_contents($FQFN);
- } else {
- // Fall-back to implode-file chain
- $content = implode("", file($FQFN));
- }
-
- // Prepare SQL queries?
- if ($sqlPrepare === true) {
- // Remove some unwanted chars
- $content = str_replace("\r", "", $content);
- $content = str_replace("\n\n", "\n", $content);
- } // END - if
-
- // Return the content
- return $content;
-}
-
-// Writes content to a file
-function WRITE_FILE ($FQFN, $content) {
- // Is the file writeable?
- if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
- // Not writeable!
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
-
- // Failed! :(
- return false;
+// Generates an error code from given account status
+function generateErrorCodeFromUserStatus ($status='') {
+ // If no status is provided, use the default, cached
+ if ((empty($status)) && (isMember())) {
+ // Get user status
+ $status = getUserData('status');
} // END - if
- // By default all is failed...
- $return = false;
-
- // Is the function there?
- if (function_exists('file_put_contents')) {
- // Write it directly
- $return = file_put_contents($FQFN, $content);
- } else {
- // Write it with fopen
- $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN)."!");
- fwrite($fp, $content);
- fclose($fp);
-
- // Set CHMOD rights
- $return = chmod($FQFN, 0644);
- }
-
- // Return status
- return $return;
-}
-
-// Generates an error code from given account status
-function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
// Default error code if unknown account status
$errorCode = getCode('UNKNOWN_STATUS');
// Generate constant name
- $constantName = sprintf("ID_%s", $status);
+ $codeName = sprintf("ID_%s", $status);
// Is the constant there?
- if (isCodeSet($constantName)) {
+ if (isCodeSet($codeName)) {
// Then get it!
- $errorCode = getCode($constantName);
+ $errorCode = getCode($codeName);
} else {
// Unknown status
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
}
// Return error code
return $errorCode;
}
-// Clears the output buffer. This function does *NOT* backup sent content.
-function clearOutputBuffer () {
- // Trigger an error on failure
- if (!ob_end_clean()) {
- // Failed!
- debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
- } // END - if
-}
-
// Function to search for the last modifified file
function searchDirsRecursive ($dir, &$last_changed) {
// Get dir as array
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ):dir=".$dir."
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ):dir=" . $dir.'
');
// Does it match what we are looking for? (We skip a lot files already!)
- // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
- $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
- $ds = GET_DIR_AS_ARRAY($dir, "", true, false, $excludePattern);
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ):ds[]=".count($ds)."
\n";
+ // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
+ $excludePattern = '@(\.revision|debug\.log|\.cache|config\.php)$@';
+ $ds = getArrayFromDirectory($dir, '', true, false, array(), '.php', $excludePattern);
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ):ds[]=".count($ds).'
');
// Walk through all entries
foreach ($ds as $d) {
// Generate proper FQFN
- $FQFN = str_replace("//", "/", constant('PATH') . $dir. "/". $d);
+ $FQFN = str_replace('//', '/', getConfig('PATH') . $dir. '/'. $d);
// Is it a file and readable?
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ):FQFN={$FQFN}
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ):FQFN={$FQFN}
");
if (isDirectory($FQFN)) {
- // $FQFN is a directory so also crawl into this directory
+ // $FQFN is a directory so also crawl into this directory
$newDir = $d;
- if (!empty($dir)) $newDir = $dir . "/". $d;
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ):DESCENT: ".$newDir."
\n";
+ if (!empty($dir)) $newDir = $dir . '/'. $d;
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ):DESCENT: " . $newDir.'
');
searchDirsRecursive($newDir, $last_changed);
- } elseif (FILE_READABLE($FQFN)) {
+ } elseif (isFileReadable($FQFN)) {
// $FQFN is a filename and no directory
$time = filemtime($FQFN);
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ):File: ".$d." found. (".($last_changed['time'] - $time).")
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ):File: " . $d." found. (".($last_changed['time'] - $time).")
");
if ($last_changed['time'] < $time) {
// This file is newer as the file before
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ) - NEWER!
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ) - NEWER!
");
$last_changed['path_name'] = $FQFN;
$last_changed['time'] = $time;
} // END - if
@@ -2553,55 +2458,44 @@ function getActualVersion ($type = 'Revision') {
// By default nothing is new... ;-)
$new = false;
- if (EXT_IS_ACTIVE("cache")) {
- // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
- if (isset($_GET['check_revision_data']) && $_GET['check_revision_data'] == 'yes') $new = true;
- if (!isset($GLOBALS['cache_array']['revision'][$type])
- || count($GLOBALS['cache_array']['revision']) < 3
- || !$GLOBALS['cache_instance']->loadCacheFile("revision")) $new = true;
-
- // Is the cache file outdated/invalid?
- if ($new === true){
- $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
-
- // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
- unset($GLOBALS['cache_array']['revision']);
-
- // Reload load_cach-revison.php
- LOAD_INC("inc/loader/load_cache-revision.php");
- } // END - if
+ // Is the cache entry there?
+ if (isset($GLOBALS['cache_array']['revision'][$type])) {
+ // Found so increase cache hit
+ incrementStatsEntry('cache_hits');
- // Return found value
+ // Return it
return $GLOBALS['cache_array']['revision'][$type][0];
-
} else {
- // Old Version without ext-cache active (deprecated ?)
-
// FQFN of revision file
- $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
+ $FQFN = sprintf("%s/.revision", getConfig('CACHE_PATH'));
- // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
- if ((isset($_GET['check_revision_data'])) && ($_GET['check_revision_data'] == 'yes')) {
- // Has changed!
+ // Check if 'check_revision_data' is setted (switch for manually rewrite the .revision-File)
+ if ((isGetRequestElementSet('check_revision_data')) && (getRequestElement('check_revision_data') == 'yes')) {
+ // Forced rebuild of .revision file
$new = true;
} else {
// Check for revision file
- if (!FILE_READABLE($FQFN)) {
+ if (!isFileReadable($FQFN)) {
// Not found, so we need to create it
$new = true;
} else {
// Revision file found
- $ins_vers = explode("\n", READ_FILE($FQFN));
+ $ins_vers = explode("\n", readFromFile($FQFN));
// Get array for mapping information
$mapper = array_flip(getSearchFor());
- //* DEBUG: */ print("
".print_r($mapper, true).print_r($ins_vers, true)." ");
+ //* DEBUG: */ print('
mapper='.print_r($mapper, true).' ins_vers=
'.print_r($ins_vers, true).' ');
// Is the content valid?
- if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == "") || ($ins_vers[0]) == "new") {
+ if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == 'new') {
// File needs update!
$new = true;
} else {
+ // Generate fake cache entry
+ foreach ($mapper as $map=>$idx) {
+ $GLOBALS['cache_array']['revision'][$map][0] = $ins_vers[$idx];
+ } // END - foreach
+
// Return found value
return trim($ins_vers[$mapper[$type]]);
}
@@ -2610,110 +2504,93 @@ function getActualVersion ($type = 'Revision') {
// Has it been updated?
if ($new === true) {
- WRITE_FILE($FQFN, implode("\n", getAkt_vers()));
+ // Write it
+ writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
+
+ // ... and call recursive
+ return getActualVersion($type);
} // END - if
}
}
// Repares an array we are looking for
-// The returned Array is needed twice (in getAkt_vers() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
+// The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
function getSearchFor () {
// Add Revision, Date, Tag and Author
- $searchFor = array('Revision', 'Date', 'Tag', 'Author');
+ $searchFor = array('Revision', 'Date', 'Tag', 'Author', 'File');
// Return the created array
return $searchFor;
}
-function getAkt_vers () {
+// @TODO Please describe this function
+function getArrayFromActualVersion () {
// Init variables
- $next_dir = ""; // Directory to start with search
+ $next_dir = '';
+
+ // Directory to start with search
$last_changed = array(
- 'path_name' => "",
+ 'path_name' => '',
'time' => 0
);
- $akt_vers = array(); // Init return array
- $res = 0; // Init value for counting the founded keywords
+
+ // Init return array
+ $akt_vers = array();
+
+ // Init value for counting the founded keywords
+ $res = '0';
// Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
// Get file
- $last_file = READ_FILE($last_changed['path_name']);
+ $last_file = readFromFile($last_changed['path_name']);
// Get all the keywords to search for
$searchFor = getSearchFor();
// This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
foreach ($searchFor as $search) {
- //Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
- $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
- // This trimms the search-result and puts it in the $akt_vers-return array
- if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
+ // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
+ $res += preg_match('@\$' . $search.'(:|::) (.*) \$@U', $last_file, $t);
+ // This trimms the search-result and puts it in the $GLOBALS['cache_array']['revision']-return array
+ if (isset($t[2])) $GLOBALS['cache_array']['revision'][$search] = trim($t[2]);
} // END - foreach
// Save the last-changed filename for debugging
- $akt_vers['File'] = $last_changed['path_name'];
+ $GLOBALS['cache_array']['revision']['File'] = $last_changed['path_name'];
// at least 3 keyword-Tags are needed for propper values
if ($res && $res >= 3
- && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
- && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
- && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
+ && isset($GLOBALS['cache_array']['revision']['Revision']) && $GLOBALS['cache_array']['revision']['Revision'] != ''
+ && isset($GLOBALS['cache_array']['revision']['Date']) && $GLOBALS['cache_array']['revision']['Date'] != ''
+ && isset($GLOBALS['cache_array']['revision']['Tag']) && $GLOBALS['cache_array']['revision']['Tag'] != '') {
// Prepare content witch need special treadment
// Prepare timestamp for date
- preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
- $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
+ preg_match('@(....)-(..)-(..) (..):(..):(..)@', $GLOBALS['cache_array']['revision']['Date'], $match_d);
+ $GLOBALS['cache_array']['revision']['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
// Add author to the Tag if the author is set and is not quix0r (lead coder)
- if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
- $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
+ if ((isset($GLOBALS['cache_array']['revision']['Author'])) && ($GLOBALS['cache_array']['revision']['Author'] != 'quix0r')) {
+ $GLOBALS['cache_array']['revision']['Tag'] .= '-'.strtoupper($GLOBALS['cache_array']['revision']['Author']);
} // END - if
} else {
// No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
- $version = GET_URL("check-updates3.php");
+ $version = sendGetRequest('check-updates3.php');
// Prepare content
// Only sets not setted or not proper values to the Online-Server-Fallback-Solution
- if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
- if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
- if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
- if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
+ if (!isset($GLOBALS['cache_array']['revision']['Revision']) || $GLOBALS['cache_array']['revision']['Revision'] == '') $GLOBALS['cache_array']['revision']['Revision'] = trim($version[10]);
+ if (!isset($GLOBALS['cache_array']['revision']['Date']) || $GLOBALS['cache_array']['revision']['Date'] == '') $GLOBALS['cache_array']['revision']['Date'] = trim($version[9]);
+ if (!isset($GLOBALS['cache_array']['revision']['Tag']) || $GLOBALS['cache_array']['revision']['Tag'] == '') $GLOBALS['cache_array']['revision']['Tag'] = trim($version[8]);
+ if (!isset($GLOBALS['cache_array']['revision']['Author']) || $GLOBALS['cache_array']['revision']['Author'] == '') $GLOBALS['cache_array']['revision']['Author'] = 'quix0r';
+ if (!isset($GLOBALS['cache_array']['revision']['File']) || $GLOBALS['cache_array']['revision']['File'] == '') $GLOBALS['cache_array']['revision']['File'] = trim($version[11]);
}
// Return prepared array
- return $akt_vers;
-}
-
-
-// Loads an include file and logs any missing files for debug purposes
-function LOAD_INC ($INC) {
- // Add the path. This is why we need a trailing slash in config.php
- $FQFN = constant('PATH') . $INC;
-
- // Is the include file there?
- if (!INCLUDE_READABLE($INC)) {
- // Not there so log it
- debug_report_bug(sprintf("Include file %s not found.", $INC));
- return false;
- } // END - if
-
- // Try to load it
- require($FQFN);
-}
-
-// Loads an include file once
-function LOAD_INC_ONCE ($INC) {
- // Is it not loaded?
- if (!isset($GLOBALS['load_once'][$INC])) {
- // Then try to load it
- LOAD_INC($INC);
-
- // And mark it as loaded
- $GLOBALS['load_once'][$INC] = "loaded";
- } // END - if
+ return $GLOBALS['cache_array']['revision'];
}
// Back-ported from the new ship-simu engine. :-)
@@ -2727,7 +2604,7 @@ function debug_get_printable_backtrace () {
if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
if (!isset($trace['line'])) $trace['line'] = __LINE__;
if (!isset($trace['args'])) $trace['args'] = array();
- $backtrace .= "
".basename($trace['file'])." :".$trace['line'].", ".$trace['function']."(".count($trace['args']).") \n";
+ $backtrace .= "
".basename($trace['file'])." :" . $trace['line'].", " . $trace['function'].'('.count($trace['args']).") \n";
} // END - foreach
// Close it
@@ -2738,9 +2615,21 @@ function debug_get_printable_backtrace () {
}
// Output a debug backtrace to the user
-function debug_report_bug ($message = "") {
+function debug_report_bug ($message = '') {
+ // Is this already called?
+ if (isset($GLOBALS[__FUNCTION__])) {
+ // Other backtrace
+ print 'Message:'.$message.'
Backtrace:
';
+ debug_print_backtrace();
+ die(' ');
+ } // END - if
+
+ // Set this function as called
+ $GLOBALS[__FUNCTION__] = true;
+
// Init message
- $debug = "";
+ $debug = '';
+
// Is the optional message set?
if (!empty($message)) {
// Use and log it
@@ -2749,13 +2638,13 @@ function debug_report_bug ($message = "") {
);
// @TODO Add a little more infos here
- DEBUG_LOG(__FUNCTION__, __LINE__, $message);
+ logDebugMessage(__FUNCTION__, __LINE__, strip_tags($message));
} // END - if
// Add output
- $debug .= "Please report this bug at
bugs.mxchange.org :
";
+ $debug .= "Please report this bug at bugs.mxchange.org and include the logfile from " . getConfig('CACHE_PATH') . "debug.log in your report (you can now attach files):";
$debug .= debug_get_printable_backtrace();
- $debug .= " Request-URI: ".$_SERVER['REQUEST_URI']." \n";
+ $debug .= " \nRequest-URI: " . getRequestUri()."
\n";
$debug .= "Thank you for finding bugs.";
// And abort here
@@ -2765,135 +2654,117 @@ function debug_report_bug ($message = "") {
// Generates a ***weak*** seed (taken from de.php.net/mt_srand)
function generateSeed () {
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$sec + (float)$usec);
+ list($usec, $sec) = explode(' ', microtime());
+ $microTime = (((float)$sec + (float)$usec)) * 100000;
+ return $microTime;
}
// Converts a message code to a human-readable message
-function convertCodeToMessage ($code) {
- $msg = "";
+function getMessageFromErrorCode ($code) {
+ $message = '';
switch ($code) {
- case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
- case getCode('LOGOUT_FAILED') : $msg = "
{--LOGOUT_FAILED--} "; break;
- case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
- case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
- case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
- case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
- case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
- case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
+ case '': break;
+ case getCode('LOGOUT_DONE') : $message = getMessage('LOGOUT_DONE'); break;
+ case getCode('LOGOUT_FAILED') : $message = "
{--LOGOUT_FAILED--} "; break;
+ case getCode('DATA_INVALID') : $message = getMessage('MAIL_DATA_INVALID'); break;
+ case getCode('POSSIBLE_INVALID') : $message = getMessage('MAIL_POSSIBLE_INVALID'); break;
+ case getCode('ACCOUNT_LOCKED') : $message = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
+ case getCode('USER_404') : $message = getMessage('USER_404'); break;
+ case getCode('STATS_404') : $message = getMessage('MAIL_STATS_404'); break;
+ case getCode('ALREADY_CONFIRMED'): $message = getMessage('MAIL_ALREADY_CONFIRMED'); break;
+ case getCode('WRONG_PASS') : $message = getMessage('LOGIN_WRONG_PASS'); break;
+ case getCode('WRONG_ID') : $message = getMessage('LOGIN_WRONG_ID'); break;
+ case getCode('ID_LOCKED') : $message = getMessage('LOGIN_ID_LOCKED'); break;
+ case getCode('ID_UNCONFIRMED') : $message = getMessage('LOGIN_ID_UNCONFIRMED'); break;
+ case getCode('ID_GUEST') : $message = getMessage('LOGIN_ID_GUEST'); break;
+ case getCode('NO_COOKIES') : $message = getMessage('LOGIN_NO_COOKIES'); break;
+ case getCode('COOKIES_DISABLED') : $message = getMessage('LOGIN_NO_COOKIES'); break;
+ case getCode('BEG_SAME_AS_OWN') : $message = getMessage('BEG_SAME_UID_AS_OWN'); break;
+ case getCode('LOGIN_FAILED') : $message = getMessage('LOGIN_FAILED_GENERAL'); break;
+ case getCode('MODULE_MEM_ONLY') : $message = sprintf(getMessage('MODULE_MEM_ONLY'), getRequestElement('mod')); break;
+ case getCode('OVERLENGTH') : $message = getMessage('MEMBER_TEXT_OVERLENGTH'); break;
+ case getCode('URL_FOUND') : $message = getMessage('MEMBER_TEXT_CONTAINS_URL'); break;
+ case getCode('SUBJ_URL') : $message = getMessage('MEMBER_SUBJ_CONTAINS_URL'); break;
+ case getCode('BLIST_URL') : $message = "{--MEMBER_URL_BLACK_LISTED--}
\n{--MEMBER_BLIST_TIME--}: ".generateDateTime(getRequestElement('blist'), 0); break;
+ case getCode('NO_RECS_LEFT') : $message = getMessage('MEMBER_SELECTED_MORE_RECS'); break;
+ case getCode('INVALID_TAGS') : $message = getMessage('MEMBER_HTML_INVALID_TAGS'); break;
+ case getCode('MORE_POINTS') : $message = getMessage('MEMBER_MORE_POINTS_NEEDED'); break;
+ case getCode('MORE_RECEIVERS1') : $message = getMessage('MEMBER_ENTER_MORE_RECEIVERS'); break;
+ case getCode('MORE_RECEIVERS2') : $message = getMessage('MEMBER_NO_MORE_RECEIVERS_FOUND'); break;
+ case getCode('MORE_RECEIVERS3') : $message = sprintf(getMessage('MEMBER_ENTER_MORE_MIN_RECEIVERS'), getConfig('order_min')); break;
+ case getCode('INVALID_URL') : $message = getMessage('MEMBER_ENTER_INVALID_URL'); break;
case getCode('ERROR_MAILID'):
- if (EXT_IS_ACTIVE($ext, true)) {
- $msg = getMessage('ERROR_CONFIRMING_MAIL');
+ if (isExtensionActive('mailid', true)) {
+ $message = getMessage('ERROR_CONFIRMING_MAIL');
} else {
- $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
+ $message = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
}
break;
case getCode('EXTENSION_PROBLEM'):
- if (REQUEST_ISSET_GET(('ext'))) {
- $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
+ if (isGetRequestElementSet('ext')) {
+ $message = generateExtensionInactiveNotInstalledMessage(getRequestElement('ext'));
} else {
- $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
+ $message = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
}
break;
- case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
- case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
- case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
- case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
-
- default:
- // Missing/invalid code
- $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
-
- // Log it
- DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
- break;
- } // END - switch
-
- // Return the message
- return $msg;
-}
-
-// Checks wether the given extension is currently not installed
-// and redirects if so.
-function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
- // Is the extension uninstalled/inactive?
- if (!EXT_IS_ACTIVE($ext_name)) {
- // Redirect to index
- LOAD_URL("modules.php?module=index&msg=".getCode('EXTENSION_PROBLEM')."&ext=".$ext_name);
- } // END - if
-}
+ case getCode('URL_TLOCK'):
+ $result = SQL_QUERY_ESC("SELECT `timestamp` FROM `{?_MYSQL_PREFIX?}_pool` WHERE `id`=%s LIMIT 1",
+ array(bigintval(getRequestElement('id'))), __FILE__, __LINE__);
-// Generate a "link" for the given admin id (aid)
-function GENERATE_AID_LINK ($aid) {
- // No assigned admin is default
- $admin = "
{--ADMIN_NO_ADMIN_ASSIGNED--} ";
+ // Load timestamp from last order
+ list($timestamp) = SQL_FETCHROW($result);
+ $timestamp = generateDateTime($timestamp, 1);
- // Zero? = Not assigned
- if (bigintval($aid) > 0) {
- // Load admin's login
- $login = GET_ADMIN_LOGIN($aid);
+ // Free memory
+ SQL_FREERESULT($result);
- // Is the login valid?
- if ($login != "***") {
- // Is the extension there?
- if (EXT_IS_ACTIVE("admins")) {
- // Admin found
- $admin = "
".$login." ";
- } else {
- // Extension not found
- $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
- }
- } else {
- // Maybe deleted?
- $admin = "
".sprintf(getMessage('ADMIN_ID_404'), $aid)."
";
- }
- } // END - if
+ // Calculate hours...
+ $STD = round(getConfig('url_tlock') / 60 / 60);
- // Return result
- return $admin;
-}
+ // Minutes...
+ $MIN = round((getConfig('url_tlock') - $STD * 60 * 60) / 60);
-// Checks wether an include file (non-FQFN better) is readable
-function INCLUDE_READABLE ($INC) {
- // Construct FQFN
- $FQFN = constant('PATH') . $INC;
+ // And seconds
+ $SEC = getConfig('url_tlock') - $STD * 60 * 60 - $MIN * 60;
- // Is it readable?
- return FILE_READABLE($FQFN);
-}
+ // Finally contruct the message
+ // @TODO Rewrite this old lost code to a template
+ $message = "{--MEMBER_URL_TIME_LOCK--}
{--CONFIG_URL_TLOCK--} ".$STD."
+ {--_HOURS--}, ".$MIN." {--_MINUTES--} {--_AND--} ".$SEC." {--_SECONDS--}
+ {--MEMBER_LAST_TLOCK--}: ".$timestamp;
+ break;
-// Encode strings
-// @TODO Implement $compress
-function encodeString ($str, $compress=true) {
- $str = urlencode(base64_encode(compileUriCode($str)));
- return $str;
-}
+ default:
+ // Missing/invalid code
+ $message = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
-// Decode strings encoded with encodeString()
-// @TODO Implement $decompress
-function decodeString ($str, $decompress=true) {
- $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
- return $str;
+ // Log it
+ logDebugMessage(__FUNCTION__, __LINE__, $message);
+ break;
+ } // END - switch
+
+ // Return the message
+ return $message;
}
// Compile characters which are allowed in URLs
-function compileUriCode ($code, $simple=true) {
+function compileUriCode ($code, $simple = true) {
// Compile constants
- if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
+ if ($simple === false) $code = str_replace('{--', '".', str_replace('--}', '."', $code));
// Compile QUOT and other non-HTML codes
- $code = str_replace("{DOT}", ".",
- str_replace("{SLASH}", "/",
- str_replace("{QUOT}", "'",
- str_replace("{DOLLAR}", "$",
- str_replace("{OPEN_ANCHOR}", "(",
- str_replace("{CLOSE_ANCHOR}", ")",
- str_replace("{OPEN_SQR}", "[",
- str_replace("{CLOSE_SQR}", "]",
- str_replace("{PER}", "%",
+ $code = str_replace('{DOT}', '.',
+ str_replace('{SLASH}', '/',
+ str_replace('{QUOT}', "'",
+ str_replace('{DOLLAR}', '$',
+ str_replace('{OPEN_ANCHOR}', '(',
+ str_replace('{CLOSE_ANCHOR}', ')',
+ str_replace('{OPEN_SQR}', '[',
+ str_replace('{CLOSE_SQR}', ']',
+ str_replace('{PER}', '%',
$code
)))))))));
@@ -2902,9 +2773,9 @@ function compileUriCode ($code, $simple=true) {
}
// Function taken from user comments on www.php.net / function eregi()
-function isUrlValid ($url) {
+function isUrlValidSimple ($url) {
// Prepare URL
- $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
+ $url = secureString(str_replace("\\", '', compileRawCode(urldecode($url))));
// Allows http and https
$http = "(http|https)+(:\/\/)";
@@ -2921,44 +2792,42 @@ function isUrlValid ($url) {
// ... and the string after and including question character
$getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
// Pattern for URLs like http://url/dir/doc.html?var=value
- $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
- $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
- $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
+ $pattern['d1dpg1'] = $http . $domain1 . $dir . $page . $getstring1;
+ $pattern['d2dpg1'] = $http . $domain2 . $dir . $page . $getstring1;
+ $pattern['ipdpg1'] = $http . $ip . $dir . $page . $getstring1;
// Pattern for URLs like http://url/dir/?var=value
- $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
- $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
- $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
+ $pattern['d1dg1'] = $http . $domain1 . $dir.'/' . $getstring1;
+ $pattern['d2dg1'] = $http . $domain2 . $dir.'/' . $getstring1;
+ $pattern['ipdg1'] = $http . $ip . $dir.'/' . $getstring1;
// Pattern for URLs like http://url/dir/page.ext
- $pattern['d1dp'] = $http.$domain1.$dir.$page;
- $pattern['d1dp'] = $http.$domain2.$dir.$page;
- $pattern['ipdp'] = $http.$ip.$dir.$page;
+ $pattern['d1dp'] = $http . $domain1 . $dir . $page;
+ $pattern['d1dp'] = $http . $domain2 . $dir . $page;
+ $pattern['ipdp'] = $http . $ip . $dir . $page;
// Pattern for URLs like http://url/dir
- $pattern['d1d'] = $http.$domain1.$dir;
- $pattern['d2d'] = $http.$domain2.$dir;
- $pattern['ipd'] = $http.$ip.$dir;
+ $pattern['d1d'] = $http . $domain1 . $dir;
+ $pattern['d2d'] = $http . $domain2 . $dir;
+ $pattern['ipd'] = $http . $ip . $dir;
// Pattern for URLs like http://url/?var=value
- $pattern['d1g1'] = $http.$domain1."/".$getstring1;
- $pattern['d2g1'] = $http.$domain2."/".$getstring1;
- $pattern['ipg1'] = $http.$ip."/".$getstring1;
+ $pattern['d1g1'] = $http . $domain1 . '/' . $getstring1;
+ $pattern['d2g1'] = $http . $domain2 . '/' . $getstring1;
+ $pattern['ipg1'] = $http . $ip . '/' . $getstring1;
// Pattern for URLs like http://url?var=value
- $pattern['d1g12'] = $http.$domain1.$getstring1;
- $pattern['d2g12'] = $http.$domain2.$getstring1;
- $pattern['ipg12'] = $http.$ip.$getstring1;
+ $pattern['d1g12'] = $http . $domain1 . $getstring1;
+ $pattern['d2g12'] = $http . $domain2 . $getstring1;
+ $pattern['ipg12'] = $http . $ip . $getstring1;
// Test all patterns
$reg = false;
- foreach ($pattern as $key=>$pat) {
+ foreach ($pattern as $key => $pat) {
// Debug regex?
- if (defined('DEBUG_REGEX')) {
- $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
- $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
- $pat = str_replace("[:digit:]", "0-9", $pat);
- $pat = str_replace(".", "\.", $pat);
- $pat = str_replace("@", "\@", $pat);
- echo $key."= ".$pat."
";
- }
+ if (isDebugRegExpressionEnabled()) {
+ // @TODO Are these convertions still required?
+ $pat = str_replace('.', "\.", $pat);
+ $pat = str_replace('@', "\@", $pat);
+ //* DEBUG: */ outputHtml($key."= " . $pat . '
');
+ } // END - if
// Check if expression matches
- $reg = ($reg || preg_match(("^".$pat."^"), $url));
+ $reg = ($reg || preg_match(('^' . $pat.'^'), $url));
// Does it match?
if ($reg === true) break;
@@ -2968,23 +2837,8 @@ function isUrlValid ($url) {
return $reg;
}
-// Smartly adds slashes
-function smartAddSlashes ($unquoted) {
- $unquoted = str_replace("\\", "", $unquoted);
- return addslashes($unquoted);
-}
-
-// Decode entities in a nicer way
-function decodeEntities ($str) {
- // @TODO We may want to switch over to UTF-8 here!
- $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
-
- // Return decoded string
- return $decodedString;
-}
-
// Wtites data to a config.php-style file
-// @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
+// @TODO Rewrite this function to use readFromFile() and writeToFile()
function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
// Initialize some variables
$done = false;
@@ -2993,160 +2847,99 @@ function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
$found = false;
// Is the file there and read-/write-able?
- if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
- $search = "CFG: ".$comment;
- $tmp = $FQFN.".tmp";
+ if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
+ $search = 'CFG: ' . $comment;
+ $tmp = $FQFN . '.tmp';
// Open the source file
- $fp = fopen($FQFN, 'r') or OUTPUT_HTML("
READ: ".$FQFN."
");
+ $fp = fopen($FQFN, 'r') or outputHtml('
READ: ' . $FQFN . '
');
// Is the resource valid?
if (is_resource($fp)) {
// Open temporary file
- $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("
WRITE: ".$tmp."
");
+ $fp_tmp = fopen($tmp, 'w') or outputHtml('
WRITE: ' . $tmp . '
');
// Is the resource again valid?
if (is_resource($fp_tmp)) {
+ // Mark temporary file as readable
+ $GLOBALS['file_readable'][$tmp] = true;
+
+ // Start reading
while (!feof($fp)) {
// Read from source file
$line = fgets ($fp, 1024);
- if (strpos($line, $search) > -1) { $next = 0; $found = true; }
+ if (strpos($line, $search) > -1) { $next = '0'; $found = true; }
if ($next > -1) {
if ($next === $seek) {
$next = -1;
- $line = $prefix . $DATA . $suffix."\n";
+ $line = $prefix . $DATA . $suffix . "\n";
} else {
$next++;
}
- }
+ } // END - if
// Write to temp file
fputs($fp_tmp, $line);
- }
+ } // END - while
// Close temp file
fclose($fp_tmp);
// Finished writing tmp file
$done = true;
- }
+ } // END - if
// Close source file
fclose($fp);
- if (($done) && ($found)) {
+ if (($done === true) && ($found === true)) {
// Copy back tmp file and delete tmp :-)
- copy($tmp, $FQFN);
- return unlink($tmp);
- } elseif (!$found) {
- OUTPUT_HTML("
CHANGE: 404!");
+ copyFileVerified($tmp, $FQFN, 0644);
+ return removeFile($tmp);
+ } elseif ($found === false) {
+ outputHtml('
CHANGE: 404!');
} else {
- OUTPUT_HTML("
TMP: UNDONE!");
+ outputHtml('
TMP: UNDONE!');
}
}
} else {
// File not found, not readable or writeable
- OUTPUT_HTML("
404: ".$FQFN."
");
+ outputHtml('
404: ' . $FQFN . '
');
}
// An error was detected!
return false;
}
// Send notification to admin
-function SEND_ADMIN_NOTIFICATION ($subject, $templateName, $content=array(), $uid="0") {
- if (GET_EXT_VERSION("admins") >= "0.4.1") {
+function sendAdminNotification ($subject, $templateName, $content=array(), $userid = '0') {
+ if (isExtensionInstalledAndNewer('admins', '0.4.1')) {
// Send new way
- SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
+ sendAdminsEmails($subject, $templateName, $content, $userid);
} else {
// Send out out-dated way
- $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
- SEND_ADMIN_EMAILS($subject, $msg);
- }
-}
-
-// Merges an array together but only if both are arrays
-function merge_array ($array1, $array2) {
- // Are both an array?
- if ((is_array($array1)) && (is_array($array2))) {
- // Merge all together
- return array_merge($array1, $array2);
- } elseif (is_array($array1)) {
- // Return left array
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
- return $array1;
- } elseif (is_array($array2)) {
- // Return right array
- DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
- return $array2;
+ $message = loadEmailTemplate($templateName, $content, $userid);
+ sendAdminEmails($subject, $message);
}
-
- // Both are not arrays
- debug_report_bug(__FUNCTION__.": No arrays provided!");
}
// Debug message logger
-function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
+function logDebugMessage ($funcFile, $line, $message, $force=true) {
// Is debug mode enabled?
if ((isDebugModeEnabled()) || ($force === true)) {
// Remove CRLF
- $message = str_replace("\r", "", str_replace("\n", "", $message));
+ $message = str_replace("\r", '', str_replace("\n", '', $message));
- // Log this message away
- $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
- fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
+ // Log this message away, we better don't call app_die() here to prevent an endless loop
+ $fp = fopen(getConfig('CACHE_PATH') . 'debug.log', 'a') or die(__FUNCTION__.'['.__LINE__.']: Cannot write logfile debug.log!');
+ fwrite($fp, date('d.m.Y|H:i:s', time()) . '|' . getModule(false) . '|' . basename($funcFile) . '|' . $line . '|' . $message . "\n");
fclose($fp);
} // END - if
}
-// Load more reset scripts
-function runResetIncludes () {
- // Is the reset set or old sql_patches?
- if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
- // Then abort here
- DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
- } // END - if
-
- // Get more daily reset scripts
- SET_INC_POOL(GET_DIR_AS_ARRAY("inc/reset/", "reset_"));
-
- // Update database
- if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
-
- // Is the config entry set?
- if (GET_EXT_VERSION("sql_patches") >= "0.4.2") {
- // Create current week mark
- $currWeek = date("W", time());
-
- // Has it changed?
- if (getConfig('last_week') != $currWeek) {
- // Include weekly reset scripts
- MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
-
- // Update config
- if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
- } // END - if
-
- // Create current month mark
- $currMonth = date("m", time());
-
- // Has it changed?
- if (getConfig('last_month') != $currMonth) {
- // Include monthly reset scripts
- MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
-
- // Update config
- if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
- } // END - if
- } // END - if
-
- // Run the filter
- runFilterChain('load_includes');
-}
-
// Handle extra values
-function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
+function handleExtraValues ($filterFunction, $value, $extraValue) {
// Default is the value itself
$ret = $value;
@@ -3178,62 +2971,56 @@ function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
return $ret;
}
-// Check if given FQFN is a readable file
-function FILE_READABLE ($FQFN) {
- // Check all...
- return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
-}
-
// Converts timestamp selections into a timestamp
-function CONVERT_SELECTIONS_TO_TIMESTAMP (&$POST, &$DATA, &$id, &$skip) {
+function convertSelectionsToTimestamp (&$postData, &$DATA, &$id, &$skip) {
// Init test variable
- $test2 = "";
+ $skip = false;
+ $test2 = '';
// Get last three chars
$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', '_we', '_da', '_ho', '_mi', '_se'))) {
// Found a multi-selection for timings?
$test = substr($id, 0, -3);
- if ((isset($POST[$test."_ye"])) && (isset($POST[$test."_mo"])) && (isset($POST[$test."_we"])) && (isset($POST[$test."_da"])) && (isset($POST[$test."_ho"])) && (isset($POST[$test."_mi"])) && (isset($POST[$test."_se"])) && ($test != $test2)) {
+ 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)) {
// Generate timestamp
- $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
- $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
+ $postData[$test] = createTimestampFromSelections($test, $postData);
+ $DATA[] = 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) {
- unset($POST[$test."_".$rem]);
+ foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
+ unset($postData[$test . '_' . $rem]);
} // END - foreach
// Skip adding
- unset($id); $skip = true; $test2 = $test;
+ unset($id);
+ $skip = true;
+ $test2 = $test;
} // END - if
- } else {
- // Process this entry
- $skip = false;
- $test2 = "";
- }
+ } // END - if
}
// Reverts the german decimal comma into Computer decimal dot
-function REVERT_COMMA ($str) {
+function convertCommaToDot ($str) {
// Default float is not a float... ;-)
$float = false;
// Which language is selected?
- switch (GET_LANGUAGE()) {
- case "de": // German language
+ switch (getLanguage()) {
+ case 'de': // German language
// Remove german thousand dots first
- $str = str_replace(".", "", $str);
+ $str = str_replace('.', '', $str);
// Replace german commata with decimal dot and cast it
- $float = (float)str_replace(",", ".", $str);
+ $float = (float)str_replace(',', '.', $str);
break;
default: // US and so on
// Remove thousand dots first and cast
- $float = (float)str_replace(",", "", $str);
+ $float = (float)str_replace(',', '', $str);
break;
}
@@ -3242,28 +3029,28 @@ function REVERT_COMMA ($str) {
}
// Handle menu-depending failed logins and return the rendered content
-function HANDLE_LOGIN_FAILTURES ($accessLevel) {
+function handleLoginFailtures ($accessLevel) {
// Default output is empty ;-)
- $OUT = "";
+ $OUT = '';
// Is the session data set?
- if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
+ if ((isSessionVariableSet('mxchange_' . $accessLevel.'_failures')) && (isSessionVariableSet('mxchange_' . $accessLevel.'_last_fail'))) {
// Ignore zero values
- if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
+ if (getSession('mxchange_' . $accessLevel.'_failures') > 0) {
// Non-guest has login failures found, get both data and prepare it for template
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ):accessLevel={$accessLevel}
\n";
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ):accessLevel={$accessLevel}
");
$content = array(
- 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
- 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
+ 'login_failures' => getSession('mxchange_' . $accessLevel.'_failures'),
+ 'last_failure' => generateDateTime(getSession('mxchange_' . $accessLevel.'_last_fail'), 2)
);
// Load template
- $OUT = LOAD_TEMPLATE("login_failures", true, $content);
+ $OUT = loadTemplate('login_failures', true, $content);
} // END - if
// Reset session data
- set_session('mxchange_'.$accessLevel.'_failures', "");
- set_session('mxchange_'.$accessLevel.'_last_fail', "");
+ setSession('mxchange_' . $accessLevel.'_failures', '');
+ setSession('mxchange_' . $accessLevel.'_last_fail', '');
} // END - if
// Return rendered content
@@ -3271,77 +3058,43 @@ function HANDLE_LOGIN_FAILTURES ($accessLevel) {
}
// Rebuild cache
-function rebuildCacheFiles ($cache, $inc="") {
+function rebuildCacheFile ($cache, $inc = '', $force = false) {
+ // Debug message
+ /* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("cache=%s, inc=%s, force=%s", $cache, $inc, intval($force)));
+
// Shall I remove the cache file?
- if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
+ if (isCacheInstanceValid()) {
// Rebuild cache
if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
// Destroy it
- $GLOBALS['cache_instance']->destroyCacheFile();
+ $GLOBALS['cache_instance']->removeCacheFile($force);
} // END - if
// Include file given?
if (!empty($inc)) {
// Construct FQFN
- $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
+ $inc = sprintf("inc/loader/load_cache-%s.php", $inc);
// Is the include there?
- if (INCLUDE_READABLE($INC)) {
+ if (isIncludeReadable($inc)) {
// And rebuild it from scratch
- //* DEBUG: */ print __FUNCTION__."(
".__LINE__." ): inc={$inc} - LOADED!
\n";
- LOAD_INC($INC);
+ //* DEBUG: */ outputHtml(__FUNCTION__."(
".__LINE__." ): inc={$inc} - LOADED!
");
+ loadInclude($inc);
} else {
// Include not found!
- DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
+ logDebugMessage(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
}
} // END - if
} // END - if
}
-// Purge admin menu cache
-function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
- // Is the cache extension enabled or no cache instance or admin menu cache disabled?
- if (!EXT_IS_ACTIVE("cache")) {
- // Cache extension not active
- return false;
- } elseif (!isCacheInstanceValid()) {
- // No cache instance!
- DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
- return false;
- } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
- // Caching disabled (currently experiemental!)
- return false;
- }
-
- // Experiemental feature!
- debug_report_bug("
Experimental feature: You have to delete the admin_*.cache files by yourself at this point.");
-}
-
-// Translates the "pool type" into human-readable
-function TRANSLATE_POOL_TYPE ($type) {
- // Default?type is unknown
- $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
-
- // Generate constant
- $constName = sprintf("POOL_TYPE_%s", $type);
-
- // Does it exist?
- if (defined($constName)) {
- // Then use it
- $translated = getMessage($constName);
- } // END - if
-
- // Return "translation"
- return $translated;
-}
-
// Determines the real remote address
function determineRealRemoteAddress () {
// Is a proxy in use?
- if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
+ if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Proxy was used
$address = $_SERVER['HTTP_X_FORWARDED_FOR'];
- } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
+ } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
// Yet, another proxy
$address = $_SERVER['HTTP_CLIENT_IP'];
} else {
@@ -3350,8 +3103,8 @@ function determineRealRemoteAddress () {
}
// This strips out the real address from proxy output
- if (strstr($address, ",")){
- $addressArray = explode(",", $address);
+ if (strstr($address, ',')) {
+ $addressArray = explode(',', $address);
$address = $addressArray[0];
} // END - if
@@ -3359,193 +3112,124 @@ function determineRealRemoteAddress () {
return $address;
}
-// "Getter" for remote IP number
-function GET_REMOTE_ADDR () {
- // Get remote ip from environment
- $remoteAddr = determineRealRemoteAddress();
-
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
- } // END - if
-
- // Return it
- return $remoteAddr;
-}
-
-// "Getter" for remote hostname
-function GET_REMOTE_HOST () {
- // Get remote ip from environment
- $remoteHost = getenv('REMOTE_HOST');
-
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
- } // END - if
-
- // Return it
- return $remoteHost;
-}
-
-// "Getter" for user agent
-function GET_USER_AGENT () {
- // Get remote ip from environment
- $userAgent = getenv('HTTP_USER_AGENT');
-
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
- } // END - if
-
- // Return it
- return $userAgent;
-}
-
-// "Getter" for referer
-function GET_REFERER () {
- // Get remote ip from environment
- $referer = getenv('HTTP_REFERER');
-
- // Is removeip installed?
- if (EXT_IS_ACTIVE("removeip")) {
- // Then anonymize it
- $referer = GET_ANONYMOUS_REFERER($referer);
- } // END - if
-
- // Return it
- return $referer;
-}
-
// Adds a bonus mail to the queue
// This is a high-level function!
-function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
+function addNewBonusMail ($data, $mode = '', $output=true) {
// Use mode from data if not set and availble ;-)
if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
// Generate receiver list
- $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
+ $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
// Receivers added?
if (!empty($RECEIVER)) {
// Add bonus mail to queue
- ADD_BONUS_MAIL_TO_QUEUE(
- $data['subject'],
- $data['text'],
- $RECEIVER,
- $data['points'],
- $data['seconds'],
- $data['url'],
- $data['cat'],
- $mode,
- $data['receiver']
+ addBonusMailToQueue(
+ $data['subject'],
+ $data['text'],
+ $RECEIVER,
+ $data['points'],
+ $data['seconds'],
+ $data['url'],
+ $data['cat'],
+ $mode,
+ $data['receiver']
);
// Mail inserted into bonus pool
- if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
+ if ($output) loadTemplate('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
} elseif ($output) {
// More entered than can be reached!
- LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
+ loadTemplate('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
} else {
// Debug log
- DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
+ logDebugMessage(__FUNCTION__, __LINE__, "cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
}
}
// Determines referal id and sets it
-function DETERMINE_REFID () {
+function determineReferalId () {
+ // Skip this in non-html-mode and outside ref.php
+ if ((getOutputMode() != 0) && (basename($_SERVER['PHP_SELF']) != 'ref.php')) return false;
+
// Check if refid is set
- if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
+ if ((isset($GLOBALS['refid'])) && ($GLOBALS['refid'] > 0)) {
+ // This is fine...
+ } elseif ((isGetRequestElementSet('user')) && (basename($_SERVER['PHP_SELF']) == 'click.php')) {
// The variable user comes from the click-counter script click.php and we only accept this here
- $GLOBALS['refid'] = bigintval($_GET['user']);
- } elseif (!empty($_POST['refid'])) {
+ $GLOBALS['refid'] = bigintval(getRequestElement('user'));
+ } elseif (isPostRequestElementSet('refid')) {
// Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
- $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
- } elseif (!empty($_GET['refid'])) {
+ $GLOBALS['refid'] = secureString(postRequestElement('refid'));
+ } elseif (isGetRequestElementSet('refid')) {
// Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
- $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
- } elseif (!empty($_GET['ref'])) {
+ $GLOBALS['refid'] = secureString(getRequestElement('refid'));
+ } elseif (isGetRequestElementSet('ref')) {
// Set refid=ref (the referal link uses such variable)
- $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
- } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
+ $GLOBALS['refid'] = secureString(getRequestElement('ref'));
+ } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
// Set session refid als global
- $GLOBALS['refid'] = bigintval(get_session('refid'));
- } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
- // Set default refid as refid in URL
- $GLOBALS['refid'] = getConfig(('def_refid'));
- } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
+ $GLOBALS['refid'] = bigintval(getSession('refid'));
+ } elseif ((isExtensionInstalledAndNewer('user', '0.3.4')) && (getConfig('select_user_zero_refid')) == 'Y') {
// Select a random user which has confirmed enougth mails
- $GLOBALS['refid'] = SELECT_RANDOM_REFID();
+ $GLOBALS['refid'] = determineRandomReferalId();
+ } elseif ((isExtensionInstalled('sql_patches')) && (getConfig('def_refid') > 0)) {
+ // Set default refid as refid in URL
+ $GLOBALS['refid'] = getConfig('def_refid');
} else {
- // No default ID when sql_patches is not installed or none set
- $GLOBALS['refid'] = 0;
+ // No default id when sql_patches is not installed or none set
+ $GLOBALS['refid'] = '0';
}
// Set cookie when default refid > 0
- if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
+ if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (isConfigEntrySet('def_refid')) && (getConfig('def_refid') > 0))) {
+ // Default is not found
+ $found = false;
+
+ // Set current userid here if no member
+ if (!isMember()) setCurrentUserId($GLOBALS['refid']);
+
+ // Do we have nickname or userid set?
+ if (isNicknameUsed($GLOBALS['refid'])) {
+ // Nickname in URL, so load the id
+ $found = fetchUserData($GLOBALS['refid'], 'nickname');
+ } elseif ($GLOBALS['refid'] > 0) {
+ // Direct userid entered
+ $found = fetchUserData($GLOBALS['refid']);
+ }
+
+ // Is the record valid?
+ if (($found === false) || (!isUserDataValid())) {
+ // No, then reset referal id
+ $GLOBALS['refid'] = getConfig('def_refid');
+ } // END - if
+
// Set cookie
- set_session('refid', $GLOBALS['refid']);
+ setSession('refid', $GLOBALS['refid']);
} // END - if
// Return determined refid
return $GLOBALS['refid'];
}
-// Check wether we are installing
-function isInstalling () {
- $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
- //* DEBUG: */ var_dump($installing);
- return $installing;
-}
-
-// Check wether this script is installed
-function isInstalled () {
- return isBooleanConstantAndTrue('mxchange_installed');
-}
-
-// Check wether an admin is registered
-function isAdminRegistered () {
- return isBooleanConstantAndTrue('admin_registered');
-}
-
-// Enables the reset mode. Only call this function if you really want the
-// reset to be run!
-function enableResetMode () {
+// Enables the reset mode and runs it
+function doReset () {
// Enable the reset mode
$GLOBALS['reset_enabled'] = true;
// Run filters
- runFilterChain('reset_enabled');
-}
-
-// Checks wether the reset mode is active
-function isResetModeEnabled () {
- // Now simply check it
- return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
-}
-
-// Checks wether the debug mode is enabled
-function isDebugModeEnabled () {
- // Simply check it
- return isBooleanConstantAndTrue('DEBUG_MODE');
-}
-
-// Checks wether the cache instance is valid
-function isCacheInstanceValid () {
- return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
+ runFilterChain('reset');
}
// Our shutdown-function
function shutdown () {
// Call the filter chain 'shutdown'
- runFilterChain('shutdown', null, false);
+ runFilterChain('shutdown', null);
if (SQL_IS_LINK_UP()) {
// Close link
SQL_CLOSE(__FILE__, __LINE__);
- } elseif ((!isInstalling()) && (isInstalled())) {
+ } elseif (!isInstallationPhase()) {
// No database link
addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
}
@@ -3554,58 +3238,456 @@ function shutdown () {
exit;
}
-// Setter for userid
-function setUserId ($userid) {
- $GLOBALS['userid'] = bigintval($userid);
+// Init member id
+function initMemberId () {
+ $GLOBALS['member_id'] = '0';
+}
+
+// Setter for member id
+function setMemberId ($memberid) {
+ // We should not set member id to zero
+ if ($memberid == '0') debug_report_bug('Userid should not be set zero.');
+
+ // Set it secured
+ $GLOBALS['member_id'] = bigintval($memberid);
}
-// Getter for userid or returns zero
-function getUserId () {
- // Default userid
- $userid = 0;
+// Getter for member id or returns zero
+function getMemberId () {
+ // Default member id
+ $memberid = '0';
- // Is the userid set?
- if (isUserIdSet()) {
+ // Is the member id set?
+ if (isMemberIdSet()) {
// Then use it
- $userid = $GLOBALS['userid'];
+ $memberid = $GLOBALS['member_id'];
} // END - if
// Return it
- return $userid;
+ return $memberid;
}
-// Checks ether the userid is set
-function isUserIdSet () {
- return (isset($GLOBALS['userid']));
-}
-
-// Checks wether the given FQFN is a directory and not .,.. or .svn
-function isDirectory ($FQFN) {
- // Generate baseName
- $baseName = basename($FQFN);
-
- // Check it
- $isDirectory = ((is_dir($FQFN)) && ($baseName != ".") && ($baseName != "..") && ($baseName != ".svn"));
-
- // Return the result
- return $isDirectory;
+// Checks ether the member id is set
+function isMemberIdSet () {
+ return (isset($GLOBALS['member_id']));
}
// Handle message codes from URL
function handleCodeMessage () {
- if (REQUEST_ISSET_GET(('msg'))) {
- // Default extension is "unknown"
- $ext = "unknown";
+ if (isGetRequestElementSet('code')) {
+ // Default extension is 'unknown'
+ $ext = 'unknown';
// Is extension given?
- if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
+ if (isGetRequestElementSet('ext')) $ext = getRequestElement('ext');
- // Convert the 'msg' parameter from URL to a human-readable message
- $msg = convertCodeToMessage(REQUEST_GET('msg'));
+ // Convert the 'code' parameter from URL to a human-readable message
+ $message = getMessageFromErrorCode(getRequestElement('code'));
// Load message template
- LOAD_TEMPLATE("message", false, $msg);
+ loadTemplate('message', false, $message);
+ } // END - if
+}
+
+// Setter for extra title
+function setExtraTitle ($extraTitle) {
+ $GLOBALS['extra_title'] = $extraTitle;
+}
+
+// Getter for extra title
+function getExtraTitle () {
+ // Is the extra title set?
+ if (!isExtraTitleSet()) {
+ // No, then abort here
+ debug_report_bug('extra_title is not set!');
+ } // END - if
+
+ // Return it
+ return $GLOBALS['extra_title'];
+}
+
+// Checks if the extra title is set
+function isExtraTitleSet () {
+ return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
+}
+
+// Generates a 'extension foo inactive' message
+function generateExtensionInactiveMessage ($ext_name) {
+ // Is the extension empty?
+ if (empty($ext_name)) {
+ // This should not happen
+ debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
+ } // END - if
+
+ // Default message
+ $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
+
+ // Is an admin logged in?
+ if (isAdmin()) {
+ // Then output admin message
+ $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_INACTIVE'), $ext_name);
+ } // END - if
+
+ // Return prepared message
+ return $message;
+}
+
+// Generates a 'extension foo not installed' message
+function generateExtensionNotInstalledMessage ($ext_name) {
+ // Is the extension empty?
+ if (empty($ext_name)) {
+ // This should not happen
+ debug_report_bug(__FUNCTION__ . ': Parameter ext is empty. This should not happen.');
+ } // END - if
+
+ // Default message
+ $message = sprintf(getMessage('EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
+
+ // Is an admin logged in?
+ if (isAdmin()) {
+ // Then output admin message
+ $message = sprintf(getMessage('ADMIN_EXTENSION_PROBLEM_EXT_NOT_INSTALLED'), $ext_name);
+ } // END - if
+
+ // Return prepared message
+ return $message;
+}
+
+// Generates a message depending on if the extension is not installed or not
+// just activated
+function generateExtensionInactiveNotInstalledMessage ($ext_name) {
+ // Init message
+ $message = '';
+
+ // Is the extension not installed or just deactivated?
+ switch (isExtensionInstalled($ext_name)) {
+ case true; // Deactivated!
+ $message = generateExtensionInactiveMessage($ext_name);
+ break;
+
+ case false; // Not installed!
+ $message = generateExtensionNotInstalledMessage($ext_name);
+ break;
+
+ default: // Should not happen!
+ logDebugMessage(__FUNCTION__, __LINE__, sprintf("Invalid state of extension %s detected.", $ext_name));
+ $message = sprintf("Invalid state of extension %s detected.", $ext_name);
+ break;
+ } // END - switch
+
+ // Return the message
+ return $message;
+}
+
+// Reads a directory recursively by default and searches for files not matching
+// an exclusion pattern. You can now keep the exclusion pattern empty for reading
+// a whole directory.
+function getArrayFromDirectory ($baseDir, $prefix, $fileIncludeDirs = false, $addBaseDir = true, $excludeArray = array(), $extension = '.php', $excludePattern = '@(\.|\.\.)$@', $recursive = true) {
+ // Add default entries we should exclude
+ $excludeArray[] = '.';
+ $excludeArray[] = '..';
+ $excludeArray[] = '.svn';
+ $excludeArray[] = '.htaccess';
+
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix} - Entered!");
+ // Init includes
+ $files = array();
+
+ // Open directory
+ $dirPointer = opendir(getConfig('PATH') . $baseDir) or app_die(__FUNCTION__, __LINE__, 'Cannot read directory ' . basename($baseDir) . '.');
+
+ // Read all entries
+ while ($baseFile = readdir($dirPointer)) {
+ // Exclude '.', '..' and entries in $excludeArray automatically
+ if (in_array($baseFile, $excludeArray, true)) {
+ // Exclude them
+ //* DEBUG: */ outputHtml('excluded=' . $baseFile . '
');
+ continue;
+ } // END - if
+
+ // Construct include filename and FQFN
+ $fileName = $baseDir . $baseFile;
+ $FQFN = getConfig('PATH') . $fileName;
+
+ // Remove double slashes
+ $FQFN = str_replace('//', '/', $FQFN);
+
+ // Check if the base filename matches an exclusion pattern and if the pattern is not empty
+ if ((!empty($excludePattern)) && (preg_match($excludePattern, $baseFile, $match))) {
+ // These Lines are only for debugging!!
+ //* DEBUG: */ outputHtml('baseDir:' . $baseDir . '
');
+ //* DEBUG: */ outputHtml('baseFile:' . $baseFile . '
');
+ //* DEBUG: */ outputHtml('FQFN:' . $FQFN . '
');
+
+ // Exclude this one
+ continue;
+ } // END - if
+
+ // Skip also files with non-matching prefix genericly
+ if (($recursive === true) && (isDirectory($FQFN))) {
+ // Is a redirectory so read it as well
+ $files = merge_array($files, getArrayFromDirectory($baseDir . $baseFile . '/', $prefix, $fileIncludeDirs, $addBaseDir, $excludeArray, $extension, $excludePattern, $recursive));
+
+ // And skip further processing
+ continue;
+ } elseif (substr($baseFile, 0, strlen($prefix)) != $prefix) {
+ // Skip this file
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Invalid prefix in file " . $baseFile . ", prefix=" . $prefix);
+ continue;
+ } elseif (!isFileReadable($FQFN)) {
+ // Not readable so skip it
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "File " . $FQFN . " is not readable!");
+ continue;
+ }
+
+ // Is the file a PHP script or other?
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}");
+ if ((substr($baseFile, -4, 4) == '.php') || (($fileIncludeDirs === true) && (isDirectory($FQFN)))) {
+ // Is this a valid include file?
+ if ($extension == '.php') {
+ // Remove both for extension name
+ $extName = substr($baseFile, strlen($prefix), -4);
+
+ // Is the extension valid and active?
+ if (isExtensionNameValid($extName)) {
+ // Then add this file
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension entry ' . $baseFile . ' added.');
+ $files[] = $fileName;
+ } else {
+ // Add non-extension files as well
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Regular entry ' . $baseFile . ' added.');
+ if ($addBaseDir === true) {
+ $files[] = $fileName;
+ } else {
+ $files[] = $baseFile;
+ }
+ }
+ } else {
+ // We found .php file but should not search for them, why?
+ debug_report_bug('We should find files with extension=' . $extension . ', but we found a PHP script.');
+ }
+ } elseif (substr($baseFile, -4, 4) == $extension) {
+ // Other, generic file found
+ $files[] = $fileName;
+ }
+ } // END - while
+
+ // Close directory
+ closedir($dirPointer);
+
+ // Sort array
+ asort($files);
+
+ // Return array with include files
+ //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
+ return $files;
+}
+
+// Maps a module name into a database table name
+function mapModuleToTable ($moduleName) {
+ // Map only these, still lame code...
+ switch ($moduleName) {
+ // 'index' is the guest's menu
+ case 'index': $moduleName = 'guest'; break;
+ // ... and 'login' the member's menu
+ case 'login': $moduleName = 'member'; break;
+ // Anything else will not be mapped, silently.
+ } // END - switch
+
+ // Return result
+ return $moduleName;
+}
+
+// Add SQL debug data to array for later output
+function addSqlToDebug ($result, $sqlString, $timing, $F, $L) {
+ // Already executed?
+ if (isset($GLOBALS['debug_sqls'][$F][$L][$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;
+
+ // Do we have cache?
+ if (!isset($GLOBALS['debug_sql_available'])) {
+ // Check it and cache it in $GLOBALS
+ $GLOBALS['debug_sql_available'] = ((isConfigurationLoaded()) && (isExtensionInstalledAndNewer('other', '0.2.2')) && (getConfig('display_debug_sqls') == 'Y'));
+ } // 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
+
+ // Generate record
+ $record = array(
+ 'num_rows' => SQL_NUMROWS($result),
+ 'affected' => SQL_AFFECTEDROWS(),
+ 'sql_str' => $sqlString,
+ 'timing' => $timing,
+ 'file' => basename($F),
+ 'line' => $L
+ );
+
+ // Add it
+ $GLOBALS['debug_sqls'][] = $record;
+}
+
+// Initializes the cache instance
+function initCacheInstance () {
+ // Load include for CacheSystem class
+ loadIncludeOnce('inc/classes/cachesystem.class.php');
+
+ // Initialize cache system only when it's needed
+ $GLOBALS['cache_instance'] = new CacheSystem();
+ if ($GLOBALS['cache_instance']->getStatus() != 'done') {
+ // Failed to initialize cache sustem
+ addFatalMessage(__FILE__, __LINE__, '(
' . __LINE__ . ' ): ' . getMessage('CACHE_CANNOT_INITIALIZE'));
+ } // END - if
+}
+
+// Getter for message from array or raw message
+function getMessageFromIndexedArray ($message, $pos, $array) {
+ // Check if the requested message was found in array
+ if (isset($array[$pos])) {
+ // ... if yes then use it!
+ $ret = $array[$pos];
+ } else {
+ // ... else use default message
+ $ret = $message;
+ }
+
+ // Return result
+ return $ret;
+}
+
+// Print code with line numbers
+function linenumberCode ($code) {
+ if (!is_array($code)) $codeE = explode("\n", $code); else $codeE = $code;
+ $count_lines = count($codeE);
+
+ $r = 'Line | Code:
';
+ foreach($codeE as $line => $c) {
+ $r .= '
';
+ if ($count_lines == 1) {
+ $r .= 1;
+ } else {
+ $r .= ($line == ($count_lines - 1)) ? '' : ($line+1);
+ }
+ $r .= ' |';
+
+ // Add code
+ $r .= '' . htmlentities($c) . '
';
+ }
+
+ return '
' . $r . '
';
+}
+
+// Convert ';' to ', ' for e.g. receiver list
+function convertReceivers ($old) {
+ return str_replace(';', ', ', $old);
+}
+
+// Determines the right page title
+function determinePageTitle () {
+ // Config and database connection valid?
+ if ((isConfigLocalLoaded()) && (isConfigurationLoaded()) && (SQL_IS_LINK_UP()) && (isExtensionInstalledAndNewer('sql_patches', '0.1.6'))) {
+ // Init title
+ $TITLE = '';
+
+ // Title decoration enabled?
+ if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_left') != '')) $TITLE .= trim(getConfig('title_left'))." ";
+
+ // Do we have some extra title?
+ if (isExtraTitleSet()) {
+ // Then prepent it
+ $TITLE .= getExtraTitle() . ' by ';
+ } // END - if
+
+ // Add main title
+ $TITLE .= getConfig('MAIN_TITLE');
+
+ // Add title of module? (middle decoration will also be added!)
+ if ((getConfig('enable_mod_title') == 'Y') || ((!isWhatSet()) && (!isActionSet())) || (getModule() == 'admin')) {
+ $TITLE .= ' ' . trim(getConfig('title_middle')) . ' ' . getModuleTitle(getModule());
+ } // END - if
+
+ // Add title from what file
+ $mode = '';
+ if (getModule() == 'login') $mode = 'member';
+ elseif (getModule() == 'index') $mode = 'guest';
+ if ((!empty($mode)) && (getConfig('enable_what_title') == 'Y')) $TITLE .= " ".trim(getConfig('title_middle'))." ".getModuleDescription($mode, getWhat());
+
+ // Add title decorations? (right)
+ if ((getConfig('enable_title_deco') == 'Y') && (getConfig('title_right') != '')) $TITLE .= " ".trim(getConfig('title_right'));
+
+ // Remember title in constant for the template
+ $pageTitle = $TITLE;
+ } elseif ((isInstalled()) && (isAdminRegistered())) {
+ // Installed, admin registered but no ext-sql_patches
+ $pageTitle = '[-- ' . getConfig('MAIN_TITLE').' - '.getModuleTitle(getModule()) . ' --]';
+ } elseif ((isInstalled()) && (!isAdminRegistered())) {
+ // Installed but no admin registered
+ $pageTitle = sprintf(getMessage('SETUP_OF_MXCHANGE'), getConfig('MAIN_TITLE'));
+ } elseif ((!isInstalled()) || (!isAdminRegistered())) {
+ // Installation mode
+ $pageTitle = getMessage('INSTALLATION_OF_MXCHANGE');
+ } else {
+ // Configuration not found!
+ $pageTitle = getMessage('NO_CONFIG_FOUND_TITLE');
+
+ // Do not add the fatal message in installation mode
+ if ((!isInstalling()) && (!isConfigurationLoaded())) addFatalMessage(__FILE__, __LINE__, getMessage('NO_CONFIG_FOUND'));
+ }
+
+ // Return title
+ return $pageTitle;
+}
+
+// Checks wethere there is a cache file there. This function is cached.
+function isTemplateCached ($template) {
+ // Do we have cached this result?
+ if (!isset($GLOBALS['template_cache'][$template])) {
+ // Generate FQFN
+ $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+ // Is it there?
+ $GLOBALS['template_cache'][$template] = isFileReadable($FQFN);
+ } // END - if
+
+ // Return it
+ return $GLOBALS['template_cache'][$template];
+}
+
+// Flushes non-flushed template cache to disk
+function flushTemplateCache ($template, $eval) {
+ // Is this cache flushed?
+ if ((!isTemplateCached($template)) && ($eval != '404')) {
+ // Generate FQFN
+ $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+ // Replace username with a call
+ $eval = str_replace('$username', '".getUsername()."', $eval);
+
+ // And flush it
+ writeToFile($FQFN, $eval, true);
+ } // END - if
+}
+
+// Reads a template cache
+function readTemplateCache ($template) {
+ // Check it again
+ if (isTemplateCached($template)) {
+ // Generate FQFN
+ $FQFN = sprintf("%s_compiled/templates/%s.tpl.cache", getConfig('CACHE_PATH'), $template);
+
+ // And read from it
+ $GLOBALS['template_eval'][$template] = readFromFile($FQFN);
} // END - if
+
+ // And return it
+ return $GLOBALS['template_eval'][$template];
}
//////////////////////////////////////////////////
@@ -3621,5 +3703,29 @@ if (!function_exists('html_entity_decode')) {
}
} // END - if
+if (!function_exists('http_build_query')) {
+ // Taken from documentation on www.php.net, credits to Marco K. (Germany)
+ function http_build_query($data, $prefix='', $sep='', $key='') {
+ $ret = array();
+ foreach ((array)$data as $k => $v) {
+ if (is_int($k) && $prefix != null) {
+ $k = urlencode($prefix . $k);
+ } // END - if
+
+ if ((!empty($key)) || ($key === 0)) $k = $key.'['.urlencode($k).']';
+
+ if (is_array($v) || is_object($v)) {
+ array_push($ret, http_build_query($v, '', $sep, $k));
+ } else {
+ array_push($ret, $k.'='.urlencode($v));
+ }
+ } // END - foreach
+
+ if (empty($sep)) $sep = ini_get('arg_separator.output');
+
+ return implode($sep, $ret);
+ }
+}// // END - if
+
// [EOF]
?>