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 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Check if our config file is writeable or not
41 function IS_INC_WRITEABLE($inc) {
43 $fqfn = sprintf("%sinc/%s.php", constant('PATH'), $inc);
45 // Abort by simple test
46 if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
50 // Test if we can append data
51 $fp = @fopen($fqfn, 'a');
52 if ($inc == "dummy") {
57 // Close all other files
62 // Output HTML code directly or "render" it. You addionally switch the new-line character off
63 function OUTPUT_HTML ($HTML, $newLine = true) {
64 // Some global variables
65 global $OUTPUT, $footer, $CSS;
67 // Do we have HTML-Code here?
69 // Yes, so we handle it as you have configured
70 switch (constant('OUTPUT_MODE'))
73 // That's why you don't need any \n at the end of your HTML code... :-)
74 if (constant('_OB_CACHING') == "on") {
75 // Output into PHP's internal buffer
78 // That's why you don't need any \n at the end of your HTML code... :-)
79 if ($newLine) echo "\n";
81 // Render mode for old or lame servers...
84 // That's why you don't need any \n at the end of your HTML code... :-)
85 if ($newLine) $OUTPUT .= "\n";
90 // If we are switching from render to direct output rendered code
91 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
93 // The same as above... ^
95 if ($newLine) echo "\n";
99 // Huh, something goes wrong or maybe you have edited config.php ???
100 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
101 mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
104 } elseif ((constant('_OB_CACHING') == "on") && ($footer == 1)) {
105 // Headers already sent?
106 if (headers_sent()) {
108 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
110 // Trigger an user error
111 debug_report_bug("Headers are already sent!");
114 // Output cached HTML code
115 $OUTPUT = ob_get_contents();
117 // Clear output buffer for later output
121 header("HTTP/1.1 200");
124 $now = gmdate('D, d M Y H:i:s') . ' GMT';
126 // General headers for no caching
127 header("Expired: " . $now); // RFC2616 - Section 14.21
128 header("Last-Modified: " . $now);
129 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
130 header("Pragma: no-cache"); // HTTP/1.0
131 header("Connection: Close");
133 // Extension "rewrite" installed?
134 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
135 $OUTPUT = REWRITE_LINKS($OUTPUT);
138 // Compile and run finished rendered HTML code
139 while (strpos($OUTPUT, '{!') > 0) {
140 // Prepare the content and eval() it...
142 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
145 // Was that eval okay?
146 if (empty($newContent)) {
147 // Something went wrong!
148 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
150 $OUTPUT = $newContent;
153 // Output code here, DO NOT REMOVE! ;-)
155 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
156 // Rewrite links when rewrite extension is active
157 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
158 $OUTPUT = REWRITE_LINKS($OUTPUT);
161 // Compile and run finished rendered HTML code
162 while (strpos($OUTPUT, '{!') > 0) {
163 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
167 // Output code here, DO NOT REMOVE! ;-)
172 // Output the raw HTML code
173 function OUTPUT_RAW ($HTML) {
174 // Output stripped HTML code to avoid broken JavaScript code, etc.
175 echo stripslashes(stripslashes($HTML));
177 // Flush the output if only constant('_OB_CACHING') is not "on"
178 if (constant('_OB_CACHING') != "on") {
184 // Add a fatal error message to the queue array
185 function addFatalMessage ($message, $extra="") {
189 // Regular text message to add to $FATAL
192 // $message is text with a mask plus extras to insert into the text
193 $message = sprintf($message, $extra);
197 // Log fatal messages away
198 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
201 // Getter for total fatal message count
202 function getTotalFatalErrors () {
208 // Do we have at least the first entry?
209 if (!empty($FATAL[0])) {
211 $count = count($FATAL);
218 // Load a template file and return it's content (only it's name; do not use ' or ")
219 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
220 // Add more variables which you want to use in your template files
221 global $DATA, $_CONFIG, $username;
223 // Make all template names lowercase
224 $template = strtolower($template);
226 // Count the template load
227 incrementConfigEntry('num_templates');
229 // Prepare IP number and User Agent
230 $REMOTE_ADDR = GET_REMOTE_ADDR();
231 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
232 $HTTP_USER_AGENT = GET_USER_AGENT();
236 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
238 // @DEPRECATED Try to rewrite the if() condition
239 if ($template == "member_support_form") {
240 // Support request of a member
241 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
242 array($GLOBALS['userid']), __FILE__, __LINE__);
244 // Is content an array?
245 if (is_array($content)) {
247 $content = merge_array($content, SQL_FETCHARRAY($result));
250 $content['gender'] = TRANSLATE_GENDER($content['gender']);
252 // DEPRECATED: Load data in direct variables
253 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
256 $gender = TRANSLATE_GENDER($gender);
257 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
261 SQL_FREERESULT($result);
264 // Generate date/time string
265 $date_time = MAKE_DATETIME(time(), "1");
268 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
271 // Check for admin/guest/member templates
272 if (strpos($template, "admin_") > -1) {
273 // Admin template found
275 } elseif (strpos($template, "guest_") > -1) {
276 // Guest template found
278 } elseif (strpos($template, "member_") > -1) {
279 // Member template found
281 } elseif (strpos($template, "install_") > -1) {
282 // Installation template found
284 } elseif (strpos($template, "ext_") > -1) {
285 // Extension template found
287 } elseif (strpos($template, "la_") > -1) {
288 // "Logical-area" template found
291 // Test for extension
292 $test = substr($template, 0, strpos($template, "_"));
293 if (EXT_IS_ACTIVE($test)) {
294 // Set extra path to extension's name
299 ////////////////////////
300 // Generate file name //
301 ////////////////////////
302 $file = $BASE.$MODE.$template.".tpl";
304 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
305 // Select what depended header/footer template file for admin/guest/member area
306 $file2 = sprintf("%s%s%s_%s.tpl",
310 SQL_ESCAPE($GLOBALS['what'])
314 if (FILE_READABLE($file2)) $file = $file2;
316 // Remove variable from memory
320 // Does the special template exists?
321 if (!FILE_READABLE($file)) {
322 // Reset to default template
323 $file = $BASE.$template.".tpl";
326 // Now does the final template exists?
327 if (FILE_READABLE($file)) {
328 // The local file does exists so we load it. :)
329 $tmpl_file = READ_FILE($file);
331 // Replace ' to our own chars to preventing them being quoted
332 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
334 // Do we have to compile the code?
336 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
338 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
341 // Simply return loaded code
345 // Add surrounding HTML comments to help finding bugs faster
346 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
347 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
348 // Only admins shall see this warning or when installation mode is active
349 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
350 (".basename($file).")<br />
353 <pre>".print_r($content, true)."</pre>
355 <pre>".print_r($DATA, true)."</pre>
359 // Remove content and data
363 // Do we have some content to output or return?
365 // Not empty so let's put it out! ;)
367 // Return the HTML code
373 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
374 // Warning, empty output!
375 return "E:".$template."<br />\n";
379 // Send mail out to an email address
380 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
381 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
383 // Compile subject line (for POINTS constant etc.)
384 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
388 if ((!eregi("@", $TO)) && ($TO > 0)) {
389 // Value detected, is the message extension installed?
390 if (EXT_IS_ACTIVE("msg")) {
391 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
394 // Load email address
395 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
396 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
398 // Does the user exist?
399 if (SQL_NUMROWS($result_email)) {
400 // Load email address
401 list($TO) = SQL_FETCHROW($result_email);
404 $TO = constant('WEBMASTER');
408 SQL_FREERESULT($result_email);
410 } elseif ("$TO" == "0") {
412 $TO = constant('WEBMASTER');
414 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
416 // Check for PHPMailer or debug-mode
417 if (!CHECK_PHPMAILER_USAGE()) {
418 // Not in PHPMailer-Mode
420 // Load email header template
421 $FROM = LOAD_EMAIL_TEMPLATE("header");
424 $FROM .= LOAD_EMAIL_TEMPLATE("header");
426 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
428 // Load email header template
429 $FROM = LOAD_EMAIL_TEMPLATE("header");
432 $FROM .= LOAD_EMAIL_TEMPLATE("header");
437 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
441 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
444 // Fix HTML parameter (default is no!)
445 if (empty($HTML)) $HTML = "N";
446 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
447 // In debug mode we want to display the mail instead of sending it away so we can debug this part
449 ".htmlentities(trim($FROM))."
451 Subject : ".$SUBJECT."
454 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
455 // Send mail as HTML away
456 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
457 } elseif (!empty($TO)) {
459 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
460 } elseif ($HTML == "N") {
462 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
466 // Check if legacy or PHPMailer command
468 function CHECK_PHPMAILER_USAGE() {
469 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
473 * Send out a raw email with PHPMailer class or legacy mail() command
475 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
476 // Shall we use PHPMailer class or legacy mode?
477 if (CHECK_PHPMAILER_USAGE()) {
478 // Use PHPMailer class with SMTP enabled
479 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
480 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
483 $mail = new PHPMailer();
484 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
487 $mail->SMTPAuth = true;
488 $mail->Host = constant('SMTP_HOSTNAME');
490 $mail->Username = constant('SMTP_USER');
491 $mail->Password = constant('SMTP_PASSWORD');
493 $mail->From = constant('WEBMASTER');
497 $mail->FromName = constant('MAIN_TITLE');
498 $mail->Subject = $subject;
499 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
501 $mail->AltBody = "Your mail program required HTML support to read this mail!";
502 $mail->WordWrap = 70;
505 $mail->Body = html_entity_decode($msg);
507 $mail->AddAddress($to, "");
508 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
509 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
510 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
513 // Use legacy mail() command
514 @mail($to, $subject, html_entity_decode($msg), $from);
519 // Generate a password in a specified length or use default password length
520 function GEN_PASS ($LEN = 0) {
521 // Auto-fix invalid length of zero
522 if ($LEN == 0) $LEN = getConfig('pass_len');
524 // Initialize array with all allowed chars
525 $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,-,+,_,/");
527 // Start creating password
529 for ($i = 0; $i < $LEN; $i++) {
530 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
533 // When the size is below 40 we can also add additional security by scrambling it
534 if (strlen($PASS) <= 40) {
535 // Also scramble the password
536 $PASS = scrambleString($PASS);
539 // Return the password
543 function MAKE_DATETIME ($time, $mode="0")
547 return NEVER_HAPPENED;
549 // Filter out numbers
550 $time = bigintval($time);
553 switch (GET_LANGUAGE())
555 case "de": // German date / time format
557 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
558 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
559 case "2": $ret = date("d.m.Y|H:i", $time); break;
560 case "3": $ret = date("d.m.Y", $time); break;
562 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
567 default: // Default is the US date / time format!
569 case "0": $ret = date("r", $time); break;
570 case "1": $ret = date("Y-m-d - g:i A", $time); break;
571 case "2": $ret = date("y-m-d|H:i", $time); break;
572 case "3": $ret = date("y-m-d", $time); break;
574 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
581 // Translates the american decimal dot into a german comma
582 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
583 // Default is 3 you can change this in admin area "Misc -> Misc Options"
584 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
586 // Use from config is default
587 $maxComma = getConfig('max_comma');
589 // Use from parameter?
590 if ($max > 0) $maxComma = $max;
593 if (($cut) && ($max == 0)) {
594 // Test for commata if in cut-mode
595 $com = explode(".", $dotted);
596 if (count($com) < 2) {
597 // Don't display commatas even if there are none... ;-)
603 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
606 switch (GET_LANGUAGE()) {
608 $dotted = number_format($dotted, $maxComma, ",", ".");
612 $dotted = number_format($dotted, $maxComma, ".", ",");
616 // Return translated value
621 function DEREFERER ($URL) {
622 // Don't de-refer our own links!
623 if (substr($URL, 0, strlen(URL)) != URL) {
624 // De-refer this link
625 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
633 function TRANSLATE_GENDER ($gender) {
636 case "M": $ret = GENDER_M; break;
637 case "F": $ret = GENDER_F; break;
638 case "C": $ret = GENDER_C; break;
639 default : $ret = $gender; break;
644 function FRAMETESTER($URL) {
645 // Prepare frametester URL
646 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
648 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
650 return $frametesterUrl;
653 function SELECTION_COUNT($array) {
655 if (is_array($array)) {
656 foreach ($array as $key => $sel) {
657 if (!empty($sel)) $ret++;
663 function IMG_CODE ($code, $type, $DATA, $uid) {
664 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
667 function TRANSLATE_STATUS($status) {
671 $ret = ACCOUNT_UNCONFIRMED;
675 $ret = ACCOUNT_CONFIRMED;
679 $ret = ACCOUNT_LOCKED;
684 $ret = ACCOUNT_DELETED;
688 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
689 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
695 function GET_LANGUAGE() {
698 // Set default return value to default language from config
699 $ret = constant('DEFAULT_LANG');
704 // Is the variable set
705 if (!empty($_GET['mx_lang'])) {
706 // Accept only first 2 chars
707 $lang = substr($_GET['mx_lang'], 0, 2);
708 } elseif (isset($cacheArray['language'])) {
710 $ret = $cacheArray['language'];
711 } elseif (!empty($lang)) {
712 // Check if main language file does exist
713 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
714 // Okay found, so let's update cookies
717 } elseif (!isSessionVariableSet('mx_lang')) {
718 // Return stored value from cookie
719 $ret = get_session('mx_lang');
721 // Fixes a warning before the session has the mx_lang constant
722 if (empty($ret)) $ret = constant('DEFAULT_LANG');
726 $cacheArray['language'] = $ret;
732 function SET_LANGUAGE ($lang) {
733 // Accept only first 2 chars!
734 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
737 set_session('mx_lang', $lang);
740 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
741 global $DATA, $REPLACER, $_CONFIG;
743 // Make sure all template names are lowercase!
744 $template = strtolower($template);
746 // Default "nickname" if extension is not installed
749 // Prepare IP number and User Agent
750 $REMOTE_ADDR = GET_REMOTE_ADDR();
751 $HTTP_USER_AGENT = GET_USER_AGENT();
754 $ADMIN = constant('MAIN_TITLE');
756 // Is the admin logged in?
759 $aid = GET_CURRENT_ADMIN_ID();
762 $ADMIN = GET_ADMIN_EMAIL($aid);
765 // Neutral email address is default
766 $email = constant('WEBMASTER');
768 // Expiration in a nice output format
769 if (getConfig('auto_purge') == 0) {
770 // Will never expire!
771 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
773 // Create nice date string
774 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
777 // Is content an array?
778 if (is_array($content)) {
779 // Add expiration to array, $EXPIRATION is now deprecated!
780 $content['expiration'] = $EXPIRATION;
784 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
785 if (($UID > 0) && (is_array($content))) {
786 // If nickname extension is installed, fetch nickname as well
787 if (EXT_IS_ACTIVE("nickname")) {
788 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
790 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
791 array(bigintval($UID)), __FILE__, __LINE__);
793 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
795 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
796 array(bigintval($UID)), __FILE__, __LINE__);
799 // Fetch and merge data
800 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
801 $content = merge_array($content, SQL_FETCHARRAY($result));
802 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
805 SQL_FREERESULT($result);
808 // Translate M to male or F to female if present
809 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
811 // Overwrite email from data if present
812 if (isset($content['email'])) $email = $content['email'];
814 // Store email for some functions in global data array
815 $DATA['email'] = $email;
818 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
820 // Check for admin/guest/member templates
821 if (strpos($template, "admin_") > -1) {
822 // Admin template found
823 $file = $BASE."admin/".$template.".tpl";
824 } elseif (strpos($template, "guest_") > -1) {
825 // Guest template found
826 $file = $BASE."guest/".$template.".tpl";
827 } elseif (strpos($template, "member_") > -1) {
828 // Member template found
829 $file = $BASE."member/".$template.".tpl";
831 // Test for extension
832 $test = substr($template, 0, strpos($template, "_"));
833 if (EXT_IS_ACTIVE($test)) {
834 // Set extra path to extension's name
835 $file = $BASE.$test."/".$template.".tpl";
837 // No special filename
838 $file = $BASE.$template.".tpl";
842 // Does the special template exists?
843 if (!FILE_READABLE($file)) {
844 // Reset to default template
845 $file = $BASE.$template.".tpl";
848 // Now does the final template exists?
850 if (FILE_READABLE($file)) {
851 // The local file does exists so we load it. :)
852 $tmpl_file = READ_FILE($file);
853 $tmpl_file = addslashes($tmpl_file);
856 $tmpl_file = "\$newContent = html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
858 } elseif (!empty($template)) {
859 // Template file not found!
860 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
861 {--TEMPLATE_CONTENT--}
862 <pre>".print_r($content, true)."</pre>
864 <pre>".print_r($DATA, true)."</pre>
867 // Debug mode not active? Then remove the HTML tags
868 if (!isBooleanConstantAndTrue('DEBUG_MODE')) $newContent = strip_tags($newContent);
870 // No template name supplied!
871 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
874 // Is there some content?
875 if (empty($newContent)) {
877 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
878 // Add last error if the required function exists
879 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
882 // Remove content and data
886 // Return compiled content
887 return COMPILE_CODE($newContent);
890 function MAKE_TIME($H, $M, $S, $stamp) {
891 // Extract day, month and year from given timestamp
892 $DAY = date("d", $stamp);
893 $MONTH = date("m", $stamp);
894 $YEAR = date('Y', $stamp);
896 // Create timestamp for wished time which depends on extracted date
897 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
900 function LOAD_URL($URL, $addUrlData=true) {
901 global $CSS, $footer;
903 // Compile out URI codes
904 $URL = COMPILE_CODE($URL);
906 // Check if http(s):// is there
907 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
908 // Make all URLs full-qualified
913 //* DEBUG: */ debug_report_bug();
914 $OUTPUT = ob_get_contents();
916 // Clear it only if there is content
917 if (!empty($OUTPUT)) {
921 // Add some data to URL if cookies are not accepted
922 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
924 // Probe for bot from search engine
925 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
926 // Search engine bot detected so let's rewrite many chars for the link
927 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
929 // Output new location link as anchor
930 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
931 } elseif (!headers_sent()) {
932 // Load URL when headers are not sent
933 //* DEBUG: */ debug_report_bug("URL={$URL}");
934 header ("Location: ".str_replace("&", "&", $URL));
936 // Output error message
937 LOAD_INC("inc/header.php");
938 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
939 LOAD_INC("inc/footer.php");
944 // Wrapper for LOAD_URL but URL comes from a configuration entry
945 function LOAD_CONFIGURED_URL ($configEntry) {
947 $URL = getConfig($configEntry);
952 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
960 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
961 global $SEC_CHARS, $URL_CHARS;
962 // Is the code a string?
963 if (!is_string($code)) {
964 // Silently return it
970 // Select smaller set of chars to replace when we e.g. want to compile URLs
971 if (!$full) $ARRAY = $URL_CHARS;
975 // BEFORE 0.2.1 : Language and data constants
976 // WITH 0.2.1+ : Only language constants
977 $code = str_replace('{--','".', str_replace('--}','."', $code));
979 // BEFORE 0.2.1 : Not used
980 // WITH 0.2.1+ : Data constants
981 $code = str_replace('{!','".', str_replace("!}", '."', $code));
984 // Compile QUOT and other non-HTML codes
985 foreach ($ARRAY['to'] as $k => $to) {
986 // Do the reversed thing as in inc/libs/security_functions.php
987 $code = str_replace($to, $ARRAY['from'][$k], $code);
990 // But shall I keep simple quotes for later use?
991 if ($simple) $code = str_replace("'", '{QUOT}', $code);
993 // Find $content[bla][blub] entries
994 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
996 // Are some matches found?
997 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
998 // Replace all matches
999 $matchesFound = array();
1000 foreach ($matches[0] as $key => $match) {
1001 // Fuzzy look has failed by default
1002 $fuzzyFound = false;
1004 // Fuzzy look on match if already found
1005 foreach ($matchesFound as $found => $set) {
1007 $test = substr($found, 0, strlen($match));
1009 // Does this entry exist?
1010 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1011 if ($test == $match) {
1013 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1020 if ($fuzzyFound) continue;
1022 // Take all string elements
1023 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1024 // Replace it in the code
1025 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1026 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1027 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1028 $matchesFound[$key."_".$matches[4][$key]] = 1;
1029 $matchesFound[$match] = 1;
1030 } elseif (!isset($matchesFound[$match])) {
1031 // Not yet replaced!
1032 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1033 $code = str_replace($match, "\".".$match.".\"", $code);
1034 $matchesFound[$match] = 1;
1039 // Return compiled code
1043 /************************************************************************
1045 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1046 * $a_sort sortiert: *
1048 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1049 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1050 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1051 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1052 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1054 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1055 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1056 * Sie, dass es doch nicht so schwer ist! :-) *
1058 ************************************************************************/
1059 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1062 while ($primary_key < count($a_sort)) {
1063 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1064 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1067 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1068 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1069 } elseif ($key != $key2) {
1070 // Sort numbers (E.g.: 9 < 10)
1071 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1072 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1076 // We have found two different values, so let's sort whole array
1077 foreach ($dummy as $sort_key => $sort_val) {
1078 $t = $dummy[$sort_key][$key];
1079 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1080 $dummy[$sort_key][$key2] = $t;
1091 // Write back sorted array
1095 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1096 global $MONTH_DESCR;
1099 if ($type == "yn") {
1100 // This is a yes/no selection only!
1101 if ($id > 0) $prefix .= "[".$id."]";
1102 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1104 // Begin with regular selection box here
1105 if (!empty($prefix)) $prefix .= "_";
1107 if ($id > 0) $type2 .= "[".$id."]";
1108 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1113 for ($idx = 1; $idx < 32; $idx++) {
1114 $OUT .= "<option value=\"".$idx."\"";
1115 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1116 $OUT .= ">".$idx."</option>\n";
1120 case "month": // Month
1121 foreach ($MONTH_DESCR as $month => $descr) {
1122 $OUT .= "<option value=\"".$month."\"";
1123 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1124 $OUT .= ">".$descr."</option>\n";
1128 case "year": // Year
1130 $YEAR = date('Y', time());
1132 // Use configured min age or fixed?
1133 if (GET_EXT_VERSION("other") >= "0.2.1") {
1135 $startYear = $YEAR - getConfig('min_age');
1138 $startYear = $YEAR - 16;
1141 // Calculate earliest year (100 years old people can still enter Internet???)
1142 $minYear = $YEAR - 100;
1144 // Check if the default value is larger than minimum and bigger than actual year
1145 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1146 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1147 $OUT .= "<option value=\"".$idx."\"";
1148 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1149 $OUT .= ">".$idx."</option>\n";
1151 } elseif ($DEFAULT == -1) {
1152 // Current year minus 1
1153 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1155 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1158 // Get current year and subtract the configured minimum age
1159 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1160 // Calculate earliest year depending on extension version
1161 if (GET_EXT_VERSION("other") >= "0.2.1") {
1162 // Use configured minimum age
1163 $YEAR = date('Y', time()) - getConfig('min_age');
1165 // Use fixed 16 years age
1166 $YEAR = date('Y', time()) - 16;
1169 // Construct year selection list
1170 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1171 $OUT .= "<option value=\"".$idx."\"";
1172 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1173 $OUT .= ">".$idx."</option>\n";
1180 for ($idx = 0; $idx < 60; $idx+=5) {
1181 if (strlen($idx) == 1) $idx = "0".$idx;
1182 $OUT .= "<option value=\"".$idx."\"";
1183 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1184 $OUT .= ">".$idx."</option>\n";
1189 for ($idx = 0; $idx < 24; $idx++) {
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 $OUT .= "<option value=\"Y\"";
1199 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1200 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1201 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1202 $OUT .= ">{--NO--}</option>\n";
1205 $OUT .= " </select>\n";
1209 function TRANSLATE_YESNO($yn)
1213 case "Y": $yn = YES; break;
1214 case "N": $yn = NO; break;
1215 default : $yn = "??? (".$yn.")"; break;
1220 // Deprecated : $length
1223 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1224 // Fix missing _MAX constant
1225 if (!defined('_MAX')) define('_MAX', 15235);
1227 // Build server string
1228 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1231 $keys = SITE_KEY.":".DATE_KEY;
1232 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1233 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1234 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1235 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1237 // Build string from misc data
1238 $data = $code.":".$uid.":".$DATA;
1240 // Add more additional data
1241 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1242 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1243 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1244 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1245 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1247 // Calculate number for generating the code
1248 $a = $code + constant('_ADD') - 1;
1250 if (getConfig('master_hash') != null) {
1251 // Generate hash with master salt from modula of number with the prime number and other data
1252 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1254 // Create number from hash
1255 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1257 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1258 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1260 // Create number from hash
1261 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1264 // At least 10 numbers shall be secure enought!
1265 $len = getConfig('code_length');
1266 if ($len == 0) $len = $length;
1267 if ($len == 0) $len = 10;
1269 // Cut off requested counts of number
1270 $return = substr(str_replace('.', "", $rcode), 0, $len);
1272 // Done building code
1275 // Does only allow numbers
1276 function bigintval($num, $castValue = true) {
1277 // Filter all numbers out
1278 $ret = preg_replace("/[^0123456789]/", "", $num);
1281 if ($castValue) $ret = (double)$ret;
1283 // Has the whole value changed?
1284 // @TODO Remove this if() block if all is working fine
1285 if ("".$ret."" != "".$num."") {
1293 // Insert the code in $img_code into jpeg or PNG image
1294 function GENERATE_IMAGE($img_code, $header=true) {
1295 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1296 // Stop execution of function here because of over-sized code length
1298 } elseif (!$header) {
1299 // Return in an HTML code code
1300 return "<IMG src=\"{!URL!}/img.php?code=".$img_code."\">\n";
1304 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1305 if (FILE_READABLE($img)) {
1306 // Switch image type
1307 switch (getConfig('img_type'))
1310 // Okay, load image and hide all errors
1311 $image = @imagecreatefromjpeg($img);
1315 // Okay, load image and hide all errors
1316 $image = @imagecreatefrompng($img);
1320 // Exit function here
1324 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1325 $text_color = imagecolorallocate($image, 0, 0, 0);
1327 // Insert code into image
1328 imagestring($image, 5, 14, 2, $img_code, $text_color);
1330 // Return to browser
1331 header ("Content-Type: image/".getConfig('img_type'));
1333 // Output image with matching image factory
1334 switch (getConfig('img_type')) {
1335 case "jpg": imagejpeg($image); break;
1336 case "png": imagepng($image); break;
1339 // Remove image from memory
1340 imagedestroy($image);
1342 // Create selection box or array of splitted timestamp
1343 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1344 // Calculate 2-seconds timestamp
1345 $stamp = round($timestamp);
1346 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1348 // Do we have a leap year?
1350 $TEST = date('Y', time()) / 4;
1351 $M1 = date("m", time());
1352 $M2 = date("m", (time() + $timestamp));
1354 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1355 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1357 // First of all years...
1358 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1359 //* DEBUG: */ print("Y={$Y}<br />\n");
1361 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1362 //* DEBUG: */ print("M={$M}<br />\n");
1364 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1365 //* DEBUG: */ print("W={$W}<br />\n");
1367 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1368 //* DEBUG: */ print("D={$D}<br />\n");
1370 $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));
1371 //* DEBUG: */ print("h={$h}<br />\n");
1373 $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));
1374 //* DEBUG: */ print("m={$m}<br />\n");
1375 // And at last seconds...
1376 $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));
1377 //* DEBUG: */ print("s={$s}<br />\n");
1379 // Is seconds zero and time is < 60 seconds?
1380 if (($s == 0) && ($timestamp < 60)) {
1382 $s = round($timestamp);
1386 // Now we convert them in seconds...
1388 if ($return_array) {
1389 // Just put all data in an array for later use
1401 $OUT = "<div align=\"".$align."\">\n";
1402 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1405 if (ereg('Y', $display) || (empty($display))) {
1406 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._YEARS."</strong></td>\n";
1409 if (ereg("M", $display) || (empty($display))) {
1410 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MONTHS."</strong></td>\n";
1413 if (ereg("W", $display) || (empty($display))) {
1414 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._WEEKS."</strong></td>\n";
1417 if (ereg("D", $display) || (empty($display))) {
1418 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._DAYS."</strong></td>\n";
1421 if (ereg("h", $display) || (empty($display))) {
1422 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._HOURS."</strong></td>\n";
1425 if (ereg("m", $display) || (empty($display))) {
1426 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MINUTES."</strong></td>\n";
1429 if (ereg("s", $display) || (empty($display))) {
1430 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._SECONDS."</strong></td>\n";
1436 if (ereg('Y', $display) || (empty($display))) {
1437 // Generate year selection
1438 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1439 for ($idx = 0; $idx <= 10; $idx++) {
1440 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1441 if ($idx == $Y) $OUT .= " selected default";
1442 $OUT .= ">".$idx."</option>\n";
1444 $OUT .= " </select></td>\n";
1446 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1449 if (ereg("M", $display) || (empty($display))) {
1450 // Generate month selection
1451 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1452 for ($idx = 0; $idx <= 11; $idx++)
1454 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1455 if ($idx == $M) $OUT .= " selected default";
1456 $OUT .= ">".$idx."</option>\n";
1458 $OUT .= " </select></td>\n";
1460 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1463 if (ereg("W", $display) || (empty($display))) {
1464 // Generate week selection
1465 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1466 for ($idx = 0; $idx <= 4; $idx++) {
1467 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1468 if ($idx == $W) $OUT .= " selected default";
1469 $OUT .= ">".$idx."</option>\n";
1471 $OUT .= " </select></td>\n";
1473 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1476 if (ereg("D", $display) || (empty($display))) {
1477 // Generate day selection
1478 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1479 for ($idx = 0; $idx <= 31; $idx++) {
1480 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $D) $OUT .= " selected default";
1482 $OUT .= ">".$idx."</option>\n";
1484 $OUT .= " </select></td>\n";
1486 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1489 if (ereg("h", $display) || (empty($display))) {
1490 // Generate hour selection
1491 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1492 for ($idx = 0; $idx <= 23; $idx++) {
1493 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1494 if ($idx == $h) $OUT .= " selected default";
1495 $OUT .= ">".$idx."</option>\n";
1497 $OUT .= " </select></td>\n";
1499 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1502 if (ereg("m", $display) || (empty($display))) {
1503 // Generate minute selection
1504 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1505 for ($idx = 0; $idx <= 59; $idx++) {
1506 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1507 if ($idx == $m) $OUT .= " selected default";
1508 $OUT .= ">".$idx."</option>\n";
1510 $OUT .= " </select></td>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1515 if (ereg("s", $display) || (empty($display))) {
1516 // Generate second selection
1517 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1518 for ($idx = 0; $idx <= 59; $idx++) {
1519 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1520 if ($idx == $s) $OUT .= " selected default";
1521 $OUT .= ">".$idx."</option>\n";
1523 $OUT .= " </select></td>\n";
1525 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1528 $OUT .= "</table>\n";
1530 // Return generated HTML code
1535 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1536 // Initial return value
1539 // Do we have a leap year?
1541 $TEST = date('Y', time()) / 4;
1542 $M1 = date("m", time());
1543 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1544 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1545 // First add years...
1546 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1548 $ret += $POST[$prefix."_mo"] * 2628000;
1550 $ret += $POST[$prefix."_we"] * 604800;
1552 $ret += $POST[$prefix."_da"] * 86400;
1554 $ret += $POST[$prefix."_ho"] * 3600;
1556 $ret += $POST[$prefix."_mi"] * 60;
1557 // And at last seconds...
1558 $ret += $POST[$prefix."_se"];
1559 // Return calculated value
1562 // Sends out mail to all administrators
1563 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1564 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1565 // Trim template name
1566 $template = trim($template);
1568 // Load email template
1569 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1571 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1572 // Older version detected!
1573 return SEND_ADMIN_EMAILS($subj, $msg);
1576 // Check which admin shall receive this mail
1577 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1578 array($template), __FILE__, __LINE__);
1579 if (SQL_NUMROWS($result) == 0) {
1580 // Create new entry (to all admins)
1581 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1582 array($template), __FILE__, __LINE__);
1584 // Load admin IDs...
1586 while (list($aid) = SQL_FETCHROW($result)) {
1591 SQL_FREERESULT($result);
1593 // "implode" IDs and query string
1594 $aid = implode(",", $aids);
1596 // Add line to userlog
1597 USERLOG_ADD_LINE($subj, $msg, $UID);
1599 } elseif ($aid == "0") {
1600 // Select all email adresses
1601 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`", __FILE__, __LINE__);
1603 // If Admin-ID is not "to-all" select
1604 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`", array($aid), __FILE__, __LINE__);
1608 // Load email addresses and send away
1609 while (list($email) = SQL_FETCHROW($result)) {
1610 SEND_EMAIL($email, $subj, $msg);
1614 SQL_FREERESULT($result);
1617 function CREATE_FANCY_TIME ($stamp) {
1618 // Get data array with years/months/weeks/days/...
1619 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1621 foreach($data as $k => $v) {
1623 // Value is greater than 0 "eval" data to return string
1624 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1630 // Do we have something there?
1631 if (strlen($ret) > 0) {
1632 // Remove leading commata and space
1633 $ret = substr($ret, 2);
1636 $ret = "0 "._SECONDS;
1639 // Return fancy time string
1643 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1644 $SEP = ""; $TOP = "";
1647 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1651 for ($page = 1; $page <= $PAGES; $page++) {
1652 // Is the page currently selected or shall we generate a link to it?
1653 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1654 // Is currently selected, so only highlight it
1655 $NAV .= "<strong>-";
1657 // Open anchor tag and add base URL
1658 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1660 // Add userid when we shall show all mails from a single member
1661 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1663 // Close open anchor tag
1667 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1668 // Is currently selected, so only highlight it
1669 $NAV .= "-</strong>";
1675 // Add seperator if we have not yet reached total pages
1676 if ($page < $PAGES) $NAV .= " | ";
1679 // Define constants only once
1680 if (!defined('__NAV_OUTPUT')) {
1681 define('__NAV_OUTPUT' , $NAV);
1682 define('__NAV_COLSPAN', $colspan);
1683 define('__NAV_TOP' , $TOP);
1684 define('__NAV_SEP' , $SEP);
1687 // Load navigation template
1688 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1691 // Return generated HTML-Code
1699 // Extract host from script name
1700 function EXTRACT_HOST (&$script) {
1701 // Use default SERVER_URL by default... ;) So?
1704 // Is this URL valid?
1705 if (substr($script, 0, 7) == "http://") {
1706 // Use the hostname from script URL as new hostname
1707 $url = substr($script, 7);
1708 $extract = explode("/", $url);
1710 // Done extracting the URL :)
1713 // Extract host name
1714 $host = str_replace("http://", "", $url);
1715 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1717 // Generate relative URL
1718 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1719 if (substr(strtolower($script), 0, 7) == "http://") {
1720 // But only if http:// is in front!
1721 $script = substr($script, (strlen($url) + 7));
1722 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1724 $script = substr($script, (strlen($url) + 8));
1727 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1728 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1734 // Send a GET request
1735 function GET_URL ($script) {
1736 // Compile the script name
1737 $script = COMPILE_CODE($script);
1739 // Extract host name from script
1740 $host = EXTRACT_HOST($script);
1742 // Generate GET request header
1743 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1744 $request .= "Host: " . $host . "\r\n";
1745 $request .= "Referer: " . URL . "/admin.php\r\n";
1746 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1747 $request .= "Content-Type: text/plain\r\n";
1748 $request .= "Cache-Control: no-cache\r\n";
1749 $request .= "Connection: Close\r\n\r\n";
1751 // Send the raw request
1752 $response = SEND_RAW_REQUEST($host, $request);
1754 // Return the result to the caller function
1758 // Send a POST request
1759 function POST_URL ($script, $postData) {
1760 // Is postData an array?
1761 if (!is_array($postData)) {
1763 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1764 return array("", "", "");
1767 // Compile the script name
1768 $script = COMPILE_CODE($script);
1770 // Extract host name from script
1771 $host = EXTRACT_HOST($script);
1773 // Construct request
1774 $data = http_build_query($postData, '','&');
1776 // Generate POST request header
1777 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1778 $request .= "Host: " . $host . "\r\n";
1779 $request .= "Referer: " . URL . "/admin.php\r\n";
1780 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1781 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1782 $request .= "Content-length: " . strlen($data) . "\r\n";
1783 $request .= "Cache-Control: no-cache\r\n";
1784 $request .= "Connection: Close\r\n\r\n";
1787 // Send the raw request
1788 $response = SEND_RAW_REQUEST($host, $request);
1790 // Return the result to the caller function
1794 // Sends a raw request to another host
1795 function SEND_RAW_REQUEST ($host, $request) {
1797 $response = array("", "", "");
1799 // Default is not to use proxy
1802 // Are proxy settins set?
1803 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1809 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1811 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1813 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1817 if (!is_resource($fp)) {
1824 // Generate CONNECT request header
1825 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1826 $proxyTunnel .= "Host: ".$host."\r\n";
1828 // Use login data to proxy? (username at least!)
1829 if (getConfig('proxy_username') != "") {
1831 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1832 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1835 // Add last new-line
1836 $proxyTunnel .= "\r\n";
1837 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1840 fputs($fp, $proxyTunnel);
1844 // No response received
1848 // Read the first line
1849 $resp = trim(fgets($fp, 10240));
1850 $respArray = explode(" ", $resp);
1851 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1852 // Invalid response!
1858 fputs($fp, $request);
1862 $response[] = trim(fgets($fp, 1024));
1868 // Skip first empty lines
1870 foreach ($resp as $idx => $line) {
1872 $line = trim($line);
1874 // Is this line empty?
1877 array_shift($response);
1879 // Abort on first non-empty line
1884 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1886 // Proxy agent found?
1887 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1888 // Proxy header detected, so remove two lines
1889 array_shift($response);
1890 array_shift($response);
1893 // Was the request successfull?
1894 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1895 // Not found / access forbidden
1896 $response = array("", "", "");
1902 // Taken from www.php.net eregi() user comments
1903 function VALIDATE_EMAIL($email) {
1905 $email = COMPILE_CODE($email);
1907 // Check first part of email address
1908 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1911 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1914 $regex = "^".$first."@".$domain."$";
1916 // Return check result
1917 return eregi($regex, $email);
1919 // Function taken from user comments on www.php.net / function eregi()
1920 function VALIDATE_URL ($URL, $compile=true) {
1921 // Trim URL a little
1922 $URL = trim(urldecode($URL));
1923 //* DEBUG: */ echo $URL."<br />";
1925 // Compile some chars out...
1926 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1927 //* DEBUG: */ echo $URL."<br />";
1929 // Check for the extension filter
1930 if (EXT_IS_ACTIVE("filter")) {
1931 // Use the extension's filter set
1932 return FILTER_VALIDATE_URL($URL, false);
1935 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1936 // https:// in front of the URLs
1937 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1940 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1941 // Define all main targets
1942 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1944 // Begin of navigation links
1945 $eval = "\$OUT = \"[ ";
1947 foreach ($TARGETS as $tar) {
1948 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1949 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1950 if (($tar == "lock_user") && ($status == "LOCKED")) {
1951 // Locked accounts shall be unlocked
1952 $eval .= "UNLOCK_USER";
1954 // All other status is fine
1955 $eval .= strtoupper($tar);
1957 $eval .= "_TITLE--}\\\">{--ADMIN_";
1958 if (($tar == "lock_user") && ($status == "LOCKED")) {
1959 // Locked accounts shall be unlocked
1960 $eval .= "UNLOCK_USER";
1962 // All other status is fine
1963 $eval .= strtoupper($tar);
1965 $eval .= "--}</a></span> | ";
1968 // Finish navigation link
1969 $eval = substr($eval, 0, -7)."]\";";
1975 // Function for backward-compatiblity
1976 function ADD_CATEGORY_table ($MODE, $return=false) {
1977 // Load it from the register extension
1978 return REGISTER_ADD_CATEGORY_table ($MODE, $return);
1980 // Generate an email link
1981 function CREATE_EMAIL_LINK ($email, $table = "admins") {
1982 // Default email link (INSECURE! Spammer can read this by harvester programs)
1983 $EMAIL = "mailto:".$email;
1985 // Check for several extensions
1986 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
1987 // Create email link for contacting admin in guest area
1988 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
1989 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
1990 // Create email link for contacting a member within admin area (or later in other areas, too?)
1991 $EMAIL = USER_CREATE_EMAIL_LINK($email);
1992 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
1993 // Create email link to contact sponsor within admin area (or like the link above?)
1994 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
1997 // Shall I close the link when there is no admin?
1998 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2000 // Return email link
2003 // Generate a hash for extra-security for all passwords
2004 function generateHash ($plainText, $salt = "") {
2007 // Is the required extension "sql_patches" there and a salt is not given?
2008 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2009 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2010 return md5($plainText);
2013 // Do we miss an arry element here?
2014 if (!isConfigEntrySet('file_hash')) {
2016 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2019 // When the salt is empty build a new one, else use the first x configured characters as the salt
2021 // Build server string
2022 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2025 $keys = constant('SITE_KEY').":".constant('DATE_KEY').":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime'))).":".getConfig('master_salt');
2028 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2030 // Calculate number for generating the code
2031 $a = time() + constant('_ADD') - 1;
2033 // Generate SHA1 sum from modula of number and the prime number
2034 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2035 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2036 $sha1 = scrambleString($sha1);
2037 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2038 //* DEBUG: */ $sha1b = descrambleString($sha1);
2039 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2041 // Generate the password salt string
2042 $salt = substr($sha1, 0, getConfig('salt_length'));
2043 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2046 $salt = substr($salt, 0, getConfig('salt_length'));
2047 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2051 return $salt.sha1($salt.$plainText);
2054 function scrambleString($str) {
2058 // Final check, in case of failture it will return unscrambled string
2059 if (strlen($str) > 40) {
2060 // The string is to long
2062 } elseif (strlen($str) == 40) {
2064 $scrambleNums = explode(":", getConfig('pass_scramble'));
2066 // Generate new numbers
2067 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2070 // Scramble string here
2071 //* DEBUG: */ echo "***Original=".$str."***<br />";
2072 for ($idx = 0; $idx < strlen($str); $idx++) {
2073 // Get char on scrambled position
2074 $char = substr($str, $scrambleNums[$idx], 1);
2076 // Add it to final output string
2077 $scrambled .= $char;
2080 // Return scrambled string
2081 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2085 function descrambleString($str) {
2086 // Scramble only 40 chars long strings
2087 if (strlen($str) != 40) return $str;
2089 // Load numbers from config
2090 $scrambleNums = explode(":", getConfig('pass_scramble'));
2093 if (count($scrambleNums) != 40) return $str;
2095 // Begin descrambling
2096 $orig = str_repeat(" ", 40);
2097 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2098 for ($idx = 0; $idx < 40; $idx++) {
2099 $char = substr($str, $idx, 1);
2100 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2103 // Return scrambled string
2104 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2108 function genScrambleString ($len) {
2109 // Prepare array for the numbers
2110 $scrambleNumbers = array();
2112 // First we need to setup randomized numbers from 0 to 31
2113 for ($idx = 0; $idx < $len; $idx++) {
2115 $rand = mt_rand(0, ($len -1));
2117 // Check for it by creating more numbers
2118 while (array_key_exists($rand, $scrambleNumbers)) {
2119 $rand = mt_rand(0, ($len -1));
2123 $scrambleNumbers[$rand] = $rand;
2126 // So let's create the string for storing it in database
2127 $scrambleString = implode(":", $scrambleNumbers);
2128 return $scrambleString;
2131 // Append data like session ID or referal ID to the given URL which would
2132 // normally be stored in cookies
2133 function ADD_URL_DATA ($URL) {
2137 // Determine URL binder
2139 if (strpos($URL, "?") !== false) $BIND = "&";
2141 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2142 // Cookies are not accepted
2143 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2144 // Cookie found in URL
2145 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2146 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2147 // Not found! So let's set default here
2148 $ADD .= $BIND."refid=".getConfig('def_refid');
2152 // Add all together and return it
2156 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2157 function generatePassString ($passHash) {
2158 // Return vanilla password hash
2161 // Is a secret key and master salt already initialized?
2162 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2163 // Only calculate when the secret key is generated
2164 $newHash = ""; $start = 9;
2165 for ($idx = 0; $idx < 10; $idx++) {
2166 $part1 = hexdec(substr($passHash, $start, 4));
2167 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2168 $mod = dechex($idx);
2169 if ($part1 > $part2) {
2170 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2171 } elseif ($part2 > $part1) {
2172 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2174 $mod = substr(round($mod), 0, 4);
2175 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2176 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2181 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2182 $ret = generateHash($newHash, getConfig('master_salt'));
2183 //* DEBUG: */ print($ret."<br />\n");
2186 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2187 $ret = md5($passHash);
2188 //* DEBUG: */ echo "++".$ret."++<br />\n";
2195 // Fix "deleted" cookies
2196 function FIX_DELETED_COOKIES ($cookies) {
2197 // Is this an array with entries?
2198 if ((is_array($cookies)) && (count($cookies) > 0)) {
2199 // Then check all cookies if they are marked as deleted!
2200 foreach ($cookies as $cookieName) {
2201 // Is the cookie set to "deleted"?
2202 if (get_session($cookieName) == "deleted") {
2203 set_session($cookieName, "");
2209 // Output error messages in a fasioned way and die...
2210 function mxchange_die ($msg) {
2212 LOAD_INC_ONCE("inc/header.php");
2214 // Load the message template
2215 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2218 LOAD_INC_ONCE("inc/footer.php");
2224 // Display parsing time and number of SQL queries in footer
2225 function DISPLAY_PARSING_TIME_FOOTER() {
2226 // Is the timer started?
2227 if (!isset($GLOBALS['startTime'])) {
2233 $endTime = microtime(true);
2235 // "Explode" both times
2236 $start = explode(" ", $GLOBALS['startTime']);
2237 $end = explode(" ", $endTime);
2238 $runTime = $end[0] - $start[0];
2239 if ($runTime < 0) $runTime = 0;
2240 $runTime = TRANSLATE_COMMA($runTime);
2244 'runtime' => $runTime,
2245 'numSQLs' => (getConfig('sql_count') + 1),
2246 'numTemplates' => (getConfig('num_templates') + 1)
2249 // Load the template
2250 LOAD_TEMPLATE("show_timings", false, $content);
2253 // Unset/set session variables
2254 function set_session ($var, $value) {
2257 // Abort in CSS mode here
2258 if ($CSS == 1) return true;
2260 // Trim value and session variable
2261 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2263 // Is the session variable set?
2264 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2265 // Remove the session
2266 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2267 unset($_SESSION[$var]);
2268 return session_unregister($var);
2269 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2271 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2272 $_SESSION[$var] = $value;
2273 return session_register($var);
2274 } elseif (!empty($value)) {
2276 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2277 $_SESSION[$var] = $value;
2281 // Ignored (but valid)
2282 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2286 // Check wether a boolean constant is set
2287 // Taken from user comments in PHP documentation for function constant()
2288 function isBooleanConstantAndTrue($constName) { // : Boolean
2291 // Failed by default
2295 if (isset($cacheArray['const'][$constName])) {
2297 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2298 $res = $cacheArray['const'][$constName];
2301 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2302 if (defined($constName)) $res = (constant($constName) === true);
2305 $cacheArray['const'][$constName] = $res;
2307 //* DEBUG: */ var_dump($res);
2313 // Check wether a session variable is set
2314 function isSessionVariableSet ($var) {
2315 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2316 return (isset($_SESSION[$var]));
2318 // Returns wether the value of the session variable or NULL if not set
2319 function get_session ($var) {
2322 // Default is not found! ;-)
2325 // Is the variable there or cached values?
2326 if (isset($cacheArray['session'][$var])) {
2327 // Get cached value (skips a lot SQL_ESCAPE() calles!
2328 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2329 $value = $cacheArray['session'][$var];
2330 } elseif (isSessionVariableSet($var)) {
2331 // Then get it secured!
2332 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2333 $value = SQL_ESCAPE($_SESSION[$var]);
2336 $cacheArray['session'][$var] = $value;
2343 // Send notification to admin
2344 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2345 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2347 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2349 // Send outdated way
2350 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2351 SEND_ADMIN_EMAILS($subject, $msg);
2355 // Destroy user session
2356 function destroy_user_session () {
2358 $GLOBALS['userid'] = 0;
2360 // Remove all user data from session
2361 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2364 // Merges an array together but only if both are arrays
2365 function merge_array ($array1, $array2) {
2366 // Are both an array?
2367 if ((is_array($array1)) && (is_array($array2))) {
2368 // Merge all together
2369 return array_merge($array1, $array2);
2370 } elseif (is_array($array1)) {
2371 // Return left array
2372 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
2374 } elseif (is_array($array2)) {
2375 // Return right array
2376 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
2380 // Both are not arrays
2381 debug_report_bug(__FUNCTION__.":");
2384 // Debug message logger
2385 function DEBUG_LOG ($file, $line, $message, $force=true) {
2386 // Is debug mode enabled?
2387 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2388 // Log this message away
2389 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2390 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2395 // Reads a directory with PHP files in and gets only files back
2396 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2400 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2403 while ($baseFile = readdir($dirPointer)) {
2404 // Load file only if extension is active
2406 $file = $baseDir.$baseFile;
2408 // Is this a valid reset file?
2409 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2410 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2411 // Remove both for extension name
2412 $extName = substr($baseFile, strlen($prefix), -4);
2415 $extId = GET_EXT_ID($extName);
2417 // Is the extension valid and active?
2418 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2419 // Then add this file
2421 } elseif ($extId == 0) {
2422 // Add non-extension files as well
2429 closedir($dirPointer);
2434 // Return array with include files
2437 // Load more reset scripts
2438 function RESET_ADD_INCLUDES () {
2439 // Is the reset set or old sql_patches?
2440 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2445 // Get more daily reset scripts
2446 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2449 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2451 // Create current week mark
2452 $currWeek = date("W", time());
2455 if (getConfig('last_week') != $currWeek) {
2456 // Include weekly reset scripts
2457 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2460 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2463 // Create current month mark
2464 $currMonth = date("m", time());
2467 if (getConfig('last_month') != $currMonth) {
2468 // Include monthly reset scripts
2469 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2472 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2478 // Handle extra values
2479 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2480 // Default is the value itself
2483 // Do we have a special filter function?
2484 if (!empty($filterFunction)) {
2485 // Does the filter function exist?
2486 if (function_exists($filterFunction)) {
2487 // Do we have extra parameters here?
2488 if (!empty($extraValue)) {
2489 // Put both parameters in one new array by default
2490 $args = array($value, $extraValue);
2492 // If we have an array simply use it and pre-extend it with our value
2493 if (is_array($extraValue)) {
2494 // Make the new args array
2495 $args = merge_array(array($value), $extraValue);
2498 // Call the multi-parameter call-back
2499 $ret = call_user_func_array($filterFunction, $args);
2501 // One parameter call
2502 $ret = call_user_func($filterFunction, $value);
2510 // Check if given FQFN is a readable file
2511 function FILE_READABLE($fqfn) {
2513 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2515 // Converts timestamp selections into a timestamp
2516 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2517 // Init test variable
2520 // Get last three chars
2521 $test = substr($id, -3);
2523 // Improved way of checking! :-)
2524 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2525 // Found a multi-selection for timings?
2526 $test = substr($id, 0, -3);
2527 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)) {
2528 // Generate timestamp
2529 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2530 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2532 // Remove data from array
2533 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2534 unset($POST[$test."_".$rem]);
2538 unset($id); $skip = true; $test2 = $test;
2541 // Process this entry
2542 $skip = false; $test2 = "";
2545 // Reverts the german decimal comma into Computer decimal dot
2546 function REVERT_COMMA ($str) {
2547 // Default float is not a float... ;-)
2550 // Which language is selected?
2551 switch (GET_LANGUAGE()) {
2552 case "de": // German language
2553 // Remove german thousand dots first
2554 $str = str_replace(".", "", $str);
2556 // Replace german commata with decimal dot and cast it
2557 $float = (float)str_replace(",", ".", $str);
2560 default: // US and so on
2561 // Remove thousand dots first and cast
2562 $float = (float)str_replace(",", "", $str);
2570 // Handle menu-depending failed logins and return the rendered content
2571 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2572 // Default output is empty ;-)
2575 // Is the session data set?
2576 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2577 // Ignore zero values
2578 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
2579 // Non-guest has login failures found, get both data and prepare it for template
2580 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2582 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
2583 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2587 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
2590 // Reset session data
2591 set_session('mxchange_'.$accessLevel.'_failures', "");
2592 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2595 // Return rendered content
2600 function REBUILD_CACHE ($cache, $inc="") {
2601 global $cacheInstance, $CSS;
2603 // Shall I remove the cache file?
2604 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2606 if ($cacheInstance->loadCacheFile($cache)) {
2608 $cacheInstance->destroyCacheFile();
2611 // Include file given?
2614 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
2616 // Is the include there?
2617 if (FILE_READABLE($INC)) {
2618 // And rebuild it from scratch
2619 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2622 // Include not found!
2623 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2629 // Purge admin menu cache
2630 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2631 global $cacheInstance;
2633 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2634 if (!EXT_IS_ACTIVE("cache")) {
2635 // Cache extension not active
2637 } elseif (!is_object($cacheInstance)) {
2638 // No cache instance!
2639 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2641 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
2642 // Caching disabled (currently experiemental!)
2646 // Experiemental feature!
2647 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2650 // Translates the "pool type" into human-readable
2651 function TRANSLATE_POOL_TYPE ($type) {
2652 // Default type is unknown
2653 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
2655 // Generate constant
2656 $constName = sprintf("POOL_TYPE_%s", $type);
2659 if (defined($constName)) {
2661 $translated = constant($constName);
2664 // Return "translation"
2668 // "Getter" for remote IP number
2669 function GET_REMOTE_ADDR () {
2670 // Get remote ip from environment
2671 $remoteAddr = getenv('REMOTE_ADDR');
2673 // Is removeip installed?
2674 if (EXT_IS_ACTIVE("removeip")) {
2675 // Then anonymize it
2676 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2682 // "Getter" for remote hostname
2683 function GET_REMOTE_HOST () {
2684 // Get remote ip from environment
2685 $remoteHost = getenv('REMOTE_HOST');
2687 // Is removeip installed?
2688 if (EXT_IS_ACTIVE("removeip")) {
2689 // Then anonymize it
2690 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2696 // "Getter" for user agent
2697 function GET_USER_AGENT () {
2698 // Get remote ip from environment
2699 $userAgent = getenv('HTTP_USER_AGENT');
2701 // Is removeip installed?
2702 if (EXT_IS_ACTIVE("removeip")) {
2703 // Then anonymize it
2704 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2710 // "Getter" for referer
2711 function GET_REFERER () {
2712 // Get remote ip from environment
2713 $referer = getenv('HTTP_REFERER');
2715 // Is removeip installed?
2716 if (EXT_IS_ACTIVE("removeip")) {
2717 // Then anonymize it
2718 $referer = GET_ANONYMOUS_REFERER($referer);
2725 // Adds a bonus mail to the queue
2726 // This is a high-level function!
2727 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2728 // Use mode from data if not set and availble ;-)
2729 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2731 // Generate receiver list
2732 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2735 if (!empty($RECEIVER)) {
2736 // Add bonus mail to queue
2737 ADD_BONUS_MAIL_TO_QUEUE(
2749 // Mail inserted into bonus pool
2750 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
2751 } elseif ($output) {
2752 // More entered than can be reached!
2753 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
2756 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2760 // Determines referal id and sets it
2761 function DETERMINE_REFID () {
2762 global $CLICK, $_SERVER;
2764 // Check if refid is set
2765 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2766 // The variable user comes from the click-counter script click.php and we only accept this here
2767 $GLOBALS['refid'] = bigintval($_GET['user']);
2768 } elseif (!empty($_POST['refid'])) {
2769 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2770 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2771 } elseif (!empty($_GET['refid'])) {
2772 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2773 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2774 } elseif (!empty($_GET['ref'])) {
2775 // Set refid=ref (the referal link uses such variable)
2776 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2777 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2778 // Set session refid als global
2779 $GLOBALS['refid'] = bigintval(get_session('refid'));
2780 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2781 // Set default refid as refid in URL
2782 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2783 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2784 // Select a random user which has confirmed enougth mails
2785 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2787 // No default ID when sql_patches is not installed or none set
2788 $GLOBALS['refid'] = 0;
2791 // Set cookie when default refid > 0
2792 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2794 set_session('refid', $GLOBALS['refid']);
2797 // Return determined refid
2798 return $GLOBALS['refid'];
2801 // Destroys the admin session
2802 function destroyAdminSession ($destroy = true) {
2803 // Kill maybe existing session variables including array elements
2804 set_session('admin_login', "");
2805 set_session('admin_md5' , "");
2806 set_session('admin_last' , "");
2807 set_session('admin_to' , "");
2809 // Destroy session and return status
2811 return session_destroy();
2814 // All fine if we shall not really destroy the session
2818 // Checks if a given apache module is loaded
2819 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2820 // Check it and return result
2821 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2824 // Getter for $_CONFIG entries
2825 function getConfig ($entry) {
2831 // Is the entry there?
2832 if (isConfigEntrySet($entry)) {
2834 $value = $_CONFIG[$entry];
2841 // Setter for $_CONFIG entries
2842 function setConfigEntry ($entry, $value) {
2845 // Secure the entry name
2846 $entry = SQL_ESCAPE($entry);
2849 $_CONFIG[$entry] = $value;
2852 // Checks wether the given config entry is set
2853 function isConfigEntrySet ($entry) {
2855 return (isset($_CONFIG[$entry]));
2858 // Increment or init with given value or 1 as default the given config entry
2859 function incrementConfigEntry ($configEntry, $value=1) {
2862 // Increment it if set or init it with 1
2863 if (getConfig($configEntry) > 0) {
2864 $_CONFIG[$configEntry] += $value;
2866 $_CONFIG[$configEntry] = $value;
2870 // "Getter" for language strings
2871 // @TODO Rewrite all language constants to this function.
2872 function getMessage ($messageId) {
2873 // Default is not found!
2874 $return = "!".$messageId."!";
2876 // Is the language string found?
2877 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2878 // Language array element found in small_letters
2879 $return = $GLOBALS['msg'][$messageId];
2880 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2881 // @DEPRECATED Language array element found in BIG_LETTERS
2882 $return = $GLOBALS['msg'][$messageId];
2883 } elseif (defined($messageId)) {
2884 // @DEPRECATED Deprecated constant found
2885 $return = constant($messageId);
2887 // Missing language constant
2888 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2891 // Return the string
2895 // Get current theme name
2896 function GET_CURR_THEME() {
2897 global $INC_POOL, $CSS, $cacheArray;
2899 // The default theme is 'default'... ;-)
2902 // Load default theme if not empty from configuration
2903 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2905 if (!isSessionVariableSet('mxchange_theme')) {
2906 // Set default theme
2907 set_session('mxchange_theme', $ret);
2908 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2909 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2910 // Get theme from cookie
2911 $ret = get_session('mxchange_theme');
2914 if (THEME_GET_ID($ret) == 0) {
2915 // Fix it to default
2918 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2919 // Prepare FQFN for checking
2920 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_GET['theme']));
2922 // Installation mode active
2923 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2924 // Set cookie from URL data
2925 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2926 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_POST['theme'])))) {
2927 // Set cookie from posted data
2928 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2932 $ret = get_session('mxchange_theme');
2934 // Invalid design, reset cookie
2935 set_session('mxchange_theme', $ret);
2938 // Add (maybe) found theme.php file to inclusion list
2939 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2941 // Try to load the requested include file
2942 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2944 // Return theme value
2948 // Get id from theme
2949 function THEME_GET_ID ($name) {
2952 // Is the extension "theme" installed?
2953 if (!EXT_IS_ACTIVE("theme")) {
2961 // Is the cache entry there?
2962 if (isset($cacheArray['themes']['id'][$name])) {
2963 // Get the version from cache
2964 $id = $cacheArray['themes']['id'][$name];
2967 incrementConfigEntry('cache_hits');
2968 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2969 // Check if current theme is already imported or not
2970 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2971 array($name), __FILE__, __LINE__);
2974 if (SQL_NUMROWS($result) == 1) {
2976 list($id) = SQL_FETCHROW($result);
2980 SQL_FREERESULT($result);
2987 // Read a given file
2988 function READ_FILE ($FQFN, $sqlPrepare = false) {
2990 if (function_exists('file_get_contents')) {
2992 $content = file_get_contents($FQFN);
2994 // Fall-back to implode-file chain
2995 $content = implode("", file($FQFN));
2998 // Prepare SQL queries?
2999 if ($sqlPrepare === true) {
3000 // Remove some unwanted chars
3001 $content = str_replace("\r", "", $content);
3002 $content = str_replace("\n\n", "\n", $content);
3005 // Return the content
3009 // Writes content to a file
3010 function WRITE_FILE ($FQFN, $content) {
3011 // Is the function there?
3012 if (function_exists('file_put_contents')) {
3013 // Write it directly
3014 file_put_contents($FQFN, $content);
3016 // Write it with fopen
3017 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
3018 fwrite($fp, $content);
3026 // Generates an error code from given account status
3027 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3028 // Default error code if unknown account status
3029 $ERROR = constant('CODE_UNKNOWN_STATUS');
3031 // Generate constant name
3032 $constantName = sprintf("CODE_ID_%s", $status);
3034 // Is the constant there?
3035 if (defined($constantName)) {
3037 $ERROR = constant($constantName);
3040 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3043 // Return error code
3047 // Clears the output buffer. This function does *NOT* backup sent content.
3048 function clearOutputBuffer () {
3049 // Trigger an error on failure
3050 if (!ob_end_clean()) {
3052 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
3056 // "Getter" for revision/version data
3057 function getActualVersion ($type = 0) {
3058 // By default nothing is new... ;-)
3061 // FQFN of revision file
3062 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
3064 // Check for revision file
3065 if (!FILE_READABLE($FQFN)) {
3066 // Not found, so we need to create it
3069 // Revision file found
3070 $ins_vers = explode("\n", READ_FILE($FQFN));
3072 // Is the content valid?
3073 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
3074 // File needs update!
3077 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
3078 return trim($ins_vers[$type]);
3082 // Has it been updated?
3083 if ($new === true) {
3084 // No Revision-File or has no valid Data so read the Revision from the Server.
3085 $version = GET_URL("check-updates3.php");
3088 $akt_vers[] = trim($version[10]);
3089 $akt_vers[] = trim($version[9]);
3090 $akt_vers[] = trim($version[8]);
3093 WRITE_FILE($FQFN, implode("\n", $akt_vers));
3095 // Return requested content
3096 return trim($akt_vers[$type]);
3100 // Loads an include file and logs any missing files for debug purposes
3101 function LOAD_INC ($INC) {
3102 // Get constant path
3103 $PATH = constant('PATH');
3105 // Use the include file name directly
3106 // @TODO Try to find all locations where an FQFN is given to these two
3107 // @TODO functions and avoid it.
3110 // Check if PATH is in $INC
3111 if (substr($INC, 0, $PATH) != $PATH) {
3112 // Add it. This is why we need a trailing slash in config.php
3113 $FQFN = $PATH . $INC;
3116 // Is the include file there?
3117 if (!FILE_READABLE($FQFN)) {
3118 // Not there so log it
3119 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Include file %s not found.", basename($INC)));
3127 // Loads an include file once
3128 function LOAD_INC_ONCE ($INC) {
3131 // Is it not loaded?
3132 if (!isset($cacheArray['load_once'][$INC])) {
3133 // Then try to load it
3136 // And mark it as loaded
3137 $cacheArray['load_once'][$INC] = true;
3141 // Back-ported from the new ship-simu engine. :-)
3142 function debug_get_printable_backtrace () {
3144 $backtrace = "<ol>\n";
3146 // Get and prepare backtrace for output
3147 $backtraceArray = debug_backtrace();
3148 foreach ($backtraceArray as $key => $trace) {
3149 if (!isset($trace['file'])) $trace['file'] = __FILE__;
3150 if (!isset($trace['line'])) $trace['line'] = __LINE__;
3151 if (!isset($trace['args'])) $trace['args'] = array();
3152 $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";
3156 $backtrace .= "</ol>\n";
3158 // Return the backtrace
3162 // Output a debug backtrace to the user
3163 function debug_report_bug ($message = "") {
3166 // Is the optional message set?
3167 if (!empty($message)) {
3169 $debug = sprintf("Note: %s<br />\n",
3173 // @TODO Add a little more infos here
3174 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
3178 $debug .= ("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
3179 $debug .= (debug_get_printable_backtrace());
3180 $debug .= ("</pre>Thank you for your help finding bugs.");
3186 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
3187 function generateSeed () {
3188 list($usec, $sec) = explode(" ", microtime());
3189 return ((float)$sec + (float)$usec);
3192 // Converts a message code to a human-readable message
3193 function convertCodeToMessage ($code) {
3196 case constant('CODE_LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
3197 case constant('CODE_LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
3198 case constant('CODE_DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
3199 case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
3200 case constant('CODE_ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
3201 case constant('CODE_USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
3202 case constant('CODE_STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
3203 case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
3205 case constant('CODE_ERROR_MAILID'):
3206 if (EXT_IS_ACTIVE($ext, true)) {
3207 $msg = getMessage('ERROR_CONFIRMING_MAIL');
3209 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
3213 case constant('CODE_EXTENSION_PROBLEM'):
3214 if (isset($_GET['ext'])) {
3215 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), SQL_ESCAPE($_GET['ext']));
3217 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
3221 case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
3222 case constant('CODE_BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
3223 case constant('CODE_LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
3224 default : $msg = UNKNOWN_MAILID_CODE_1.$code.UNKNOWN_MAILID_CODE_2; break;
3227 // Return the message
3231 // Checks wether the given extension is currently not installed
3232 // and redirects if so.
3233 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
3234 // Is the extension uninstalled/inactive?
3235 if (!EXT_IS_ACTIVE($ext_name)) {
3236 // Redirect to index
3237 LOAD_URL("modules.php?module=index&msg=".constant('CODE_EXTENSION_PROBLEM')."&ext=".$ext_name);
3241 //////////////////////////////////////////////////
3242 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3243 //////////////////////////////////////////////////
3245 if (!function_exists('html_entity_decode')) {
3246 // Taken from documentation on www.php.net
3247 function html_entity_decode ($string) {
3248 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3249 $trans_tbl = array_flip($trans_tbl);
3250 return strtr($string, $trans_tbl);