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 if (is_array($extra)) {
195 // Multiple extras for a message with masks
196 $message = call_user_func_array('sprintf', $extra);
197 } elseif (!empty($extra)) {
198 // $message is text with a mask plus extras to insert into the text
199 $message = sprintf($message, $extra);
202 // Add message to $GLOBALS['fatal_messages']
203 $GLOBALS['fatal_messages'][] = $message;
205 // Log fatal messages away
206 DEBUG_LOG($F, $L, " message={$message}");
209 // Getter for total fatal message count
210 function getTotalFatalErrors () {
214 // Do we have at least the first entry?
215 if (!empty($GLOBALS['fatal_messages'][0])) {
217 $count = count($GLOBALS['fatal_messages']);
224 // Load a template file and return it's content (only it's name; do not use ' or ")
225 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
226 // Add more variables which you want to use in your template files
227 global $DATA, $_CONFIG, $username;
229 // Make all template names lowercase
230 $template = strtolower($template);
232 // Count the template load
233 incrementConfigEntry('num_templates');
235 // Prepare IP number and User Agent
236 $REMOTE_ADDR = GET_REMOTE_ADDR();
237 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
238 $HTTP_USER_AGENT = GET_USER_AGENT();
242 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
244 // @DEPRECATED Try to rewrite the if() condition
245 if ($template == "member_support_form") {
246 // Support request of a member
247 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
248 array(getUserId()), __FUNCTION__, __LINE__);
250 // Is content an array?
251 if (is_array($content)) {
253 $content = merge_array($content, SQL_FETCHARRAY($result));
256 $content['gender'] = TRANSLATE_GENDER($content['gender']);
259 // @TODO Fine all templates which are using these direct variables and rewrite them.
260 // @TODO After this step is done, this else-block is history
261 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
264 $gender = TRANSLATE_GENDER($gender);
265 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
269 SQL_FREERESULT($result);
272 // Generate date/time string
273 $date_time = MAKE_DATETIME(time(), "1");
276 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
279 // Check for admin/guest/member templates
280 if (strpos($template, "admin_") > -1) {
281 // Admin template found
283 } elseif (strpos($template, "guest_") > -1) {
284 // Guest template found
286 } elseif (strpos($template, "member_") > -1) {
287 // Member template found
289 } elseif (strpos($template, "install_") > -1) {
290 // Installation template found
292 } elseif (strpos($template, "ext_") > -1) {
293 // Extension template found
295 } elseif (strpos($template, "la_") > -1) {
296 // "Logical-area" template found
299 // Test for extension
300 $test = substr($template, 0, strpos($template, "_"));
301 if (EXT_IS_ACTIVE($test)) {
302 // Set extra path to extension's name
307 ////////////////////////
308 // Generate file name //
309 ////////////////////////
310 $FQFN = $BASE.$MODE.$template.".tpl";
312 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
313 // Select what depended header/footer template file for admin/guest/member area
314 $file2 = sprintf("%s%s%s_%s.tpl",
318 SQL_ESCAPE($GLOBALS['what'])
322 if (FILE_READABLE($file2)) $FQFN = $file2;
324 // Remove variable from memory
328 // Does the special template exists?
329 if (!FILE_READABLE($FQFN)) {
330 // Reset to default template
331 $FQFN = $BASE.$template.".tpl";
334 // Now does the final template exists?
335 if (FILE_READABLE($FQFN)) {
336 // The local file does exists so we load it. :)
337 $tmpl_file = READ_FILE($FQFN);
339 // Replace ' to our own chars to preventing them being quoted
340 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
342 // Do we have to compile the code?
344 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
346 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
349 // Simply return loaded code
353 // Add surrounding HTML comments to help finding bugs faster
354 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
355 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
356 // Only admins shall see this warning or when installation mode is active
357 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
358 (".basename($FQFN).")<br />
361 <pre>".print_r($content, true)."</pre>
363 <pre>".print_r($DATA, true)."</pre>
367 // Remove content and data
371 // Do we have some content to output or return?
373 // Not empty so let's put it out! ;)
374 if ($return === true) {
375 // Return the HTML code
381 } elseif (isDebugModeEnabled()) {
382 // Warning, empty output!
383 return "E:".$template."<br />\n";
387 // Send mail out to an email address
388 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
389 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
391 // Compile subject line (for POINTS constant etc.)
392 $eval = "\$SUBJECT = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($SUBJECT))."\");";
396 if ((!eregi("@", $TO)) && ($TO > 0)) {
397 // Value detected, is the message extension installed?
398 if (EXT_IS_ACTIVE("msg")) {
399 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
402 // Load email address
403 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FUNCTION__, __LINE__);
404 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
406 // Does the user exist?
407 if (SQL_NUMROWS($result_email)) {
408 // Load email address
409 list($TO) = SQL_FETCHROW($result_email);
412 $TO = constant('WEBMASTER');
416 SQL_FREERESULT($result_email);
418 } elseif ("$TO" == "0") {
420 $TO = constant('WEBMASTER');
422 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
424 // Check for PHPMailer or debug-mode
425 if (!CHECK_PHPMAILER_USAGE()) {
426 // Not in PHPMailer-Mode
428 // Load email header template
429 $FROM = LOAD_EMAIL_TEMPLATE("header");
432 $FROM .= LOAD_EMAIL_TEMPLATE("header");
434 } elseif (isDebugModeEnabled()) {
436 // Load email header template
437 $FROM = LOAD_EMAIL_TEMPLATE("header");
440 $FROM .= LOAD_EMAIL_TEMPLATE("header");
445 $eval = "\$TO = \"".COMPILE_CODE(smartAddSlashes($TO))."\";";
449 $eval = "\$MSG = \"".COMPILE_CODE(smartAddSlashes($MSG))."\";";
452 // Fix HTML parameter (default is no!)
453 if (empty($HTML)) $HTML = "N";
454 if (isDebugModeEnabled()) {
455 // In debug mode we want to display the mail instead of sending it away so we can debug this part
457 ".htmlentities(trim($FROM))."
459 Subject : ".$SUBJECT."
462 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
463 // Send mail as HTML away
464 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
465 } elseif (!empty($TO)) {
467 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
468 } elseif ($HTML == "N") {
470 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
474 // Check if legacy or PHPMailer command
475 // @TODO Rewrite this to an extension 'smtp'
477 function CHECK_PHPMAILER_USAGE() {
478 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != "") && (constant('SMTP_USER') != ""));
482 * Send out a raw email with PHPMailer class or legacy mail() command
484 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
485 // Shall we use PHPMailer class or legacy mode?
486 if (CHECK_PHPMAILER_USAGE()) {
487 // Use PHPMailer class with SMTP enabled
488 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
489 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
492 $mail = new PHPMailer();
493 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
496 $mail->SMTPAuth = true;
497 $mail->Host = constant('SMTP_HOSTNAME');
499 $mail->Username = constant('SMTP_USER');
500 $mail->Password = constant('SMTP_PASSWORD');
502 $mail->From = constant('WEBMASTER');
506 $mail->FromName = constant('MAIN_TITLE');
507 $mail->Subject = $subject;
508 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
510 $mail->AltBody = "Your mail program required HTML support to read this mail!";
511 $mail->WordWrap = 70;
514 $mail->Body = decodeEntities($msg);
516 $mail->AddAddress($to, "");
517 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
518 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
519 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
522 // Use legacy mail() command
523 @mail($to, $subject, decodeEntities($msg), $from);
528 // Generate a password in a specified length or use default password length
529 function GEN_PASS ($LEN = 0) {
530 // Auto-fix invalid length of zero
531 if ($LEN == 0) $LEN = getConfig('pass_len');
533 // Initialize array with all allowed chars
534 $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,-,+,_,/");
536 // Start creating password
538 for ($i = 0; $i < $LEN; $i++) {
539 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
542 // When the size is below 40 we can also add additional security by scrambling it
543 if (strlen($PASS) <= 40) {
544 // Also scramble the password
545 $PASS = scrambleString($PASS);
548 // Return the password
552 function MAKE_DATETIME ($time, $mode="0")
556 return NEVER_HAPPENED;
558 // Filter out numbers
559 $time = bigintval($time);
562 switch (GET_LANGUAGE())
564 case "de": // German date / time format
566 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
567 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
568 case "2": $ret = date("d.m.Y|H:i", $time); break;
569 case "3": $ret = date("d.m.Y", $time); break;
571 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
576 default: // Default is the US date / time format!
578 case "0": $ret = date("r", $time); break;
579 case "1": $ret = date("Y-m-d - g:i A", $time); break;
580 case "2": $ret = date("y-m-d|H:i", $time); break;
581 case "3": $ret = date("y-m-d", $time); break;
583 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
590 // Translates the american decimal dot into a german comma
591 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
592 // Default is 3 you can change this in admin area "Misc -> Misc Options"
593 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
595 // Use from config is default
596 $maxComma = getConfig('max_comma');
598 // Use from parameter?
599 if ($max > 0) $maxComma = $max;
602 if (($cut) && ($max == 0)) {
603 // Test for commata if in cut-mode
604 $com = explode(".", $dotted);
605 if (count($com) < 2) {
606 // Don't display commatas even if there are none... ;-)
612 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
615 switch (GET_LANGUAGE()) {
617 $dotted = number_format($dotted, $maxComma, ",", ".");
621 $dotted = number_format($dotted, $maxComma, ".", ",");
625 // Return translated value
630 function DEREFERER ($URL) {
631 // Don't de-refer our own links!
632 if (substr($URL, 0, strlen(URL)) != URL) {
633 // De-refer this link
634 $URL = "modules.php?module=loader&url=".encodeString(compileUriCode($URL));
641 // Translate Uni*-like gender to human-readable
642 function TRANSLATE_GENDER ($gender) {
644 $ret = "!{$gender}!";
646 // Male/female or company?
648 case "M": $ret = getMessage('GENDER_M'); break;
649 case "F": $ret = getMessage('GENDER_F'); break;
650 case "C": $ret = getMessage('GENDER_C'); break;
652 // Log unknown gender
653 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
657 // Return translated gender
662 function FRAMETESTER ($URL) {
663 // Prepare frametester URL
664 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
665 encodeString(compileUriCode($URL))
667 return $frametesterUrl;
671 function SELECTION_COUNT ($array) {
673 if (is_array($array)) {
674 foreach ($array as $key => $selected) {
675 if (!empty($selected)) $ret++;
681 function IMG_CODE ($code, $type, $DATA, $uid) {
682 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
685 function TRANSLATE_STATUS ($status) {
691 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
696 $ret = getMessage('ACCOUNT_DELETED');
700 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
701 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
709 function GET_LANGUAGE() {
710 // Set default return value to default language from config
711 $ret = constant('DEFAULT_LANG');
716 // Is the variable set
717 if (REQUEST_ISSET_GET(('mx_lang'))) {
718 // Accept only first 2 chars
719 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
720 } elseif (isset($GLOBALS['cache_array']['language'])) {
722 $ret = $GLOBALS['cache_array']['language'];
723 } elseif (!empty($lang)) {
724 // Check if main language file does exist
725 if (FILE_READABLE(constant('PATH')."inc/language/".$lang.".php")) {
726 // Okay found, so let's update cookies
729 } elseif (!isSessionVariableSet('mx_lang')) {
730 // Return stored value from cookie
731 $ret = get_session('mx_lang');
733 // Fixes a warning before the session has the mx_lang constant
734 if (empty($ret)) $ret = constant('DEFAULT_LANG');
738 $GLOBALS['cache_array']['language'] = $ret;
744 function SET_LANGUAGE ($lang) {
745 // Accept only first 2 chars!
746 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
749 set_session('mx_lang', $lang);
752 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
753 global $DATA, $_CONFIG;
755 // Make sure all template names are lowercase!
756 $template = strtolower($template);
758 // Default "nickname" if extension is not installed
761 // Prepare IP number and User Agent
762 $REMOTE_ADDR = GET_REMOTE_ADDR();
763 $HTTP_USER_AGENT = GET_USER_AGENT();
766 $ADMIN = constant('MAIN_TITLE');
768 // Is the admin logged in?
771 $aid = GET_CURRENT_ADMIN_ID();
774 $ADMIN = GET_ADMIN_EMAIL($aid);
777 // Neutral email address is default
778 $email = constant('WEBMASTER');
780 // Expiration in a nice output format
781 if (getConfig('auto_purge') == 0) {
782 // Will never expire!
783 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
785 // Create nice date string
786 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
789 // Is content an array?
790 if (is_array($content)) {
791 // Add expiration to array, $EXPIRATION is now deprecated!
792 $content['expiration'] = $EXPIRATION;
796 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
797 if (($UID > 0) && (is_array($content))) {
798 // If nickname extension is installed, fetch nickname as well
799 if (EXT_IS_ACTIVE("nickname")) {
800 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
802 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
803 array(bigintval($UID)), __FUNCTION__, __LINE__);
805 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
807 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
808 array(bigintval($UID)), __FUNCTION__, __LINE__);
811 // Fetch and merge data
812 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
813 $content = merge_array($content, SQL_FETCHARRAY($result));
814 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
817 SQL_FREERESULT($result);
820 // Translate M to male or F to female if present
821 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
823 // Overwrite email from data if present
824 if (isset($content['email'])) $email = $content['email'];
826 // Store email for some functions in global data array
827 $DATA['email'] = $email;
830 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
832 // Check for admin/guest/member templates
833 if (strpos($template, "admin_") > -1) {
834 // Admin template found
835 $FQFN = $BASE."admin/".$template.".tpl";
836 } elseif (strpos($template, "guest_") > -1) {
837 // Guest template found
838 $FQFN = $BASE."guest/".$template.".tpl";
839 } elseif (strpos($template, "member_") > -1) {
840 // Member template found
841 $FQFN = $BASE."member/".$template.".tpl";
843 // Test for extension
844 $test = substr($template, 0, strpos($template, "_"));
845 if (EXT_IS_ACTIVE($test)) {
846 // Set extra path to extension's name
847 $FQFN = $BASE.$test."/".$template.".tpl";
849 // No special filename
850 $FQFN = $BASE.$template.".tpl";
854 // Does the special template exists?
855 if (!FILE_READABLE($FQFN)) {
856 // Reset to default template
857 $FQFN = $BASE.$template.".tpl";
860 // Now does the final template exists?
862 if (FILE_READABLE($FQFN)) {
863 // The local file does exists so we load it. :)
864 $tmpl_file = READ_FILE($FQFN);
865 $tmpl_file = SQL_ESCAPE($tmpl_file);
868 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
870 } elseif (!empty($template)) {
871 // Template file not found!
872 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
873 {--TEMPLATE_CONTENT--}
874 <pre>".print_r($content, true)."</pre>
876 <pre>".print_r($DATA, true)."</pre>
879 // Debug mode not active? Then remove the HTML tags
880 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
882 // No template name supplied!
883 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
886 // Is there some content?
887 if (empty($newContent)) {
889 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
890 // Add last error if the required function exists
891 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
894 // Remove content and data
898 // Return compiled content
899 return COMPILE_CODE($newContent);
902 function MAKE_TIME ($H, $M, $S, $stamp) {
903 // Extract day, month and year from given timestamp
904 $DAY = date("d", $stamp);
905 $MONTH = date("m", $stamp);
906 $YEAR = date('Y', $stamp);
908 // Create timestamp for wished time which depends on extracted date
909 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
912 function LOAD_URL ($URL, $addUrlData=true) {
913 // Compile out URI codes
914 $URL = compileUriCode($URL);
916 // Check if http(s):// is there
917 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
918 // Make all URLs full-qualified
923 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
924 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
925 $OUTPUT = ob_get_contents();
927 // Clear it only if there is content
928 if (!empty($OUTPUT)) {
932 // Add some data to URL if cookies are not accepted
933 if (((!defined('__COOKIES')) || (!constant('__COOKIES'))) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
935 // Probe for bot from search engine
936 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
937 // Search engine bot detected so let's rewrite many chars for the link
938 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
940 // Output new location link as anchor
941 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
942 } elseif (!headers_sent()) {
943 // Load URL when headers are not sent
944 //* DEBUG: */ debug_report_bug("URL={$URL}");
945 header ("Location: ".str_replace("&", "&", $URL));
947 // Output error message
948 LOAD_INC("inc/header.php");
949 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
950 LOAD_INC("inc/footer.php");
955 // Wrapper for LOAD_URL but URL comes from a configuration entry
956 function LOAD_CONFIGURED_URL ($configEntry) {
958 $URL = getConfig($configEntry);
963 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
971 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
972 // Is the code a string?
973 if (!is_string($code)) {
974 // Silently return it
978 $ARRAY = $GLOBALS['security_chars'];
980 // Select smaller set of chars to replace when we e.g. want to compile URLs
981 if (!$full) $ARRAY = $GLOBALS['url_chars'];
985 // BEFORE 0.2.1 : Language and data constants
986 // WITH 0.2.1+ : Only language constants
987 $code = str_replace('{--','".', str_replace('--}','."', $code));
989 // BEFORE 0.2.1 : Not used
990 // WITH 0.2.1+ : Data constants
991 $code = str_replace('{!','".', str_replace("!}", '."', $code));
994 // Compile QUOT and other non-HTML codes
995 foreach ($ARRAY['to'] as $k => $to) {
996 // Do the reversed thing as in inc/libs/security_functions.php
997 $code = str_replace($to, $ARRAY['from'][$k], $code);
1000 // But shall I keep simple quotes for later use?
1001 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1003 // Find $content[bla][blub] entries
1004 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1006 // Are some matches found?
1007 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1008 // Replace all matches
1009 $matchesFound = array();
1010 foreach ($matches[0] as $key => $match) {
1011 // Fuzzy look has failed by default
1012 $fuzzyFound = false;
1014 // Fuzzy look on match if already found
1015 foreach ($matchesFound as $found => $set) {
1017 $test = substr($found, 0, strlen($match));
1019 // Does this entry exist?
1020 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1021 if ($test == $match) {
1023 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1030 if ($fuzzyFound) continue;
1032 // Take all string elements
1033 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1034 // Replace it in the code
1035 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1036 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1037 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1038 $matchesFound[$key."_".$matches[4][$key]] = 1;
1039 $matchesFound[$match] = 1;
1040 } elseif (!isset($matchesFound[$match])) {
1041 // Not yet replaced!
1042 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1043 $code = str_replace($match, "\".".$match.".\"", $code);
1044 $matchesFound[$match] = 1;
1049 // Return compiled code
1053 /************************************************************************
1055 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1056 * $a_sort sortiert: *
1058 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1059 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1060 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1061 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1062 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1064 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1065 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1066 * Sie, dass es doch nicht so schwer ist! :-) *
1068 ************************************************************************/
1069 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1071 while ($primary_key < count($a_sort)) {
1072 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1073 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1076 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1077 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1078 } elseif ($key != $key2) {
1079 // Sort numbers (E.g.: 9 < 10)
1080 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1081 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1085 // We have found two different values, so let's sort whole array
1086 foreach ($dummy as $sort_key => $sort_val) {
1087 $t = $dummy[$sort_key][$key];
1088 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1089 $dummy[$sort_key][$key2] = $t;
1100 // Write back sorted array
1105 function ADD_SELECTION ($type, $DEFAULT, $prefix="", $id="0") {
1108 if ($type == "yn") {
1109 // This is a yes/no selection only!
1110 if ($id > 0) $prefix .= "[".$id."]";
1111 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1113 // Begin with regular selection box here
1114 if (!empty($prefix)) $prefix .= "_";
1116 if ($id > 0) $type2 .= "[".$id."]";
1117 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1122 for ($idx = 1; $idx < 32; $idx++) {
1123 $OUT .= "<option value=\"".$idx."\"";
1124 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1125 $OUT .= ">".$idx."</option>\n";
1129 case "month": // Month
1130 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1131 $OUT .= "<option value=\"".$month."\"";
1132 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1133 $OUT .= ">".$descr."</option>\n";
1137 case "year": // Year
1139 $YEAR = date('Y', time());
1141 // Use configured min age or fixed?
1142 if (GET_EXT_VERSION("other") >= "0.2.1") {
1144 $startYear = $YEAR - getConfig('min_age');
1147 $startYear = $YEAR - 16;
1150 // Calculate earliest year (100 years old people can still enter Internet???)
1151 $minYear = $YEAR - 100;
1153 // Check if the default value is larger than minimum and bigger than actual year
1154 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1155 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1156 $OUT .= "<option value=\"".$idx."\"";
1157 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1158 $OUT .= ">".$idx."</option>\n";
1160 } elseif ($DEFAULT == -1) {
1161 // Current year minus 1
1162 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1164 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1167 // Get current year and subtract the configured minimum age
1168 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1169 // Calculate earliest year depending on extension version
1170 if (GET_EXT_VERSION("other") >= "0.2.1") {
1171 // Use configured minimum age
1172 $YEAR = date('Y', time()) - getConfig('min_age');
1174 // Use fixed 16 years age
1175 $YEAR = date('Y', time()) - 16;
1178 // Construct year selection list
1179 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1180 $OUT .= "<option value=\"".$idx."\"";
1181 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1182 $OUT .= ">".$idx."</option>\n";
1189 for ($idx = 0; $idx < 60; $idx+=5) {
1190 if (strlen($idx) == 1) $idx = "0".$idx;
1191 $OUT .= "<option value=\"".$idx."\"";
1192 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1193 $OUT .= ">".$idx."</option>\n";
1198 for ($idx = 0; $idx < 24; $idx++) {
1199 if (strlen($idx) == 1) $idx = "0".$idx;
1200 $OUT .= "<option value=\"".$idx."\"";
1201 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1202 $OUT .= ">".$idx."</option>\n";
1207 $OUT .= "<option value=\"Y\"";
1208 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1209 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1210 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1211 $OUT .= ">{--NO--}</option>\n";
1214 $OUT .= " </select>\n";
1219 function TRANSLATE_YESNO ($yn) {
1221 $translated = "??? (".$yn.")";
1223 case "Y": $translated = getMessage('YES'); break;
1224 case "N": $translated = getMessage('NO'); break;
1226 // Log unknown value
1227 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
1236 // Deprecated : $length
1239 function generateRandomCodde ($length, $code, $uid, $DATA="") {
1240 // Fix missing _MAX constant
1241 // @TODO Rewrite this unnice code
1242 if (!defined('_MAX')) define('_MAX', 15235);
1244 // Build server string
1245 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
1248 $keys = constant('SITE_KEY').":".constant('DATE_KEY');
1249 if (isConfigEntrySet('secret_key')) $keys .= ":".getConfig('secret_key');
1250 if (isConfigEntrySet('file_hash')) $keys .= ":".getConfig('file_hash');
1251 $keys .= ":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1252 if (isConfigEntrySet('master_salt')) $keys .= ":".getConfig('master_salt');
1254 // Build string from misc data
1255 $data = $code.":".$uid.":".$DATA;
1257 // Add more additional data
1258 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1259 if (isUserIdSet()) $data .= ":".getUserId();
1260 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1261 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1262 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1264 // Calculate number for generating the code
1265 $a = $code + constant('_ADD') - 1;
1267 if (isConfigEntrySet('master_hash')) {
1268 // Generate hash with master salt from modula of number with the prime number and other data
1269 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1271 // Create number from hash
1272 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1274 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1275 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1277 // Create number from hash
1278 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1281 // At least 10 numbers shall be secure enought!
1282 $len = getConfig('code_length');
1283 if ($len == 0) $len = $length;
1284 if ($len == 0) $len = 10;
1286 // Cut off requested counts of number
1287 $return = substr(str_replace('.', "", $rcode), 0, $len);
1289 // Done building code
1293 // Does only allow numbers
1294 function bigintval ($num, $castValue = true) {
1295 // Filter all numbers out
1296 $ret = preg_replace("/[^0123456789]/", "", $num);
1299 if ($castValue) $ret = (double)$ret;
1301 // Has the whole value changed?
1302 // @TODO Remove this if() block if all is working fine
1303 if ("".$ret."" != "".$num."") {
1305 debug_report_bug("{$ret}<>{$num}");
1312 // Insert the code in $img_code into jpeg or PNG image
1313 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1314 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1315 // Stop execution of function here because of over-sized code length
1317 } elseif (!$headerSent) {
1318 // Return in an HTML code code
1319 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1323 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1324 if (FILE_READABLE($img)) {
1325 // Switch image type
1326 switch (getConfig('img_type'))
1329 // Okay, load image and hide all errors
1330 $image = @imagecreatefromjpeg($img);
1334 // Okay, load image and hide all errors
1335 $image = @imagecreatefrompng($img);
1339 // Exit function here
1340 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1344 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1345 $text_color = imagecolorallocate($image, 0, 0, 0);
1347 // Insert code into image
1348 imagestring($image, 5, 14, 2, $img_code, $text_color);
1350 // Return to browser
1351 header ("Content-Type: image/".getConfig('img_type'));
1353 // Output image with matching image factory
1354 switch (getConfig('img_type')) {
1355 case "jpg": imagejpeg($image); break;
1356 case "png": imagepng($image); break;
1359 // Remove image from memory
1360 imagedestroy($image);
1362 // Create selection box or array of splitted timestamp
1363 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1364 // Calculate 2-seconds timestamp
1365 $stamp = round($timestamp);
1366 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1368 // Do we have a leap year?
1370 $TEST = date('Y', time()) / 4;
1371 $M1 = date("m", time());
1372 $M2 = date("m", (time() + $timestamp));
1374 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1375 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1377 // First of all years...
1378 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1379 //* DEBUG: */ print("Y={$Y}<br />\n");
1381 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1382 //* DEBUG: */ print("M={$M}<br />\n");
1384 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1385 //* DEBUG: */ print("W={$W}<br />\n");
1387 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1388 //* DEBUG: */ print("D={$D}<br />\n");
1390 $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));
1391 //* DEBUG: */ print("h={$h}<br />\n");
1393 $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));
1394 //* DEBUG: */ print("m={$m}<br />\n");
1395 // And at last seconds...
1396 $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));
1397 //* DEBUG: */ print("s={$s}<br />\n");
1399 // Is seconds zero and time is < 60 seconds?
1400 if (($s == 0) && ($timestamp < 60)) {
1402 $s = round($timestamp);
1406 // Now we convert them in seconds...
1408 if ($return_array) {
1409 // Just put all data in an array for later use
1421 $OUT = "<div align=\"".$align."\">\n";
1422 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1425 if (ereg('Y', $display) || (empty($display))) {
1426 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1429 if (ereg("M", $display) || (empty($display))) {
1430 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1433 if (ereg("W", $display) || (empty($display))) {
1434 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1437 if (ereg("D", $display) || (empty($display))) {
1438 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1441 if (ereg("h", $display) || (empty($display))) {
1442 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1445 if (ereg("m", $display) || (empty($display))) {
1446 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1449 if (ereg("s", $display) || (empty($display))) {
1450 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1456 if (ereg('Y', $display) || (empty($display))) {
1457 // Generate year selection
1458 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1459 for ($idx = 0; $idx <= 10; $idx++) {
1460 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1461 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1462 $OUT .= ">".$idx."</option>\n";
1464 $OUT .= " </select></td>\n";
1466 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1469 if (ereg("M", $display) || (empty($display))) {
1470 // Generate month selection
1471 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1472 for ($idx = 0; $idx <= 11; $idx++)
1474 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1475 if ($idx == $M) $OUT .= " selected=\"selected\"";
1476 $OUT .= ">".$idx."</option>\n";
1478 $OUT .= " </select></td>\n";
1480 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1483 if (ereg("W", $display) || (empty($display))) {
1484 // Generate week selection
1485 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1486 for ($idx = 0; $idx <= 4; $idx++) {
1487 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1488 if ($idx == $W) $OUT .= " selected=\"selected\"";
1489 $OUT .= ">".$idx."</option>\n";
1491 $OUT .= " </select></td>\n";
1493 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1496 if (ereg("D", $display) || (empty($display))) {
1497 // Generate day selection
1498 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1499 for ($idx = 0; $idx <= 31; $idx++) {
1500 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1501 if ($idx == $D) $OUT .= " selected=\"selected\"";
1502 $OUT .= ">".$idx."</option>\n";
1504 $OUT .= " </select></td>\n";
1506 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1509 if (ereg("h", $display) || (empty($display))) {
1510 // Generate hour selection
1511 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1512 for ($idx = 0; $idx <= 23; $idx++) {
1513 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1514 if ($idx == $h) $OUT .= " selected=\"selected\"";
1515 $OUT .= ">".$idx."</option>\n";
1517 $OUT .= " </select></td>\n";
1519 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1522 if (ereg("m", $display) || (empty($display))) {
1523 // Generate minute selection
1524 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1525 for ($idx = 0; $idx <= 59; $idx++) {
1526 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1527 if ($idx == $m) $OUT .= " selected=\"selected\"";
1528 $OUT .= ">".$idx."</option>\n";
1530 $OUT .= " </select></td>\n";
1532 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1535 if (ereg("s", $display) || (empty($display))) {
1536 // Generate second selection
1537 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1538 for ($idx = 0; $idx <= 59; $idx++) {
1539 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1540 if ($idx == $s) $OUT .= " selected=\"selected\"";
1541 $OUT .= ">".$idx."</option>\n";
1543 $OUT .= " </select></td>\n";
1545 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1548 $OUT .= "</table>\n";
1550 // Return generated HTML code
1556 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1557 // Initial return value
1560 // Do we have a leap year?
1562 $TEST = date('Y', time()) / 4;
1563 $M1 = date("m", time());
1564 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1565 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1566 // First add years...
1567 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1569 $ret += $POST[$prefix."_mo"] * 2628000;
1571 $ret += $POST[$prefix."_we"] * 604800;
1573 $ret += $POST[$prefix."_da"] * 86400;
1575 $ret += $POST[$prefix."_ho"] * 3600;
1577 $ret += $POST[$prefix."_mi"] * 60;
1578 // And at last seconds...
1579 $ret += $POST[$prefix."_se"];
1580 // Return calculated value
1584 // Sends out mail to all administrators
1585 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1586 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1587 // Trim template name
1588 $template = trim($template);
1590 // Load email template
1591 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1593 // Check which admin shall receive this mail
1594 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1595 array($template), __FUNCTION__, __LINE__);
1596 if (SQL_NUMROWS($result) == 0) {
1597 // Create new entry (to all admins)
1598 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1599 array($template), __FUNCTION__, __LINE__);
1601 // Load admin IDs...
1602 // @TODO This can be, somehow, rewritten
1603 $adminIds = array();
1604 while ($content = SQL_FETCHARRAY($result)) {
1605 $adminIds[] = $content['admin_id'];
1609 SQL_FREERESULT($result);
1614 // "implode" IDs and query string
1615 $aid = implode(",", $adminIds);
1617 if (EXT_IS_ACTIVE("events")) {
1618 // Add line to user events
1619 EVENTS_ADD_LINE($subj, $msg, $UID);
1621 // Log error for debug
1622 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1628 } elseif ($aid == "0") {
1629 // Select all email adresses
1630 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1631 __FUNCTION__, __LINE__);
1633 // If Admin-ID is not "to-all" select
1634 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1635 array($aid), __FUNCTION__, __LINE__);
1639 // Load email addresses and send away
1640 while ($content = SQL_FETCHARRAY($result)) {
1641 SEND_EMAIL($content['email'], $subj, $msg);
1645 SQL_FREERESULT($result);
1649 function CREATE_FANCY_TIME ($stamp) {
1650 // Get data array with years/months/weeks/days/...
1651 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1653 foreach($data as $k => $v) {
1655 // Value is greater than 0 "eval" data to return string
1656 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1662 // Do we have something there?
1663 if (strlen($ret) > 0) {
1664 // Remove leading commata and space
1665 $ret = substr($ret, 2);
1668 $ret = "0 {--_SECONDS--}";
1671 // Return fancy time string
1676 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1677 $SEP = ""; $TOP = "";
1680 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1684 for ($page = 1; $page <= $PAGES; $page++) {
1685 // Is the page currently selected or shall we generate a link to it?
1686 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1687 // Is currently selected, so only highlight it
1688 $NAV .= "<strong>-";
1690 // Open anchor tag and add base URL
1691 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1693 // Add userid when we shall show all mails from a single member
1694 if ((REQUEST_ISSET_GET(('uid'))) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1696 // Close open anchor tag
1700 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1701 // Is currently selected, so only highlight it
1702 $NAV .= "-</strong>";
1708 // Add seperator if we have not yet reached total pages
1709 if ($page < $PAGES) $NAV .= " | ";
1712 // Define constants only once
1713 if (!defined('__NAV_OUTPUT')) {
1714 define('__NAV_OUTPUT' , $NAV);
1715 define('__NAV_COLSPAN', $colspan);
1716 define('__NAV_TOP' , $TOP);
1717 define('__NAV_SEP' , $SEP);
1720 // Load navigation template
1721 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1723 if ($return === true) {
1724 // Return generated HTML-Code
1732 // Extract host from script name
1733 function EXTRACT_HOST (&$script) {
1734 // Use default SERVER_URL by default... ;) So?
1735 $url = constant('SERVER_URL');
1737 // Is this URL valid?
1738 if (substr($script, 0, 7) == "http://") {
1739 // Use the hostname from script URL as new hostname
1740 $url = substr($script, 7);
1741 $extract = explode("/", $url);
1743 // Done extracting the URL :)
1746 // Extract host name
1747 $host = str_replace("http://", "", $url);
1748 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1750 // Generate relative URL
1751 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1752 if (substr(strtolower($script), 0, 7) == "http://") {
1753 // But only if http:// is in front!
1754 $script = substr($script, (strlen($url) + 7));
1755 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1757 $script = substr($script, (strlen($url) + 8));
1760 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1761 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1767 // Send a GET request
1768 function GET_URL ($script) {
1769 // Compile the script name
1770 $script = COMPILE_CODE($script);
1772 // Extract host name from script
1773 $host = EXTRACT_HOST($script);
1775 // Generate GET request header
1776 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1777 $request .= "Host: " . $host . "\r\n";
1778 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1779 if (defined('FULL_VERSION')) {
1780 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1782 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1784 $request .= "Content-Type: text/plain\r\n";
1785 $request .= "Cache-Control: no-cache\r\n";
1786 $request .= "Connection: Close\r\n\r\n";
1788 // Send the raw request
1789 $response = SEND_RAW_REQUEST($host, $request);
1791 // Return the result to the caller function
1795 // Send a POST request
1796 function POST_URL ($script, $postData) {
1797 // Is postData an array?
1798 if (!is_array($postData)) {
1800 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1801 return array("", "", "");
1804 // Compile the script name
1805 $script = COMPILE_CODE($script);
1807 // Extract host name from script
1808 $host = EXTRACT_HOST($script);
1810 // Construct request
1811 $data = http_build_query($postData, '','&');
1813 // Generate POST request header
1814 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1815 $request .= "Host: " . $host . "\r\n";
1816 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1817 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1818 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1819 $request .= "Content-length: " . strlen($data) . "\r\n";
1820 $request .= "Cache-Control: no-cache\r\n";
1821 $request .= "Connection: Close\r\n\r\n";
1824 // Send the raw request
1825 $response = SEND_RAW_REQUEST($host, $request);
1827 // Return the result to the caller function
1831 // Sends a raw request to another host
1832 function SEND_RAW_REQUEST ($host, $request) {
1834 $response = array("", "", "");
1836 // Default is not to use proxy
1839 // Are proxy settins set?
1840 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1846 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1848 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1850 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1854 if (!is_resource($fp)) {
1861 // Generate CONNECT request header
1862 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1863 $proxyTunnel .= "Host: ".$host."\r\n";
1865 // Use login data to proxy? (username at least!)
1866 if (getConfig('proxy_username') != "") {
1868 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1869 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1872 // Add last new-line
1873 $proxyTunnel .= "\r\n";
1874 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1877 fputs($fp, $proxyTunnel);
1881 // No response received
1885 // Read the first line
1886 $resp = trim(fgets($fp, 10240));
1887 $respArray = explode(" ", $resp);
1888 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1889 // Invalid response!
1895 fputs($fp, $request);
1898 while (!feof($fp)) {
1899 $response[] = trim(fgets($fp, 1024));
1905 // Skip first empty lines
1907 foreach ($resp as $idx => $line) {
1909 $line = trim($line);
1911 // Is this line empty?
1914 array_shift($response);
1916 // Abort on first non-empty line
1921 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1923 // Proxy agent found?
1924 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1925 // Proxy header detected, so remove two lines
1926 array_shift($response);
1927 array_shift($response);
1930 // Was the request successfull?
1931 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1932 // Not found / access forbidden
1933 $response = array("", "", "");
1940 // Taken from www.php.net eregi() user comments
1941 function VALIDATE_EMAIL ($email) {
1943 $email = COMPILE_CODE($email);
1945 // Check first part of email address
1946 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1949 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1952 $regex = "^".$first."@".$domain."$";
1954 // Return check result
1955 return eregi($regex, $email);
1958 // Function taken from user comments on www.php.net / function eregi()
1959 function VALIDATE_URL ($URL, $compile=true) {
1960 // Trim URL a little
1961 $URL = trim(urldecode($URL));
1962 //* DEBUG: */ echo $URL."<br />";
1964 // Compile some chars out...
1965 if ($compile) $URL = compileUriCode($URL, false, false, false);
1966 //* DEBUG: */ echo $URL."<br />";
1968 // Check for the extension filter
1969 if (EXT_IS_ACTIVE("filter")) {
1970 // Use the extension's filter set
1971 return FILTER_VALIDATE_URL($URL, false);
1974 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1975 // https:// in front of the URLs
1976 return isUrlValid($URL);
1979 // Generate a list of administrative links to a given userid
1980 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1981 // Define all main targets
1982 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1984 // Begin of navigation links
1985 $eval = "\$OUT = \"[ ";
1987 foreach ($TARGETS as $tar) {
1988 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1989 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1990 if (($tar == "lock_user") && ($status == "LOCKED")) {
1991 // Locked accounts shall be unlocked
1992 $eval .= "UNLOCK_USER";
1994 // All other status is fine
1995 $eval .= strtoupper($tar);
1997 $eval .= "_TITLE--}\\\">{--ADMIN_";
1998 if (($tar == "lock_user") && ($status == "LOCKED")) {
1999 // Locked accounts shall be unlocked
2000 $eval .= "UNLOCK_USER";
2002 // All other status is fine
2003 $eval .= strtoupper($tar);
2005 $eval .= "--}</a></span> | ";
2008 // Finish navigation link
2009 $eval = substr($eval, 0, -7)."]\";";
2016 // Generate an email link
2017 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2018 // Default email link (INSECURE! Spammer can read this by harvester programs)
2019 $EMAIL = "mailto:".$email;
2021 // Check for several extensions
2022 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2023 // Create email link for contacting admin in guest area
2024 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2025 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2026 // Create email link for contacting a member within admin area (or later in other areas, too?)
2027 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2028 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2029 // Create email link to contact sponsor within admin area (or like the link above?)
2030 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2033 // Shall I close the link when there is no admin?
2034 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2036 // Return email link
2040 // Generate a hash for extra-security for all passwords
2041 function generateHash ($plainText, $salt = "") {
2042 // Is the required extension "sql_patches" there and a salt is not given?
2043 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2044 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2045 return md5($plainText);
2048 // Do we miss an arry element here?
2049 if (!isConfigEntrySet('file_hash')) {
2051 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2054 // When the salt is empty build a new one, else use the first x configured characters as the salt
2056 // Build server string
2057 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
2060 $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');
2063 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2065 // Calculate number for generating the code
2066 $a = time() + constant('_ADD') - 1;
2068 // Generate SHA1 sum from modula of number and the prime number
2069 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2070 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2071 $sha1 = scrambleString($sha1);
2072 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2073 //* DEBUG: */ $sha1b = descrambleString($sha1);
2074 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2076 // Generate the password salt string
2077 $salt = substr($sha1, 0, getConfig('salt_length'));
2078 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2081 $salt = substr($salt, 0, getConfig('salt_length'));
2082 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2086 return $salt.sha1($salt.$plainText);
2089 // Scramble a string
2090 function scrambleString($str) {
2094 // Final check, in case of failture it will return unscrambled string
2095 if (strlen($str) > 40) {
2096 // The string is to long
2098 } elseif (strlen($str) == 40) {
2100 $scrambleNums = explode(":", getConfig('pass_scramble'));
2102 // Generate new numbers
2103 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2106 // Scramble string here
2107 //* DEBUG: */ echo "***Original=".$str."***<br />";
2108 for ($idx = 0; $idx < strlen($str); $idx++) {
2109 // Get char on scrambled position
2110 $char = substr($str, $scrambleNums[$idx], 1);
2112 // Add it to final output string
2113 $scrambled .= $char;
2116 // Return scrambled string
2117 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2121 // De-scramble a string scrambled by scrambleString()
2122 function descrambleString($str) {
2123 // Scramble only 40 chars long strings
2124 if (strlen($str) != 40) return $str;
2126 // Load numbers from config
2127 $scrambleNums = explode(":", getConfig('pass_scramble'));
2130 if (count($scrambleNums) != 40) return $str;
2132 // Begin descrambling
2133 $orig = str_repeat(" ", 40);
2134 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2135 for ($idx = 0; $idx < 40; $idx++) {
2136 $char = substr($str, $idx, 1);
2137 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2140 // Return scrambled string
2141 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2145 // Generated a "string" for scrambling
2146 function genScrambleString ($len) {
2147 // Prepare array for the numbers
2148 $scrambleNumbers = array();
2150 // First we need to setup randomized numbers from 0 to 31
2151 for ($idx = 0; $idx < $len; $idx++) {
2153 $rand = mt_rand(0, ($len -1));
2155 // Check for it by creating more numbers
2156 while (array_key_exists($rand, $scrambleNumbers)) {
2157 $rand = mt_rand(0, ($len -1));
2161 $scrambleNumbers[$rand] = $rand;
2164 // So let's create the string for storing it in database
2165 $scrambleString = implode(":", $scrambleNumbers);
2166 return $scrambleString;
2169 // Append data like session ID or referal ID to the given URL which would
2170 // normally be stored in cookies
2171 function ADD_URL_DATA ($URL) {
2175 // Determine URL binder
2177 if (strpos($URL, "?") !== false) $BIND = "&";
2179 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2180 // Cookies are not accepted
2181 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2182 // Cookie found in URL
2183 $ADD .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2184 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2185 // Not found! So let's set default here
2186 $ADD .= $BIND."refid=".getConfig('def_refid');
2190 // Add all together and return it
2194 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2195 function generatePassString ($passHash) {
2196 // Return vanilla password hash
2199 // Is a secret key and master salt already initialized?
2200 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2201 // Only calculate when the secret key is generated
2202 $newHash = ""; $start = 9;
2203 for ($idx = 0; $idx < 10; $idx++) {
2204 $part1 = hexdec(substr($passHash, $start, 4));
2205 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2206 $mod = dechex($idx);
2207 if ($part1 > $part2) {
2208 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2209 } elseif ($part2 > $part1) {
2210 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2212 $mod = substr(round($mod), 0, 4);
2213 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2214 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2219 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2220 $ret = generateHash($newHash, getConfig('master_salt'));
2221 //* DEBUG: */ print($ret."<br />\n");
2224 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2225 $ret = md5($passHash);
2226 //* DEBUG: */ echo "++".$ret."++<br />\n";
2233 // Fix "deleted" cookies
2234 function FIX_DELETED_COOKIES ($cookies) {
2235 // Is this an array with entries?
2236 if ((is_array($cookies)) && (count($cookies) > 0)) {
2237 // Then check all cookies if they are marked as deleted!
2238 foreach ($cookies as $cookieName) {
2239 // Is the cookie set to "deleted"?
2240 if (get_session($cookieName) == "deleted") {
2241 set_session($cookieName, "");
2247 // Output error messages in a fasioned way and die...
2248 function mxchange_die ($msg) {
2250 LOAD_INC_ONCE("inc/header.php");
2252 // Load the message template
2253 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2256 LOAD_INC_ONCE("inc/footer.php");
2262 // Display parsing time and number of SQL queries in footer
2263 function DISPLAY_PARSING_TIME_FOOTER() {
2264 // Is the timer started?
2265 if (!isset($GLOBALS['startTime'])) {
2271 $endTime = microtime(true);
2273 // "Explode" both times
2274 $start = explode(" ", $GLOBALS['startTime']);
2275 $end = explode(" ", $endTime);
2276 $runTime = $end[0] - $start[0];
2277 if ($runTime < 0) $runTime = 0;
2278 $runTime = TRANSLATE_COMMA($runTime);
2282 'runtime' => $runTime,
2283 'numSQLs' => (getConfig('sql_count') + 1),
2284 'numTemplates' => (getConfig('num_templates') + 1)
2287 // Load the template
2288 LOAD_TEMPLATE("show_timings", false, $content);
2291 // Check wether a boolean constant is set
2292 // Taken from user comments in PHP documentation for function constant()
2293 function isBooleanConstantAndTrue ($constName) { // : Boolean
2294 // Failed by default
2298 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2300 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2301 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2304 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2305 if (defined($constName)) {
2307 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2308 $res = (constant($constName) === true);
2312 $GLOBALS['cache_array']['const'][$constName] = $res;
2314 //* DEBUG: */ var_dump($res);
2320 // Checks if a given apache module is loaded
2321 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2322 // Check it and return result
2323 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2326 // "Getter" for language strings
2327 // @TODO Rewrite all language constants to this function.
2328 function getMessage ($messageId) {
2329 // Default is not found!
2330 $return = "!".$messageId."!";
2332 // Is the language string found?
2333 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2334 // Language array element found in small_letters
2335 $return = $GLOBALS['msg'][$messageId];
2336 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2337 // @DEPRECATED Language array element found in BIG_LETTERS
2338 $return = $GLOBALS['msg'][$messageId];
2339 } elseif (defined($messageId)) {
2340 // @DEPRECATED Deprecated constant found
2341 $return = constant($messageId);
2343 // Missing language constant
2344 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2347 // Return the string
2351 // Get current theme name
2352 function GET_CURR_THEME() {
2353 // The default theme is 'default'... ;-)
2356 // Load default theme if not empty from configuration
2357 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2359 if (!isSessionVariableSet('mxchange_theme')) {
2360 // Set default theme
2361 set_session('mxchange_theme', $ret);
2362 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2363 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2364 // Get theme from cookie
2365 $ret = get_session('mxchange_theme');
2368 if (THEME_GET_ID($ret) == 0) {
2369 // Fix it to default
2372 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
2373 // Prepare FQFN for checking
2374 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
2376 // Installation mode active
2377 if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
2378 // Set cookie from URL data
2379 set_session('mxchange_theme', REQUEST_GET(('theme')));
2380 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2381 // Set cookie from posted data
2382 set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2386 $ret = get_session('mxchange_theme');
2388 // Invalid design, reset cookie
2389 set_session('mxchange_theme', $ret);
2392 // Add (maybe) found theme.php file to inclusion list
2393 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2395 // Try to load the requested include file
2396 if (INCLUDE_READABLE($INC)) ADD_INC_TO_POOL($INC);
2398 // Return theme value
2402 // Get id from theme
2403 function THEME_GET_ID ($name) {
2404 // Is the extension "theme" installed?
2405 if (!EXT_IS_ACTIVE("theme")) {
2413 // Is the cache entry there?
2414 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2415 // Get the version from cache
2416 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2419 incrementConfigEntry('cache_hits');
2420 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2421 // Check if current theme is already imported or not
2422 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2423 array($name), __FUNCTION__, __LINE__);
2426 if (SQL_NUMROWS($result) == 1) {
2428 list($id) = SQL_FETCHROW($result);
2432 SQL_FREERESULT($result);
2439 // Read a given file
2440 function READ_FILE ($FQFN, $sqlPrepare = false) {
2442 if (function_exists('file_get_contents')) {
2444 $content = file_get_contents($FQFN);
2446 // Fall-back to implode-file chain
2447 $content = implode("", file($FQFN));
2450 // Prepare SQL queries?
2451 if ($sqlPrepare === true) {
2452 // Remove some unwanted chars
2453 $content = str_replace("\r", "", $content);
2454 $content = str_replace("\n\n", "\n", $content);
2457 // Return the content
2461 // Writes content to a file
2462 function WRITE_FILE ($FQFN, $content) {
2463 // Is the file writeable?
2464 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2466 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2472 // By default all is failed...
2475 // Is the function there?
2476 if (function_exists('file_put_contents')) {
2477 // Write it directly
2478 $return = file_put_contents($FQFN, $content);
2480 // Write it with fopen
2481 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
2482 fwrite($fp, $content);
2486 $return = chmod($FQFN, 0644);
2493 // Generates an error code from given account status
2494 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
2495 // Default error code if unknown account status
2496 $ERROR = getCode('UNKNOWN_STATUS');
2498 // Generate constant name
2499 $constantName = sprintf("ID_%s", $status);
2501 // Is the constant there?
2502 if (isCodeSet($constantName)) {
2504 $ERROR = getCode($constantName);
2507 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2510 // Return error code
2514 // Clears the output buffer. This function does *NOT* backup sent content.
2515 function clearOutputBuffer () {
2516 // Trigger an error on failure
2517 if (!ob_end_clean()) {
2519 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
2523 // Function to search for the last modifified file
2524 function searchDirsRecursive ($dir, &$last_changed) {
2526 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2527 $ds = GET_DIR_AS_ARRAY($dir, "", true, false);
2528 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2530 // Walk through all entries
2531 foreach ($ds as $d) {
2532 // Generate proper FQFN
2533 $FQFN = str_replace("//", "/", constant('PATH') . $dir. "/". $d);
2535 // Does it match what we are looking for? (We skip a lot files already!)
2536 if (!preg_match('@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache)$@', $d)) { // no . or .. or .revision or .svn in the filename
2537 // Is it a file and readable?
2538 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2539 if (isDirectory($FQFN)) {
2540 // $FQFN is a directory so also crawl into this directory
2542 if (!empty($dir)) $newDir = $dir . "/". $d;
2543 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2544 searchDirsRecursive($newDir, $last_changed);
2545 } elseif (FILE_READABLE($FQFN)) {
2546 // $FQFN is a filename and no directory
2547 $time = filemtime($FQFN);
2548 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2549 if ($last_changed['time'] < $time) {
2550 // This file is newer as the file before
2551 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2552 $last_changed['path_name'] = $FQFN;
2553 $last_changed['time'] = $time;
2560 // "Getter" for revision/version data
2561 function getActualVersion ($type = 'Revision') {
2562 // By default nothing is new... ;-)
2565 if (EXT_IS_ACTIVE("cache")) {
2566 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2567 if (isset($_GET['check_revision_data']) && $_GET['check_revision_data'] == 'yes') $new = true;
2568 if (!isset($GLOBALS['cache_array']['revision'][$type])
2569 || count($GLOBALS['cache_array']['revision']) < 3
2570 || !$GLOBALS['cache_instance']->loadCacheFile("revision")) $new = true;
2572 // Is the cache file outdated/invalid?
2574 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2576 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2577 unset($GLOBALS['cache_array']['revision']);
2579 // Reload load_cach-revison.php
2580 LOAD_INC("inc/loader/load_cache-revision.php");
2583 // Return found value
2584 return $GLOBALS['cache_array']['revision'][$type][0];
2587 // Old Version without ext-cache active (deprecated ?)
2589 // FQFN of revision file
2590 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2592 // Check if $_GET['check_revision_data'] is setted (switch for manually rewrite the .revision-File)
2593 if ((isset($_GET['check_revision_data'])) && ($_GET['check_revision_data'] == 'yes')) {
2597 // Check for revision file
2598 if (!FILE_READABLE($FQFN)) {
2599 // Not found, so we need to create it
2602 // Revision file found
2603 $ins_vers = explode("\n", READ_FILE($FQFN));
2605 // Get array for mapping information
2606 $mapper = array_flip(getSearchFor());
2607 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2609 // Is the content valid?
2610 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == "") || ($ins_vers[0]) == "new") {
2611 // File needs update!
2614 // Return found value
2615 return trim($ins_vers[$mapper[$type]]);
2620 // Has it been updated?
2621 if ($new === true) {
2622 WRITE_FILE($FQFN, implode("\n", getAkt_vers()));
2627 // Repares an array we are looking for
2628 function getSearchFor () {
2629 // Add Revision, Date, Tag and Author
2630 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2632 // Return the created array
2636 function getAkt_vers () {
2639 $last_changed = array(
2643 $akt_vers = array();
2646 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2647 searchDirsRecursive($next_dir, $last_changed);
2650 $last_file = READ_FILE($last_changed['path_name']);
2651 $searchFor = getSearchFor();
2653 // @TODO What does this loop/regex do? Document it, please.
2654 foreach ($searchFor as $search) {
2655 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2656 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2659 if ($res && $res >= 3) {
2661 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2663 // Prepare timestamp for date
2664 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2666 // Add Tag if the author is set and is not quix0r (lead coder)
2667 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2668 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2671 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Could be removed I think.
2672 $version = GET_URL("check-updates3.php");
2675 $akt_vers['Revision'] = trim($version[10]);
2676 $akt_vers['Date'] = trim($version[9]);
2677 $akt_vers['Tag'] = trim($version[8]);
2678 $akt_vers['Author'] = "quix0r";
2681 // Return prepared array
2686 // Loads an include file and logs any missing files for debug purposes
2687 function LOAD_INC ($INC) {
2688 // Add the path. This is why we need a trailing slash in config.php
2689 $FQFN = constant('PATH') . $INC;
2691 // Is the include file there?
2692 if (!FILE_READABLE($FQFN)) {
2693 // Not there so log it
2694 debug_report_bug(sprintf("Include file %s not found.", $INC));
2702 // Loads an include file once
2703 function LOAD_INC_ONCE ($INC) {
2704 // Is it not loaded?
2705 if (!isset($GLOBALS['load_once'][$INC])) {
2706 // Then try to load it
2709 // And mark it as loaded
2710 $GLOBALS['load_once'][$INC] = "loaded";
2714 // Back-ported from the new ship-simu engine. :-)
2715 function debug_get_printable_backtrace () {
2717 $backtrace = "<ol>\n";
2719 // Get and prepare backtrace for output
2720 $backtraceArray = debug_backtrace();
2721 foreach ($backtraceArray as $key => $trace) {
2722 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2723 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2724 if (!isset($trace['args'])) $trace['args'] = array();
2725 $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";
2729 $backtrace .= "</ol>\n";
2731 // Return the backtrace
2735 // Output a debug backtrace to the user
2736 function debug_report_bug ($message = "") {
2739 // Is the optional message set?
2740 if (!empty($message)) {
2742 $debug = sprintf("Note: %s<br />\n",
2746 // @TODO Add a little more infos here
2747 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2751 $debug .= "Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2752 $debug .= debug_get_printable_backtrace();
2753 $debug .= "</pre>Thank you for finding bugs.";
2756 // @TODO This cannot be rewritten to mxchange_die(), try to find a solution for this.
2760 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2761 function generateSeed () {
2762 list($usec, $sec) = explode(" ", microtime());
2763 return ((float)$sec + (float)$usec);
2766 // Converts a message code to a human-readable message
2767 function convertCodeToMessage ($code) {
2770 case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2771 case getCode('LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2772 case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2773 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2774 case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2775 case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2776 case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2777 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2779 case getCode('ERROR_MAILID'):
2780 if (EXT_IS_ACTIVE($ext, true)) {
2781 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2783 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
2787 case getCode('EXTENSION_PROBLEM'):
2788 if (REQUEST_ISSET_GET(('ext'))) {
2789 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2791 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2795 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2796 case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2797 case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2798 case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2801 // Missing/invalid code
2802 $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2805 DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2809 // Return the message
2813 // Checks wether the given extension is currently not installed
2814 // and redirects if so.
2815 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
2816 // Is the extension uninstalled/inactive?
2817 if (!EXT_IS_ACTIVE($ext_name)) {
2818 // Redirect to index
2819 LOAD_URL("modules.php?module=index&msg=".getCode('EXTENSION_PROBLEM')."&ext=".$ext_name);
2823 // Generate a "link" for the given admin id (aid)
2824 function GENERATE_AID_LINK ($aid) {
2825 // No assigned admin is default
2826 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2828 // Zero? = Not assigned
2830 // Load admin's login
2831 $login = GET_ADMIN_LOGIN($aid);
2832 if ($login != "***") {
2833 // Is the extension there?
2834 if (EXT_IS_ACTIVE("admins")) {
2836 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
2838 // Extension not found
2839 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
2843 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2851 // Checks wether an include file (non-FQFN better) is readable
2852 function INCLUDE_READABLE ($INC) {
2854 $FQFN = constant('PATH') . $INC;
2857 return FILE_READABLE($FQFN);
2861 // @TODO Implement $compress
2862 function encodeString ($str, $compress=true) {
2863 $str = urlencode(base64_encode(compileUriCode($str)));
2867 // Decode strings encoded with encodeString()
2868 // @TODO Implement $decompress
2869 function decodeString ($str, $decompress=true) {
2870 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2874 // Compile characters which are allowed in URLs
2875 function compileUriCode ($code, $simple=true) {
2876 // Compile constants
2877 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2879 // Compile QUOT and other non-HTML codes
2880 $code = str_replace("{DOT}", ".",
2881 str_replace("{SLASH}", "/",
2882 str_replace("{QUOT}", "'",
2883 str_replace("{DOLLAR}", "$",
2884 str_replace("{OPEN_ANCHOR}", "(",
2885 str_replace("{CLOSE_ANCHOR}", ")",
2886 str_replace("{OPEN_SQR}", "[",
2887 str_replace("{CLOSE_SQR}", "]",
2888 str_replace("{PER}", "%",
2892 // Return compiled code
2896 // Function taken from user comments on www.php.net / function eregi()
2897 function isUrlValid ($url) {
2899 $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
2901 // Allows http and https
2902 $http = "(http|https)+(:\/\/)";
2904 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2905 // Test double-domains (e.g. .de.vu)
2906 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2908 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2910 $dir = "((/)+([-_\.[:alnum:]])+)*";
2912 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2913 // ... and the string after and including question character
2914 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2915 // Pattern for URLs like http://url/dir/doc.html?var=value
2916 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2917 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2918 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2919 // Pattern for URLs like http://url/dir/?var=value
2920 $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
2921 $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
2922 $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
2923 // Pattern for URLs like http://url/dir/page.ext
2924 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2925 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2926 $pattern['ipdp'] = $http.$ip.$dir.$page;
2927 // Pattern for URLs like http://url/dir
2928 $pattern['d1d'] = $http.$domain1.$dir;
2929 $pattern['d2d'] = $http.$domain2.$dir;
2930 $pattern['ipd'] = $http.$ip.$dir;
2931 // Pattern for URLs like http://url/?var=value
2932 $pattern['d1g1'] = $http.$domain1."/".$getstring1;
2933 $pattern['d2g1'] = $http.$domain2."/".$getstring1;
2934 $pattern['ipg1'] = $http.$ip."/".$getstring1;
2935 // Pattern for URLs like http://url?var=value
2936 $pattern['d1g12'] = $http.$domain1.$getstring1;
2937 $pattern['d2g12'] = $http.$domain2.$getstring1;
2938 $pattern['ipg12'] = $http.$ip.$getstring1;
2939 // Test all patterns
2941 foreach ($pattern as $key=>$pat) {
2943 if (defined('DEBUG_REGEX')) {
2944 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2945 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2946 $pat = str_replace("[:digit:]", "0-9", $pat);
2947 $pat = str_replace(".", "\.", $pat);
2948 $pat = str_replace("@", "\@", $pat);
2949 echo $key."= ".$pat."<br />";
2952 // Check if expression matches
2953 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2956 if ($reg === true) break;
2959 // Return true/false
2963 // Smartly adds slashes
2964 function smartAddSlashes ($unquoted) {
2965 $unquoted = str_replace("\\", "", $unquoted);
2966 return addslashes($unquoted);
2969 // Decode entities in a nicer way
2970 function decodeEntities ($str) {
2971 // @TODO We may want to switch over to UTF-8 here!
2972 $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
2974 // Return decoded string
2975 return $decodedString;
2978 // Wtites data to a config.php-style file
2979 // @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
2980 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2981 // Initialize some variables
2987 // Is the file there and read-/write-able?
2988 if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
2989 $search = "CFG: ".$comment;
2990 $tmp = $FQFN.".tmp";
2992 // Open the source file
2993 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2995 // Is the resource valid?
2996 if (is_resource($fp)) {
2997 // Open temporary file
2998 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
3000 // Is the resource again valid?
3001 if (is_resource($fp_tmp)) {
3002 while (!feof($fp)) {
3003 // Read from source file
3004 $line = fgets ($fp, 1024);
3006 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
3009 if ($next === $seek) {
3011 $line = $prefix . $DATA . $suffix."\n";
3017 // Write to temp file
3018 fputs($fp_tmp, $line);
3024 // Finished writing tmp file
3028 // Close source file
3031 if (($done) && ($found)) {
3032 // Copy back tmp file and delete tmp :-)
3034 return unlink($tmp);
3035 } elseif (!$found) {
3036 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
3038 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
3042 // File not found, not readable or writeable
3043 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
3046 // An error was detected!
3049 // Send notification to admin
3050 function SEND_ADMIN_NOTIFICATION ($subject, $templateName, $content=array(), $uid="0") {
3051 if (GET_EXT_VERSION("admins") >= "0.4.1") {
3053 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
3055 // Send out out-dated way
3056 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
3057 SEND_ADMIN_EMAILS($subject, $msg);
3061 // Merges an array together but only if both are arrays
3062 function merge_array ($array1, $array2) {
3063 // Are both an array?
3064 if ((is_array($array1)) && (is_array($array2))) {
3065 // Merge all together
3066 return array_merge($array1, $array2);
3067 } elseif (is_array($array1)) {
3068 // Return left array
3069 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
3071 } elseif (is_array($array2)) {
3072 // Return right array
3073 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
3077 // Both are not arrays
3078 debug_report_bug(__FUNCTION__.": No arrays provided!");
3081 // Debug message logger
3082 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
3083 // Is debug mode enabled?
3084 if ((isDebugModeEnabled()) || ($force === true)) {
3086 $message = str_replace("\r", "", str_replace("\n", "", $message));
3088 // Log this message away
3089 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
3090 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
3095 // Reads a directory with PHP files in and gets only files back
3096 function GET_DIR_AS_ARRAY ($baseDir, $prefix, $includeDirs = false, $addBaseDir = true) {
3101 $dirPointer = opendir(constant('PATH') . $baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
3104 while ($baseFile = readdir($dirPointer)) {
3105 // Construct include filename and FQFN
3106 $INC = $baseDir . "/" . $baseFile;
3107 $FQFN = constant('PATH') . $INC;
3109 // Is this a valid reset file?
3110 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
3111 if (((FILE_READABLE($FQFN)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) || (($includeDirs) && (isDirectory($FQFN)))) {
3112 // Remove both for extension name
3113 $extName = substr($baseFile, strlen($prefix), -4);
3116 $extId = GET_EXT_ID($extName);
3118 // Is the extension valid and active?
3119 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
3120 // Then add this file
3121 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Extension entry ".$baseFile." added.<br />\n";
3123 } elseif ($extId == 0) {
3124 // Add non-extension files as well
3125 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): Regular entry ".$baseFile." added.<br />\n";
3129 $INCs[] = $baseFile;
3136 closedir($dirPointer);
3141 // Return array with include files
3145 // Load more reset scripts
3146 function runResetIncludes () {
3147 // Is the reset set or old sql_patches?
3148 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
3150 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3153 // Get more daily reset scripts
3154 SET_INC_POOL(GET_DIR_AS_ARRAY("inc/reset/", "reset_"));
3157 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
3159 // Is the config entry set?
3160 if (GET_EXT_VERSION("sql_patches") >= "0.4.2") {
3161 // Create current week mark
3162 $currWeek = date("W", time());
3165 if (getConfig('last_week') != $currWeek) {
3166 // Include weekly reset scripts
3167 MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
3170 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
3173 // Create current month mark
3174 $currMonth = date("m", time());
3177 if (getConfig('last_month') != $currMonth) {
3178 // Include monthly reset scripts
3179 MERGE_INC_POOL(GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
3182 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
3187 runFilterChain('load_includes');
3190 // Handle extra values
3191 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
3192 // Default is the value itself
3195 // Do we have a special filter function?
3196 if (!empty($filterFunction)) {
3197 // Does the filter function exist?
3198 if (function_exists($filterFunction)) {
3199 // Do we have extra parameters here?
3200 if (!empty($extraValue)) {
3201 // Put both parameters in one new array by default
3202 $args = array($value, $extraValue);
3204 // If we have an array simply use it and pre-extend it with our value
3205 if (is_array($extraValue)) {
3206 // Make the new args array
3207 $args = merge_array(array($value), $extraValue);
3210 // Call the multi-parameter call-back
3211 $ret = call_user_func_array($filterFunction, $args);
3213 // One parameter call
3214 $ret = call_user_func($filterFunction, $value);
3223 // Check if given FQFN is a readable file
3224 function FILE_READABLE ($FQFN) {
3226 return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3229 // Converts timestamp selections into a timestamp
3230 function CONVERT_SELECTIONS_TO_TIMESTAMP (&$POST, &$DATA, &$id, &$skip) {
3231 // Init test variable
3234 // Get last three chars
3235 $test = substr($id, -3);
3237 // Improved way of checking! :-)
3238 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
3239 // Found a multi-selection for timings?
3240 $test = substr($id, 0, -3);
3241 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)) {
3242 // Generate timestamp
3243 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
3244 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3246 // Remove data from array
3247 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
3248 unset($POST[$test."_".$rem]);
3252 unset($id); $skip = true; $test2 = $test;
3255 // Process this entry
3261 // Reverts the german decimal comma into Computer decimal dot
3262 function REVERT_COMMA ($str) {
3263 // Default float is not a float... ;-)
3266 // Which language is selected?
3267 switch (GET_LANGUAGE()) {
3268 case "de": // German language
3269 // Remove german thousand dots first
3270 $str = str_replace(".", "", $str);
3272 // Replace german commata with decimal dot and cast it
3273 $float = (float)str_replace(",", ".", $str);
3276 default: // US and so on
3277 // Remove thousand dots first and cast
3278 $float = (float)str_replace(",", "", $str);
3286 // Handle menu-depending failed logins and return the rendered content
3287 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3288 // Default output is empty ;-)
3291 // Is the session data set?
3292 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3293 // Ignore zero values
3294 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
3295 // Non-guest has login failures found, get both data and prepare it for template
3296 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3298 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
3299 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
3303 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
3306 // Reset session data
3307 set_session('mxchange_'.$accessLevel.'_failures', "");
3308 set_session('mxchange_'.$accessLevel.'_last_fail', "");
3311 // Return rendered content
3316 function rebuildCacheFiles ($cache, $inc="") {
3317 // Shall I remove the cache file?
3318 if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
3320 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3322 $GLOBALS['cache_instance']->destroyCacheFile();
3325 // Include file given?
3328 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3330 // Is the include there?
3331 if (INCLUDE_READABLE($INC)) {
3332 // And rebuild it from scratch
3333 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3336 // Include not found!
3337 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3343 // Purge admin menu cache
3344 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
3345 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3346 if (!EXT_IS_ACTIVE("cache")) {
3347 // Cache extension not active
3349 } elseif (!isCacheInstanceValid()) {
3350 // No cache instance!
3351 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3353 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
3354 // Caching disabled (currently experiemental!)
3358 // Experiemental feature!
3359 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3362 // Translates the "pool type" into human-readable
3363 function TRANSLATE_POOL_TYPE ($type) {
3364 // Default type is unknown
3365 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
3367 // Generate constant
3368 $constName = sprintf("POOL_TYPE_%s", $type);
3371 if (defined($constName)) {
3373 $translated = getMessage($constName);
3376 // Return "translation"
3380 // "Getter" for remote IP number
3381 function GET_REMOTE_ADDR () {
3382 // Get remote ip from environment
3383 $remoteAddr = getenv('REMOTE_ADDR');
3385 // Is removeip installed?
3386 if (EXT_IS_ACTIVE("removeip")) {
3387 // Then anonymize it
3388 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3395 // "Getter" for remote hostname
3396 function GET_REMOTE_HOST () {
3397 // Get remote ip from environment
3398 $remoteHost = getenv('REMOTE_HOST');
3400 // Is removeip installed?
3401 if (EXT_IS_ACTIVE("removeip")) {
3402 // Then anonymize it
3403 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3410 // "Getter" for user agent
3411 function GET_USER_AGENT () {
3412 // Get remote ip from environment
3413 $userAgent = getenv('HTTP_USER_AGENT');
3415 // Is removeip installed?
3416 if (EXT_IS_ACTIVE("removeip")) {
3417 // Then anonymize it
3418 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3425 // "Getter" for referer
3426 function GET_REFERER () {
3427 // Get remote ip from environment
3428 $referer = getenv('HTTP_REFERER');
3430 // Is removeip installed?
3431 if (EXT_IS_ACTIVE("removeip")) {
3432 // Then anonymize it
3433 $referer = GET_ANONYMOUS_REFERER($referer);
3440 // Adds a bonus mail to the queue
3441 // This is a high-level function!
3442 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
3443 // Use mode from data if not set and availble ;-)
3444 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3446 // Generate receiver list
3447 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
3450 if (!empty($RECEIVER)) {
3451 // Add bonus mail to queue
3452 ADD_BONUS_MAIL_TO_QUEUE(
3464 // Mail inserted into bonus pool
3465 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
3466 } elseif ($output) {
3467 // More entered than can be reached!
3468 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
3471 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3475 // Determines referal id and sets it
3476 function DETERMINE_REFID () {
3477 // Check if refid is set
3478 if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3479 // The variable user comes from the click-counter script click.php and we only accept this here
3480 $GLOBALS['refid'] = bigintval($_GET['user']);
3481 } elseif (!empty($_POST['refid'])) {
3482 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3483 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3484 } elseif (!empty($_GET['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($_GET['refid']));
3487 } elseif (!empty($_GET['ref'])) {
3488 // Set refid=ref (the referal link uses such variable)
3489 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3490 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
3491 // Set session refid als global
3492 $GLOBALS['refid'] = bigintval(get_session('refid'));
3493 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
3494 // Set default refid as refid in URL
3495 $GLOBALS['refid'] = getConfig(('def_refid'));
3496 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
3497 // Select a random user which has confirmed enougth mails
3498 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3500 // No default ID when sql_patches is not installed or none set
3501 $GLOBALS['refid'] = 0;
3504 // Set cookie when default refid > 0
3505 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
3507 set_session('refid', $GLOBALS['refid']);
3510 // Return determined refid
3511 return $GLOBALS['refid'];
3514 // Check wether we are installing
3515 function isInstalling () {
3516 $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
3517 //* DEBUG: */ var_dump($installing);
3521 // Check wether this script is installed
3522 function isInstalled () {
3523 return isBooleanConstantAndTrue('mxchange_installed');
3526 // Check wether an admin is registered
3527 function isAdminRegistered () {
3528 return isBooleanConstantAndTrue('admin_registered');
3531 // Enables the reset mode. Only call this function if you really want the
3533 function enableResetMode () {
3534 // Enable the reset mode
3535 $GLOBALS['reset_enabled'] = true;
3538 runFilterChain('reset_enabled');
3541 // Checks wether the reset mode is active
3542 function isResetModeEnabled () {
3543 // Now simply check it
3544 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3547 // Checks wether the debug mode is enabled
3548 function isDebugModeEnabled () {
3550 return isBooleanConstantAndTrue('DEBUG_MODE');
3553 // Checks wether the cache instance is valid
3554 function isCacheInstanceValid () {
3555 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3558 // Our shutdown-function
3559 function shutdown () {
3560 // Call the filter chain 'shutdown'
3561 runFilterChain('shutdown', null, false);
3563 if (SQL_IS_LINK_UP()) {
3565 SQL_CLOSE(__FILE__, __LINE__);
3566 } elseif ((!isInstalling()) && (isInstalled())) {
3568 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3571 // Stop executing here
3575 // Setter for userid
3576 function setUserId ($userid) {
3577 $GLOBALS['userid'] = bigintval($userid);
3580 // Getter for userid or returns zero
3581 function getUserId () {
3585 // Is the userid set?
3586 if (isUserIdSet()) {
3588 $userid = $GLOBALS['userid'];
3595 // Checks ether the userid is set
3596 function isUserIdSet () {
3597 return (isset($GLOBALS['userid']));
3600 // Checks wether the given FQFN is a directory and not .,.. or .svn
3601 function isDirectory ($FQFN) {
3602 // Generate baseName
3603 $baseName = basename($FQFN);
3606 $isDirectory = ((is_dir($FQFN)) && ($baseName != ".") && ($baseName != "..") && ($baseName != ".svn"));
3608 // Return the result
3609 return $isDirectory;
3613 function INIT_INC_POOL () {
3614 $GLOBALS['inc_pool'] = array();
3617 // Setter for INC_POOL
3618 function SET_INC_POOL ($includePool) {
3619 $GLOBALS['inc_pool'] = (array) $includePool;
3622 // Getter for INC_POOL
3623 function GET_INC_POOL () {
3624 return $GLOBALS['inc_pool'];
3628 function COUNT_INC_POOL () {
3629 return count($GLOBALS['inc_pool']);
3632 // Merge INC_POOL into given
3633 function MERGE_INC_POOL ($includePool) {
3634 SET_INC_POOL(merge_array(GET_INC_POOL(), $includePool));
3637 // Add single include file to INC_POOL
3638 function ADD_INC_TO_POOL ($INC) {
3639 $GLOBALS['inc_pool'][] = (string) $INC;
3642 // Remove an include file from INC_POOL
3643 function REMOVE_INC_FROM_POOL ($INC) {
3645 $key = array_search($INC, GET_INC_POOL());
3648 if ($key !== false) {
3650 unset($GLOBALS['inc_pool'][$key]);
3652 // And sort the list
3653 asort($GLOBALS['inc_pool']);
3657 // Handle message codes from URL
3658 function handleCodeMessage () {
3659 if (REQUEST_ISSET_GET(('msg'))) {
3660 // Default extension is "unknown"
3663 // Is extension given?
3664 if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
3666 // Convert the 'msg' parameter from URL to a human-readable message
3667 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3669 // Load message template
3670 LOAD_TEMPLATE("message", false, $msg);
3674 //////////////////////////////////////////////////
3675 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3676 //////////////////////////////////////////////////
3678 if (!function_exists('html_entity_decode')) {
3679 // Taken from documentation on www.php.net
3680 function html_entity_decode ($string) {
3681 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3682 $trans_tbl = array_flip($trans_tbl);
3683 return strtr($string, $trans_tbl);