2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
44 // Output HTML code directly or "render" it. You addionally switch the new-line character off
45 function OUTPUT_HTML ($HTML, $newLine = true) {
46 // Some global variables
49 // Do we have HTML-Code here?
51 // Yes, so we handle it as you have configured
52 switch (constant('OUTPUT_MODE'))
55 // That's why you don't need any \n at the end of your HTML code... :-)
56 if (constant('_OB_CACHING') == "on") {
57 // Output into PHP's internal buffer
60 // That's why you don't need any \n at the end of your HTML code... :-)
61 if ($newLine) echo "\n";
63 // Render mode for old or lame servers...
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine) $OUTPUT .= "\n";
72 // If we are switching from render to direct output rendered code
73 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
75 // The same as above... ^
77 if ($newLine) echo "\n";
81 // Huh, something goes wrong or maybe you have edited config.php ???
82 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
83 mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
86 } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
87 // Headers already sent?
90 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
92 // Trigger an user error
93 debug_report_bug("Headers are already sent!");
96 // Output cached HTML code
97 $OUTPUT = ob_get_contents();
99 // Clear output buffer for later output if output is found
100 if (!empty($OUTPUT)) {
105 header("HTTP/1.1 200");
108 $now = gmdate('D, d M Y H:i:s') . ' GMT';
110 // General headers for no caching
111 header("Expired: " . $now); // RFC2616 - Section 14.21
112 header("Last-Modified: " . $now);
113 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
114 header("Pragma: no-cache"); // HTTP/1.0
115 header("Connection: Close");
117 // Extension "rewrite" installed?
118 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
119 $OUTPUT = REWRITE_LINKS($OUTPUT);
122 // Compile and run finished rendered HTML code
123 while (strpos($OUTPUT, '{!') > 0) {
124 // Prepare the content and eval() it...
126 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
129 // Was that eval okay?
130 if (empty($newContent)) {
131 // Something went wrong!
132 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
134 $OUTPUT = $newContent;
137 // Output code here, DO NOT REMOVE! ;-)
139 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
140 // Rewrite links when rewrite extension is active
141 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
142 $OUTPUT = REWRITE_LINKS($OUTPUT);
145 // Compile and run finished rendered HTML code
146 while (strpos($OUTPUT, '{!') > 0) {
147 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
151 // Output code here, DO NOT REMOVE! ;-)
156 // Output the raw HTML code
157 function OUTPUT_RAW ($HTML) {
158 // Output stripped HTML code to avoid broken JavaScript code, etc.
159 echo stripslashes(stripslashes($HTML));
161 // Flush the output if only constant('_OB_CACHING') is not "on"
162 if (constant('_OB_CACHING') != "on") {
168 // Init fatal message array
169 function initFatalMessages () {
170 $GLOBALS['fatal_messages'] = array();
173 // Getter for whole fatal error messages
174 function getFatalArray () {
175 return $GLOBALS['fatal_messages'];
178 // Add a fatal error message to the queue array
179 function addFatalMessage ($F, $L, $message, $extra="") {
180 debug_report_bug($message);
181 if (is_array($extra)) {
182 // Multiple extras for a message with masks
183 $message = call_user_func_array('sprintf', $extra);
184 } elseif (!empty($extra)) {
185 // $message is text with a mask plus extras to insert into the text
186 $message = sprintf($message, $extra);
189 // Add message to $GLOBALS['fatal_messages']
190 $GLOBALS['fatal_messages'][] = $message;
192 // Log fatal messages away
193 DEBUG_LOG($F, $L, " message={$message}");
196 // Getter for total fatal message count
197 function getTotalFatalErrors () {
201 // Do we have at least the first entry?
202 if (!empty($GLOBALS['fatal_messages'][0])) {
204 $count = count($GLOBALS['fatal_messages']);
211 // Load a template file and return it's content (only it's name; do not use ' or ")
212 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
213 // Add more variables which you want to use in your template files
214 global $DATA, $_CONFIG, $username;
216 // Make all template names lowercase
217 $template = strtolower($template);
219 // Count the template load
220 incrementConfigEntry('num_templates');
222 // Prepare IP number and User Agent
223 $REMOTE_ADDR = GET_REMOTE_ADDR();
224 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
225 $HTTP_USER_AGENT = GET_USER_AGENT();
229 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
231 // @DEPRECATED Try to rewrite the if() condition
232 if ($template == "member_support_form") {
233 // Support request of a member
234 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
235 array(getUserId()), __FUNCTION__, __LINE__);
237 // Is content an array?
238 if (is_array($content)) {
240 $content = merge_array($content, SQL_FETCHARRAY($result));
243 $content['gender'] = TRANSLATE_GENDER($content['gender']);
246 // @TODO Fine all templates which are using these direct variables and rewrite them.
247 // @TODO After this step is done, this else-block is history
248 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
251 $gender = TRANSLATE_GENDER($gender);
252 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
256 SQL_FREERESULT($result);
259 // Generate date/time string
260 $date_time = MAKE_DATETIME(time(), "1");
263 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
266 // Check for admin/guest/member templates
267 if (strpos($template, "admin_") > -1) {
268 // Admin template found
270 } elseif (strpos($template, "guest_") > -1) {
271 // Guest template found
273 } elseif (strpos($template, "member_") > -1) {
274 // Member template found
276 } elseif (strpos($template, "install_") > -1) {
277 // Installation template found
279 } elseif (strpos($template, "ext_") > -1) {
280 // Extension template found
282 } elseif (strpos($template, "la_") > -1) {
283 // "Logical-area" template found
286 // Test for extension
287 $test = substr($template, 0, strpos($template, "_"));
288 if (EXT_IS_ACTIVE($test)) {
289 // Set extra path to extension's name
294 ////////////////////////
295 // Generate file name //
296 ////////////////////////
297 $FQFN = $BASE.$MODE.$template.".tpl";
299 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
300 // Select what depended header/footer template file for admin/guest/member area
301 $file2 = sprintf("%s%s%s_%s.tpl",
305 SQL_ESCAPE($GLOBALS['what'])
309 if (FILE_READABLE($file2)) $FQFN = $file2;
311 // Remove variable from memory
315 // Does the special template exists?
316 if (!FILE_READABLE($FQFN)) {
317 // Reset to default template
318 $FQFN = $BASE.$template.".tpl";
321 // Now does the final template exists?
322 if (FILE_READABLE($FQFN)) {
323 // The local file does exists so we load it. :)
324 $tmpl_file = READ_FILE($FQFN);
326 // Replace ' to our own chars to preventing them being quoted
327 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
329 // Do we have to compile the code?
331 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
333 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
336 // Simply return loaded code
340 // Add surrounding HTML comments to help finding bugs faster
341 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
342 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
343 // Only admins shall see this warning or when installation mode is active
344 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
345 (".basename($FQFN).")<br />
348 <pre>".print_r($content, true)."</pre>
350 <pre>".print_r($DATA, true)."</pre>
354 // Remove content and data
358 // Do we have some content to output or return?
360 // Not empty so let's put it out! ;)
361 if ($return === true) {
362 // Return the HTML code
368 } elseif (isDebugModeEnabled()) {
369 // Warning, empty output!
370 return "E:".$template."<br />\n";
374 // Send mail out to an email address
375 function SEND_EMAIL($toEmail, $subject, $message, $HTML = "N", $mailHeader = "") {
376 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
378 // Compile subject line (for POINTS constant etc.)
379 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
383 if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
384 // Value detected, is the message extension installed?
385 if (EXT_IS_ACTIVE("msg")) {
386 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
389 // Load email address
390 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
391 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
393 // Does the user exist?
394 if (SQL_NUMROWS($result_email)) {
395 // Load email address
396 list($toEmail) = SQL_FETCHROW($result_email);
399 $toEmail = constant('WEBMASTER');
403 SQL_FREERESULT($result_email);
405 } elseif ("$toEmail" == "0") {
407 $toEmail = constant('WEBMASTER');
409 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
411 // Check for PHPMailer or debug-mode
412 if (!CHECK_PHPMAILER_USAGE()) {
413 // Not in PHPMailer-Mode
414 if (empty($mailHeader)) {
415 // Load email header template
416 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
419 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
421 } elseif (isDebugModeEnabled()) {
422 if (empty($mailHeader)) {
423 // Load email header template
424 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
427 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
432 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
436 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
439 // Fix HTML parameter (default is no!)
440 if (empty($HTML)) $HTML = "N";
441 if (isDebugModeEnabled()) {
442 // In debug mode we want to display the mail instead of sending it away so we can debug this part
444 ".htmlentities(trim($mailHeader))."
446 Subject : ".$subject."
447 Message : ".$message."
449 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
450 // Send mail as HTML away
451 SEND_HTML_EMAIL($toEmail, $subject, $message, $mailHeader);
452 } elseif (!empty($toEmail)) {
454 SEND_RAW_EMAIL($toEmail, $subject, $message, $mailHeader);
455 } elseif ($HTML == "N") {
457 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$subject, $message, $mailHeader);
461 // Check if legacy or PHPMailer command
462 // @TODO Rewrite this to an extension 'smtp'
464 function CHECK_PHPMAILER_USAGE() {
465 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != "") && (constant('SMTP_USER') != ""));
469 * Send out a raw email with PHPMailer class or legacy mail() command
471 function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
472 // Shall we use PHPMailer class or legacy mode?
473 if (CHECK_PHPMAILER_USAGE()) {
474 // Use PHPMailer class with SMTP enabled
475 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
476 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
479 $mail = new PHPMailer();
480 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
483 $mail->SMTPAuth = true;
484 $mail->Host = constant('SMTP_HOSTNAME');
486 $mail->Username = constant('SMTP_USER');
487 $mail->Password = constant('SMTP_PASSWORD');
489 $mail->From = constant('WEBMASTER');
493 $mail->FromName = constant('MAIN_TITLE');
494 $mail->Subject = $subject;
495 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
497 $mail->AltBody = "Your mail program required HTML support to read this mail!";
498 $mail->WordWrap = 70;
501 $mail->Body = decodeEntities($msg);
503 $mail->AddAddress($toEmail, "");
504 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
505 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
506 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
509 // Use legacy mail() command
510 @mail($toEmail, $subject, decodeEntities($msg), $from);
515 // Generate a password in a specified length or use default password length
516 function GEN_PASS ($LEN = 0) {
517 // Auto-fix invalid length of zero
518 if ($LEN == 0) $LEN = getConfig('pass_len');
520 // Initialize array with all allowed chars
521 $ABC = explode(",", "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,-,+,_,/");
523 // Start creating password
525 for ($i = 0; $i < $LEN; $i++) {
526 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
529 // When the size is below 40 we can also add additional security by scrambling it
530 if (strlen($PASS) <= 40) {
531 // Also scramble the password
532 $PASS = scrambleString($PASS);
535 // Return the password
539 function MAKE_DATETIME ($time, $mode="0")
543 return NEVER_HAPPENED;
545 // Filter out numbers
546 $time = bigintval($time);
549 switch (GET_LANGUAGE())
551 case "de": // German date / time format
553 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
554 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
555 case "2": $ret = date("d.m.Y|H:i", $time); break;
556 case "3": $ret = date("d.m.Y", $time); break;
558 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
563 default: // Default is the US date / time format!
565 case "0": $ret = date("r", $time); break;
566 case "1": $ret = date("Y-m-d - g:i A", $time); break;
567 case "2": $ret = date("y-m-d|H:i", $time); break;
568 case "3": $ret = date("y-m-d", $time); break;
570 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
577 // Translates the american decimal dot into a german comma
578 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
579 // Default is 3 you can change this in admin area "Misc -> Misc Options"
580 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
582 // Use from config is default
583 $maxComma = getConfig('max_comma');
585 // Use from parameter?
586 if ($max > 0) $maxComma = $max;
589 if (($cut) && ($max == 0)) {
590 // Test for commata if in cut-mode
591 $com = explode(".", $dotted);
592 if (count($com) < 2) {
593 // Don't display commatas even if there are none... ;-)
599 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
602 switch (GET_LANGUAGE()) {
604 $dotted = number_format($dotted, $maxComma, ",", ".");
608 $dotted = number_format($dotted, $maxComma, ".", ",");
612 // Return translated value
617 function DEREFERER ($URL) {
618 // Don't de-refer our own links!
619 if (substr($URL, 0, strlen(URL)) != URL) {
620 // De-refer this link
621 $URL = "modules.php?module=loader&url=".encodeString(compileUriCode($URL));
628 // Translate Uni*-like gender to human-readable
629 function TRANSLATE_GENDER ($gender) {
631 $ret = "!{$gender}!";
633 // Male/female or company?
635 case "M": $ret = getMessage('GENDER_M'); break;
636 case "F": $ret = getMessage('GENDER_F'); break;
637 case "C": $ret = getMessage('GENDER_C'); break;
639 // Log unknown gender
640 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
644 // Return translated gender
649 function FRAMETESTER ($URL) {
650 // Prepare frametester URL
651 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
652 encodeString(compileUriCode($URL))
654 return $frametesterUrl;
658 function SELECTION_COUNT ($array) {
660 if (is_array($array)) {
661 foreach ($array as $key => $selected) {
662 if (!empty($selected)) $ret++;
668 function IMG_CODE ($code, $type, $DATA, $uid) {
669 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
672 function TRANSLATE_STATUS ($status) {
678 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
683 $ret = getMessage('ACCOUNT_DELETED');
687 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
688 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
696 function GET_LANGUAGE() {
697 // Set default return value to default language from config
698 $ret = constant('DEFAULT_LANG');
703 // Is the variable set
704 if (REQUEST_ISSET_GET(('mx_lang'))) {
705 // Accept only first 2 chars
706 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
707 } elseif (isset($GLOBALS['cache_array']['language'])) {
709 $ret = $GLOBALS['cache_array']['language'];
710 } elseif (!empty($lang)) {
711 // Check if main language file does exist
712 if (FILE_READABLE(constant('PATH')."inc/language/".$lang.".php")) {
713 // Okay found, so let's update cookies
716 } elseif (!isSessionVariableSet('mx_lang')) {
717 // Return stored value from cookie
718 $ret = get_session('mx_lang');
720 // Fixes a warning before the session has the mx_lang constant
721 if (empty($ret)) $ret = constant('DEFAULT_LANG');
725 $GLOBALS['cache_array']['language'] = $ret;
731 function SET_LANGUAGE ($lang) {
732 // Accept only first 2 chars!
733 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
736 set_session('mx_lang', $lang);
739 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
740 global $DATA, $_CONFIG;
742 // Make sure all template names are lowercase!
743 $template = strtolower($template);
745 // Default "nickname" if extension is not installed
748 // Prepare IP number and User Agent
749 $REMOTE_ADDR = GET_REMOTE_ADDR();
750 $HTTP_USER_AGENT = GET_USER_AGENT();
753 $ADMIN = constant('MAIN_TITLE');
755 // Is the admin logged in?
758 $aid = GET_CURRENT_ADMIN_ID();
761 $ADMIN = GET_ADMIN_EMAIL($aid);
764 // Neutral email address is default
765 $email = constant('WEBMASTER');
767 // Expiration in a nice output format
768 if (getConfig('auto_purge') == 0) {
769 // Will never expire!
770 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
772 // Create nice date string
773 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
776 // Is content an array?
777 if (is_array($content)) {
778 // Add expiration to array, $EXPIRATION is now deprecated!
779 $content['expiration'] = $EXPIRATION;
783 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
784 if (($UID > 0) && (is_array($content))) {
785 // If nickname extension is installed, fetch nickname as well
786 if (EXT_IS_ACTIVE("nickname")) {
787 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
789 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
790 array(bigintval($UID)), __FUNCTION__, __LINE__);
792 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
794 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
795 array(bigintval($UID)), __FUNCTION__, __LINE__);
798 // Fetch and merge data
799 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
800 $content = merge_array($content, SQL_FETCHARRAY($result));
801 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
804 SQL_FREERESULT($result);
807 // Translate M to male or F to female if present
808 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
810 // Overwrite email from data if present
811 if (isset($content['email'])) $email = $content['email'];
813 // Store email for some functions in global data array
814 $DATA['email'] = $email;
817 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
819 // Check for admin/guest/member templates
820 if (strpos($template, "admin_") > -1) {
821 // Admin template found
822 $FQFN = $BASE."admin/".$template.".tpl";
823 } elseif (strpos($template, "guest_") > -1) {
824 // Guest template found
825 $FQFN = $BASE."guest/".$template.".tpl";
826 } elseif (strpos($template, "member_") > -1) {
827 // Member template found
828 $FQFN = $BASE."member/".$template.".tpl";
830 // Test for extension
831 $test = substr($template, 0, strpos($template, "_"));
832 if (EXT_IS_ACTIVE($test)) {
833 // Set extra path to extension's name
834 $FQFN = $BASE.$test."/".$template.".tpl";
836 // No special filename
837 $FQFN = $BASE.$template.".tpl";
841 // Does the special template exists?
842 if (!FILE_READABLE($FQFN)) {
843 // Reset to default template
844 $FQFN = $BASE.$template.".tpl";
847 // Now does the final template exists?
849 if (FILE_READABLE($FQFN)) {
850 // The local file does exists so we load it. :)
851 $tmpl_file = READ_FILE($FQFN);
852 $tmpl_file = SQL_ESCAPE($tmpl_file);
855 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
857 } elseif (!empty($template)) {
858 // Template file not found!
859 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
860 {--TEMPLATE_CONTENT--}
861 <pre>".print_r($content, true)."</pre>
863 <pre>".print_r($DATA, true)."</pre>
866 // Debug mode not active? Then remove the HTML tags
867 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
869 // No template name supplied!
870 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
873 // Is there some content?
874 if (empty($newContent)) {
876 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
877 // Add last error if the required function exists
878 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
881 // Remove content and data
885 // Return compiled content
886 return COMPILE_CODE($newContent);
889 function MAKE_TIME ($H, $M, $S, $stamp) {
890 // Extract day, month and year from given timestamp
891 $DAY = date("d", $stamp);
892 $MONTH = date("m", $stamp);
893 $YEAR = date('Y', $stamp);
895 // Create timestamp for wished time which depends on extracted date
896 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
899 function LOAD_URL ($URL, $addUrlData=true) {
900 // Compile out URI codes
901 $URL = compileUriCode($URL);
903 // Check if http(s):// is there
904 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
905 // Make all URLs full-qualified
910 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
911 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
912 $OUTPUT = ob_get_contents();
914 // Clear it only if there is content
915 if (!empty($OUTPUT)) {
919 // Add some data to URL if cookies are not accepted
920 if (((!defined('__COOKIES')) || (!constant('__COOKIES'))) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
922 // Probe for bot from search engine
923 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
924 // Search engine bot detected so let's rewrite many chars for the link
925 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
927 // Output new location link as anchor
928 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
929 } elseif (!headers_sent()) {
930 // Load URL when headers are not sent
931 //* DEBUG: */ debug_report_bug("URL={$URL}");
932 header ("Location: ".str_replace("&", "&", $URL));
934 // Output error message
935 LOAD_INC("inc/header.php");
936 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
937 LOAD_INC("inc/footer.php");
942 // Wrapper for LOAD_URL but URL comes from a configuration entry
943 function LOAD_CONFIGURED_URL ($configEntry) {
945 $URL = getConfig($configEntry);
950 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
958 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
959 // Is the code a string?
960 if (!is_string($code)) {
961 // Silently return it
965 // Init replacement-array with full security characters
966 $secChars = $GLOBALS['security_chars'];
968 // Select smaller set of chars to replace when we e.g. want to compile URLs
969 if (!$full) $secChars = $GLOBALS['url_chars'];
972 if ($constants === true) {
973 // BEFORE 0.2.1 : Language and data constants
974 // WITH 0.2.1+ : Only language constants
975 $code = str_replace('{--','".', str_replace('--}','."', $code));
977 // BEFORE 0.2.1 : Not used
978 // WITH 0.2.1+ : Data constants
979 $code = str_replace('{!','".', str_replace("!}", '."', $code));
982 // Compile QUOT and other non-HTML codes
983 foreach ($secChars['to'] as $k => $to) {
984 // Do the reversed thing as in inc/libs/security_functions.php
985 $code = str_replace($to, $secChars['from'][$k], $code);
988 // But shall I keep simple quotes for later use?
989 if ($simple) $code = str_replace("'", '{QUOT}', $code);
991 // Find $content[bla][blub] entries
992 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
994 // Are some matches found?
995 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
996 // Replace all matches
997 $matchesFound = array();
998 foreach ($matches[0] as $key => $match) {
999 // Fuzzy look has failed by default
1000 $fuzzyFound = false;
1002 // Fuzzy look on match if already found
1003 foreach ($matchesFound as $found => $set) {
1005 $test = substr($found, 0, strlen($match));
1007 // Does this entry exist?
1008 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1009 if ($test == $match) {
1011 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1018 if ($fuzzyFound) continue;
1020 // Take all string elements
1021 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1022 // Replace it in the code
1023 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1024 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1025 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1026 $matchesFound[$key."_".$matches[4][$key]] = 1;
1027 $matchesFound[$match] = 1;
1028 } elseif (!isset($matchesFound[$match])) {
1029 // Not yet replaced!
1030 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1031 $code = str_replace($match, "\".".$match.".\"", $code);
1032 $matchesFound[$match] = 1;
1037 // Return compiled code
1041 /************************************************************************
1043 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1044 * $a_sort sortiert: *
1046 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1047 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1048 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1049 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1050 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1052 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1053 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1054 * Sie, dass es doch nicht so schwer ist! :-) *
1056 ************************************************************************/
1057 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1059 while ($primary_key < count($a_sort)) {
1060 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1061 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1064 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1065 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1066 } elseif ($key != $key2) {
1067 // Sort numbers (E.g.: 9 < 10)
1068 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1069 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1073 // We have found two different values, so let's sort whole array
1074 foreach ($dummy as $sort_key => $sort_val) {
1075 $t = $dummy[$sort_key][$key];
1076 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1077 $dummy[$sort_key][$key2] = $t;
1088 // Write back sorted array
1093 function ADD_SELECTION ($type, $DEFAULT, $prefix="", $id="0") {
1096 if ($type == "yn") {
1097 // This is a yes/no selection only!
1098 if ($id > 0) $prefix .= "[".$id."]";
1099 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1101 // Begin with regular selection box here
1102 if (!empty($prefix)) $prefix .= "_";
1104 if ($id > 0) $type2 .= "[".$id."]";
1105 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1110 for ($idx = 1; $idx < 32; $idx++) {
1111 $OUT .= "<option value=\"".$idx."\"";
1112 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1113 $OUT .= ">".$idx."</option>\n";
1117 case "month": // Month
1118 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1119 $OUT .= "<option value=\"".$month."\"";
1120 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1121 $OUT .= ">".$descr."</option>\n";
1125 case "year": // Year
1127 $YEAR = date('Y', time());
1129 // Use configured min age or fixed?
1130 if (GET_EXT_VERSION("other") >= "0.2.1") {
1132 $startYear = $YEAR - getConfig('min_age');
1135 $startYear = $YEAR - 16;
1138 // Calculate earliest year (100 years old people can still enter Internet???)
1139 $minYear = $YEAR - 100;
1141 // Check if the default value is larger than minimum and bigger than actual year
1142 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1143 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1144 $OUT .= "<option value=\"".$idx."\"";
1145 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1146 $OUT .= ">".$idx."</option>\n";
1148 } elseif ($DEFAULT == -1) {
1149 // Current year minus 1
1150 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1152 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1155 // Get current year and subtract the configured minimum age
1156 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1157 // Calculate earliest year depending on extension version
1158 if (GET_EXT_VERSION("other") >= "0.2.1") {
1159 // Use configured minimum age
1160 $YEAR = date('Y', time()) - getConfig('min_age');
1162 // Use fixed 16 years age
1163 $YEAR = date('Y', time()) - 16;
1166 // Construct year selection list
1167 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1168 $OUT .= "<option value=\"".$idx."\"";
1169 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1170 $OUT .= ">".$idx."</option>\n";
1177 for ($idx = 0; $idx < 60; $idx+=5) {
1178 if (strlen($idx) == 1) $idx = "0".$idx;
1179 $OUT .= "<option value=\"".$idx."\"";
1180 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1181 $OUT .= ">".$idx."</option>\n";
1186 for ($idx = 0; $idx < 24; $idx++) {
1187 if (strlen($idx) == 1) $idx = "0".$idx;
1188 $OUT .= "<option value=\"".$idx."\"";
1189 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1190 $OUT .= ">".$idx."</option>\n";
1195 $OUT .= "<option value=\"Y\"";
1196 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1197 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1198 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1199 $OUT .= ">{--NO--}</option>\n";
1202 $OUT .= " </select>\n";
1207 function TRANSLATE_YESNO ($yn) {
1209 $translated = "??? (".$yn.")";
1211 case "Y": $translated = getMessage('YES'); break;
1212 case "N": $translated = getMessage('NO'); break;
1214 // Log unknown value
1215 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
1224 // Deprecated : $length
1227 function generateRandomCodde ($length, $code, $uid, $DATA="") {
1228 // Fix missing _MAX constant
1229 // @TODO Rewrite this unnice code
1230 if (!defined('_MAX')) define('_MAX', 15235);
1232 // Build server string
1233 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
1236 $keys = constant('SITE_KEY').":".constant('DATE_KEY');
1237 if (isConfigEntrySet('secret_key')) $keys .= ":".getConfig('secret_key');
1238 if (isConfigEntrySet('file_hash')) $keys .= ":".getConfig('file_hash');
1239 $keys .= ":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1240 if (isConfigEntrySet('master_salt')) $keys .= ":".getConfig('master_salt');
1242 // Build string from misc data
1243 $data = $code.":".$uid.":".$DATA;
1245 // Add more additional data
1246 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1247 if (isUserIdSet()) $data .= ":".getUserId();
1248 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1249 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1250 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1252 // Calculate number for generating the code
1253 $a = $code + constant('_ADD') - 1;
1255 if (isConfigEntrySet('master_hash')) {
1256 // Generate hash with master salt from modula of number with the prime number and other data
1257 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1259 // Create number from hash
1260 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1262 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1263 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1265 // Create number from hash
1266 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1269 // At least 10 numbers shall be secure enought!
1270 $len = getConfig('code_length');
1271 if ($len == 0) $len = $length;
1272 if ($len == 0) $len = 10;
1274 // Cut off requested counts of number
1275 $return = substr(str_replace('.', "", $rcode), 0, $len);
1277 // Done building code
1281 // Does only allow numbers
1282 function bigintval ($num, $castValue = true) {
1283 // Filter all numbers out
1284 $ret = preg_replace("/[^0123456789]/", "", $num);
1287 if ($castValue) $ret = (double)$ret;
1289 // Has the whole value changed?
1290 // @TODO Remove this if() block if all is working fine
1291 if ("".$ret."" != "".$num."") {
1293 debug_report_bug("{$ret}<>{$num}");
1300 // Insert the code in $img_code into jpeg or PNG image
1301 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1302 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1303 // Stop execution of function here because of over-sized code length
1305 } elseif (!$headerSent) {
1306 // Return in an HTML code code
1307 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1311 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1312 if (FILE_READABLE($img)) {
1313 // Switch image type
1314 switch (getConfig('img_type'))
1317 // Okay, load image and hide all errors
1318 $image = @imagecreatefromjpeg($img);
1322 // Okay, load image and hide all errors
1323 $image = @imagecreatefrompng($img);
1327 // Exit function here
1328 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1332 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1333 $text_color = imagecolorallocate($image, 0, 0, 0);
1335 // Insert code into image
1336 imagestring($image, 5, 14, 2, $img_code, $text_color);
1338 // Return to browser
1339 header ("Content-Type: image/".getConfig('img_type'));
1341 // Output image with matching image factory
1342 switch (getConfig('img_type')) {
1343 case "jpg": imagejpeg($image); break;
1344 case "png": imagepng($image); break;
1347 // Remove image from memory
1348 imagedestroy($image);
1350 // Create selection box or array of splitted timestamp
1351 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1352 // Calculate 2-seconds timestamp
1353 $stamp = round($timestamp);
1354 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1356 // Do we have a leap year?
1358 $TEST = date('Y', time()) / 4;
1359 $M1 = date("m", time());
1360 $M2 = date("m", (time() + $timestamp));
1362 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1363 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1365 // First of all years...
1366 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1367 //* DEBUG: */ print("Y={$Y}<br />\n");
1369 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1370 //* DEBUG: */ print("M={$M}<br />\n");
1372 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1373 //* DEBUG: */ print("W={$W}<br />\n");
1375 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1376 //* DEBUG: */ print("D={$D}<br />\n");
1378 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
1379 //* DEBUG: */ print("h={$h}<br />\n");
1381 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1382 //* DEBUG: */ print("m={$m}<br />\n");
1383 // And at last seconds...
1384 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1385 //* DEBUG: */ print("s={$s}<br />\n");
1387 // Is seconds zero and time is < 60 seconds?
1388 if (($s == 0) && ($timestamp < 60)) {
1390 $s = round($timestamp);
1394 // Now we convert them in seconds...
1396 if ($return_array) {
1397 // Just put all data in an array for later use
1409 $OUT = "<div align=\"".$align."\">\n";
1410 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1413 if (ereg('Y', $display) || (empty($display))) {
1414 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1417 if (ereg("M", $display) || (empty($display))) {
1418 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1421 if (ereg("W", $display) || (empty($display))) {
1422 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1425 if (ereg("D", $display) || (empty($display))) {
1426 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1429 if (ereg("h", $display) || (empty($display))) {
1430 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1433 if (ereg("m", $display) || (empty($display))) {
1434 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1437 if (ereg("s", $display) || (empty($display))) {
1438 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1444 if (ereg('Y', $display) || (empty($display))) {
1445 // Generate year selection
1446 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1447 for ($idx = 0; $idx <= 10; $idx++) {
1448 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1449 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1450 $OUT .= ">".$idx."</option>\n";
1452 $OUT .= " </select></td>\n";
1454 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1457 if (ereg("M", $display) || (empty($display))) {
1458 // Generate month selection
1459 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1460 for ($idx = 0; $idx <= 11; $idx++)
1462 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1463 if ($idx == $M) $OUT .= " selected=\"selected\"";
1464 $OUT .= ">".$idx."</option>\n";
1466 $OUT .= " </select></td>\n";
1468 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1471 if (ereg("W", $display) || (empty($display))) {
1472 // Generate week selection
1473 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1474 for ($idx = 0; $idx <= 4; $idx++) {
1475 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1476 if ($idx == $W) $OUT .= " selected=\"selected\"";
1477 $OUT .= ">".$idx."</option>\n";
1479 $OUT .= " </select></td>\n";
1481 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1484 if (ereg("D", $display) || (empty($display))) {
1485 // Generate day selection
1486 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1487 for ($idx = 0; $idx <= 31; $idx++) {
1488 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1489 if ($idx == $D) $OUT .= " selected=\"selected\"";
1490 $OUT .= ">".$idx."</option>\n";
1492 $OUT .= " </select></td>\n";
1494 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1497 if (ereg("h", $display) || (empty($display))) {
1498 // Generate hour selection
1499 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1500 for ($idx = 0; $idx <= 23; $idx++) {
1501 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1502 if ($idx == $h) $OUT .= " selected=\"selected\"";
1503 $OUT .= ">".$idx."</option>\n";
1505 $OUT .= " </select></td>\n";
1507 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1510 if (ereg("m", $display) || (empty($display))) {
1511 // Generate minute selection
1512 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1513 for ($idx = 0; $idx <= 59; $idx++) {
1514 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1515 if ($idx == $m) $OUT .= " selected=\"selected\"";
1516 $OUT .= ">".$idx."</option>\n";
1518 $OUT .= " </select></td>\n";
1520 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1523 if (ereg("s", $display) || (empty($display))) {
1524 // Generate second selection
1525 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1526 for ($idx = 0; $idx <= 59; $idx++) {
1527 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1528 if ($idx == $s) $OUT .= " selected=\"selected\"";
1529 $OUT .= ">".$idx."</option>\n";
1531 $OUT .= " </select></td>\n";
1533 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1536 $OUT .= "</table>\n";
1538 // Return generated HTML code
1544 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1545 // Initial return value
1548 // Do we have a leap year?
1550 $TEST = date('Y', time()) / 4;
1551 $M1 = date("m", time());
1552 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1553 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1554 // First add years...
1555 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1557 $ret += $POST[$prefix."_mo"] * 2628000;
1559 $ret += $POST[$prefix."_we"] * 604800;
1561 $ret += $POST[$prefix."_da"] * 86400;
1563 $ret += $POST[$prefix."_ho"] * 3600;
1565 $ret += $POST[$prefix."_mi"] * 60;
1566 // And at last seconds...
1567 $ret += $POST[$prefix."_se"];
1568 // Return calculated value
1572 // Sends out mail to all administrators
1573 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1574 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1575 // Trim template name
1576 $template = trim($template);
1578 // Load email template
1579 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1581 // Check which admin shall receive this mail
1582 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1583 array($template), __FUNCTION__, __LINE__);
1584 if (SQL_NUMROWS($result) == 0) {
1585 // Create new entry (to all admins)
1586 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1587 array($template), __FUNCTION__, __LINE__);
1589 // Load admin IDs...
1590 // @TODO This can be, somehow, rewritten
1591 $adminIds = array();
1592 while ($content = SQL_FETCHARRAY($result)) {
1593 $adminIds[] = $content['admin_id'];
1597 SQL_FREERESULT($result);
1602 // "implode" IDs and query string
1603 $aid = implode(",", $adminIds);
1605 if (EXT_IS_ACTIVE("events")) {
1606 // Add line to user events
1607 EVENTS_ADD_LINE($subj, $msg, $UID);
1609 // Log error for debug
1610 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1616 } elseif ($aid == "0") {
1617 // Select all email adresses
1618 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1619 __FUNCTION__, __LINE__);
1621 // If Admin-ID is not "to-all" select
1622 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1623 array($aid), __FUNCTION__, __LINE__);
1627 // Load email addresses and send away
1628 while ($content = SQL_FETCHARRAY($result)) {
1629 SEND_EMAIL($content['email'], $subj, $msg);
1633 SQL_FREERESULT($result);
1637 function CREATE_FANCY_TIME ($stamp) {
1638 // Get data array with years/months/weeks/days/...
1639 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1641 foreach($data as $k => $v) {
1643 // Value is greater than 0 "eval" data to return string
1644 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1650 // Do we have something there?
1651 if (strlen($ret) > 0) {
1652 // Remove leading commata and space
1653 $ret = substr($ret, 2);
1656 $ret = "0 {--_SECONDS--}";
1659 // Return fancy time string
1664 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1665 $SEP = ""; $TOP = "";
1668 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1672 for ($page = 1; $page <= $PAGES; $page++) {
1673 // Is the page currently selected or shall we generate a link to it?
1674 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1675 // Is currently selected, so only highlight it
1676 $NAV .= "<strong>-";
1678 // Open anchor tag and add base URL
1679 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1681 // Add userid when we shall show all mails from a single member
1682 if ((REQUEST_ISSET_GET(('uid'))) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1684 // Close open anchor tag
1688 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1689 // Is currently selected, so only highlight it
1690 $NAV .= "-</strong>";
1696 // Add seperator if we have not yet reached total pages
1697 if ($page < $PAGES) $NAV .= " | ";
1700 // Define constants only once
1701 if (!defined('__NAV_OUTPUT')) {
1702 define('__NAV_OUTPUT' , $NAV);
1703 define('__NAV_COLSPAN', $colspan);
1704 define('__NAV_TOP' , $TOP);
1705 define('__NAV_SEP' , $SEP);
1708 // Load navigation template
1709 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1711 if ($return === true) {
1712 // Return generated HTML-Code
1720 // Extract host from script name
1721 function EXTRACT_HOST (&$script) {
1722 // Use default SERVER_URL by default... ;) So?
1723 $url = constant('SERVER_URL');
1725 // Is this URL valid?
1726 if (substr($script, 0, 7) == "http://") {
1727 // Use the hostname from script URL as new hostname
1728 $url = substr($script, 7);
1729 $extract = explode("/", $url);
1731 // Done extracting the URL :)
1734 // Extract host name
1735 $host = str_replace("http://", "", $url);
1736 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1738 // Generate relative URL
1739 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1740 if (substr(strtolower($script), 0, 7) == "http://") {
1741 // But only if http:// is in front!
1742 $script = substr($script, (strlen($url) + 7));
1743 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1745 $script = substr($script, (strlen($url) + 8));
1748 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1749 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1755 // Send a GET request
1756 function GET_URL ($script) {
1757 // Compile the script name
1758 $script = COMPILE_CODE($script);
1760 // Extract host name from script
1761 $host = EXTRACT_HOST($script);
1763 // Generate GET request header
1764 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1765 $request .= "Host: " . $host . "\r\n";
1766 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1767 if (defined('FULL_VERSION')) {
1768 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1770 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1772 $request .= "Content-Type: text/plain\r\n";
1773 $request .= "Cache-Control: no-cache\r\n";
1774 $request .= "Connection: Close\r\n\r\n";
1776 // Send the raw request
1777 $response = SEND_RAW_REQUEST($host, $request);
1779 // Return the result to the caller function
1783 // Send a POST request
1784 function POST_URL ($script, $postData) {
1785 // Is postData an array?
1786 if (!is_array($postData)) {
1788 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1789 return array("", "", "");
1792 // Compile the script name
1793 $script = COMPILE_CODE($script);
1795 // Extract host name from script
1796 $host = EXTRACT_HOST($script);
1798 // Construct request
1799 $data = http_build_query($postData, '','&');
1801 // Generate POST request header
1802 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1803 $request .= "Host: " . $host . "\r\n";
1804 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1805 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1806 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1807 $request .= "Content-length: " . strlen($data) . "\r\n";
1808 $request .= "Cache-Control: no-cache\r\n";
1809 $request .= "Connection: Close\r\n\r\n";
1812 // Send the raw request
1813 $response = SEND_RAW_REQUEST($host, $request);
1815 // Return the result to the caller function
1819 // Sends a raw request to another host
1820 function SEND_RAW_REQUEST ($host, $request) {
1822 $response = array("", "", "");
1824 // Default is not to use proxy
1827 // Are proxy settins set?
1828 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1834 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1836 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1838 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1842 if (!is_resource($fp)) {
1849 // Generate CONNECT request header
1850 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1851 $proxyTunnel .= "Host: ".$host."\r\n";
1853 // Use login data to proxy? (username at least!)
1854 if (getConfig('proxy_username') != "") {
1856 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1857 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1860 // Add last new-line
1861 $proxyTunnel .= "\r\n";
1862 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1865 fputs($fp, $proxyTunnel);
1869 // No response received
1873 // Read the first line
1874 $resp = trim(fgets($fp, 10240));
1875 $respArray = explode(" ", $resp);
1876 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1877 // Invalid response!
1883 fputs($fp, $request);
1886 while (!feof($fp)) {
1887 $response[] = trim(fgets($fp, 1024));
1893 // Skip first empty lines
1895 foreach ($resp as $idx => $line) {
1897 $line = trim($line);
1899 // Is this line empty?
1902 array_shift($response);
1904 // Abort on first non-empty line
1909 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1911 // Proxy agent found?
1912 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1913 // Proxy header detected, so remove two lines
1914 array_shift($response);
1915 array_shift($response);
1918 // Was the request successfull?
1919 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1920 // Not found / access forbidden
1921 $response = array("", "", "");
1928 // Taken from www.php.net eregi() user comments
1929 function VALIDATE_EMAIL ($email) {
1931 $email = COMPILE_CODE($email);
1933 // Check first part of email address
1934 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1937 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1940 $regex = "^".$first."@".$domain."$";
1942 // Return check result
1943 return eregi($regex, $email);
1946 // Function taken from user comments on www.php.net / function eregi()
1947 function VALIDATE_URL ($URL, $compile=true) {
1948 // Trim URL a little
1949 $URL = trim(urldecode($URL));
1950 //* DEBUG: */ echo $URL."<br />";
1952 // Compile some chars out...
1953 if ($compile) $URL = compileUriCode($URL, false, false, false);
1954 //* DEBUG: */ echo $URL."<br />";
1956 // Check for the extension filter
1957 if (EXT_IS_ACTIVE("filter")) {
1958 // Use the extension's filter set
1959 return FILTER_VALIDATE_URL($URL, false);
1962 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1963 // https:// in front of the URLs
1964 return isUrlValid($URL);
1967 // Generate a list of administrative links to a given userid
1968 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1969 // Define all main targets
1970 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1972 // Begin of navigation links
1973 $eval = "\$OUT = \"[ ";
1975 foreach ($TARGETS as $tar) {
1976 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1977 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1978 if (($tar == "lock_user") && ($status == "LOCKED")) {
1979 // Locked accounts shall be unlocked
1980 $eval .= "UNLOCK_USER";
1982 // All other status is fine
1983 $eval .= strtoupper($tar);
1985 $eval .= "_TITLE--}\\\">{--ADMIN_";
1986 if (($tar == "lock_user") && ($status == "LOCKED")) {
1987 // Locked accounts shall be unlocked
1988 $eval .= "UNLOCK_USER";
1990 // All other status is fine
1991 $eval .= strtoupper($tar);
1993 $eval .= "--}</a></span> | ";
1996 // Finish navigation link
1997 $eval = substr($eval, 0, -7)."]\";";
2004 // Generate an email link
2005 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2006 // Default email link (INSECURE! Spammer can read this by harvester programs)
2007 $EMAIL = "mailto:".$email;
2009 // Check for several extensions
2010 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2011 // Create email link for contacting admin in guest area
2012 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2013 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2014 // Create email link for contacting a member within admin area (or later in other areas, too?)
2015 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2016 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2017 // Create email link to contact sponsor within admin area (or like the link above?)
2018 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2021 // Shall I close the link when there is no admin?
2022 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2024 // Return email link
2028 // Generate a hash for extra-security for all passwords
2029 function generateHash ($plainText, $salt = "") {
2030 // Is the required extension "sql_patches" there and a salt is not given?
2031 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2032 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2033 return md5($plainText);
2036 // Do we miss an arry element here?
2037 if (!isConfigEntrySet('file_hash')) {
2039 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2042 // When the salt is empty build a new one, else use the first x configured characters as the salt
2044 // Build server string
2045 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
2048 $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');
2051 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2053 // Calculate number for generating the code
2054 $a = time() + constant('_ADD') - 1;
2056 // Generate SHA1 sum from modula of number and the prime number
2057 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2058 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2059 $sha1 = scrambleString($sha1);
2060 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2061 //* DEBUG: */ $sha1b = descrambleString($sha1);
2062 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2064 // Generate the password salt string
2065 $salt = substr($sha1, 0, getConfig('salt_length'));
2066 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2069 $salt = substr($salt, 0, getConfig('salt_length'));
2070 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2074 return $salt.sha1($salt.$plainText);
2077 // Scramble a string
2078 function scrambleString($str) {
2082 // Final check, in case of failture it will return unscrambled string
2083 if (strlen($str) > 40) {
2084 // The string is to long
2086 } elseif (strlen($str) == 40) {
2088 $scrambleNums = explode(":", getConfig('pass_scramble'));
2090 // Generate new numbers
2091 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2094 // Scramble string here
2095 //* DEBUG: */ echo "***Original=".$str."***<br />";
2096 for ($idx = 0; $idx < strlen($str); $idx++) {
2097 // Get char on scrambled position
2098 $char = substr($str, $scrambleNums[$idx], 1);
2100 // Add it to final output string
2101 $scrambled .= $char;
2104 // Return scrambled string
2105 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2109 // De-scramble a string scrambled by scrambleString()
2110 function descrambleString($str) {
2111 // Scramble only 40 chars long strings
2112 if (strlen($str) != 40) return $str;
2114 // Load numbers from config
2115 $scrambleNums = explode(":", getConfig('pass_scramble'));
2118 if (count($scrambleNums) != 40) return $str;
2120 // Begin descrambling
2121 $orig = str_repeat(" ", 40);
2122 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2123 for ($idx = 0; $idx < 40; $idx++) {
2124 $char = substr($str, $idx, 1);
2125 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2128 // Return scrambled string
2129 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2133 // Generated a "string" for scrambling
2134 function genScrambleString ($len) {
2135 // Prepare array for the numbers
2136 $scrambleNumbers = array();
2138 // First we need to setup randomized numbers from 0 to 31
2139 for ($idx = 0; $idx < $len; $idx++) {
2141 $rand = mt_rand(0, ($len -1));
2143 // Check for it by creating more numbers
2144 while (array_key_exists($rand, $scrambleNumbers)) {
2145 $rand = mt_rand(0, ($len -1));
2149 $scrambleNumbers[$rand] = $rand;
2152 // So let's create the string for storing it in database
2153 $scrambleString = implode(":", $scrambleNumbers);
2154 return $scrambleString;
2157 // Append data like session ID or referal ID to the given URL which would
2158 // normally be stored in cookies
2159 function ADD_URL_DATA ($URL) {
2163 // Determine URL binder
2165 if (strpos($URL, "?") !== false) $BIND = "&";
2167 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2168 // Cookies are not accepted
2169 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2170 // Cookie found in URL
2171 $add .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2172 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2173 // Not found! So let's set default here
2174 $add .= $BIND."refid=".getConfig('def_refid');
2178 // Add all together and return it
2182 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2183 function generatePassString ($passHash) {
2184 // Return vanilla password hash
2187 // Is a secret key and master salt already initialized?
2188 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2189 // Only calculate when the secret key is generated
2190 $newHash = ""; $start = 9;
2191 for ($idx = 0; $idx < 10; $idx++) {
2192 $part1 = hexdec(substr($passHash, $start, 4));
2193 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2194 $mod = dechex($idx);
2195 if ($part1 > $part2) {
2196 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2197 } elseif ($part2 > $part1) {
2198 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2200 $mod = substr(round($mod), 0, 4);
2201 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2202 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2207 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2208 $ret = generateHash($newHash, getConfig('master_salt'));
2209 //* DEBUG: */ print($ret."<br />\n");
2212 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2213 $ret = md5($passHash);
2214 //* DEBUG: */ echo "++".$ret."++<br />\n";
2221 // Fix "deleted" cookies
2222 function FIX_DELETED_COOKIES ($cookies) {
2223 // Is this an array with entries?
2224 if ((is_array($cookies)) && (count($cookies) > 0)) {
2225 // Then check all cookies if they are marked as deleted!
2226 foreach ($cookies as $cookieName) {
2227 // Is the cookie set to "deleted"?
2228 if (get_session($cookieName) == "deleted") {
2229 set_session($cookieName, "");
2235 // Output error messages in a fasioned way and die...
2236 function mxchange_die ($msg) {
2238 LOAD_INC_ONCE("inc/header.php");
2240 // Load the message template
2241 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2244 LOAD_INC_ONCE("inc/footer.php");
2250 // Display parsing time and number of SQL queries in footer
2251 function DISPLAY_PARSING_TIME_FOOTER() {
2252 // Is the timer started?
2253 if (!isset($GLOBALS['startTime'])) {
2259 $endTime = microtime(true);
2261 // "Explode" both times
2262 $start = explode(" ", $GLOBALS['startTime']);
2263 $end = explode(" ", $endTime);
2264 $runTime = $end[0] - $start[0];
2265 if ($runTime < 0) $runTime = 0;
2266 $runTime = TRANSLATE_COMMA($runTime);
2270 'runtime' => $runTime,
2271 'numSQLs' => (getConfig('sql_count') + 1),
2272 'numTemplates' => (getConfig('num_templates') + 1)
2275 // Load the template
2276 LOAD_TEMPLATE("show_timings", false, $content);
2279 // Check wether a boolean constant is set
2280 // Taken from user comments in PHP documentation for function constant()
2281 function isBooleanConstantAndTrue ($constName) { // : Boolean
2282 // Failed by default
2286 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2288 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2289 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2292 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2293 if (defined($constName)) {
2295 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2296 $res = (constant($constName) === true);
2300 $GLOBALS['cache_array']['const'][$constName] = $res;
2302 //* DEBUG: */ var_dump($res);
2308 // Checks if a given apache module is loaded
2309 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2310 // Check it and return result
2311 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2314 // "Getter" for language strings
2315 // @TODO Rewrite all language constants to this function.
2316 function getMessage ($messageId) {
2317 // Default is not found!
2318 $return = "!".$messageId."!";
2320 // Is the language string found?
2321 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2322 // Language array element found in small_letters
2323 $return = $GLOBALS['msg'][$messageId];
2324 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2325 // @DEPRECATED Language array element found in BIG_LETTERS
2326 $return = $GLOBALS['msg'][$messageId];
2327 } elseif (defined($messageId)) {
2328 // @DEPRECATED Deprecated constant found
2329 $return = constant($messageId);
2331 // Missing language constant
2332 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2335 // Return the string
2339 // Get current theme name
2340 function GET_CURR_THEME() {
2341 // The default theme is 'default'... ;-)
2344 // Load default theme if not empty from configuration
2345 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2347 if (!isSessionVariableSet('mxchange_theme')) {
2348 // Set default theme
2349 set_session('mxchange_theme', $ret);
2350 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2351 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2352 // Get theme from cookie
2353 $ret = get_session('mxchange_theme');
2356 if (THEME_GET_ID($ret) == 0) {
2357 // Fix it to default
2360 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
2361 // Prepare FQFN for checking
2362 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
2364 // Installation mode active
2365 if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
2366 // Set cookie from URL data
2367 set_session('mxchange_theme', REQUEST_GET(('theme')));
2368 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2369 // Set cookie from posted data
2370 set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2374 $ret = get_session('mxchange_theme');
2376 // Invalid design, reset cookie
2377 set_session('mxchange_theme', $ret);
2380 // Add (maybe) found theme.php file to inclusion list
2381 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2383 // Try to load the requested include file
2384 if (INCLUDE_READABLE($INC)) ADD_INC_TO_POOL($INC);
2386 // Return theme value
2390 // Get id from theme
2391 function THEME_GET_ID ($name) {
2392 // Is the extension "theme" installed?
2393 if (!EXT_IS_ACTIVE("theme")) {
2401 // Is the cache entry there?
2402 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2403 // Get the version from cache
2404 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2407 incrementConfigEntry('cache_hits');
2408 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2409 // Check if current theme is already imported or not
2410 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2411 array($name), __FUNCTION__, __LINE__);
2414 if (SQL_NUMROWS($result) == 1) {
2416 list($id) = SQL_FETCHROW($result);
2420 SQL_FREERESULT($result);
2427 // Read a given file
2428 function READ_FILE ($FQFN, $sqlPrepare = false) {
2430 if (function_exists('file_get_contents')) {
2432 $content = file_get_contents($FQFN);
2434 // Fall-back to implode-file chain
2435 $content = implode("", file($FQFN));
2438 // Prepare SQL queries?
2439 if ($sqlPrepare === true) {
2440 // Remove some unwanted chars
2441 $content = str_replace("\r", "", $content);
2442 $content = str_replace("\n\n", "\n", $content);
2445 // Return the content
2449 // Writes content to a file
2450 function WRITE_FILE ($FQFN, $content) {
2451 // Is the file writeable?
2452 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2454 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2460 // By default all is failed...
2463 // Is the function there?
2464 if (function_exists('file_put_contents')) {
2465 // Write it directly
2466 $return = file_put_contents($FQFN, $content);
2468 // Write it with fopen
2469 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
2470 fwrite($fp, $content);
2474 $return = chmod($FQFN, 0644);
2481 // Generates an error code from given account status
2482 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
2483 // Default error code if unknown account status
2484 $ERROR = getCode('UNKNOWN_STATUS');
2486 // Generate constant name
2487 $constantName = sprintf("ID_%s", $status);
2489 // Is the constant there?
2490 if (isCodeSet($constantName)) {
2492 $ERROR = getCode($constantName);
2495 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2498 // Return error code
2502 // Clears the output buffer. This function does *NOT* backup sent content.
2503 function clearOutputBuffer () {
2504 // Trigger an error on failure
2505 if (!ob_end_clean()) {
2507 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
2511 // Function to search for the last modifified file
2512 function searchDirsRecursive ($dir, &$last_changed) {
2514 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2515 $ds = GET_DIR_AS_ARRAY($dir, "", true, false);
2516 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2518 // Walk through all entries
2519 foreach ($ds as $d) {
2520 // Generate proper FQFN
2521 $FQFN = str_replace("//", "/", constant('PATH') . $dir. "/". $d);
2523 // Does it match what we are looking for? (We skip a lot files already!)
2524 if (!preg_match('@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@', $d)) { // no ., .., .revision, .svn, debug.log or .cache in the filename
2526 // Is it a file and readable?
2527 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2528 if (isDirectory($FQFN)) {
2529 // $FQFN is a directory so also crawl into this directory
2531 if (!empty($dir)) $newDir = $dir . "/". $d;
2532 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2533 searchDirsRecursive($newDir, $last_changed);
2534 } elseif (FILE_READABLE($FQFN)) {
2535 // $FQFN is a filename and no directory
2536 $time = filemtime($FQFN);
2537 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2538 if ($last_changed['time'] < $time) {
2539 // This file is newer as the file before
2540 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2541 $last_changed['path_name'] = $FQFN;
2542 $last_changed['time'] = $time;
2549 // "Getter" for revision/version data
2550 function getActualVersion ($type = 'Revision') {
2551 // By default nothing is new... ;-)
2554 if (EXT_IS_ACTIVE("cache")) {
2555 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2556 if (isset($_GET['check_revision_data']) && $_GET['check_revision_data'] == 'yes') $new = true;
2557 if (!isset($GLOBALS['cache_array']['revision'][$type])
2558 || count($GLOBALS['cache_array']['revision']) < 3
2559 || !$GLOBALS['cache_instance']->loadCacheFile("revision")) $new = true;
2561 // Is the cache file outdated/invalid?
2563 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2565 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2566 unset($GLOBALS['cache_array']['revision']);
2568 // Reload load_cach-revison.php
2569 LOAD_INC("inc/loader/load_cache-revision.php");
2572 // Return found value
2573 return $GLOBALS['cache_array']['revision'][$type][0];
2576 // Old Version without ext-cache active (deprecated ?)
2578 // FQFN of revision file
2579 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2581 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2582 if ((isset($_GET['check_revision_data'])) && ($_GET['check_revision_data'] == 'yes')) {
2586 // Check for revision file
2587 if (!FILE_READABLE($FQFN)) {
2588 // Not found, so we need to create it
2591 // Revision file found
2592 $ins_vers = explode("\n", READ_FILE($FQFN));
2594 // Get array for mapping information
2595 $mapper = array_flip(getSearchFor());
2596 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2598 // Is the content valid?
2599 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == "") || ($ins_vers[0]) == "new") {
2600 // File needs update!
2603 // Return found value
2604 return trim($ins_vers[$mapper[$type]]);
2609 // Has it been updated?
2610 if ($new === true) {
2611 WRITE_FILE($FQFN, implode("\n", getAkt_vers()));
2616 // Repares an array we are looking for
2617 // 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
2618 function getSearchFor () {
2619 // Add Revision, Date, Tag and Author
2620 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2622 // Return the created array
2626 function getAkt_vers () {
2628 $next_dir = ""; // Directory to start with search
2629 $last_changed = array(
2633 $akt_vers = array(); // Init return array
2634 $res = 0; // Init value for counting the founded keywords
2636 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2637 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2640 $last_file = READ_FILE($last_changed['path_name']);
2642 // Get all the keywords to search for
2643 $searchFor = getSearchFor();
2645 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2646 foreach ($searchFor as $search) {
2647 //Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2648 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2649 // This trimms the search-result and puts it in the $akt_vers-return array
2650 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2653 // Save the last-changed filename for debugging
2654 $akt_vers['File'] = $last_changed['path_name'];
2656 // at least 3 keyword-Tags are needed for propper values
2657 if ($res && $res >= 3
2658 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2659 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2660 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2661 // Prepare content witch need special treadment
2663 // Prepare timestamp for date
2664 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2665 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2667 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2668 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2669 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2673 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2674 $version = GET_URL("check-updates3.php");
2677 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2678 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2679 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2680 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2681 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2684 // Return prepared array
2689 // Loads an include file and logs any missing files for debug purposes
2690 function LOAD_INC ($INC) {
2691 // Add the path. This is why we need a trailing slash in config.php
2692 $FQFN = constant('PATH') . $INC;
2694 // Is the include file there?
2695 if (!INCLUDE_READABLE($INC)) {
2696 // Not there so log it
2697 debug_report_bug(sprintf("Include file %s not found.", $INC));
2705 // Loads an include file once
2706 function LOAD_INC_ONCE ($INC) {
2707 // Is it not loaded?
2708 if (!isset($GLOBALS['load_once'][$INC])) {
2709 // Then try to load it
2712 // And mark it as loaded
2713 $GLOBALS['load_once'][$INC] = "loaded";
2717 // Back-ported from the new ship-simu engine. :-)
2718 function debug_get_printable_backtrace () {
2720 $backtrace = "<ol>\n";
2722 // Get and prepare backtrace for output
2723 $backtraceArray = debug_backtrace();
2724 foreach ($backtraceArray as $key => $trace) {
2725 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2726 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2727 if (!isset($trace['args'])) $trace['args'] = array();
2728 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span></li>\n";
2732 $backtrace .= "</ol>\n";
2734 // Return the backtrace
2738 // Output a debug backtrace to the user
2739 function debug_report_bug ($message = "") {
2742 // Is the optional message set?
2743 if (!empty($message)) {
2745 $debug = sprintf("Note: %s<br />\n",
2749 // @TODO Add a little more infos here
2750 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2754 $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2755 $debug .= debug_get_printable_backtrace();
2756 $debug .= "</pre>Request-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2757 $debug .= "Thank you for finding bugs.";
2760 // @TODO This cannot be rewritten to mxchange_die(), try to find a solution for this.
2764 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2765 function generateSeed () {
2766 list($usec, $sec) = explode(" ", microtime());
2767 return ((float)$sec + (float)$usec);
2770 // Converts a message code to a human-readable message
2771 function convertCodeToMessage ($code) {
2774 case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2775 case getCode('LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2776 case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2777 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2778 case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2779 case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2780 case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2781 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2783 case getCode('ERROR_MAILID'):
2784 if (EXT_IS_ACTIVE($ext, true)) {
2785 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2787 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
2791 case getCode('EXTENSION_PROBLEM'):
2792 if (REQUEST_ISSET_GET(('ext'))) {
2793 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2795 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2799 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2800 case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2801 case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2802 case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2805 // Missing/invalid code
2806 $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2809 DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2813 // Return the message
2817 // Checks wether the given extension is currently not installed
2818 // and redirects if so.
2819 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
2820 // Is the extension uninstalled/inactive?
2821 if (!EXT_IS_ACTIVE($ext_name)) {
2822 // Redirect to index
2823 LOAD_URL("modules.php?module=index&msg=".getCode('EXTENSION_PROBLEM')."&ext=".$ext_name);
2827 // Generate a "link" for the given admin id (aid)
2828 function GENERATE_AID_LINK ($aid) {
2829 // No assigned admin is default
2830 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2832 // Zero? = Not assigned
2834 // Load admin's login
2835 $login = GET_ADMIN_LOGIN($aid);
2836 if ($login != "***") {
2837 // Is the extension there?
2838 if (EXT_IS_ACTIVE("admins")) {
2840 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
2842 // Extension not found
2843 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
2847 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2855 // Checks wether an include file (non-FQFN better) is readable
2856 function INCLUDE_READABLE ($INC) {
2858 $FQFN = constant('PATH') . $INC;
2861 return FILE_READABLE($FQFN);
2865 // @TODO Implement $compress
2866 function encodeString ($str, $compress=true) {
2867 $str = urlencode(base64_encode(compileUriCode($str)));
2871 // Decode strings encoded with encodeString()
2872 // @TODO Implement $decompress
2873 function decodeString ($str, $decompress=true) {
2874 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2878 // Compile characters which are allowed in URLs
2879 function compileUriCode ($code, $simple=true) {
2880 // Compile constants
2881 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2883 // Compile QUOT and other non-HTML codes
2884 $code = str_replace("{DOT}", ".",
2885 str_replace("{SLASH}", "/",
2886 str_replace("{QUOT}", "'",
2887 str_replace("{DOLLAR}", "$",
2888 str_replace("{OPEN_ANCHOR}", "(",
2889 str_replace("{CLOSE_ANCHOR}", ")",
2890 str_replace("{OPEN_SQR}", "[",
2891 str_replace("{CLOSE_SQR}", "]",
2892 str_replace("{PER}", "%",
2896 // Return compiled code
2900 // Function taken from user comments on www.php.net / function eregi()
2901 function isUrlValid ($url) {
2903 $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
2905 // Allows http and https
2906 $http = "(http|https)+(:\/\/)";
2908 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2909 // Test double-domains (e.g. .de.vu)
2910 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2912 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2914 $dir = "((/)+([-_\.[:alnum:]])+)*";
2916 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2917 // ... and the string after and including question character
2918 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2919 // Pattern for URLs like http://url/dir/doc.html?var=value
2920 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2921 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2922 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2923 // Pattern for URLs like http://url/dir/?var=value
2924 $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
2925 $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
2926 $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
2927 // Pattern for URLs like http://url/dir/page.ext
2928 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2929 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2930 $pattern['ipdp'] = $http.$ip.$dir.$page;
2931 // Pattern for URLs like http://url/dir
2932 $pattern['d1d'] = $http.$domain1.$dir;
2933 $pattern['d2d'] = $http.$domain2.$dir;
2934 $pattern['ipd'] = $http.$ip.$dir;
2935 // Pattern for URLs like http://url/?var=value
2936 $pattern['d1g1'] = $http.$domain1."/".$getstring1;
2937 $pattern['d2g1'] = $http.$domain2."/".$getstring1;
2938 $pattern['ipg1'] = $http.$ip."/".$getstring1;
2939 // Pattern for URLs like http://url?var=value
2940 $pattern['d1g12'] = $http.$domain1.$getstring1;
2941 $pattern['d2g12'] = $http.$domain2.$getstring1;
2942 $pattern['ipg12'] = $http.$ip.$getstring1;
2943 // Test all patterns
2945 foreach ($pattern as $key=>$pat) {
2947 if (defined('DEBUG_REGEX')) {
2948 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2949 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2950 $pat = str_replace("[:digit:]", "0-9", $pat);
2951 $pat = str_replace(".", "\.", $pat);
2952 $pat = str_replace("@", "\@", $pat);
2953 echo $key."= ".$pat."<br />";
2956 // Check if expression matches
2957 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2960 if ($reg === true) break;
2963 // Return true/false
2967 // Smartly adds slashes
2968 function smartAddSlashes ($unquoted) {
2969 $unquoted = str_replace("\\", "", $unquoted);
2970 return addslashes($unquoted);
2973 // Decode entities in a nicer way
2974 function decodeEntities ($str) {
2975 // @TODO We may want to switch over to UTF-8 here!
2976 $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
2978 // Return decoded string
2979 return $decodedString;
2982 // Wtites data to a config.php-style file
2983 // @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
2984 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2985 // Initialize some variables
2991 // Is the file there and read-/write-able?
2992 if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
2993 $search = "CFG: ".$comment;
2994 $tmp = $FQFN.".tmp";
2996 // Open the source file
2997 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2999 // Is the resource valid?
3000 if (is_resource($fp)) {
3001 // Open temporary file
3002 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
3004 // Is the resource again valid?
3005 if (is_resource($fp_tmp)) {
3006 while (!feof($fp)) {
3007 // Read from source file
3008 $line = fgets ($fp, 1024);
3010 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
3013 if ($next === $seek) {
3015 $line = $prefix . $DATA . $suffix."\n";
3021 // Write to temp file
3022 fputs($fp_tmp, $line);
3028 // Finished writing tmp file
3032 // Close source file
3035 if (($done) && ($found)) {
3036 // Copy back tmp file and delete tmp :-)
3038 return unlink($tmp);
3039 } elseif (!$found) {
3040 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
3042 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
3046 // File not found, not readable or writeable
3047 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
3050 // An error was detected!
3053 // Send notification to admin
3054 function SEND_ADMIN_NOTIFICATION ($subject, $templateName, $content=array(), $uid="0") {
3055 if (GET_EXT_VERSION("admins") >= "0.4.1") {
3057 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
3059 // Send out out-dated way
3060 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
3061 SEND_ADMIN_EMAILS($subject, $msg);
3065 // Merges an array together but only if both are arrays
3066 function merge_array ($array1, $array2) {
3067 // Are both an array?
3068 if ((is_array($array1)) && (is_array($array2))) {
3069 // Merge all together
3070 return array_merge($array1, $array2);
3071 } elseif (is_array($array1)) {
3072 // Return left array
3073 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
3075 } elseif (is_array($array2)) {
3076 // Return right array
3077 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
3081 // Both are not arrays
3082 debug_report_bug(__FUNCTION__.": No arrays provided!");
3085 // Debug message logger
3086 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
3087 // Is debug mode enabled?
3088 if ((isDebugModeEnabled()) || ($force === true)) {
3090 $message = str_replace("\r", "", str_replace("\n", "", $message));
3092 // Log this message away
3093 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
3094 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
3099 // Load more reset scripts
3100 function runResetIncludes () {
3101 // Is the reset set or old sql_patches?
3102 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
3104 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3107 // Get more daily reset scripts
3108 SET_INC_POOL(GET_DIR_AS_ARRAY("inc/reset/", "reset_"));
3111 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
3113 // Is the config entry set?
3114 if (GET_EXT_VERSION("sql_patches") >= "0.4.2") {
3115 // Create current week mark
3116 $currWeek = date("W", time());
3119 if (getConfig('last_week') != $currWeek) {
3120 // Include weekly reset scripts
3121 MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
3124 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
3127 // Create current month mark
3128 $currMonth = date("m", time());
3131 if (getConfig('last_month') != $currMonth) {
3132 // Include monthly reset scripts
3133 MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
3136 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
3141 runFilterChain('load_includes');
3144 // Handle extra values
3145 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
3146 // Default is the value itself
3149 // Do we have a special filter function?
3150 if (!empty($filterFunction)) {
3151 // Does the filter function exist?
3152 if (function_exists($filterFunction)) {
3153 // Do we have extra parameters here?
3154 if (!empty($extraValue)) {
3155 // Put both parameters in one new array by default
3156 $args = array($value, $extraValue);
3158 // If we have an array simply use it and pre-extend it with our value
3159 if (is_array($extraValue)) {
3160 // Make the new args array
3161 $args = merge_array(array($value), $extraValue);
3164 // Call the multi-parameter call-back
3165 $ret = call_user_func_array($filterFunction, $args);
3167 // One parameter call
3168 $ret = call_user_func($filterFunction, $value);
3177 // Check if given FQFN is a readable file
3178 function FILE_READABLE ($FQFN) {
3180 return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3183 // Converts timestamp selections into a timestamp
3184 function CONVERT_SELECTIONS_TO_TIMESTAMP (&$POST, &$DATA, &$id, &$skip) {
3185 // Init test variable
3188 // Get last three chars
3189 $test = substr($id, -3);
3191 // Improved way of checking! :-)
3192 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
3193 // Found a multi-selection for timings?
3194 $test = substr($id, 0, -3);
3195 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)) {
3196 // Generate timestamp
3197 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
3198 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3200 // Remove data from array
3201 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
3202 unset($POST[$test."_".$rem]);
3206 unset($id); $skip = true; $test2 = $test;
3209 // Process this entry
3215 // Reverts the german decimal comma into Computer decimal dot
3216 function REVERT_COMMA ($str) {
3217 // Default float is not a float... ;-)
3220 // Which language is selected?
3221 switch (GET_LANGUAGE()) {
3222 case "de": // German language
3223 // Remove german thousand dots first
3224 $str = str_replace(".", "", $str);
3226 // Replace german commata with decimal dot and cast it
3227 $float = (float)str_replace(",", ".", $str);
3230 default: // US and so on
3231 // Remove thousand dots first and cast
3232 $float = (float)str_replace(",", "", $str);
3240 // Handle menu-depending failed logins and return the rendered content
3241 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3242 // Default output is empty ;-)
3245 // Is the session data set?
3246 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3247 // Ignore zero values
3248 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
3249 // Non-guest has login failures found, get both data and prepare it for template
3250 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3252 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
3253 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
3257 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
3260 // Reset session data
3261 set_session('mxchange_'.$accessLevel.'_failures', "");
3262 set_session('mxchange_'.$accessLevel.'_last_fail', "");
3265 // Return rendered content
3270 function rebuildCacheFiles ($cache, $inc="") {
3271 // Shall I remove the cache file?
3272 if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
3274 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3276 $GLOBALS['cache_instance']->destroyCacheFile();
3279 // Include file given?
3282 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3284 // Is the include there?
3285 if (INCLUDE_READABLE($INC)) {
3286 // And rebuild it from scratch
3287 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3290 // Include not found!
3291 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3297 // Purge admin menu cache
3298 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
3299 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3300 if (!EXT_IS_ACTIVE("cache")) {
3301 // Cache extension not active
3303 } elseif (!isCacheInstanceValid()) {
3304 // No cache instance!
3305 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3307 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
3308 // Caching disabled (currently experiemental!)
3312 // Experiemental feature!
3313 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3316 // Translates the "pool type" into human-readable
3317 function TRANSLATE_POOL_TYPE ($type) {
3318 // Default type is unknown
3319 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
3321 // Generate constant
3322 $constName = sprintf("POOL_TYPE_%s", $type);
3325 if (defined($constName)) {
3327 $translated = getMessage($constName);
3330 // Return "translation"
3334 // Determines the real remote address
3335 function determineRealRemoteAddress () {
3336 // Is a proxy in use?
3337 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3339 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3340 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3341 // Yet, another proxy
3342 $address = $_SERVER['HTTP_CLIENT_IP'];
3344 // The regular address when no proxy was used
3345 $address = $_SERVER['REMOTE_ADDR'];
3348 // This strips out the real address from proxy output
3349 if (strstr($address, ",")){
3350 $addressArray = explode(",", $address);
3351 $address = $addressArray[0];
3354 // Return the result
3358 // "Getter" for remote IP number
3359 function GET_REMOTE_ADDR () {
3360 // Get remote ip from environment
3361 $remoteAddr = determineRealRemoteAddress();
3363 // Is removeip installed?
3364 if (EXT_IS_ACTIVE("removeip")) {
3365 // Then anonymize it
3366 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3373 // "Getter" for remote hostname
3374 function GET_REMOTE_HOST () {
3375 // Get remote ip from environment
3376 $remoteHost = getenv('REMOTE_HOST');
3378 // Is removeip installed?
3379 if (EXT_IS_ACTIVE("removeip")) {
3380 // Then anonymize it
3381 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3388 // "Getter" for user agent
3389 function GET_USER_AGENT () {
3390 // Get remote ip from environment
3391 $userAgent = getenv('HTTP_USER_AGENT');
3393 // Is removeip installed?
3394 if (EXT_IS_ACTIVE("removeip")) {
3395 // Then anonymize it
3396 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3403 // "Getter" for referer
3404 function GET_REFERER () {
3405 // Get remote ip from environment
3406 $referer = getenv('HTTP_REFERER');
3408 // Is removeip installed?
3409 if (EXT_IS_ACTIVE("removeip")) {
3410 // Then anonymize it
3411 $referer = GET_ANONYMOUS_REFERER($referer);
3418 // Adds a bonus mail to the queue
3419 // This is a high-level function!
3420 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
3421 // Use mode from data if not set and availble ;-)
3422 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3424 // Generate receiver list
3425 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
3428 if (!empty($RECEIVER)) {
3429 // Add bonus mail to queue
3430 ADD_BONUS_MAIL_TO_QUEUE(
3442 // Mail inserted into bonus pool
3443 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
3444 } elseif ($output) {
3445 // More entered than can be reached!
3446 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
3449 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3453 // Determines referal id and sets it
3454 function DETERMINE_REFID () {
3455 // Check if refid is set
3456 if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3457 // The variable user comes from the click-counter script click.php and we only accept this here
3458 $GLOBALS['refid'] = bigintval($_GET['user']);
3459 } elseif (!empty($_POST['refid'])) {
3460 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3461 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3462 } elseif (!empty($_GET['refid'])) {
3463 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3464 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3465 } elseif (!empty($_GET['ref'])) {
3466 // Set refid=ref (the referal link uses such variable)
3467 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3468 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
3469 // Set session refid als global
3470 $GLOBALS['refid'] = bigintval(get_session('refid'));
3471 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
3472 // Set default refid as refid in URL
3473 $GLOBALS['refid'] = getConfig(('def_refid'));
3474 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
3475 // Select a random user which has confirmed enougth mails
3476 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3478 // No default ID when sql_patches is not installed or none set
3479 $GLOBALS['refid'] = 0;
3482 // Set cookie when default refid > 0
3483 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
3485 set_session('refid', $GLOBALS['refid']);
3488 // Return determined refid
3489 return $GLOBALS['refid'];
3492 // Check wether we are installing
3493 function isInstalling () {
3494 $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
3495 //* DEBUG: */ var_dump($installing);
3499 // Check wether this script is installed
3500 function isInstalled () {
3501 return isBooleanConstantAndTrue('mxchange_installed');
3504 // Check wether an admin is registered
3505 function isAdminRegistered () {
3506 return isBooleanConstantAndTrue('admin_registered');
3509 // Enables the reset mode. Only call this function if you really want the
3511 function enableResetMode () {
3512 // Enable the reset mode
3513 $GLOBALS['reset_enabled'] = true;
3516 runFilterChain('reset_enabled');
3519 // Checks wether the reset mode is active
3520 function isResetModeEnabled () {
3521 // Now simply check it
3522 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3525 // Checks wether the debug mode is enabled
3526 function isDebugModeEnabled () {
3528 return isBooleanConstantAndTrue('DEBUG_MODE');
3531 // Checks wether the cache instance is valid
3532 function isCacheInstanceValid () {
3533 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3536 // Our shutdown-function
3537 function shutdown () {
3538 // Call the filter chain 'shutdown'
3539 runFilterChain('shutdown', null, false);
3541 if (SQL_IS_LINK_UP()) {
3543 SQL_CLOSE(__FILE__, __LINE__);
3544 } elseif ((!isInstalling()) && (isInstalled())) {
3546 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3549 // Stop executing here
3553 // Setter for userid
3554 function setUserId ($userid) {
3555 $GLOBALS['userid'] = bigintval($userid);
3558 // Getter for userid or returns zero
3559 function getUserId () {
3563 // Is the userid set?
3564 if (isUserIdSet()) {
3566 $userid = $GLOBALS['userid'];
3573 // Checks ether the userid is set
3574 function isUserIdSet () {
3575 return (isset($GLOBALS['userid']));
3578 // Checks wether the given FQFN is a directory and not .,.. or .svn
3579 function isDirectory ($FQFN) {
3580 // Generate baseName
3581 $baseName = basename($FQFN);
3584 $isDirectory = ((is_dir($FQFN)) && ($baseName != ".") && ($baseName != "..") && ($baseName != ".svn"));
3586 // Return the result
3587 return $isDirectory;
3590 // Handle message codes from URL
3591 function handleCodeMessage () {
3592 if (REQUEST_ISSET_GET(('msg'))) {
3593 // Default extension is "unknown"
3596 // Is extension given?
3597 if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
3599 // Convert the 'msg' parameter from URL to a human-readable message
3600 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3602 // Load message template
3603 LOAD_TEMPLATE("message", false, $msg);
3607 //////////////////////////////////////////////////
3608 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3609 //////////////////////////////////////////////////
3611 if (!function_exists('html_entity_decode')) {
3612 // Taken from documentation on www.php.net
3613 function html_entity_decode ($string) {
3614 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3615 $trans_tbl = array_flip($trans_tbl);
3616 return strtr($string, $trans_tbl);