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 // Check if our config file is writeable or not
45 function IS_INC_WRITEABLE ($inc) {
47 $FQFN = sprintf("%sinc/%s.php", constant('PATH'), $inc);
49 // Abort by simple test
50 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN))) {
54 // Test write-access on directory
55 return is_writeable(dirname($FQFN));
58 // Output HTML code directly or "render" it. You addionally switch the new-line character off
59 function OUTPUT_HTML ($HTML, $newLine = true) {
60 // Some global variables
63 // Do we have HTML-Code here?
65 // Yes, so we handle it as you have configured
66 switch (constant('OUTPUT_MODE'))
69 // That's why you don't need any \n at the end of your HTML code... :-)
70 if (constant('_OB_CACHING') == "on") {
71 // Output into PHP's internal buffer
74 // That's why you don't need any \n at the end of your HTML code... :-)
75 if ($newLine) echo "\n";
77 // Render mode for old or lame servers...
80 // That's why you don't need any \n at the end of your HTML code... :-)
81 if ($newLine) $OUTPUT .= "\n";
86 // If we are switching from render to direct output rendered code
87 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
89 // The same as above... ^
91 if ($newLine) echo "\n";
95 // Huh, something goes wrong or maybe you have edited config.php ???
96 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
97 mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
100 } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
101 // Headers already sent?
102 if (headers_sent()) {
104 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
106 // Trigger an user error
107 debug_report_bug("Headers are already sent!");
110 // Output cached HTML code
111 $OUTPUT = ob_get_contents();
113 // Clear output buffer for later output if output is found
114 if (!empty($OUTPUT)) {
119 header("HTTP/1.1 200");
122 $now = gmdate('D, d M Y H:i:s') . ' GMT';
124 // General headers for no caching
125 header("Expired: " . $now); // RFC2616 - Section 14.21
126 header("Last-Modified: " . $now);
127 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
128 header("Pragma: no-cache"); // HTTP/1.0
129 header("Connection: Close");
131 // Extension "rewrite" installed?
132 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
133 $OUTPUT = REWRITE_LINKS($OUTPUT);
136 // Compile and run finished rendered HTML code
137 while (strpos($OUTPUT, '{!') > 0) {
138 // Prepare the content and eval() it...
140 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
143 // Was that eval okay?
144 if (empty($newContent)) {
145 // Something went wrong!
146 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
148 $OUTPUT = $newContent;
151 // Output code here, DO NOT REMOVE! ;-)
153 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
154 // Rewrite links when rewrite extension is active
155 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
156 $OUTPUT = REWRITE_LINKS($OUTPUT);
159 // Compile and run finished rendered HTML code
160 while (strpos($OUTPUT, '{!') > 0) {
161 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
165 // Output code here, DO NOT REMOVE! ;-)
170 // Output the raw HTML code
171 function OUTPUT_RAW ($HTML) {
172 // Output stripped HTML code to avoid broken JavaScript code, etc.
173 echo stripslashes(stripslashes($HTML));
175 // Flush the output if only constant('_OB_CACHING') is not "on"
176 if (constant('_OB_CACHING') != "on") {
182 // Init fatal message array
183 function initFatalMessages () {
184 $GLOBALS['fatal_messages'] = array();
187 // Getter for whole fatal error messages
188 function getFatalArray () {
189 return $GLOBALS['fatal_messages'];
192 // Add a fatal error message to the queue array
193 function addFatalMessage ($F, $L, $message, $extra="") {
194 debug_report_bug($message);
195 if (is_array($extra)) {
196 // Multiple extras for a message with masks
197 $message = call_user_func_array('sprintf', $extra);
198 } elseif (!empty($extra)) {
199 // $message is text with a mask plus extras to insert into the text
200 $message = sprintf($message, $extra);
203 // Add message to $GLOBALS['fatal_messages']
204 $GLOBALS['fatal_messages'][] = $message;
206 // Log fatal messages away
207 DEBUG_LOG($F, $L, " message={$message}");
210 // Getter for total fatal message count
211 function getTotalFatalErrors () {
215 // Do we have at least the first entry?
216 if (!empty($GLOBALS['fatal_messages'][0])) {
218 $count = count($GLOBALS['fatal_messages']);
225 // Load a template file and return it's content (only it's name; do not use ' or ")
226 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
227 // Add more variables which you want to use in your template files
228 global $DATA, $_CONFIG, $username;
230 // Make all template names lowercase
231 $template = strtolower($template);
233 // Count the template load
234 incrementConfigEntry('num_templates');
236 // Prepare IP number and User Agent
237 $REMOTE_ADDR = GET_REMOTE_ADDR();
238 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
239 $HTTP_USER_AGENT = GET_USER_AGENT();
243 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
245 // @DEPRECATED Try to rewrite the if() condition
246 if ($template == "member_support_form") {
247 // Support request of a member
248 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
249 array(getUserId()), __FUNCTION__, __LINE__);
251 // Is content an array?
252 if (is_array($content)) {
254 $content = merge_array($content, SQL_FETCHARRAY($result));
257 $content['gender'] = TRANSLATE_GENDER($content['gender']);
260 // @TODO Fine all templates which are using these direct variables and rewrite them.
261 // @TODO After this step is done, this else-block is history
262 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
265 $gender = TRANSLATE_GENDER($gender);
266 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
270 SQL_FREERESULT($result);
273 // Generate date/time string
274 $date_time = MAKE_DATETIME(time(), "1");
277 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
280 // Check for admin/guest/member templates
281 if (strpos($template, "admin_") > -1) {
282 // Admin template found
284 } elseif (strpos($template, "guest_") > -1) {
285 // Guest template found
287 } elseif (strpos($template, "member_") > -1) {
288 // Member template found
290 } elseif (strpos($template, "install_") > -1) {
291 // Installation template found
293 } elseif (strpos($template, "ext_") > -1) {
294 // Extension template found
296 } elseif (strpos($template, "la_") > -1) {
297 // "Logical-area" template found
300 // Test for extension
301 $test = substr($template, 0, strpos($template, "_"));
302 if (EXT_IS_ACTIVE($test)) {
303 // Set extra path to extension's name
308 ////////////////////////
309 // Generate file name //
310 ////////////////////////
311 $FQFN = $BASE.$MODE.$template.".tpl";
313 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
314 // Select what depended header/footer template file for admin/guest/member area
315 $file2 = sprintf("%s%s%s_%s.tpl",
319 SQL_ESCAPE($GLOBALS['what'])
323 if (FILE_READABLE($file2)) $FQFN = $file2;
325 // Remove variable from memory
329 // Does the special template exists?
330 if (!FILE_READABLE($FQFN)) {
331 // Reset to default template
332 $FQFN = $BASE.$template.".tpl";
335 // Now does the final template exists?
336 if (FILE_READABLE($FQFN)) {
337 // The local file does exists so we load it. :)
338 $tmpl_file = READ_FILE($FQFN);
340 // Replace ' to our own chars to preventing them being quoted
341 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
343 // Do we have to compile the code?
345 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
347 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
350 // Simply return loaded code
354 // Add surrounding HTML comments to help finding bugs faster
355 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
356 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
357 // Only admins shall see this warning or when installation mode is active
358 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
359 (".basename($FQFN).")<br />
362 <pre>".print_r($content, true)."</pre>
364 <pre>".print_r($DATA, true)."</pre>
368 // Remove content and data
372 // Do we have some content to output or return?
374 // Not empty so let's put it out! ;)
375 if ($return === true) {
376 // Return the HTML code
382 } elseif (isDebugModeEnabled()) {
383 // Warning, empty output!
384 return "E:".$template."<br />\n";
388 // Send mail out to an email address
389 function SEND_EMAIL($toEmail, $subject, $message, $HTML = "N", $mailHeader = "") {
390 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
392 // Compile subject line (for POINTS constant etc.)
393 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
397 if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
398 // Value detected, is the message extension installed?
399 if (EXT_IS_ACTIVE("msg")) {
400 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
403 // Load email address
404 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
405 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
407 // Does the user exist?
408 if (SQL_NUMROWS($result_email)) {
409 // Load email address
410 list($toEmail) = SQL_FETCHROW($result_email);
413 $toEmail = constant('WEBMASTER');
417 SQL_FREERESULT($result_email);
419 } elseif ("$toEmail" == "0") {
421 $toEmail = constant('WEBMASTER');
423 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
425 // Check for PHPMailer or debug-mode
426 if (!CHECK_PHPMAILER_USAGE()) {
427 // Not in PHPMailer-Mode
428 if (empty($mailHeader)) {
429 // Load email header template
430 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
433 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
435 } elseif (isDebugModeEnabled()) {
436 if (empty($mailHeader)) {
437 // Load email header template
438 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
441 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
446 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
450 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
453 // Fix HTML parameter (default is no!)
454 if (empty($HTML)) $HTML = "N";
455 if (isDebugModeEnabled()) {
456 // In debug mode we want to display the mail instead of sending it away so we can debug this part
458 ".htmlentities(trim($mailHeader))."
460 Subject : ".$subject."
461 Message : ".$message."
463 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
464 // Send mail as HTML away
465 SEND_HTML_EMAIL($toEmail, $subject, $message, $mailHeader);
466 } elseif (!empty($toEmail)) {
468 SEND_RAW_EMAIL($toEmail, $subject, $message, $mailHeader);
469 } elseif ($HTML == "N") {
471 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$subject, $message, $mailHeader);
475 // Check if legacy or PHPMailer command
476 // @TODO Rewrite this to an extension 'smtp'
478 function CHECK_PHPMAILER_USAGE() {
479 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != "") && (constant('SMTP_USER') != ""));
483 * Send out a raw email with PHPMailer class or legacy mail() command
485 function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
486 // Shall we use PHPMailer class or legacy mode?
487 if (CHECK_PHPMAILER_USAGE()) {
488 // Use PHPMailer class with SMTP enabled
489 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
490 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
493 $mail = new PHPMailer();
494 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
497 $mail->SMTPAuth = true;
498 $mail->Host = constant('SMTP_HOSTNAME');
500 $mail->Username = constant('SMTP_USER');
501 $mail->Password = constant('SMTP_PASSWORD');
503 $mail->From = constant('WEBMASTER');
507 $mail->FromName = constant('MAIN_TITLE');
508 $mail->Subject = $subject;
509 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
511 $mail->AltBody = "Your mail program required HTML support to read this mail!";
512 $mail->WordWrap = 70;
515 $mail->Body = decodeEntities($msg);
517 $mail->AddAddress($toEmail, "");
518 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
519 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
520 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
523 // Use legacy mail() command
524 @mail($toEmail, $subject, decodeEntities($msg), $from);
529 // Generate a password in a specified length or use default password length
530 function GEN_PASS ($LEN = 0) {
531 // Auto-fix invalid length of zero
532 if ($LEN == 0) $LEN = getConfig('pass_len');
534 // Initialize array with all allowed chars
535 $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,-,+,_,/");
537 // Start creating password
539 for ($i = 0; $i < $LEN; $i++) {
540 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
543 // When the size is below 40 we can also add additional security by scrambling it
544 if (strlen($PASS) <= 40) {
545 // Also scramble the password
546 $PASS = scrambleString($PASS);
549 // Return the password
553 function MAKE_DATETIME ($time, $mode="0")
557 return NEVER_HAPPENED;
559 // Filter out numbers
560 $time = bigintval($time);
563 switch (GET_LANGUAGE())
565 case "de": // German date / time format
567 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
568 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
569 case "2": $ret = date("d.m.Y|H:i", $time); break;
570 case "3": $ret = date("d.m.Y", $time); break;
572 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
577 default: // Default is the US date / time format!
579 case "0": $ret = date("r", $time); break;
580 case "1": $ret = date("Y-m-d - g:i A", $time); break;
581 case "2": $ret = date("y-m-d|H:i", $time); break;
582 case "3": $ret = date("y-m-d", $time); break;
584 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
591 // Translates the american decimal dot into a german comma
592 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
593 // Default is 3 you can change this in admin area "Misc -> Misc Options"
594 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
596 // Use from config is default
597 $maxComma = getConfig('max_comma');
599 // Use from parameter?
600 if ($max > 0) $maxComma = $max;
603 if (($cut) && ($max == 0)) {
604 // Test for commata if in cut-mode
605 $com = explode(".", $dotted);
606 if (count($com) < 2) {
607 // Don't display commatas even if there are none... ;-)
613 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
616 switch (GET_LANGUAGE()) {
618 $dotted = number_format($dotted, $maxComma, ",", ".");
622 $dotted = number_format($dotted, $maxComma, ".", ",");
626 // Return translated value
631 function DEREFERER ($URL) {
632 // Don't de-refer our own links!
633 if (substr($URL, 0, strlen(URL)) != URL) {
634 // De-refer this link
635 $URL = "modules.php?module=loader&url=".encodeString(compileUriCode($URL));
642 // Translate Uni*-like gender to human-readable
643 function TRANSLATE_GENDER ($gender) {
645 $ret = "!{$gender}!";
647 // Male/female or company?
649 case "M": $ret = getMessage('GENDER_M'); break;
650 case "F": $ret = getMessage('GENDER_F'); break;
651 case "C": $ret = getMessage('GENDER_C'); break;
653 // Log unknown gender
654 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
658 // Return translated gender
663 function FRAMETESTER ($URL) {
664 // Prepare frametester URL
665 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
666 encodeString(compileUriCode($URL))
668 return $frametesterUrl;
672 function SELECTION_COUNT ($array) {
674 if (is_array($array)) {
675 foreach ($array as $key => $selected) {
676 if (!empty($selected)) $ret++;
682 function IMG_CODE ($code, $type, $DATA, $uid) {
683 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
686 function TRANSLATE_STATUS ($status) {
692 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
697 $ret = getMessage('ACCOUNT_DELETED');
701 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
702 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
710 function GET_LANGUAGE() {
711 // Set default return value to default language from config
712 $ret = constant('DEFAULT_LANG');
717 // Is the variable set
718 if (REQUEST_ISSET_GET(('mx_lang'))) {
719 // Accept only first 2 chars
720 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
721 } elseif (isset($GLOBALS['cache_array']['language'])) {
723 $ret = $GLOBALS['cache_array']['language'];
724 } elseif (!empty($lang)) {
725 // Check if main language file does exist
726 if (FILE_READABLE(constant('PATH')."inc/language/".$lang.".php")) {
727 // Okay found, so let's update cookies
730 } elseif (!isSessionVariableSet('mx_lang')) {
731 // Return stored value from cookie
732 $ret = get_session('mx_lang');
734 // Fixes a warning before the session has the mx_lang constant
735 if (empty($ret)) $ret = constant('DEFAULT_LANG');
739 $GLOBALS['cache_array']['language'] = $ret;
745 function SET_LANGUAGE ($lang) {
746 // Accept only first 2 chars!
747 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
750 set_session('mx_lang', $lang);
753 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
754 global $DATA, $_CONFIG;
756 // Make sure all template names are lowercase!
757 $template = strtolower($template);
759 // Default "nickname" if extension is not installed
762 // Prepare IP number and User Agent
763 $REMOTE_ADDR = GET_REMOTE_ADDR();
764 $HTTP_USER_AGENT = GET_USER_AGENT();
767 $ADMIN = constant('MAIN_TITLE');
769 // Is the admin logged in?
772 $aid = GET_CURRENT_ADMIN_ID();
775 $ADMIN = GET_ADMIN_EMAIL($aid);
778 // Neutral email address is default
779 $email = constant('WEBMASTER');
781 // Expiration in a nice output format
782 if (getConfig('auto_purge') == 0) {
783 // Will never expire!
784 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
786 // Create nice date string
787 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
790 // Is content an array?
791 if (is_array($content)) {
792 // Add expiration to array, $EXPIRATION is now deprecated!
793 $content['expiration'] = $EXPIRATION;
797 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
798 if (($UID > 0) && (is_array($content))) {
799 // If nickname extension is installed, fetch nickname as well
800 if (EXT_IS_ACTIVE("nickname")) {
801 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
803 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
804 array(bigintval($UID)), __FUNCTION__, __LINE__);
806 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
808 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
809 array(bigintval($UID)), __FUNCTION__, __LINE__);
812 // Fetch and merge data
813 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
814 $content = merge_array($content, SQL_FETCHARRAY($result));
815 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
818 SQL_FREERESULT($result);
821 // Translate M to male or F to female if present
822 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
824 // Overwrite email from data if present
825 if (isset($content['email'])) $email = $content['email'];
827 // Store email for some functions in global data array
828 $DATA['email'] = $email;
831 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
833 // Check for admin/guest/member templates
834 if (strpos($template, "admin_") > -1) {
835 // Admin template found
836 $FQFN = $BASE."admin/".$template.".tpl";
837 } elseif (strpos($template, "guest_") > -1) {
838 // Guest template found
839 $FQFN = $BASE."guest/".$template.".tpl";
840 } elseif (strpos($template, "member_") > -1) {
841 // Member template found
842 $FQFN = $BASE."member/".$template.".tpl";
844 // Test for extension
845 $test = substr($template, 0, strpos($template, "_"));
846 if (EXT_IS_ACTIVE($test)) {
847 // Set extra path to extension's name
848 $FQFN = $BASE.$test."/".$template.".tpl";
850 // No special filename
851 $FQFN = $BASE.$template.".tpl";
855 // Does the special template exists?
856 if (!FILE_READABLE($FQFN)) {
857 // Reset to default template
858 $FQFN = $BASE.$template.".tpl";
861 // Now does the final template exists?
863 if (FILE_READABLE($FQFN)) {
864 // The local file does exists so we load it. :)
865 $tmpl_file = READ_FILE($FQFN);
866 $tmpl_file = SQL_ESCAPE($tmpl_file);
869 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
871 } elseif (!empty($template)) {
872 // Template file not found!
873 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
874 {--TEMPLATE_CONTENT--}
875 <pre>".print_r($content, true)."</pre>
877 <pre>".print_r($DATA, true)."</pre>
880 // Debug mode not active? Then remove the HTML tags
881 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
883 // No template name supplied!
884 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
887 // Is there some content?
888 if (empty($newContent)) {
890 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
891 // Add last error if the required function exists
892 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
895 // Remove content and data
899 // Return compiled content
900 return COMPILE_CODE($newContent);
903 function MAKE_TIME ($H, $M, $S, $stamp) {
904 // Extract day, month and year from given timestamp
905 $DAY = date("d", $stamp);
906 $MONTH = date("m", $stamp);
907 $YEAR = date('Y', $stamp);
909 // Create timestamp for wished time which depends on extracted date
910 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
913 function LOAD_URL ($URL, $addUrlData=true) {
914 // Compile out URI codes
915 $URL = compileUriCode($URL);
917 // Check if http(s):// is there
918 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
919 // Make all URLs full-qualified
924 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
925 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
926 $OUTPUT = ob_get_contents();
928 // Clear it only if there is content
929 if (!empty($OUTPUT)) {
933 // Add some data to URL if cookies are not accepted
934 if (((!defined('__COOKIES')) || (!constant('__COOKIES'))) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
936 // Probe for bot from search engine
937 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
938 // Search engine bot detected so let's rewrite many chars for the link
939 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
941 // Output new location link as anchor
942 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
943 } elseif (!headers_sent()) {
944 // Load URL when headers are not sent
945 //* DEBUG: */ debug_report_bug("URL={$URL}");
946 header ("Location: ".str_replace("&", "&", $URL));
948 // Output error message
949 LOAD_INC("inc/header.php");
950 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
951 LOAD_INC("inc/footer.php");
956 // Wrapper for LOAD_URL but URL comes from a configuration entry
957 function LOAD_CONFIGURED_URL ($configEntry) {
959 $URL = getConfig($configEntry);
964 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
972 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
973 // Is the code a string?
974 if (!is_string($code)) {
975 // Silently return it
979 // Init replacement-array with full security characters
980 $secChars = $GLOBALS['security_chars'];
982 // Select smaller set of chars to replace when we e.g. want to compile URLs
983 if (!$full) $secChars = $GLOBALS['url_chars'];
986 if ($constants === true) {
987 // BEFORE 0.2.1 : Language and data constants
988 // WITH 0.2.1+ : Only language constants
989 $code = str_replace('{--','".', str_replace('--}','."', $code));
991 // BEFORE 0.2.1 : Not used
992 // WITH 0.2.1+ : Data constants
993 $code = str_replace('{!','".', str_replace("!}", '."', $code));
996 // Compile QUOT and other non-HTML codes
997 foreach ($secChars['to'] as $k => $to) {
998 // Do the reversed thing as in inc/libs/security_functions.php
999 $code = str_replace($to, $secChars['from'][$k], $code);
1002 // But shall I keep simple quotes for later use?
1003 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1005 // Find $content[bla][blub] entries
1006 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1008 // Are some matches found?
1009 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1010 // Replace all matches
1011 $matchesFound = array();
1012 foreach ($matches[0] as $key => $match) {
1013 // Fuzzy look has failed by default
1014 $fuzzyFound = false;
1016 // Fuzzy look on match if already found
1017 foreach ($matchesFound as $found => $set) {
1019 $test = substr($found, 0, strlen($match));
1021 // Does this entry exist?
1022 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1023 if ($test == $match) {
1025 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1032 if ($fuzzyFound) continue;
1034 // Take all string elements
1035 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1036 // Replace it in the code
1037 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1038 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1039 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1040 $matchesFound[$key."_".$matches[4][$key]] = 1;
1041 $matchesFound[$match] = 1;
1042 } elseif (!isset($matchesFound[$match])) {
1043 // Not yet replaced!
1044 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1045 $code = str_replace($match, "\".".$match.".\"", $code);
1046 $matchesFound[$match] = 1;
1051 // Return compiled code
1055 /************************************************************************
1057 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1058 * $a_sort sortiert: *
1060 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1061 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1062 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1063 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1064 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1066 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1067 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1068 * Sie, dass es doch nicht so schwer ist! :-) *
1070 ************************************************************************/
1071 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1073 while ($primary_key < count($a_sort)) {
1074 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1075 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1078 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1079 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1080 } elseif ($key != $key2) {
1081 // Sort numbers (E.g.: 9 < 10)
1082 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1083 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1087 // We have found two different values, so let's sort whole array
1088 foreach ($dummy as $sort_key => $sort_val) {
1089 $t = $dummy[$sort_key][$key];
1090 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1091 $dummy[$sort_key][$key2] = $t;
1102 // Write back sorted array
1107 function ADD_SELECTION ($type, $DEFAULT, $prefix="", $id="0") {
1110 if ($type == "yn") {
1111 // This is a yes/no selection only!
1112 if ($id > 0) $prefix .= "[".$id."]";
1113 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1115 // Begin with regular selection box here
1116 if (!empty($prefix)) $prefix .= "_";
1118 if ($id > 0) $type2 .= "[".$id."]";
1119 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1124 for ($idx = 1; $idx < 32; $idx++) {
1125 $OUT .= "<option value=\"".$idx."\"";
1126 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1127 $OUT .= ">".$idx."</option>\n";
1131 case "month": // Month
1132 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1133 $OUT .= "<option value=\"".$month."\"";
1134 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1135 $OUT .= ">".$descr."</option>\n";
1139 case "year": // Year
1141 $YEAR = date('Y', time());
1143 // Use configured min age or fixed?
1144 if (GET_EXT_VERSION("other") >= "0.2.1") {
1146 $startYear = $YEAR - getConfig('min_age');
1149 $startYear = $YEAR - 16;
1152 // Calculate earliest year (100 years old people can still enter Internet???)
1153 $minYear = $YEAR - 100;
1155 // Check if the default value is larger than minimum and bigger than actual year
1156 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1157 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1158 $OUT .= "<option value=\"".$idx."\"";
1159 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1160 $OUT .= ">".$idx."</option>\n";
1162 } elseif ($DEFAULT == -1) {
1163 // Current year minus 1
1164 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1166 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1169 // Get current year and subtract the configured minimum age
1170 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1171 // Calculate earliest year depending on extension version
1172 if (GET_EXT_VERSION("other") >= "0.2.1") {
1173 // Use configured minimum age
1174 $YEAR = date('Y', time()) - getConfig('min_age');
1176 // Use fixed 16 years age
1177 $YEAR = date('Y', time()) - 16;
1180 // Construct year selection list
1181 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1182 $OUT .= "<option value=\"".$idx."\"";
1183 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1184 $OUT .= ">".$idx."</option>\n";
1191 for ($idx = 0; $idx < 60; $idx+=5) {
1192 if (strlen($idx) == 1) $idx = "0".$idx;
1193 $OUT .= "<option value=\"".$idx."\"";
1194 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1195 $OUT .= ">".$idx."</option>\n";
1200 for ($idx = 0; $idx < 24; $idx++) {
1201 if (strlen($idx) == 1) $idx = "0".$idx;
1202 $OUT .= "<option value=\"".$idx."\"";
1203 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1204 $OUT .= ">".$idx."</option>\n";
1209 $OUT .= "<option value=\"Y\"";
1210 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1211 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1212 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1213 $OUT .= ">{--NO--}</option>\n";
1216 $OUT .= " </select>\n";
1221 function TRANSLATE_YESNO ($yn) {
1223 $translated = "??? (".$yn.")";
1225 case "Y": $translated = getMessage('YES'); break;
1226 case "N": $translated = getMessage('NO'); break;
1228 // Log unknown value
1229 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
1238 // Deprecated : $length
1241 function generateRandomCodde ($length, $code, $uid, $DATA="") {
1242 // Fix missing _MAX constant
1243 // @TODO Rewrite this unnice code
1244 if (!defined('_MAX')) define('_MAX', 15235);
1246 // Build server string
1247 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
1250 $keys = constant('SITE_KEY').":".constant('DATE_KEY');
1251 if (isConfigEntrySet('secret_key')) $keys .= ":".getConfig('secret_key');
1252 if (isConfigEntrySet('file_hash')) $keys .= ":".getConfig('file_hash');
1253 $keys .= ":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1254 if (isConfigEntrySet('master_salt')) $keys .= ":".getConfig('master_salt');
1256 // Build string from misc data
1257 $data = $code.":".$uid.":".$DATA;
1259 // Add more additional data
1260 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1261 if (isUserIdSet()) $data .= ":".getUserId();
1262 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1263 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1264 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1266 // Calculate number for generating the code
1267 $a = $code + constant('_ADD') - 1;
1269 if (isConfigEntrySet('master_hash')) {
1270 // Generate hash with master salt from modula of number with the prime number and other data
1271 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1273 // Create number from hash
1274 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1276 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1277 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1279 // Create number from hash
1280 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1283 // At least 10 numbers shall be secure enought!
1284 $len = getConfig('code_length');
1285 if ($len == 0) $len = $length;
1286 if ($len == 0) $len = 10;
1288 // Cut off requested counts of number
1289 $return = substr(str_replace('.', "", $rcode), 0, $len);
1291 // Done building code
1295 // Does only allow numbers
1296 function bigintval ($num, $castValue = true) {
1297 // Filter all numbers out
1298 $ret = preg_replace("/[^0123456789]/", "", $num);
1301 if ($castValue) $ret = (double)$ret;
1303 // Has the whole value changed?
1304 // @TODO Remove this if() block if all is working fine
1305 if ("".$ret."" != "".$num."") {
1307 debug_report_bug("{$ret}<>{$num}");
1314 // Insert the code in $img_code into jpeg or PNG image
1315 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1316 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1317 // Stop execution of function here because of over-sized code length
1319 } elseif (!$headerSent) {
1320 // Return in an HTML code code
1321 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1325 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1326 if (FILE_READABLE($img)) {
1327 // Switch image type
1328 switch (getConfig('img_type'))
1331 // Okay, load image and hide all errors
1332 $image = @imagecreatefromjpeg($img);
1336 // Okay, load image and hide all errors
1337 $image = @imagecreatefrompng($img);
1341 // Exit function here
1342 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1346 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1347 $text_color = imagecolorallocate($image, 0, 0, 0);
1349 // Insert code into image
1350 imagestring($image, 5, 14, 2, $img_code, $text_color);
1352 // Return to browser
1353 header ("Content-Type: image/".getConfig('img_type'));
1355 // Output image with matching image factory
1356 switch (getConfig('img_type')) {
1357 case "jpg": imagejpeg($image); break;
1358 case "png": imagepng($image); break;
1361 // Remove image from memory
1362 imagedestroy($image);
1364 // Create selection box or array of splitted timestamp
1365 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1366 // Calculate 2-seconds timestamp
1367 $stamp = round($timestamp);
1368 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1370 // Do we have a leap year?
1372 $TEST = date('Y', time()) / 4;
1373 $M1 = date("m", time());
1374 $M2 = date("m", (time() + $timestamp));
1376 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1377 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1379 // First of all years...
1380 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1381 //* DEBUG: */ print("Y={$Y}<br />\n");
1383 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1384 //* DEBUG: */ print("M={$M}<br />\n");
1386 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1387 //* DEBUG: */ print("W={$W}<br />\n");
1389 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1390 //* DEBUG: */ print("D={$D}<br />\n");
1392 $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));
1393 //* DEBUG: */ print("h={$h}<br />\n");
1395 $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));
1396 //* DEBUG: */ print("m={$m}<br />\n");
1397 // And at last seconds...
1398 $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));
1399 //* DEBUG: */ print("s={$s}<br />\n");
1401 // Is seconds zero and time is < 60 seconds?
1402 if (($s == 0) && ($timestamp < 60)) {
1404 $s = round($timestamp);
1408 // Now we convert them in seconds...
1410 if ($return_array) {
1411 // Just put all data in an array for later use
1423 $OUT = "<div align=\"".$align."\">\n";
1424 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1427 if (ereg('Y', $display) || (empty($display))) {
1428 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1431 if (ereg("M", $display) || (empty($display))) {
1432 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1435 if (ereg("W", $display) || (empty($display))) {
1436 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1439 if (ereg("D", $display) || (empty($display))) {
1440 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1443 if (ereg("h", $display) || (empty($display))) {
1444 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1447 if (ereg("m", $display) || (empty($display))) {
1448 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1451 if (ereg("s", $display) || (empty($display))) {
1452 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1458 if (ereg('Y', $display) || (empty($display))) {
1459 // Generate year selection
1460 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1461 for ($idx = 0; $idx <= 10; $idx++) {
1462 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1463 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1464 $OUT .= ">".$idx."</option>\n";
1466 $OUT .= " </select></td>\n";
1468 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1471 if (ereg("M", $display) || (empty($display))) {
1472 // Generate month selection
1473 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1474 for ($idx = 0; $idx <= 11; $idx++)
1476 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1477 if ($idx == $M) $OUT .= " selected=\"selected\"";
1478 $OUT .= ">".$idx."</option>\n";
1480 $OUT .= " </select></td>\n";
1482 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1485 if (ereg("W", $display) || (empty($display))) {
1486 // Generate week selection
1487 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1488 for ($idx = 0; $idx <= 4; $idx++) {
1489 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1490 if ($idx == $W) $OUT .= " selected=\"selected\"";
1491 $OUT .= ">".$idx."</option>\n";
1493 $OUT .= " </select></td>\n";
1495 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1498 if (ereg("D", $display) || (empty($display))) {
1499 // Generate day selection
1500 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1501 for ($idx = 0; $idx <= 31; $idx++) {
1502 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1503 if ($idx == $D) $OUT .= " selected=\"selected\"";
1504 $OUT .= ">".$idx."</option>\n";
1506 $OUT .= " </select></td>\n";
1508 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1511 if (ereg("h", $display) || (empty($display))) {
1512 // Generate hour selection
1513 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1514 for ($idx = 0; $idx <= 23; $idx++) {
1515 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1516 if ($idx == $h) $OUT .= " selected=\"selected\"";
1517 $OUT .= ">".$idx."</option>\n";
1519 $OUT .= " </select></td>\n";
1521 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1524 if (ereg("m", $display) || (empty($display))) {
1525 // Generate minute selection
1526 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1527 for ($idx = 0; $idx <= 59; $idx++) {
1528 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1529 if ($idx == $m) $OUT .= " selected=\"selected\"";
1530 $OUT .= ">".$idx."</option>\n";
1532 $OUT .= " </select></td>\n";
1534 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1537 if (ereg("s", $display) || (empty($display))) {
1538 // Generate second selection
1539 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1540 for ($idx = 0; $idx <= 59; $idx++) {
1541 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1542 if ($idx == $s) $OUT .= " selected=\"selected\"";
1543 $OUT .= ">".$idx."</option>\n";
1545 $OUT .= " </select></td>\n";
1547 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1550 $OUT .= "</table>\n";
1552 // Return generated HTML code
1558 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1559 // Initial return value
1562 // Do we have a leap year?
1564 $TEST = date('Y', time()) / 4;
1565 $M1 = date("m", time());
1566 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1567 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1568 // First add years...
1569 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1571 $ret += $POST[$prefix."_mo"] * 2628000;
1573 $ret += $POST[$prefix."_we"] * 604800;
1575 $ret += $POST[$prefix."_da"] * 86400;
1577 $ret += $POST[$prefix."_ho"] * 3600;
1579 $ret += $POST[$prefix."_mi"] * 60;
1580 // And at last seconds...
1581 $ret += $POST[$prefix."_se"];
1582 // Return calculated value
1586 // Sends out mail to all administrators
1587 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1588 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1589 // Trim template name
1590 $template = trim($template);
1592 // Load email template
1593 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1595 // Check which admin shall receive this mail
1596 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1597 array($template), __FUNCTION__, __LINE__);
1598 if (SQL_NUMROWS($result) == 0) {
1599 // Create new entry (to all admins)
1600 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1601 array($template), __FUNCTION__, __LINE__);
1603 // Load admin IDs...
1604 // @TODO This can be, somehow, rewritten
1605 $adminIds = array();
1606 while ($content = SQL_FETCHARRAY($result)) {
1607 $adminIds[] = $content['admin_id'];
1611 SQL_FREERESULT($result);
1616 // "implode" IDs and query string
1617 $aid = implode(",", $adminIds);
1619 if (EXT_IS_ACTIVE("events")) {
1620 // Add line to user events
1621 EVENTS_ADD_LINE($subj, $msg, $UID);
1623 // Log error for debug
1624 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1630 } elseif ($aid == "0") {
1631 // Select all email adresses
1632 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1633 __FUNCTION__, __LINE__);
1635 // If Admin-ID is not "to-all" select
1636 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1637 array($aid), __FUNCTION__, __LINE__);
1641 // Load email addresses and send away
1642 while ($content = SQL_FETCHARRAY($result)) {
1643 SEND_EMAIL($content['email'], $subj, $msg);
1647 SQL_FREERESULT($result);
1651 function CREATE_FANCY_TIME ($stamp) {
1652 // Get data array with years/months/weeks/days/...
1653 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1655 foreach($data as $k => $v) {
1657 // Value is greater than 0 "eval" data to return string
1658 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1664 // Do we have something there?
1665 if (strlen($ret) > 0) {
1666 // Remove leading commata and space
1667 $ret = substr($ret, 2);
1670 $ret = "0 {--_SECONDS--}";
1673 // Return fancy time string
1678 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1679 $SEP = ""; $TOP = "";
1682 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1686 for ($page = 1; $page <= $PAGES; $page++) {
1687 // Is the page currently selected or shall we generate a link to it?
1688 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1689 // Is currently selected, so only highlight it
1690 $NAV .= "<strong>-";
1692 // Open anchor tag and add base URL
1693 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1695 // Add userid when we shall show all mails from a single member
1696 if ((REQUEST_ISSET_GET(('uid'))) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1698 // Close open anchor tag
1702 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1703 // Is currently selected, so only highlight it
1704 $NAV .= "-</strong>";
1710 // Add seperator if we have not yet reached total pages
1711 if ($page < $PAGES) $NAV .= " | ";
1714 // Define constants only once
1715 if (!defined('__NAV_OUTPUT')) {
1716 define('__NAV_OUTPUT' , $NAV);
1717 define('__NAV_COLSPAN', $colspan);
1718 define('__NAV_TOP' , $TOP);
1719 define('__NAV_SEP' , $SEP);
1722 // Load navigation template
1723 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1725 if ($return === true) {
1726 // Return generated HTML-Code
1734 // Extract host from script name
1735 function EXTRACT_HOST (&$script) {
1736 // Use default SERVER_URL by default... ;) So?
1737 $url = constant('SERVER_URL');
1739 // Is this URL valid?
1740 if (substr($script, 0, 7) == "http://") {
1741 // Use the hostname from script URL as new hostname
1742 $url = substr($script, 7);
1743 $extract = explode("/", $url);
1745 // Done extracting the URL :)
1748 // Extract host name
1749 $host = str_replace("http://", "", $url);
1750 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1752 // Generate relative URL
1753 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1754 if (substr(strtolower($script), 0, 7) == "http://") {
1755 // But only if http:// is in front!
1756 $script = substr($script, (strlen($url) + 7));
1757 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1759 $script = substr($script, (strlen($url) + 8));
1762 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1763 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1769 // Send a GET request
1770 function GET_URL ($script) {
1771 // Compile the script name
1772 $script = COMPILE_CODE($script);
1774 // Extract host name from script
1775 $host = EXTRACT_HOST($script);
1777 // Generate GET request header
1778 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1779 $request .= "Host: " . $host . "\r\n";
1780 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1781 if (defined('FULL_VERSION')) {
1782 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1784 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1786 $request .= "Content-Type: text/plain\r\n";
1787 $request .= "Cache-Control: no-cache\r\n";
1788 $request .= "Connection: Close\r\n\r\n";
1790 // Send the raw request
1791 $response = SEND_RAW_REQUEST($host, $request);
1793 // Return the result to the caller function
1797 // Send a POST request
1798 function POST_URL ($script, $postData) {
1799 // Is postData an array?
1800 if (!is_array($postData)) {
1802 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1803 return array("", "", "");
1806 // Compile the script name
1807 $script = COMPILE_CODE($script);
1809 // Extract host name from script
1810 $host = EXTRACT_HOST($script);
1812 // Construct request
1813 $data = http_build_query($postData, '','&');
1815 // Generate POST request header
1816 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1817 $request .= "Host: " . $host . "\r\n";
1818 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1819 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1820 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1821 $request .= "Content-length: " . strlen($data) . "\r\n";
1822 $request .= "Cache-Control: no-cache\r\n";
1823 $request .= "Connection: Close\r\n\r\n";
1826 // Send the raw request
1827 $response = SEND_RAW_REQUEST($host, $request);
1829 // Return the result to the caller function
1833 // Sends a raw request to another host
1834 function SEND_RAW_REQUEST ($host, $request) {
1836 $response = array("", "", "");
1838 // Default is not to use proxy
1841 // Are proxy settins set?
1842 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1848 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1850 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1852 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1856 if (!is_resource($fp)) {
1863 // Generate CONNECT request header
1864 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1865 $proxyTunnel .= "Host: ".$host."\r\n";
1867 // Use login data to proxy? (username at least!)
1868 if (getConfig('proxy_username') != "") {
1870 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1871 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1874 // Add last new-line
1875 $proxyTunnel .= "\r\n";
1876 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1879 fputs($fp, $proxyTunnel);
1883 // No response received
1887 // Read the first line
1888 $resp = trim(fgets($fp, 10240));
1889 $respArray = explode(" ", $resp);
1890 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1891 // Invalid response!
1897 fputs($fp, $request);
1900 while (!feof($fp)) {
1901 $response[] = trim(fgets($fp, 1024));
1907 // Skip first empty lines
1909 foreach ($resp as $idx => $line) {
1911 $line = trim($line);
1913 // Is this line empty?
1916 array_shift($response);
1918 // Abort on first non-empty line
1923 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1925 // Proxy agent found?
1926 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1927 // Proxy header detected, so remove two lines
1928 array_shift($response);
1929 array_shift($response);
1932 // Was the request successfull?
1933 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1934 // Not found / access forbidden
1935 $response = array("", "", "");
1942 // Taken from www.php.net eregi() user comments
1943 function VALIDATE_EMAIL ($email) {
1945 $email = COMPILE_CODE($email);
1947 // Check first part of email address
1948 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1951 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1954 $regex = "^".$first."@".$domain."$";
1956 // Return check result
1957 return eregi($regex, $email);
1960 // Function taken from user comments on www.php.net / function eregi()
1961 function VALIDATE_URL ($URL, $compile=true) {
1962 // Trim URL a little
1963 $URL = trim(urldecode($URL));
1964 //* DEBUG: */ echo $URL."<br />";
1966 // Compile some chars out...
1967 if ($compile) $URL = compileUriCode($URL, false, false, false);
1968 //* DEBUG: */ echo $URL."<br />";
1970 // Check for the extension filter
1971 if (EXT_IS_ACTIVE("filter")) {
1972 // Use the extension's filter set
1973 return FILTER_VALIDATE_URL($URL, false);
1976 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1977 // https:// in front of the URLs
1978 return isUrlValid($URL);
1981 // Generate a list of administrative links to a given userid
1982 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1983 // Define all main targets
1984 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1986 // Begin of navigation links
1987 $eval = "\$OUT = \"[ ";
1989 foreach ($TARGETS as $tar) {
1990 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1991 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1992 if (($tar == "lock_user") && ($status == "LOCKED")) {
1993 // Locked accounts shall be unlocked
1994 $eval .= "UNLOCK_USER";
1996 // All other status is fine
1997 $eval .= strtoupper($tar);
1999 $eval .= "_TITLE--}\\\">{--ADMIN_";
2000 if (($tar == "lock_user") && ($status == "LOCKED")) {
2001 // Locked accounts shall be unlocked
2002 $eval .= "UNLOCK_USER";
2004 // All other status is fine
2005 $eval .= strtoupper($tar);
2007 $eval .= "--}</a></span> | ";
2010 // Finish navigation link
2011 $eval = substr($eval, 0, -7)."]\";";
2018 // Generate an email link
2019 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2020 // Default email link (INSECURE! Spammer can read this by harvester programs)
2021 $EMAIL = "mailto:".$email;
2023 // Check for several extensions
2024 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2025 // Create email link for contacting admin in guest area
2026 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2027 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2028 // Create email link for contacting a member within admin area (or later in other areas, too?)
2029 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2030 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2031 // Create email link to contact sponsor within admin area (or like the link above?)
2032 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2035 // Shall I close the link when there is no admin?
2036 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2038 // Return email link
2042 // Generate a hash for extra-security for all passwords
2043 function generateHash ($plainText, $salt = "") {
2044 // Is the required extension "sql_patches" there and a salt is not given?
2045 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2046 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2047 return md5($plainText);
2050 // Do we miss an arry element here?
2051 if (!isConfigEntrySet('file_hash')) {
2053 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2056 // When the salt is empty build a new one, else use the first x configured characters as the salt
2058 // Build server string
2059 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
2062 $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');
2065 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2067 // Calculate number for generating the code
2068 $a = time() + constant('_ADD') - 1;
2070 // Generate SHA1 sum from modula of number and the prime number
2071 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2072 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2073 $sha1 = scrambleString($sha1);
2074 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2075 //* DEBUG: */ $sha1b = descrambleString($sha1);
2076 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2078 // Generate the password salt string
2079 $salt = substr($sha1, 0, getConfig('salt_length'));
2080 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2083 $salt = substr($salt, 0, getConfig('salt_length'));
2084 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2088 return $salt.sha1($salt.$plainText);
2091 // Scramble a string
2092 function scrambleString($str) {
2096 // Final check, in case of failture it will return unscrambled string
2097 if (strlen($str) > 40) {
2098 // The string is to long
2100 } elseif (strlen($str) == 40) {
2102 $scrambleNums = explode(":", getConfig('pass_scramble'));
2104 // Generate new numbers
2105 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2108 // Scramble string here
2109 //* DEBUG: */ echo "***Original=".$str."***<br />";
2110 for ($idx = 0; $idx < strlen($str); $idx++) {
2111 // Get char on scrambled position
2112 $char = substr($str, $scrambleNums[$idx], 1);
2114 // Add it to final output string
2115 $scrambled .= $char;
2118 // Return scrambled string
2119 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2123 // De-scramble a string scrambled by scrambleString()
2124 function descrambleString($str) {
2125 // Scramble only 40 chars long strings
2126 if (strlen($str) != 40) return $str;
2128 // Load numbers from config
2129 $scrambleNums = explode(":", getConfig('pass_scramble'));
2132 if (count($scrambleNums) != 40) return $str;
2134 // Begin descrambling
2135 $orig = str_repeat(" ", 40);
2136 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2137 for ($idx = 0; $idx < 40; $idx++) {
2138 $char = substr($str, $idx, 1);
2139 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2142 // Return scrambled string
2143 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2147 // Generated a "string" for scrambling
2148 function genScrambleString ($len) {
2149 // Prepare array for the numbers
2150 $scrambleNumbers = array();
2152 // First we need to setup randomized numbers from 0 to 31
2153 for ($idx = 0; $idx < $len; $idx++) {
2155 $rand = mt_rand(0, ($len -1));
2157 // Check for it by creating more numbers
2158 while (array_key_exists($rand, $scrambleNumbers)) {
2159 $rand = mt_rand(0, ($len -1));
2163 $scrambleNumbers[$rand] = $rand;
2166 // So let's create the string for storing it in database
2167 $scrambleString = implode(":", $scrambleNumbers);
2168 return $scrambleString;
2171 // Append data like session ID or referal ID to the given URL which would
2172 // normally be stored in cookies
2173 function ADD_URL_DATA ($URL) {
2177 // Determine URL binder
2179 if (strpos($URL, "?") !== false) $BIND = "&";
2181 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2182 // Cookies are not accepted
2183 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2184 // Cookie found in URL
2185 $add .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2186 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2187 // Not found! So let's set default here
2188 $add .= $BIND."refid=".getConfig('def_refid');
2192 // Add all together and return it
2196 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2197 function generatePassString ($passHash) {
2198 // Return vanilla password hash
2201 // Is a secret key and master salt already initialized?
2202 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2203 // Only calculate when the secret key is generated
2204 $newHash = ""; $start = 9;
2205 for ($idx = 0; $idx < 10; $idx++) {
2206 $part1 = hexdec(substr($passHash, $start, 4));
2207 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2208 $mod = dechex($idx);
2209 if ($part1 > $part2) {
2210 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2211 } elseif ($part2 > $part1) {
2212 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2214 $mod = substr(round($mod), 0, 4);
2215 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2216 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2221 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2222 $ret = generateHash($newHash, getConfig('master_salt'));
2223 //* DEBUG: */ print($ret."<br />\n");
2226 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2227 $ret = md5($passHash);
2228 //* DEBUG: */ echo "++".$ret."++<br />\n";
2235 // Fix "deleted" cookies
2236 function FIX_DELETED_COOKIES ($cookies) {
2237 // Is this an array with entries?
2238 if ((is_array($cookies)) && (count($cookies) > 0)) {
2239 // Then check all cookies if they are marked as deleted!
2240 foreach ($cookies as $cookieName) {
2241 // Is the cookie set to "deleted"?
2242 if (get_session($cookieName) == "deleted") {
2243 set_session($cookieName, "");
2249 // Output error messages in a fasioned way and die...
2250 function mxchange_die ($msg) {
2252 LOAD_INC_ONCE("inc/header.php");
2254 // Load the message template
2255 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2258 LOAD_INC_ONCE("inc/footer.php");
2264 // Display parsing time and number of SQL queries in footer
2265 function DISPLAY_PARSING_TIME_FOOTER() {
2266 // Is the timer started?
2267 if (!isset($GLOBALS['startTime'])) {
2273 $endTime = microtime(true);
2275 // "Explode" both times
2276 $start = explode(" ", $GLOBALS['startTime']);
2277 $end = explode(" ", $endTime);
2278 $runTime = $end[0] - $start[0];
2279 if ($runTime < 0) $runTime = 0;
2280 $runTime = TRANSLATE_COMMA($runTime);
2284 'runtime' => $runTime,
2285 'numSQLs' => (getConfig('sql_count') + 1),
2286 'numTemplates' => (getConfig('num_templates') + 1)
2289 // Load the template
2290 LOAD_TEMPLATE("show_timings", false, $content);
2293 // Check wether a boolean constant is set
2294 // Taken from user comments in PHP documentation for function constant()
2295 function isBooleanConstantAndTrue ($constName) { // : Boolean
2296 // Failed by default
2300 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2302 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2303 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2306 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2307 if (defined($constName)) {
2309 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2310 $res = (constant($constName) === true);
2314 $GLOBALS['cache_array']['const'][$constName] = $res;
2316 //* DEBUG: */ var_dump($res);
2322 // Checks if a given apache module is loaded
2323 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2324 // Check it and return result
2325 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2328 // "Getter" for language strings
2329 // @TODO Rewrite all language constants to this function.
2330 function getMessage ($messageId) {
2331 // Default is not found!
2332 $return = "!".$messageId."!";
2334 // Is the language string found?
2335 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2336 // Language array element found in small_letters
2337 $return = $GLOBALS['msg'][$messageId];
2338 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2339 // @DEPRECATED Language array element found in BIG_LETTERS
2340 $return = $GLOBALS['msg'][$messageId];
2341 } elseif (defined($messageId)) {
2342 // @DEPRECATED Deprecated constant found
2343 $return = constant($messageId);
2345 // Missing language constant
2346 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2349 // Return the string
2353 // Get current theme name
2354 function GET_CURR_THEME() {
2355 // The default theme is 'default'... ;-)
2358 // Load default theme if not empty from configuration
2359 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2361 if (!isSessionVariableSet('mxchange_theme')) {
2362 // Set default theme
2363 set_session('mxchange_theme', $ret);
2364 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2365 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2366 // Get theme from cookie
2367 $ret = get_session('mxchange_theme');
2370 if (THEME_GET_ID($ret) == 0) {
2371 // Fix it to default
2374 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
2375 // Prepare FQFN for checking
2376 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
2378 // Installation mode active
2379 if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
2380 // Set cookie from URL data
2381 set_session('mxchange_theme', REQUEST_GET(('theme')));
2382 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2383 // Set cookie from posted data
2384 set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2388 $ret = get_session('mxchange_theme');
2390 // Invalid design, reset cookie
2391 set_session('mxchange_theme', $ret);
2394 // Add (maybe) found theme.php file to inclusion list
2395 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2397 // Try to load the requested include file
2398 if (INCLUDE_READABLE($INC)) ADD_INC_TO_POOL($INC);
2400 // Return theme value
2404 // Get id from theme
2405 function THEME_GET_ID ($name) {
2406 // Is the extension "theme" installed?
2407 if (!EXT_IS_ACTIVE("theme")) {
2415 // Is the cache entry there?
2416 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2417 // Get the version from cache
2418 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2421 incrementConfigEntry('cache_hits');
2422 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2423 // Check if current theme is already imported or not
2424 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2425 array($name), __FUNCTION__, __LINE__);
2428 if (SQL_NUMROWS($result) == 1) {
2430 list($id) = SQL_FETCHROW($result);
2434 SQL_FREERESULT($result);
2441 // Read a given file
2442 function READ_FILE ($FQFN, $sqlPrepare = false) {
2444 if (function_exists('file_get_contents')) {
2446 $content = file_get_contents($FQFN);
2448 // Fall-back to implode-file chain
2449 $content = implode("", file($FQFN));
2452 // Prepare SQL queries?
2453 if ($sqlPrepare === true) {
2454 // Remove some unwanted chars
2455 $content = str_replace("\r", "", $content);
2456 $content = str_replace("\n\n", "\n", $content);
2459 // Return the content
2463 // Writes content to a file
2464 function WRITE_FILE ($FQFN, $content) {
2465 // Is the file writeable?
2466 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2468 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2474 // By default all is failed...
2477 // Is the function there?
2478 if (function_exists('file_put_contents')) {
2479 // Write it directly
2480 $return = file_put_contents($FQFN, $content);
2482 // Write it with fopen
2483 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
2484 fwrite($fp, $content);
2488 $return = chmod($FQFN, 0644);
2495 // Generates an error code from given account status
2496 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
2497 // Default error code if unknown account status
2498 $ERROR = getCode('UNKNOWN_STATUS');
2500 // Generate constant name
2501 $constantName = sprintf("ID_%s", $status);
2503 // Is the constant there?
2504 if (isCodeSet($constantName)) {
2506 $ERROR = getCode($constantName);
2509 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2512 // Return error code
2516 // Clears the output buffer. This function does *NOT* backup sent content.
2517 function clearOutputBuffer () {
2518 // Trigger an error on failure
2519 if (!ob_end_clean()) {
2521 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
2525 // Function to search for the last modifified file
2526 function searchDirsRecursive ($dir, &$last_changed) {
2528 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2529 $ds = GET_DIR_AS_ARRAY($dir, "", true, false);
2530 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2532 // Walk through all entries
2533 foreach ($ds as $d) {
2534 // Generate proper FQFN
2535 $FQFN = str_replace("//", "/", constant('PATH') . $dir. "/". $d);
2537 // Does it match what we are looking for? (We skip a lot files already!)
2538 if (!preg_match('@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache)$@', $d)) { // no . or .. or .revision or .svn in the filename
2539 // Is it a file and readable?
2540 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2541 if (isDirectory($FQFN)) {
2542 // $FQFN is a directory so also crawl into this directory
2544 if (!empty($dir)) $newDir = $dir . "/". $d;
2545 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2546 searchDirsRecursive($newDir, $last_changed);
2547 } elseif (FILE_READABLE($FQFN)) {
2548 // $FQFN is a filename and no directory
2549 $time = filemtime($FQFN);
2550 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2551 if ($last_changed['time'] < $time) {
2552 // This file is newer as the file before
2553 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2554 $last_changed['path_name'] = $FQFN;
2555 $last_changed['time'] = $time;
2562 // "Getter" for revision/version data
2563 function getActualVersion ($type = 'Revision') {
2564 // By default nothing is new... ;-)
2567 if (EXT_IS_ACTIVE("cache")) {
2568 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2569 if (isset($_GET['check_revision_data']) && $_GET['check_revision_data'] == 'yes') $new = true;
2570 if (!isset($GLOBALS['cache_array']['revision'][$type])
2571 || count($GLOBALS['cache_array']['revision']) < 3
2572 || !$GLOBALS['cache_instance']->loadCacheFile("revision")) $new = true;
2574 // Is the cache file outdated/invalid?
2576 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2578 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2579 unset($GLOBALS['cache_array']['revision']);
2581 // Reload load_cach-revison.php
2582 LOAD_INC("inc/loader/load_cache-revision.php");
2585 // Return found value
2586 return $GLOBALS['cache_array']['revision'][$type][0];
2589 // Old Version without ext-cache active (deprecated ?)
2591 // FQFN of revision file
2592 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2594 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2595 if ((isset($_GET['check_revision_data'])) && ($_GET['check_revision_data'] == 'yes')) {
2599 // Check for revision file
2600 if (!FILE_READABLE($FQFN)) {
2601 // Not found, so we need to create it
2604 // Revision file found
2605 $ins_vers = explode("\n", READ_FILE($FQFN));
2607 // Get array for mapping information
2608 $mapper = array_flip(getSearchFor());
2609 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2611 // Is the content valid?
2612 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == "") || ($ins_vers[0]) == "new") {
2613 // File needs update!
2616 // Return found value
2617 return trim($ins_vers[$mapper[$type]]);
2622 // Has it been updated?
2623 if ($new === true) {
2624 WRITE_FILE($FQFN, implode("\n", getAkt_vers()));
2629 // Repares an array we are looking for
2630 function getSearchFor () {
2631 // Add Revision, Date, Tag and Author
2632 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2634 // Return the created array
2638 function getAkt_vers () {
2641 $last_changed = array(
2645 $akt_vers = array();
2648 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2649 searchDirsRecursive($next_dir, $last_changed);
2652 $last_file = READ_FILE($last_changed['path_name']);
2653 $searchFor = getSearchFor();
2655 // @TODO What does this loop/regex do? Document it, please.
2656 foreach ($searchFor as $search) {
2657 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2658 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2661 if ($res && $res >= 3) {
2663 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2665 // Prepare timestamp for date
2666 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2668 // Add Tag if the author is set and is not quix0r (lead coder)
2669 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2670 $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!! Could be removed I think.
2674 $version = GET_URL("check-updates3.php");
2677 $akt_vers['Revision'] = trim($version[10]);
2678 $akt_vers['Date'] = trim($version[9]);
2679 $akt_vers['Tag'] = trim($version[8]);
2680 $akt_vers['Author'] = "quix0r";
2683 // Return prepared array
2688 // Loads an include file and logs any missing files for debug purposes
2689 function LOAD_INC ($INC) {
2690 // Add the path. This is why we need a trailing slash in config.php
2691 $FQFN = constant('PATH') . $INC;
2693 // Is the include file there?
2694 if (!FILE_READABLE($FQFN)) {
2695 // Not there so log it
2696 debug_report_bug(sprintf("Include file %s not found.", $INC));
2704 // Loads an include file once
2705 function LOAD_INC_ONCE ($INC) {
2706 // Is it not loaded?
2707 if (!isset($GLOBALS['load_once'][$INC])) {
2708 // Then try to load it
2711 // And mark it as loaded
2712 $GLOBALS['load_once'][$INC] = "loaded";
2716 // Back-ported from the new ship-simu engine. :-)
2717 function debug_get_printable_backtrace () {
2719 $backtrace = "<ol>\n";
2721 // Get and prepare backtrace for output
2722 $backtraceArray = debug_backtrace();
2723 foreach ($backtraceArray as $key => $trace) {
2724 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2725 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2726 if (!isset($trace['args'])) $trace['args'] = array();
2727 $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";
2731 $backtrace .= "</ol>\n";
2733 // Return the backtrace
2737 // Output a debug backtrace to the user
2738 function debug_report_bug ($message = "") {
2741 // Is the optional message set?
2742 if (!empty($message)) {
2744 $debug = sprintf("Note: %s<br />\n",
2748 // @TODO Add a little more infos here
2749 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2753 $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2754 $debug .= debug_get_printable_backtrace();
2755 $debug .= "</pre>Request-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2756 $debug .= "Thank you for finding bugs.";
2759 // @TODO This cannot be rewritten to mxchange_die(), try to find a solution for this.
2763 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2764 function generateSeed () {
2765 list($usec, $sec) = explode(" ", microtime());
2766 return ((float)$sec + (float)$usec);
2769 // Converts a message code to a human-readable message
2770 function convertCodeToMessage ($code) {
2773 case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2774 case getCode('LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2775 case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2776 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2777 case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2778 case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2779 case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2780 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2782 case getCode('ERROR_MAILID'):
2783 if (EXT_IS_ACTIVE($ext, true)) {
2784 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2786 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
2790 case getCode('EXTENSION_PROBLEM'):
2791 if (REQUEST_ISSET_GET(('ext'))) {
2792 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2794 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2798 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2799 case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2800 case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2801 case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2804 // Missing/invalid code
2805 $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2808 DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2812 // Return the message
2816 // Checks wether the given extension is currently not installed
2817 // and redirects if so.
2818 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
2819 // Is the extension uninstalled/inactive?
2820 if (!EXT_IS_ACTIVE($ext_name)) {
2821 // Redirect to index
2822 LOAD_URL("modules.php?module=index&msg=".getCode('EXTENSION_PROBLEM')."&ext=".$ext_name);
2826 // Generate a "link" for the given admin id (aid)
2827 function GENERATE_AID_LINK ($aid) {
2828 // No assigned admin is default
2829 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2831 // Zero? = Not assigned
2833 // Load admin's login
2834 $login = GET_ADMIN_LOGIN($aid);
2835 if ($login != "***") {
2836 // Is the extension there?
2837 if (EXT_IS_ACTIVE("admins")) {
2839 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
2841 // Extension not found
2842 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
2846 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2854 // Checks wether an include file (non-FQFN better) is readable
2855 function INCLUDE_READABLE ($INC) {
2857 $FQFN = constant('PATH') . $INC;
2860 return FILE_READABLE($FQFN);
2864 // @TODO Implement $compress
2865 function encodeString ($str, $compress=true) {
2866 $str = urlencode(base64_encode(compileUriCode($str)));
2870 // Decode strings encoded with encodeString()
2871 // @TODO Implement $decompress
2872 function decodeString ($str, $decompress=true) {
2873 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2877 // Compile characters which are allowed in URLs
2878 function compileUriCode ($code, $simple=true) {
2879 // Compile constants
2880 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2882 // Compile QUOT and other non-HTML codes
2883 $code = str_replace("{DOT}", ".",
2884 str_replace("{SLASH}", "/",
2885 str_replace("{QUOT}", "'",
2886 str_replace("{DOLLAR}", "$",
2887 str_replace("{OPEN_ANCHOR}", "(",
2888 str_replace("{CLOSE_ANCHOR}", ")",
2889 str_replace("{OPEN_SQR}", "[",
2890 str_replace("{CLOSE_SQR}", "]",
2891 str_replace("{PER}", "%",
2895 // Return compiled code
2899 // Function taken from user comments on www.php.net / function eregi()
2900 function isUrlValid ($url) {
2902 $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
2904 // Allows http and https
2905 $http = "(http|https)+(:\/\/)";
2907 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2908 // Test double-domains (e.g. .de.vu)
2909 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2911 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2913 $dir = "((/)+([-_\.[:alnum:]])+)*";
2915 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2916 // ... and the string after and including question character
2917 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2918 // Pattern for URLs like http://url/dir/doc.html?var=value
2919 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2920 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2921 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2922 // Pattern for URLs like http://url/dir/?var=value
2923 $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
2924 $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
2925 $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
2926 // Pattern for URLs like http://url/dir/page.ext
2927 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2928 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2929 $pattern['ipdp'] = $http.$ip.$dir.$page;
2930 // Pattern for URLs like http://url/dir
2931 $pattern['d1d'] = $http.$domain1.$dir;
2932 $pattern['d2d'] = $http.$domain2.$dir;
2933 $pattern['ipd'] = $http.$ip.$dir;
2934 // Pattern for URLs like http://url/?var=value
2935 $pattern['d1g1'] = $http.$domain1."/".$getstring1;
2936 $pattern['d2g1'] = $http.$domain2."/".$getstring1;
2937 $pattern['ipg1'] = $http.$ip."/".$getstring1;
2938 // Pattern for URLs like http://url?var=value
2939 $pattern['d1g12'] = $http.$domain1.$getstring1;
2940 $pattern['d2g12'] = $http.$domain2.$getstring1;
2941 $pattern['ipg12'] = $http.$ip.$getstring1;
2942 // Test all patterns
2944 foreach ($pattern as $key=>$pat) {
2946 if (defined('DEBUG_REGEX')) {
2947 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2948 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2949 $pat = str_replace("[:digit:]", "0-9", $pat);
2950 $pat = str_replace(".", "\.", $pat);
2951 $pat = str_replace("@", "\@", $pat);
2952 echo $key."= ".$pat."<br />";
2955 // Check if expression matches
2956 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2959 if ($reg === true) break;
2962 // Return true/false
2966 // Smartly adds slashes
2967 function smartAddSlashes ($unquoted) {
2968 $unquoted = str_replace("\\", "", $unquoted);
2969 return addslashes($unquoted);
2972 // Decode entities in a nicer way
2973 function decodeEntities ($str) {
2974 // @TODO We may want to switch over to UTF-8 here!
2975 $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
2977 // Return decoded string
2978 return $decodedString;
2981 // Wtites data to a config.php-style file
2982 // @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
2983 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2984 // Initialize some variables
2990 // Is the file there and read-/write-able?
2991 if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
2992 $search = "CFG: ".$comment;
2993 $tmp = $FQFN.".tmp";
2995 // Open the source file
2996 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2998 // Is the resource valid?
2999 if (is_resource($fp)) {
3000 // Open temporary file
3001 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
3003 // Is the resource again valid?
3004 if (is_resource($fp_tmp)) {
3005 while (!feof($fp)) {
3006 // Read from source file
3007 $line = fgets ($fp, 1024);
3009 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
3012 if ($next === $seek) {
3014 $line = $prefix . $DATA . $suffix."\n";
3020 // Write to temp file
3021 fputs($fp_tmp, $line);
3027 // Finished writing tmp file
3031 // Close source file
3034 if (($done) && ($found)) {
3035 // Copy back tmp file and delete tmp :-)
3037 return unlink($tmp);
3038 } elseif (!$found) {
3039 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
3041 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
3045 // File not found, not readable or writeable
3046 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
3049 // An error was detected!
3052 // Send notification to admin
3053 function SEND_ADMIN_NOTIFICATION ($subject, $templateName, $content=array(), $uid="0") {
3054 if (GET_EXT_VERSION("admins") >= "0.4.1") {
3056 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
3058 // Send out out-dated way
3059 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
3060 SEND_ADMIN_EMAILS($subject, $msg);
3064 // Merges an array together but only if both are arrays
3065 function merge_array ($array1, $array2) {
3066 // Are both an array?
3067 if ((is_array($array1)) && (is_array($array2))) {
3068 // Merge all together
3069 return array_merge($array1, $array2);
3070 } elseif (is_array($array1)) {
3071 // Return left array
3072 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
3074 } elseif (is_array($array2)) {
3075 // Return right array
3076 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
3080 // Both are not arrays
3081 debug_report_bug(__FUNCTION__.": No arrays provided!");
3084 // Debug message logger
3085 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
3086 // Is debug mode enabled?
3087 if ((isDebugModeEnabled()) || ($force === true)) {
3089 $message = str_replace("\r", "", str_replace("\n", "", $message));
3091 // Log this message away
3092 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
3093 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
3098 // Reads a directory with PHP files in and gets only files back
3099 function GET_DIR_AS_ARRAY ($baseDir, $prefix, $includeDirs = false, $addBaseDir = true) {
3104 $dirPointer = opendir(constant('PATH') . $baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
3107 while ($baseFile = readdir($dirPointer)) {
3108 // Construct include filename and FQFN
3109 $INC = $baseDir . "/" . $baseFile;
3110 $FQFN = constant('PATH') . $INC;
3112 // Is this a valid reset file?
3113 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
3114 if (((FILE_READABLE($FQFN)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) || (($includeDirs) && (isDirectory($FQFN)))) {
3115 // Remove both for extension name
3116 $extName = substr($baseFile, strlen($prefix), -4);
3119 $extId = GET_EXT_ID($extName);
3121 // Is the extension valid and active?
3122 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
3123 // Then add this file
3124 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Extension entry ".$baseFile." added.<br />\n";
3126 } elseif ($extId == 0) {
3127 // Add non-extension files as well
3128 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Regular entry ".$baseFile." added.<br />\n";
3132 $INCs[] = $baseFile;
3139 closedir($dirPointer);
3144 // Return array with include files
3148 // Load more reset scripts
3149 function runResetIncludes () {
3150 // Is the reset set or old sql_patches?
3151 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
3153 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3156 // Get more daily reset scripts
3157 SET_INC_POOL(GET_DIR_AS_ARRAY("inc/reset/", "reset_"));
3160 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
3162 // Is the config entry set?
3163 if (GET_EXT_VERSION("sql_patches") >= "0.4.2") {
3164 // Create current week mark
3165 $currWeek = date("W", time());
3168 if (getConfig('last_week') != $currWeek) {
3169 // Include weekly reset scripts
3170 MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
3173 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
3176 // Create current month mark
3177 $currMonth = date("m", time());
3180 if (getConfig('last_month') != $currMonth) {
3181 // Include monthly reset scripts
3182 MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
3185 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
3190 runFilterChain('load_includes');
3193 // Handle extra values
3194 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
3195 // Default is the value itself
3198 // Do we have a special filter function?
3199 if (!empty($filterFunction)) {
3200 // Does the filter function exist?
3201 if (function_exists($filterFunction)) {
3202 // Do we have extra parameters here?
3203 if (!empty($extraValue)) {
3204 // Put both parameters in one new array by default
3205 $args = array($value, $extraValue);
3207 // If we have an array simply use it and pre-extend it with our value
3208 if (is_array($extraValue)) {
3209 // Make the new args array
3210 $args = merge_array(array($value), $extraValue);
3213 // Call the multi-parameter call-back
3214 $ret = call_user_func_array($filterFunction, $args);
3216 // One parameter call
3217 $ret = call_user_func($filterFunction, $value);
3226 // Check if given FQFN is a readable file
3227 function FILE_READABLE ($FQFN) {
3229 return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3232 // Converts timestamp selections into a timestamp
3233 function CONVERT_SELECTIONS_TO_TIMESTAMP (&$POST, &$DATA, &$id, &$skip) {
3234 // Init test variable
3237 // Get last three chars
3238 $test = substr($id, -3);
3240 // Improved way of checking! :-)
3241 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
3242 // Found a multi-selection for timings?
3243 $test = substr($id, 0, -3);
3244 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)) {
3245 // Generate timestamp
3246 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
3247 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3249 // Remove data from array
3250 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
3251 unset($POST[$test."_".$rem]);
3255 unset($id); $skip = true; $test2 = $test;
3258 // Process this entry
3264 // Reverts the german decimal comma into Computer decimal dot
3265 function REVERT_COMMA ($str) {
3266 // Default float is not a float... ;-)
3269 // Which language is selected?
3270 switch (GET_LANGUAGE()) {
3271 case "de": // German language
3272 // Remove german thousand dots first
3273 $str = str_replace(".", "", $str);
3275 // Replace german commata with decimal dot and cast it
3276 $float = (float)str_replace(",", ".", $str);
3279 default: // US and so on
3280 // Remove thousand dots first and cast
3281 $float = (float)str_replace(",", "", $str);
3289 // Handle menu-depending failed logins and return the rendered content
3290 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3291 // Default output is empty ;-)
3294 // Is the session data set?
3295 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3296 // Ignore zero values
3297 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
3298 // Non-guest has login failures found, get both data and prepare it for template
3299 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3301 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
3302 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
3306 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
3309 // Reset session data
3310 set_session('mxchange_'.$accessLevel.'_failures', "");
3311 set_session('mxchange_'.$accessLevel.'_last_fail', "");
3314 // Return rendered content
3319 function rebuildCacheFiles ($cache, $inc="") {
3320 // Shall I remove the cache file?
3321 if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
3323 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3325 $GLOBALS['cache_instance']->destroyCacheFile();
3328 // Include file given?
3331 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3333 // Is the include there?
3334 if (INCLUDE_READABLE($INC)) {
3335 // And rebuild it from scratch
3336 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3339 // Include not found!
3340 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3346 // Purge admin menu cache
3347 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
3348 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3349 if (!EXT_IS_ACTIVE("cache")) {
3350 // Cache extension not active
3352 } elseif (!isCacheInstanceValid()) {
3353 // No cache instance!
3354 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3356 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
3357 // Caching disabled (currently experiemental!)
3361 // Experiemental feature!
3362 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3365 // Translates the "pool type" into human-readable
3366 function TRANSLATE_POOL_TYPE ($type) {
3367 // Default type is unknown
3368 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
3370 // Generate constant
3371 $constName = sprintf("POOL_TYPE_%s", $type);
3374 if (defined($constName)) {
3376 $translated = getMessage($constName);
3379 // Return "translation"
3383 // "Getter" for remote IP number
3384 function GET_REMOTE_ADDR () {
3385 // Get remote ip from environment
3386 $remoteAddr = getenv('REMOTE_ADDR');
3388 // Is removeip installed?
3389 if (EXT_IS_ACTIVE("removeip")) {
3390 // Then anonymize it
3391 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3398 // "Getter" for remote hostname
3399 function GET_REMOTE_HOST () {
3400 // Get remote ip from environment
3401 $remoteHost = getenv('REMOTE_HOST');
3403 // Is removeip installed?
3404 if (EXT_IS_ACTIVE("removeip")) {
3405 // Then anonymize it
3406 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3413 // "Getter" for user agent
3414 function GET_USER_AGENT () {
3415 // Get remote ip from environment
3416 $userAgent = getenv('HTTP_USER_AGENT');
3418 // Is removeip installed?
3419 if (EXT_IS_ACTIVE("removeip")) {
3420 // Then anonymize it
3421 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3428 // "Getter" for referer
3429 function GET_REFERER () {
3430 // Get remote ip from environment
3431 $referer = getenv('HTTP_REFERER');
3433 // Is removeip installed?
3434 if (EXT_IS_ACTIVE("removeip")) {
3435 // Then anonymize it
3436 $referer = GET_ANONYMOUS_REFERER($referer);
3443 // Adds a bonus mail to the queue
3444 // This is a high-level function!
3445 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
3446 // Use mode from data if not set and availble ;-)
3447 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3449 // Generate receiver list
3450 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
3453 if (!empty($RECEIVER)) {
3454 // Add bonus mail to queue
3455 ADD_BONUS_MAIL_TO_QUEUE(
3467 // Mail inserted into bonus pool
3468 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
3469 } elseif ($output) {
3470 // More entered than can be reached!
3471 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
3474 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3478 // Determines referal id and sets it
3479 function DETERMINE_REFID () {
3480 // Check if refid is set
3481 if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3482 // The variable user comes from the click-counter script click.php and we only accept this here
3483 $GLOBALS['refid'] = bigintval($_GET['user']);
3484 } elseif (!empty($_POST['refid'])) {
3485 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3486 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3487 } elseif (!empty($_GET['refid'])) {
3488 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3489 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3490 } elseif (!empty($_GET['ref'])) {
3491 // Set refid=ref (the referal link uses such variable)
3492 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3493 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
3494 // Set session refid als global
3495 $GLOBALS['refid'] = bigintval(get_session('refid'));
3496 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
3497 // Set default refid as refid in URL
3498 $GLOBALS['refid'] = getConfig(('def_refid'));
3499 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
3500 // Select a random user which has confirmed enougth mails
3501 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3503 // No default ID when sql_patches is not installed or none set
3504 $GLOBALS['refid'] = 0;
3507 // Set cookie when default refid > 0
3508 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
3510 set_session('refid', $GLOBALS['refid']);
3513 // Return determined refid
3514 return $GLOBALS['refid'];
3517 // Check wether we are installing
3518 function isInstalling () {
3519 $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
3520 //* DEBUG: */ var_dump($installing);
3524 // Check wether this script is installed
3525 function isInstalled () {
3526 return isBooleanConstantAndTrue('mxchange_installed');
3529 // Check wether an admin is registered
3530 function isAdminRegistered () {
3531 return isBooleanConstantAndTrue('admin_registered');
3534 // Enables the reset mode. Only call this function if you really want the
3536 function enableResetMode () {
3537 // Enable the reset mode
3538 $GLOBALS['reset_enabled'] = true;
3541 runFilterChain('reset_enabled');
3544 // Checks wether the reset mode is active
3545 function isResetModeEnabled () {
3546 // Now simply check it
3547 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3550 // Checks wether the debug mode is enabled
3551 function isDebugModeEnabled () {
3553 return isBooleanConstantAndTrue('DEBUG_MODE');
3556 // Checks wether the cache instance is valid
3557 function isCacheInstanceValid () {
3558 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3561 // Our shutdown-function
3562 function shutdown () {
3563 // Call the filter chain 'shutdown'
3564 runFilterChain('shutdown', null, false);
3566 if (SQL_IS_LINK_UP()) {
3568 SQL_CLOSE(__FILE__, __LINE__);
3569 } elseif ((!isInstalling()) && (isInstalled())) {
3571 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3574 // Stop executing here
3578 // Setter for userid
3579 function setUserId ($userid) {
3580 $GLOBALS['userid'] = bigintval($userid);
3583 // Getter for userid or returns zero
3584 function getUserId () {
3588 // Is the userid set?
3589 if (isUserIdSet()) {
3591 $userid = $GLOBALS['userid'];
3598 // Checks ether the userid is set
3599 function isUserIdSet () {
3600 return (isset($GLOBALS['userid']));
3603 // Checks wether the given FQFN is a directory and not .,.. or .svn
3604 function isDirectory ($FQFN) {
3605 // Generate baseName
3606 $baseName = basename($FQFN);
3609 $isDirectory = ((is_dir($FQFN)) && ($baseName != ".") && ($baseName != "..") && ($baseName != ".svn"));
3611 // Return the result
3612 return $isDirectory;
3616 function INIT_INC_POOL () {
3617 $GLOBALS['inc_pool'] = array();
3620 // Setter for INC_POOL
3621 function SET_INC_POOL ($includePool) {
3622 $GLOBALS['inc_pool'] = (array) $includePool;
3625 // Getter for INC_POOL
3626 function GET_INC_POOL () {
3627 return $GLOBALS['inc_pool'];
3631 function COUNT_INC_POOL () {
3632 return count($GLOBALS['inc_pool']);
3635 // Merge INC_POOL into given
3636 function MERGE_INC_POOL ($includePool) {
3637 SET_INC_POOL(merge_array(GET_INC_POOL(), $includePool));
3640 // Add single include file to INC_POOL
3641 function ADD_INC_TO_POOL ($INC) {
3642 $GLOBALS['inc_pool'][] = (string) $INC;
3645 // Remove an include file from INC_POOL
3646 function REMOVE_INC_FROM_POOL ($INC) {
3648 $key = array_search($INC, GET_INC_POOL());
3651 if ($key !== false) {
3653 unset($GLOBALS['inc_pool'][$key]);
3655 // And sort the list
3656 asort($GLOBALS['inc_pool']);
3660 // Handle message codes from URL
3661 function handleCodeMessage () {
3662 if (REQUEST_ISSET_GET(('msg'))) {
3663 // Default extension is "unknown"
3666 // Is extension given?
3667 if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
3669 // Convert the 'msg' parameter from URL to a human-readable message
3670 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3672 // Load message template
3673 LOAD_TEMPLATE("message", false, $msg);
3677 //////////////////////////////////////////////////
3678 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3679 //////////////////////////////////////////////////
3681 if (!function_exists('html_entity_decode')) {
3682 // Taken from documentation on www.php.net
3683 function html_entity_decode ($string) {
3684 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3685 $trans_tbl = array_flip($trans_tbl);
3686 return strtr($string, $trans_tbl);