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", 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 // Open a table (you may want to add some header stuff here)
64 function OPEN_TABLE ($PERCENT = "", $CLASS = "", $ALIGN="left", $VALIGN="", $td_only=false) {
67 // Count tables so we can generate CSS classes for every table... :-)
69 // Class is empty so count one up and create a class
70 $table_cnt++; $CLASS = "class".$table_cnt;
72 $OUT = "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\"";
74 // Shall I add the classes to TABLE and TD or only to TD?
75 if (!$td_only) $OUT .= " class=\"".$CLASS."\"";
78 if (!empty($PERCENT)) $OUT .= " width=\"".$PERCENT."\"";
81 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
83 // Vertical align is given
84 if (!empty($VALIGN)) $OUT .= " valign=\"".$VALIGN."\"";
85 $OUT .= ">\n<TR>\n<TD";
86 if (!empty($ALIGN)) $OUT .=" align=\"".$ALIGN."\"";
87 $OUT .= " class=\"".$CLASS."\">";
91 // Close a table (you may want to add some footer stuff here)
93 function CLOSE_TABLE( $ADD="") {
94 OUTPUT_HTML(" </TD>\n</TR>");
95 if (!empty($ADD)) OUTPUT_HTML($ADD);
96 OUTPUT_HTML("</TABLE>");
99 // Output HTML code directly or "render" it. You addionally switch the new-line character off
100 function OUTPUT_HTML ($HTML, $NEW_LINE = true) {
101 // Some global variables
102 global $OUTPUT, $footer, $CSS;
104 // Do we have HTML-Code here?
106 // Yes, so we handle it as you have configured
110 // That's why you don't need any \n at the end of your HTML code... :-)
111 if (_OB_CACHING == "on") {
112 // Output into PHP's internal buffer
115 // That's why you don't need any \n at the end of your HTML code... :-)
116 if ($NEW_LINE) echo "\n";
118 // Render mode for old or lame servers...
121 // That's why you don't need any \n at the end of your HTML code... :-)
122 if ($NEW_LINE) $OUTPUT .= "\n";
127 // If we are switching from render to direct output rendered code
128 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
130 // The same as above... ^
132 if ($NEW_LINE) echo "\n";
136 // Huh, something goes wrong or maybe you have edited config.php ???
137 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", OUTPUT_MODE));
138 MXCHANGE_DIE("<strong>".FATAL_ERROR.":</strong> ".LANG_NO_RENDER_DIRECT);
141 } elseif ((_OB_CACHING == "on") && ($footer == 1)) {
142 // Headers already sent?
143 if (headers_sent()) {
145 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
147 // Trigger an user error
148 trigger_error("Headers are already sent!");
151 // Output cached HTML code
152 $OUTPUT = ob_get_contents();
154 // Clear output buffer for later output
158 header("HTTP/1.1 200");
161 $now = gmdate('D, d M Y H:i:s') . ' GMT';
163 // General headers for no caching
164 header("Expired: " . $now); // RFC2616 - Section 14.21
165 header("Last-Modified: " . $now);
166 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
167 header("Pragma: no-cache"); // HTTP/1.0
168 header("Connection: Close");
170 // Extension "rewrite" installed?
171 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
172 $OUTPUT = REWRITE_LINKS($OUTPUT);
175 // Compile and run finished rendered HTML code
176 while (strpos($OUTPUT, '{!') > 0) {
177 // Prepare the content and eval() it...
179 $eval = "\$newContent = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
182 // Was that eval okay?
183 if (empty($newContent)) {
184 // Something went wrong!
185 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
187 $OUTPUT = $newContent;
190 // Output code here, DO NOT REMOVE! ;-)
192 } elseif ((OUTPUT_MODE == "render") && (!empty($OUTPUT))) {
193 // Rewrite links when rewrite extension is active
194 if ((EXT_IS_ACTIVE("rewrite")) && ($CSS != "1") && ($CSS != "-1")) {
195 $OUTPUT = REWRITE_LINKS($OUTPUT);
198 // Compile and run finished rendered HTML code
199 while (strpos($OUTPUT, '{!') > 0) {
200 $eval = "\$OUTPUT = \"".COMPILE_CODE(addslashes($OUTPUT))."\";";
204 // Output code here, DO NOT REMOVE! ;-)
209 // Output the raw HTML code
210 function OUTPUT_RAW ($HTML) {
211 // Output stripped HTML code to avoid broken JavaScript code, etc.
212 echo stripslashes(stripslashes($HTML));
214 // Flush the output if only _OB_CACHING is not "on"
215 if (_OB_CACHING != "on") {
221 // Add a fatal error message to the queue array
222 function addFatalMessage ($message, $extra="") {
226 // Regular text message to add to $FATAL
229 // $message is text with a mask plus extras to insert into the text
230 $message = sprintf($message, $extra);
234 // Log fatal messages away
235 DEBUG_LOG(__FUNCTION__, __LINE__, " message={$message}");
238 // Getter for total fatal message count
239 function getTotalFatalMessages () {
245 // Do we have at least the first entry?
246 if (!empty($FATAL[0])) {
248 $count = count($FATAL);
255 // Load a template file and return it's content (only it's name; do not use ' or ")
256 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
257 // Add more variables which you want to use in your template files
258 global $DATA, $_CONFIG, $username;
260 // Make all template names lowercase
261 $template = strtolower($template);
263 // Count the template load
264 incrementConfigEntry('num_templates');
266 // Prepare IP number and User Agent
267 $REMOTE_ADDR = GET_REMOTE_ADDR();
268 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
269 $HTTP_USER_AGENT = GET_USER_AGENT();
273 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
275 // @DEPRECATED Try to rewrite the if() condition
276 if ($template == "member_support_form") {
277 // Support request of a member
278 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
279 array($GLOBALS['userid']), __FILE__, __LINE__);
281 // Is content an array?
282 if (is_array($content)) {
284 $content = merge_array($content, SQL_FETCHARRAY($result));
287 $content['gender'] = TRANSLATE_GENDER($content['gender']);
289 // DEPRECATED: Load data in direct variables
290 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
293 $gender = TRANSLATE_GENDER($gender);
294 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
298 SQL_FREERESULT($result);
301 // Generate date/time string
302 $date_time = MAKE_DATETIME(time(), "1");
305 $BASE = sprintf("%stemplates/%s/html/", PATH, GET_LANGUAGE());
308 // Check for admin/guest/member templates
309 if (strpos($template, "admin_") > -1) {
310 // Admin template found
312 } elseif (strpos($template, "guest_") > -1) {
313 // Guest template found
315 } elseif (strpos($template, "member_") > -1) {
316 // Member template found
318 } elseif (strpos($template, "install_") > -1) {
319 // Installation template found
321 } elseif (strpos($template, "ext_") > -1) {
322 // Extension template found
324 } elseif (strpos($template, "la_") > -1) {
325 // "Logical-area" template found
328 // Test for extension
329 $test = substr($template, 0, strpos($template, "_"));
330 if (EXT_IS_ACTIVE($test)) {
331 // Set extra path to extension's name
336 ////////////////////////
337 // Generate file name //
338 ////////////////////////
339 $file = $BASE.$MODE.$template.".tpl";
341 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
342 // Select what depended header/footer template file for admin/guest/member area
343 $file2 = sprintf("%s%s%s_%s.tpl",
347 SQL_ESCAPE($GLOBALS['what'])
351 if (FILE_READABLE($file2)) $file = $file2;
353 // Remove variable from memory
357 // Does the special template exists?
358 if (!FILE_READABLE($file)) {
359 // Reset to default template
360 $file = $BASE.$template.".tpl";
363 // Now does the final template exists?
364 if (FILE_READABLE($file)) {
365 // The local file does exists so we load it. :)
366 $tmpl_file = READ_FILE($file);
368 // Replace ' to our own chars to preventing them being quoted
369 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
371 // Do we have to compile the code?
373 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
375 $tmpl_file = "\$ret=\"".COMPILE_CODE(addslashes($tmpl_file))."\";";
378 // Simply return loaded code
382 // Add surrounding HTML comments to help finding bugs faster
383 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
384 } elseif ((IS_ADMIN()) || ((isBooleanConstantAndTrue('mxchange_installing')) && (!isBooleanConstantAndTrue('mxchange_installed')))) {
385 // Only admins shall see this warning or when installation mode is active
386 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
387 (".basename($file).")<br />
390 <pre>".print_r($content, true)."</pre>
392 <pre>".print_r($DATA, true)."</pre>
396 // Remove content and data
400 // Do we have some content to output or return?
402 // Not empty so let's put it out! ;)
404 // Return the HTML code
410 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
411 // Warning, empty output!
412 return "E:".$template."<br />\n";
416 // Send mail out to an email address
417 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
418 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
420 // Compile subject line (for POINTS constant etc.)
421 $eval = "\$SUBJECT = html_entity_decode(\"".COMPILE_CODE(addslashes($SUBJECT))."\");";
425 if ((!eregi("@", $TO)) && ($TO > 0)) {
426 // Value detected, is the message extension installed?
427 if (EXT_IS_ACTIVE("msg")) {
428 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
431 // Load email address
432 $result_email = SQL_QUERY_ESC("SELECT email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FILE__, __LINE__);
433 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
435 // Does the user exist?
436 if (SQL_NUMROWS($result_email)) {
437 // Load email address
438 list($TO) = SQL_FETCHROW($result_email);
445 SQL_FREERESULT($result_email);
447 } elseif ("$TO" == "0") {
451 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
453 // Check for PHPMailer or debug-mode
454 if (!CHECK_PHPMAILER_USAGE()) {
455 // Not in PHPMailer-Mode
457 // Load email header template
458 $FROM = LOAD_EMAIL_TEMPLATE("header");
461 $FROM .= LOAD_EMAIL_TEMPLATE("header");
463 } elseif (isBooleanConstantAndTrue('DEBUG_MODE')) {
465 // Load email header template
466 $FROM = LOAD_EMAIL_TEMPLATE("header");
469 $FROM .= LOAD_EMAIL_TEMPLATE("header");
474 $eval = "\$TO = \"".COMPILE_CODE(addslashes($TO))."\";";
478 $eval = "\$MSG = \"".COMPILE_CODE(addslashes($MSG))."\";";
481 // Fix HTML parameter (default is no!)
482 if (empty($HTML)) $HTML = "N";
483 if (isBooleanConstantAndTrue('DEBUG_MODE')) {
484 // In debug mode we want to display the mail instead of sending it away so we can debug this part
486 ".htmlentities(trim($FROM))."
488 Subject : ".$SUBJECT."
491 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
492 // Send mail as HTML away
493 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
494 } elseif (!empty($TO)) {
496 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
497 } elseif ($HTML == "N") {
499 SEND_RAW_EMAIL(WEBMASTER, "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
503 // Check if legacy or PHPMailer command
505 function CHECK_PHPMAILER_USAGE() {
506 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (SMTP_HOSTNAME != "") && (SMTP_USER != ""));
510 * Send out a raw email with PHPMailer class or legacy mail() command
512 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
513 // Shall we use PHPMailer class or legacy mode?
514 if (CHECK_PHPMAILER_USAGE()) {
515 // Use PHPMailer class with SMTP enabled
516 require_once(PATH."inc/phpmailer/class.phpmailer.php");
517 require_once(PATH."inc/phpmailer/class.smtp.php");
520 $mail = new PHPMailer();
521 $mail->PluginDir = sprintf("%sinc/phpmailer/", PATH);
524 $mail->SMTPAuth = true;
525 $mail->Host = SMTP_HOSTNAME;
527 $mail->Username = SMTP_USER;
528 $mail->Password = SMTP_PASSWORD;
530 $mail->From = WEBMASTER;
534 $mail->FromName = MAIN_TITLE;
535 $mail->Subject = $subject;
536 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
538 $mail->AltBody = "Your mail program required HTML support to read this mail!";
539 $mail->WordWrap = 70;
542 $mail->Body = html_entity_decode($msg);
544 $mail->AddAddress($to, "");
545 $mail->AddReplyTo(WEBMASTER,MAIN_TITLE);
546 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
547 $mail->AddCustomHeader("X-Loop:".WEBMASTER);
550 // Use legacy mail() command
551 @mail($to, $subject, html_entity_decode($msg), $from);
556 // Generate a password in a specified length or use default password length
557 function GEN_PASS ($LEN = 0) {
558 // Auto-fix invalid length of zero
559 if ($LEN == 0) $LEN = getConfig('pass_len');
561 // Initialize array with all allowed chars
562 $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,-,+,_,/");
564 // Initialize randomizer
565 mt_srand((double) microtime() * 1000000);
567 // Start creating password
569 for ($i = 0; $i < $LEN; $i++) {
570 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
573 // When the size is below 40 we can also add additional security by scrambling it
574 if (strlen($PASS) <= 40) {
575 // Also scramble the password
576 $PASS = scrambleString($PASS);
579 // Return the password
583 function MAKE_DATETIME ($time, $mode="0")
587 return NEVER_HAPPENED;
589 // Filter out numbers
590 $time = bigintval($time);
593 switch (GET_LANGUAGE())
595 case "de": // German date / time format
597 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
598 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
599 case "2": $ret = date("d.m.Y|H:i", $time); break;
600 case "3": $ret = date("d.m.Y", $time); break;
602 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
607 default: // Default is the US date / time format!
609 case "0": $ret = date("r", $time); break;
610 case "1": $ret = date("Y-m-d - g:i A", $time); break;
611 case "2": $ret = date("y-m-d|H:i", $time); break;
612 case "3": $ret = date("y-m-d", $time); break;
614 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
621 // Translates the american decimal dot into a german comma
622 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
625 // Default is 3 you can change this in admin area "Misc -> Misc Options"
626 if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
628 // Use from config is default
629 $maxComma = getConfig('max_comma');
631 // Use from parameter?
632 if ($max > 0) $maxComma = $max;
635 if (($cut) && ($max == 0)) {
636 // Test for commata if in cut-mode
637 $com = explode(".", $dotted);
638 if (count($com) < 2) {
639 // Don't display commatas even if there are none... ;-)
645 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
648 switch (GET_LANGUAGE()) {
650 $dotted = number_format($dotted, $maxComma, ",", ".");
654 $dotted = number_format($dotted, $maxComma, ".", ",");
658 // Return translated value
663 function DEREFERER ($URL) {
664 // Don't de-refer our own links!
665 if (substr($URL, 0, strlen(URL)) != URL) {
666 // De-refer this link
667 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
675 function TRANSLATE_GENDER ($gender) {
678 case "M": $ret = GENDER_M; break;
679 case "F": $ret = GENDER_F; break;
680 case "C": $ret = GENDER_C; break;
681 default : $ret = $gender; break;
686 function FRAMETESTER($URL) {
687 // Prepare frametester URL
688 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
690 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
692 return $frametesterUrl;
695 function SELECTION_COUNT($array) {
697 if (is_array($array)) {
698 foreach ($array as $key => $sel) {
699 if (!empty($sel)) $ret++;
705 function IMG_CODE ($code, $type, $DATA, $uid) {
706 return "<IMG border=\"0\" alt=\"Code\" src=\"".URL."/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
709 function TRANSLATE_STATUS($status) {
713 $ret = ACCOUNT_UNCONFIRMED;
717 $ret = ACCOUNT_CONFIRMED;
721 $ret = ACCOUNT_LOCKED;
726 $ret = ACCOUNT_DELETED;
730 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
731 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
737 function GET_LANGUAGE() {
740 // Set default return value to default language from config
746 // Is the variable set
747 if (!empty($_GET['mx_lang'])) {
748 // Accept only first 2 chars
749 $lang = substr($_GET['mx_lang'], 0, 2);
750 } elseif (isset($cacheArray['language'])) {
752 $ret = $cacheArray['language'];
753 } elseif (!empty($lang)) {
754 // Check if main language file does exist
755 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
756 // Okay found, so let's update cookies
759 } elseif (!isSessionVariableSet('mx_lang')) {
760 // Return stored value from cookie
761 $ret = get_session('mx_lang');
763 // Fixes a warning before the session has the mx_lang constant
764 if (empty($ret)) $ret = DEFAULT_LANG;
768 $cacheArray['language'] = $ret;
774 function SET_LANGUAGE ($lang) {
775 // Accept only first 2 chars!
776 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
779 set_session('mx_lang', $lang);
782 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
783 global $DATA, $REPLACER, $_CONFIG;
785 // Make sure all template names are lowercase!
786 $template = strtolower($template);
788 // Default "nickname" if extension is not installed
791 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
792 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = URL; $WEBMASTER = WEBMASTER;
794 // Prepare IP number and User Agent
795 $REMOTE_ADDR = GET_REMOTE_ADDR();
796 $HTTP_USER_AGENT = GET_USER_AGENT();
801 // Is the admin logged in?
804 $aid = GET_CURRENT_ADMIN_ID();
807 $ADMIN = GET_ADMIN_EMAIL($aid);
810 // Neutral email address is default
813 // Expiration in a nice output format
814 if (getConfig('auto_purge') == 0) {
815 // Will never expire!
816 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
818 // Create nice date string
819 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
822 // Is content an array?
823 if (is_array($content)) {
824 // Add expiration to array, $EXPIRATION is now deprecated!
825 $content['expiration'] = $EXPIRATION;
829 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
830 if (($UID > 0) && (is_array($content))) {
831 // If nickname extension is installed, fetch nickname as well
832 if (EXT_IS_ACTIVE("nickname")) {
833 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
835 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
836 array(bigintval($UID)), __FILE__, __LINE__);
838 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
840 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `"._MYSQL_PREFIX."_user_data` WHERE userid=%s LIMIT 1",
841 array(bigintval($UID)), __FILE__, __LINE__);
844 // Fetch and merge data
845 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
846 $content = merge_array($content, SQL_FETCHARRAY($result));
847 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
850 SQL_FREERESULT($result);
853 // Translate M to male or F to female if present
854 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
856 // Overwrite email from data if present
857 if (isset($content['email'])) $email = $content['email'];
859 // Store email for some functions in global data array
860 $DATA['email'] = $email;
863 $BASE = sprintf("%stemplates/%s/emails/", PATH, GET_LANGUAGE());
865 // Check for admin/guest/member templates
866 if (strpos($template, "admin_") > -1) {
867 // Admin template found
868 $file = $BASE."admin/".$template.".tpl";
869 } elseif (strpos($template, "guest_") > -1) {
870 // Guest template found
871 $file = $BASE."guest/".$template.".tpl";
872 } elseif (strpos($template, "member_") > -1) {
873 // Member template found
874 $file = $BASE."member/".$template.".tpl";
876 // Test for extension
877 $test = substr($template, 0, strpos($template, "_"));
878 if (EXT_IS_ACTIVE($test)) {
879 // Set extra path to extension's name
880 $file = $BASE.$test."/".$template.".tpl";
882 // No special filename
883 $file = $BASE.$template.".tpl";
887 // Does the special template exists?
888 if (!FILE_READABLE($file)) {
889 // Reset to default template
890 $file = $BASE.$template.".tpl";
893 // Now does the final template exists?
895 if (FILE_READABLE($file)) {
896 // The local file does exists so we load it. :)
897 $tmpl_file = READ_FILE($file);
898 $tmpl_file = addslashes($tmpl_file);
901 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
903 } elseif (!empty($template)) {
904 // Template file not found!
905 $newContent = TEMPLATE_404.": ".$template."<br />
907 <pre>".print_r($content, true)."</pre>
909 <pre>".print_r($DATA, true)."</pre>
912 // Debug mode not active? Then remove the HTML tags
913 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
915 // No template name supplied!
916 $newContent = NO_TEMPLATE_SUPPLIED;
919 // Is there some content?
920 if (empty($newContent)) {
922 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
923 // Add last error if the required function exists
924 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
927 // Remove content and data
931 // Return compiled content
932 return COMPILE_CODE($newContent);
935 function MAKE_TIME($H, $M, $S, $stamp) {
936 // Extract day, month and year from given timestamp
937 $DAY = date("d", $stamp);
938 $MONTH = date("m", $stamp);
939 $YEAR = date('Y', $stamp);
941 // Create timestamp for wished time which depends on extracted date
942 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
945 function LOAD_URL($URL, $addUrlData=true) {
946 global $CSS, $footer;
948 // Compile out URI codes
949 $URL = COMPILE_CODE($URL);
951 // Check if http(s):// is there
952 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
953 // Make all URLs full-qualified
960 debug_print_backtrace();
963 $OUTPUT = ob_get_contents();
965 // Clear it only if there is content
966 if (!empty($OUTPUT)) {
970 // Add some data to URL if cookies are not accepted
971 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
973 // Probe for bot from search engine
974 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
975 // Search engine bot detected so let's rewrite many chars for the link
976 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
978 // Output new location link as anchor
979 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
980 } elseif (!headers_sent()) {
981 // Load URL when headers are not sent
984 debug_print_backtrace();
985 die("</pre>URL={$URL}");
987 header ("Location: ".str_replace("&", "&", $URL));
989 // Output error message
990 include(PATH."inc/header.php");
991 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
992 include(PATH."inc/footer.php");
997 // Wrapper for LOAD_URL but URL comes from a configuration entry
998 function LOAD_CONFIGURED_URL ($configEntry) {
1000 $URL = getConfig($configEntry);
1003 if (is_null($URL)) {
1005 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry);
1013 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
1014 global $SEC_CHARS, $URL_CHARS;
1015 // Is the code a string?
1016 if (!is_string($code)) {
1017 // Silently return it
1021 $ARRAY = $SEC_CHARS;
1023 // Select smaller set of chars to replace when we e.g. want to compile URLs
1024 if (!$full) $ARRAY = $URL_CHARS;
1026 // Compile constants
1028 // BEFORE 0.2.1 : Language and data constants
1029 // WITH 0.2.1+ : Only language constants
1030 $code = str_replace('{--','".', str_replace('--}','."', $code));
1032 // BEFORE 0.2.1 : Not used
1033 // WITH 0.2.1+ : Data constants
1034 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1037 // Compile QUOT and other non-HTML codes
1038 foreach ($ARRAY['to'] as $k => $to) {
1039 // Do the reversed thing as in inc/libs/security_functions.php
1040 $code = str_replace($to, $ARRAY['from'][$k], $code);
1043 // But shall I keep simple quotes for later use?
1044 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1046 // Find $content[bla][blub] entries
1047 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1049 // Are some matches found?
1050 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1051 // Replace all matches
1052 $matchesFound = array();
1053 foreach ($matches[0] as $key => $match) {
1054 // Fuzzy look has failed by default
1055 $fuzzyFound = false;
1057 // Fuzzy look on match if already found
1058 foreach ($matchesFound as $found => $set) {
1060 $test = substr($found, 0, strlen($match));
1062 // Does this entry exist?
1063 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1064 if ($test == $match) {
1066 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1073 if ($fuzzyFound) continue;
1075 // Take all string elements
1076 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1077 // Replace it in the code
1078 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1079 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1080 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1081 $matchesFound[$key."_".$matches[4][$key]] = 1;
1082 $matchesFound[$match] = 1;
1083 } elseif (!isset($matchesFound[$match])) {
1084 // Not yet replaced!
1085 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1086 $code = str_replace($match, "\".".$match.".\"", $code);
1087 $matchesFound[$match] = 1;
1092 // Return compiled code
1096 /************************************************************************
1098 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1099 * $a_sort sortiert: *
1101 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1102 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1103 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1104 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1105 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1107 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1108 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1109 * Sie, dass es doch nicht so schwer ist! :-) *
1111 ************************************************************************/
1112 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1115 while ($primary_key < count($a_sort)) {
1116 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1117 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1120 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1121 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1122 } elseif ($key != $key2) {
1123 // Sort numbers (E.g.: 9 < 10)
1124 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1125 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1129 // We have found two different values, so let's sort whole array
1130 foreach ($dummy as $sort_key => $sort_val) {
1131 $t = $dummy[$sort_key][$key];
1132 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1133 $dummy[$sort_key][$key2] = $t;
1144 // Write back sorted array
1148 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1149 global $MONTH_DESCR;
1152 if ($type == "yn") {
1153 // This is a yes/no selection only!
1154 if ($id > 0) $prefix .= "[".$id."]";
1155 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1157 // Begin with regular selection box here
1158 if (!empty($prefix)) $prefix .= "_";
1160 if ($id > 0) $type2 .= "[".$id."]";
1161 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1166 for ($idx = 1; $idx < 32; $idx++) {
1167 $OUT .= "<option value=\"".$idx."\"";
1168 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1169 $OUT .= ">".$idx."</option>\n";
1173 case "month": // Month
1174 foreach ($MONTH_DESCR as $month => $descr) {
1175 $OUT .= "<option value=\"".$month."\"";
1176 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1177 $OUT .= ">".$descr."</option>\n";
1181 case "year": // Year
1183 $YEAR = date('Y', time());
1185 // Use configured min age or fixed?
1186 if (GET_EXT_VERSION("other") >= "0.2.1") {
1188 $startYear = $YEAR - getConfig('min_age');
1191 $startYear = $YEAR - 16;
1194 // Calculate earliest year (100 years old people can still enter Internet???)
1195 $minYear = $YEAR - 100;
1197 // Check if the default value is larger than minimum and bigger than actual year
1198 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1199 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1200 $OUT .= "<option value=\"".$idx."\"";
1201 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1202 $OUT .= ">".$idx."</option>\n";
1204 } elseif ($DEFAULT == -1) {
1205 // Current year minus 1
1206 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1208 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1211 // Get current year and subtract the configured minimum age
1212 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1213 // Calculate earliest year depending on extension version
1214 if (GET_EXT_VERSION("other") >= "0.2.1") {
1215 // Use configured minimum age
1216 $YEAR = date('Y', time()) - getConfig('min_age');
1218 // Use fixed 16 years age
1219 $YEAR = date('Y', time()) - 16;
1222 // Construct year selection list
1223 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1224 $OUT .= "<option value=\"".$idx."\"";
1225 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1226 $OUT .= ">".$idx."</option>\n";
1233 for ($idx = 0; $idx < 60; $idx+=5) {
1234 if (strlen($idx) == 1) $idx = "0".$idx;
1235 $OUT .= "<option value=\"".$idx."\"";
1236 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1237 $OUT .= ">".$idx."</option>\n";
1242 for ($idx = 0; $idx < 24; $idx++) {
1243 if (strlen($idx) == 1) $idx = "0".$idx;
1244 $OUT .= "<option value=\"".$idx."\"";
1245 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1246 $OUT .= ">".$idx."</option>\n";
1251 $OUT .= "<option value=\"Y\"";
1252 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1253 $OUT .= ">".YES."</option>\n<option value=\"N\"";
1254 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1255 $OUT .= ">".NO."</option>\n";
1258 $OUT .= " </select>\n";
1262 function TRANSLATE_YESNO($yn)
1266 case "Y": $yn = YES; break;
1267 case "N": $yn = NO; break;
1268 default : $yn = "??? (".$yn.")"; break;
1273 // Deprecated : $length
1276 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1277 // Fix missing _MAX constant
1278 if (!defined('_MAX')) define('_MAX', 15235);
1280 // Build server string
1281 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1284 $keys = SITE_KEY.":".DATE_KEY;
1285 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1286 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1287 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1288 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1290 // Build string from misc data
1291 $data = $code.":".$uid.":".$DATA;
1293 // Add more additional data
1294 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1295 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1296 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1297 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1298 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1300 // Calculate number for generating the code
1301 $a = $code + _ADD - 1;
1303 if (getConfig('master_hash') != null) {
1304 // Generate hash with master salt from modula of number with the prime number and other data
1305 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1307 // Create number from hash
1308 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1310 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1311 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1313 // Create number from hash
1314 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1317 // At least 10 numbers shall be secure enought!
1318 $len = getConfig('code_length');
1319 if ($len == 0) $len = $length;
1320 if ($len == 0) $len = 10;
1322 // Cut off requested counts of number
1323 $return = substr(str_replace('.', "", $rcode), 0, $len);
1325 // Done building code
1328 // Does only allow numbers
1329 function bigintval($num, $castValue = true) {
1330 // Filter all numbers out
1331 $ret = preg_replace("/[^0123456789]/", "", $num);
1334 if ($castValue) $ret = (double)$ret;
1336 // Has the whole value changed?
1337 if ("".$ret."" != "".$num."") {
1340 debug_print_backtrace();
1342 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1348 // Insert the code in $img_code into jpeg or PNG image
1349 function GENERATE_IMAGE($img_code, $header=true) {
1350 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1351 // Stop execution of function here because of over-sized code length
1353 } elseif (!$header) {
1354 // Return in an HTML code code
1355 return "<IMG src=\"".URL."/img.php?code=".$img_code."\">\n";
1359 $img = sprintf("%s/theme/%s/images/code_bg.%s", PATH, GET_CURR_THEME(), getConfig('img_type'));
1360 if (FILE_READABLE($img)) {
1361 // Switch image type
1362 switch (getConfig('img_type'))
1365 // Okay, load image and hide all errors
1366 $image = @imagecreatefromjpeg($img);
1370 // Okay, load image and hide all errors
1371 $image = @imagecreatefrompng($img);
1375 // Exit function here
1379 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1380 $text_color = imagecolorallocate($image, 0, 0, 0);
1382 // Insert code into image
1383 imagestring($image, 5, 14, 2, $img_code, $text_color);
1385 // Return to browser
1386 header ("Content-Type: image/".getConfig('img_type'));
1388 // Output image with matching image factory
1389 switch (getConfig('img_type')) {
1390 case "jpg": imagejpeg($image); break;
1391 case "png": imagepng($image); break;
1394 // Remove image from memory
1395 imagedestroy($image);
1397 // Create selection box or array of splitted timestamp
1398 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1399 // Calculate 2-seconds timestamp
1400 $stamp = round($timestamp);
1401 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1403 // Do we have a leap year?
1405 $TEST = date('Y', time()) / 4;
1406 $M1 = date("m", time());
1407 $M2 = date("m", (time() + $timestamp));
1409 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1410 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1412 // First of all years...
1413 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1414 //* DEBUG: */ print("Y={$Y}<br />\n");
1416 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1417 //* DEBUG: */ print("M={$M}<br />\n");
1419 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1420 //* DEBUG: */ print("W={$W}<br />\n");
1422 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1423 //* DEBUG: */ print("D={$D}<br />\n");
1425 $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));
1426 //* DEBUG: */ print("h={$h}<br />\n");
1428 $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));
1429 //* DEBUG: */ print("m={$m}<br />\n");
1430 // And at last seconds...
1431 $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));
1432 //* DEBUG: */ print("s={$s}<br />\n");
1434 // Is seconds zero and time is < 60 seconds?
1435 if (($s == 0) && ($timestamp < 60)) {
1437 $s = round($timestamp);
1441 // Now we convert them in seconds...
1443 if ($return_array) {
1444 // Just put all data in an array for later use
1456 $OUT = "<div align=\"".$align."\">\n";
1457 $OUT .= "<TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1460 if (ereg('Y', $display) || (empty($display))) {
1461 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._YEARS."</strong></TD>\n";
1464 if (ereg("M", $display) || (empty($display))) {
1465 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MONTHS."</strong></TD>\n";
1468 if (ereg("W", $display) || (empty($display))) {
1469 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._WEEKS."</strong></TD>\n";
1472 if (ereg("D", $display) || (empty($display))) {
1473 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._DAYS."</strong></TD>\n";
1476 if (ereg("h", $display) || (empty($display))) {
1477 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._HOURS."</strong></TD>\n";
1480 if (ereg("m", $display) || (empty($display))) {
1481 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MINUTES."</strong></TD>\n";
1484 if (ereg("s", $display) || (empty($display))) {
1485 $OUT .= " <TD align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._SECONDS."</strong></TD>\n";
1491 if (ereg('Y', $display) || (empty($display))) {
1492 // Generate year selection
1493 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1494 for ($idx = 0; $idx <= 10; $idx++) {
1495 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1496 if ($idx == $Y) $OUT .= " selected default";
1497 $OUT .= ">".$idx."</option>\n";
1499 $OUT .= " </select></TD>\n";
1501 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1504 if (ereg("M", $display) || (empty($display))) {
1505 // Generate month selection
1506 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1507 for ($idx = 0; $idx <= 11; $idx++)
1509 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1510 if ($idx == $M) $OUT .= " selected default";
1511 $OUT .= ">".$idx."</option>\n";
1513 $OUT .= " </select></TD>\n";
1515 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1518 if (ereg("W", $display) || (empty($display))) {
1519 // Generate week selection
1520 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1521 for ($idx = 0; $idx <= 4; $idx++) {
1522 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1523 if ($idx == $W) $OUT .= " selected default";
1524 $OUT .= ">".$idx."</option>\n";
1526 $OUT .= " </select></TD>\n";
1528 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1531 if (ereg("D", $display) || (empty($display))) {
1532 // Generate day selection
1533 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1534 for ($idx = 0; $idx <= 31; $idx++) {
1535 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1536 if ($idx == $D) $OUT .= " selected default";
1537 $OUT .= ">".$idx."</option>\n";
1539 $OUT .= " </select></TD>\n";
1541 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1544 if (ereg("h", $display) || (empty($display))) {
1545 // Generate hour selection
1546 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1547 for ($idx = 0; $idx <= 23; $idx++) {
1548 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1549 if ($idx == $h) $OUT .= " selected default";
1550 $OUT .= ">".$idx."</option>\n";
1552 $OUT .= " </select></TD>\n";
1554 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1557 if (ereg("m", $display) || (empty($display))) {
1558 // Generate minute selection
1559 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1560 for ($idx = 0; $idx <= 59; $idx++) {
1561 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1562 if ($idx == $m) $OUT .= " selected default";
1563 $OUT .= ">".$idx."</option>\n";
1565 $OUT .= " </select></TD>\n";
1567 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1570 if (ereg("s", $display) || (empty($display))) {
1571 // Generate second selection
1572 $OUT .= " <TD align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1573 for ($idx = 0; $idx <= 59; $idx++) {
1574 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1575 if ($idx == $s) $OUT .= " selected default";
1576 $OUT .= ">".$idx."</option>\n";
1578 $OUT .= " </select></TD>\n";
1580 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1583 $OUT .= "</TABLE>\n";
1585 // Return generated HTML code
1590 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1591 // Initial return value
1594 // Do we have a leap year?
1596 $TEST = date('Y', time()) / 4;
1597 $M1 = date("m", time());
1598 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1599 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1600 // First add years...
1601 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1603 $ret += $POST[$prefix."_mo"] * 2628000;
1605 $ret += $POST[$prefix."_we"] * 604800;
1607 $ret += $POST[$prefix."_da"] * 86400;
1609 $ret += $POST[$prefix."_ho"] * 3600;
1611 $ret += $POST[$prefix."_mi"] * 60;
1612 // And at last seconds...
1613 $ret += $POST[$prefix."_se"];
1614 // Return calculated value
1617 // Sends out mail to all administrators
1618 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1619 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1620 // Trim template name
1621 $template = trim($template);
1623 // Load email template
1624 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1626 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1627 // Older version detected!
1628 return SEND_ADMIN_EMAILS($subj, $msg);
1631 // Check which admin shall receive this mail
1632 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM "._MYSQL_PREFIX."_admins_mails WHERE mail_template='%s' ORDER BY admin_id",
1633 array($template), __FILE__, __LINE__);
1634 if (SQL_NUMROWS($result) == 0) {
1635 // Create new entry (to all admins)
1636 SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_admins_mails (admin_id, mail_template) VALUES (0, '%s')",
1637 array($template), __FILE__, __LINE__);
1639 // Load admin IDs...
1641 while(list($aid) = SQL_FETCHROW($result)) {
1646 SQL_FREERESULT($result);
1648 // "implode" IDs and query string
1649 $aid = implode(",", $aids);
1651 // Add line to userlog
1652 USERLOG_ADD_LINE($subj, $msg, $UID);
1654 } elseif ($aid == "0") {
1655 // Select all email adresses
1656 $result = SQL_QUERY("SELECT email FROM "._MYSQL_PREFIX."_admins ORDER BY id", __FILE__, __LINE__);
1658 // If Admin-ID is not "to-all" select
1659 $result = SQL_QUERY_ESC("SELECT email FROM "._MYSQL_PREFIX."_admins WHERE id IN (%s) ORDER BY id", array($aid), __FILE__, __LINE__);
1663 // Load email addresses and send away
1664 while (list($email) = SQL_FETCHROW($result)) {
1665 SEND_EMAIL($email, $subj, $msg);
1669 SQL_FREERESULT($result);
1672 function CREATE_FANCY_TIME ($stamp) {
1673 // Get data array with years/months/weeks/days/...
1674 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1676 foreach($data as $k => $v) {
1678 // Value is greater than 0 "eval" data to return string
1679 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1685 // Do we have something there?
1686 if (strlen($ret) > 0) {
1687 // Remove leading commata and space
1688 $ret = substr($ret, 2);
1691 $ret = "0 "._SECONDS;
1694 // Return fancy time string
1698 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1699 $SEP = ""; $TOP = "";
1702 $SEP = "<TR><TD colspan=\"".$colspan."\" class=\"seperator\"> </TD></TR>";
1706 for ($page = 1; $page <= $PAGES; $page++) {
1707 // Is the page currently selected or shall we generate a link to it?
1708 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1709 // Is currently selected, so only highlight it
1710 $NAV .= "<strong>-";
1712 // Open anchor tag and add base URL
1713 $NAV .= "<a href=\"".URL."/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1715 // Add userid when we shall show all mails from a single member
1716 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1718 // Close open anchor tag
1722 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1723 // Is currently selected, so only highlight it
1724 $NAV .= "-</strong>";
1730 // Add seperator if we have not yet reached total pages
1731 if ($page < $PAGES) $NAV .= " | ";
1734 // Define constants only once
1735 if (!defined('__NAV_OUTPUT')) {
1736 define('__NAV_OUTPUT' , $NAV);
1737 define('__NAV_COLSPAN', $colspan);
1738 define('__NAV_TOP' , $TOP);
1739 define('__NAV_SEP' , $SEP);
1742 // Load navigation template
1743 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1746 // Return generated HTML-Code
1754 // Extract host from script name
1755 function EXTRACT_HOST (&$script) {
1756 // Use default SERVER_URL by default... ;) So?
1759 // Is this URL valid?
1760 if (substr($script, 0, 7) == "http://") {
1761 // Use the hostname from script URL as new hostname
1762 $url = substr($script, 7);
1763 $extract = explode("/", $url);
1765 // Done extracting the URL :)
1768 // Extract host name
1769 $host = str_replace("http://", "", $url);
1770 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1772 // Generate relative URL
1773 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1774 if (substr(strtolower($script), 0, 7) == "http://") {
1775 // But only if http:// is in front!
1776 $script = substr($script, (strlen($url) + 7));
1777 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1779 $script = substr($script, (strlen($url) + 8));
1782 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1783 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1789 // Send a GET request
1790 function GET_URL ($script) {
1791 // Compile the script name
1792 $script = COMPILE_CODE($script);
1794 // Extract host name from script
1795 $host = EXTRACT_HOST($script);
1797 // Generate GET request header
1798 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1799 $request .= "Host: " . $host . "\r\n";
1800 $request .= "Referer: " . URL . "/admin.php\r\n";
1801 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1802 $request .= "Content-Type: text/plain\r\n";
1803 $request .= "Cache-Control: no-cache\r\n";
1804 $request .= "Connection: Close\r\n\r\n";
1806 // Send the raw request
1807 $response = SEND_RAW_REQUEST($host, $request);
1809 // Return the result to the caller function
1813 // Send a POST request
1814 function POST_URL ($script, $postData) {
1815 // Is postData an array?
1816 if (!is_array($postData)) {
1818 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1819 return array("", "", "");
1822 // Compile the script name
1823 $script = COMPILE_CODE($script);
1825 // Extract host name from script
1826 $host = EXTRACT_HOST($script);
1828 // Construct request
1829 $data = http_build_query($postData, '','&');
1831 // Generate POST request header
1832 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1833 $request .= "Host: " . $host . "\r\n";
1834 $request .= "Referer: " . URL . "/admin.php\r\n";
1835 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1836 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1837 $request .= "Content-length: " . strlen($data) . "\r\n";
1838 $request .= "Cache-Control: no-cache\r\n";
1839 $request .= "Connection: Close\r\n\r\n";
1842 // Send the raw request
1843 $response = SEND_RAW_REQUEST($host, $request);
1845 // Return the result to the caller function
1849 // Sends a raw request to another host
1850 function SEND_RAW_REQUEST ($host, $request) {
1852 $response = array("", "", "");
1854 // Default is not to use proxy
1857 // Are proxy settins set?
1858 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1864 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1866 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1868 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1872 if (!is_resource($fp)) {
1879 // Generate CONNECT request header
1880 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1881 $proxyTunnel .= "Host: ".$host."\r\n";
1883 // Use login data to proxy? (username at least!)
1884 if (getConfig('proxy_username') != "") {
1886 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1887 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1890 // Add last new-line
1891 $proxyTunnel .= "\r\n";
1892 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1895 fputs($fp, $proxyTunnel);
1899 // No response received
1903 // Read the first line
1904 $resp = trim(fgets($fp, 10240));
1905 $respArray = explode(" ", $resp);
1906 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1907 // Invalid response!
1913 fputs($fp, $request);
1917 $response[] = trim(fgets($fp, 1024));
1923 // Skip first empty lines
1925 foreach ($resp as $idx => $line) {
1927 $line = trim($line);
1929 // Is this line empty?
1932 array_shift($response);
1934 // Abort on first non-empty line
1939 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1941 // Proxy agent found?
1942 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1943 // Proxy header detected, so remove two lines
1944 array_shift($response);
1945 array_shift($response);
1948 // Was the request successfull?
1949 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1950 // Not found / access forbidden
1951 $response = array("", "", "");
1957 // Taken from www.php.net eregi() user comments
1958 function VALIDATE_EMAIL($email) {
1960 $email = COMPILE_CODE($email);
1962 // Check first part of email address
1963 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1966 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1969 $regex = "^".$first."@".$domain."$";
1971 // Return check result
1972 return eregi($regex, $email);
1974 // Function taken from user comments on www.php.net / function eregi()
1975 function VALIDATE_URL ($URL, $compile=true) {
1976 // Trim URL a little
1977 $URL = trim(urldecode($URL));
1978 //* DEBUG: */ echo $URL."<br />";
1980 // Compile some chars out...
1981 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1982 //* DEBUG: */ echo $URL."<br />";
1984 // Check for the extension filter
1985 if (EXT_IS_ACTIVE("filter")) {
1986 // Use the extension's filter set
1987 return FILTER_VALIDATE_URL($URL, false);
1990 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1991 // https:// in front of the URLs
1992 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1995 function MEMBER_ACTION_LINKS($uid, $status="") {
1996 // Define all main targets
1997 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1999 // Begin of navigation links
2000 $eval = "\$OUT = \"[ ";
2002 foreach ($TARGETS as $tar) {
2003 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"".URL."/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"\".ADMIN_LINK_";
2004 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
2005 if (($tar == "lock_user") && ($status == "LOCKED")) {
2006 // Locked accounts shall be unlocked
2007 $eval .= "UNLOCK_USER";
2009 // All other status is fine
2010 $eval .= strtoupper($tar);
2012 $eval .= "_TITLE.\"\\\">\".ADMIN_";
2013 if (($tar == "lock_user") && ($status == "LOCKED")) {
2014 // Locked accounts shall be unlocked
2015 $eval .= "UNLOCK_USER";
2017 // All other status is fine
2018 $eval .= strtoupper($tar);
2020 $eval .= ".\"</a></span> | ";
2023 // Finish navigation link
2024 $eval = substr($eval, 0, -7)."]\";";
2030 // Function for backward-compatiblity
2031 function ADD_CATEGORY_TABLE ($MODE, $return=false) {
2032 // Load it from the register extension
2033 return REGISTER_ADD_CATEGORY_TABLE ($MODE, $return);
2035 // Generate an email link
2036 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2037 // Default email link (INSECURE! Spammer can read this by harvester programs)
2038 $EMAIL = "mailto:".$email;
2040 // Check for several extensions
2041 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2042 // Create email link for contacting admin in guest area
2043 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2044 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2045 // Create email link for contacting a member within admin area (or later in other areas, too?)
2046 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2047 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2048 // Create email link to contact sponsor within admin area (or like the link above?)
2049 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2052 // Shall I close the link when there is no admin?
2053 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2055 // Return email link
2058 // Generate a hash for extra-security for all passwords
2059 function generateHash ($plainText, $salt = "") {
2062 // Is the required extension "sql_patches" there and a salt is not given?
2063 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2064 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2065 return md5($plainText);
2068 // Do we miss an arry element here?
2069 if (getConfig('file_hash') == null) {
2071 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2072 debug_print_backtrace();
2076 // When the salt is empty build a new one, else use the first x configured characters as the salt
2078 // Build server string
2079 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2082 $keys = SITE_KEY.":".DATE_KEY.":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime'))).":".getConfig('master_salt');
2085 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2087 // Calculate number for generating the code
2088 $a = time() + _ADD - 1;
2090 // Generate SHA1 sum from modula of number and the prime number
2091 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2092 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2093 $sha1 = scrambleString($sha1);
2094 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2095 //* DEBUG: */ $sha1b = descrambleString($sha1);
2096 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2098 // Generate the password salt string
2099 $salt = substr($sha1, 0, getConfig('salt_length'));
2100 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2103 $salt = substr($salt, 0, getConfig('salt_length'));
2104 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2108 return $salt.sha1($salt.$plainText);
2111 function scrambleString($str) {
2115 // Final check, in case of failture it will return unscrambled string
2116 if (strlen($str) > 40) {
2117 // The string is to long
2119 } elseif (strlen($str) == 40) {
2121 $scrambleNums = explode(":", getConfig('pass_scramble'));
2123 // Generate new numbers
2124 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2127 // Scramble string here
2128 //* DEBUG: */ echo "***Original=".$str."***<br />";
2129 for ($idx = 0; $idx < strlen($str); $idx++) {
2130 // Get char on scrambled position
2131 $char = substr($str, $scrambleNums[$idx], 1);
2133 // Add it to final output string
2134 $scrambled .= $char;
2137 // Return scrambled string
2138 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2142 function descrambleString($str) {
2143 // Scramble only 40 chars long strings
2144 if (strlen($str) != 40) return $str;
2146 // Load numbers from config
2147 $scrambleNums = explode(":", getConfig('pass_scramble'));
2150 if (count($scrambleNums) != 40) return $str;
2152 // Begin descrambling
2153 $orig = str_repeat(" ", 40);
2154 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2155 for ($idx = 0; $idx < 40; $idx++) {
2156 $char = substr($str, $idx, 1);
2157 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2160 // Return scrambled string
2161 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2165 function genScrambleString($len) {
2166 // Prepare randomizer and array for the numbers
2167 mt_srand((double) microtime() * 1000000);
2168 $scrambleNumbers = array();
2170 // First we need to setup randomized numbers from 0 to 31
2171 for ($idx = 0; $idx < $len; $idx++) {
2173 $rand = mt_rand(0, ($len -1));
2175 // Check for it by creating more numbers
2176 while (array_key_exists($rand, $scrambleNumbers)) {
2177 $rand = mt_rand(0, ($len -1));
2181 $scrambleNumbers[$rand] = $rand;
2184 // So let's create the string for storing it in database
2185 $scrambleString = implode(":", $scrambleNumbers);
2186 return $scrambleString;
2188 // Append data like session ID or referal ID to the given URL which would
2189 // normally be stored in cookies
2190 function ADD_URL_DATA ($URL) {
2194 // Determine URL binder
2196 if (strpos($URL, "?") !== false) $BIND = "&";
2198 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2199 // Cookies are not accepted
2200 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2201 // Cookie found in URL
2202 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2203 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2204 // Not found! So let's set default here
2205 $ADD .= $BIND."refid=".getConfig('def_refid');
2208 // Is there already added data? Then change the binder
2209 if (!empty($ADD)) $BIND = "&";
2212 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2213 // Add session from URL
2214 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2216 // Add current session
2217 $ADD .= $BIND."PHPSESSID=".session_id();
2221 // Add all together and return it
2224 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2225 function generatePassString($passHash) {
2226 // Return vanilla password hash
2229 // Is a secret key and master salt already initialized?
2230 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2231 // Only calculate when the secret key is generated
2232 $newHash = ""; $start = 9;
2233 for ($idx = 0; $idx < 10; $idx++) {
2234 $part1 = hexdec(substr($passHash, $start, 4));
2235 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2236 $mod = dechex($idx);
2237 if ($part1 > $part2) {
2238 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2239 } elseif ($part2 > $part1) {
2240 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2242 $mod = substr(round($mod), 0, 4);
2243 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2244 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2249 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2250 $ret = generateHash($newHash, getConfig('master_salt'));
2251 //* DEBUG: */ print($ret."<br />\n");
2254 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2255 $ret = md5($passHash);
2256 //* DEBUG: */ echo "++".$ret."++<br />\n";
2263 // Fix "deleted" cookies
2264 function FIX_DELETED_COOKIES ($cookies) {
2265 // Is this an array with entries?
2266 if ((is_array($cookies)) && (count($cookies) > 0)) {
2267 // Then check all cookies if they are marked as deleted!
2268 foreach ($cookies as $cookieName) {
2269 // Is the cookie set to "deleted"?
2270 if (get_session($cookieName) == "deleted") {
2271 set_session($cookieName, "");
2277 // Output error messages in a fasioned way and die...
2278 function mxchange_die ($msg) {
2281 // Load the message template
2282 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2285 include(PATH."inc/footer.php");
2291 // Display parsing time and number of SQL queries in footer
2292 function DISPLAY_PARSING_TIME_FOOTER() {
2293 // Is the timer started?
2294 if (!isset($GLOBALS['startTime'])) {
2300 $endTime = microtime(true);
2302 // "Explode" both times
2303 $start = explode(" ", $GLOBALS['startTime']);
2304 $end = explode(" ", $endTime);
2305 $runTime = $end[0] - $start[0];
2306 if ($runTime < 0) $runTime = 0;
2307 $runTime = TRANSLATE_COMMA($runTime);
2311 'runtime' => $runTime,
2312 'numSQLs' => (getConfig('sql_count') + 1),
2313 'numTemplates' => (getConfig('num_templates') + 1)
2316 // Load the template
2317 LOAD_TEMPLATE("show_timings", false, $content);
2320 // Unset/set session variables
2321 function set_session ($var, $value) {
2324 // Abort in CSS mode here
2325 if ($CSS == 1) return true;
2327 // Trim value and session variable
2328 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2330 // Is the session variable set?
2331 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2332 // Remove the session
2333 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2334 unset($_SESSION[$var]);
2335 return session_unregister($var);
2336 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2338 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2339 $_SESSION[$var] = $value;
2340 return session_register($var);
2341 } elseif (!empty($value)) {
2343 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2344 $_SESSION[$var] = $value;
2348 // Ignored (but valid)
2349 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2353 // Check wether a boolean constant is set
2354 // Taken from user comments in PHP documentation for function constant()
2355 function isBooleanConstantAndTrue($constName) { // : Boolean
2358 // Failed by default
2362 if (isset($cacheArray['const'][$constName])) {
2364 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2365 $res = $cacheArray['const'][$constName];
2368 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2369 if (defined($constName)) $res = (constant($constName) === true);
2372 $cacheArray['const'][$constName] = $res;
2374 //* DEBUG: */ var_dump($res);
2380 // Check wether a session variable is set
2381 function isSessionVariableSet ($var) {
2382 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2383 return (isset($_SESSION[$var]));
2385 // Returns wether the value of the session variable or NULL if not set
2386 function get_session ($var) {
2389 // Default is not found! ;-)
2392 // Is the variable there or cached values?
2393 if (isset($cacheArray['session'][$var])) {
2394 // Get cached value (skips a lot SQL_ESCAPE() calles!
2395 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2396 $value = $cacheArray['session'][$var];
2397 } elseif (isSessionVariableSet($var)) {
2398 // Then get it secured!
2399 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2400 $value = SQL_ESCAPE($_SESSION[$var]);
2403 $cacheArray['session'][$var] = $value;
2410 // Send notification to admin
2411 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2412 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2414 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2416 // Send outdated way
2417 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2418 SEND_ADMIN_EMAILS($subject, $msg);
2422 // Destroy user session
2423 function destroy_user_session () {
2425 $GLOBALS['userid'] = 0;
2427 // Remove all user data from session
2428 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2431 // Merges an array together but only if both are arrays
2432 function merge_array ($array1, $array2) {
2433 // Are both an array?
2434 if ((is_array($array1)) && (is_array($array2))) {
2435 // Merge all together
2436 return array_merge($array1, $array2);
2437 } elseif (is_array($array1)) {
2438 // Return left array
2442 // Something wired happened here...
2443 print(__FUNCTION__.":<pre>");
2444 debug_print_backtrace();
2448 // Debug message logger
2449 function DEBUG_LOG ($file, $line, $message, $force=true) {
2450 // Is debug mode enabled?
2451 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2452 // Log this message away
2453 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2454 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2459 // Reads a directory with PHP files in and gets only files back
2460 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2464 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2467 while ($baseFile = readdir($dirPointer)) {
2468 // Load file only if extension is active
2470 $file = $baseDir.$baseFile;
2472 // Is this a valid reset file?
2473 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2474 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2475 // Remove both for extension name
2476 $extName = substr($baseFile, strlen($prefix), -4);
2479 $extId = GET_EXT_ID($extName);
2481 // Is the extension valid and active?
2482 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2483 // Then add this file
2485 } elseif ($extId == 0) {
2486 // Add non-extension files as well
2493 closedir($dirPointer);
2498 // Return array with include files
2501 // Load more reset scripts
2502 function RESET_ADD_INCLUDES () {
2503 // Is the reset set or old sql_patches?
2504 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2509 // Get more daily reset scripts
2510 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2513 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2515 // Create current week mark
2516 $currWeek = date("W", time());
2519 if (getConfig('last_week') != $currWeek) {
2520 // Include weekly reset scripts
2521 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2524 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2527 // Create current month mark
2528 $currMonth = date("m", time());
2531 if (getConfig('last_month') != $currMonth) {
2532 // Include monthly reset scripts
2533 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2536 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2542 // Handle extra values
2543 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2544 // Default is the value itself
2547 // Do we have a special filter function?
2548 if (!empty($filterFunction)) {
2549 // Does the filter function exist?
2550 if (function_exists($filterFunction)) {
2551 // Do we have extra parameters here?
2552 if (!empty($extraValue)) {
2553 // Put both parameters in one new array by default
2554 $args = array($value, $extraValue);
2556 // If we have an array simply use it and pre-extend it with our value
2557 if (is_array($extraValue)) {
2558 // Make the new args array
2559 $args = merge_array(array($value), $extraValue);
2562 // Call the multi-parameter call-back
2563 $ret = call_user_func_array($filterFunction, $args);
2565 // One parameter call
2566 $ret = call_user_func($filterFunction, $value);
2574 // Check if given FQFN is a readable file
2575 function FILE_READABLE($fqfn) {
2577 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2579 // Converts timestamp selections into a timestamp
2580 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2581 // Init test variable
2584 // Get last three chars
2585 $test = substr($id, -3);
2587 // Improved way of checking! :-)
2588 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2589 // Found a multi-selection for timings?
2590 $test = substr($id, 0, -3);
2591 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)) {
2592 // Generate timestamp
2593 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2594 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2596 // Remove data from array
2597 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2598 unset($POST[$test."_".$rem]);
2602 unset($id); $skip = true; $test2 = $test;
2605 // Process this entry
2606 $skip = false; $test2 = "";
2609 // Reverts the german decimal comma into Computer decimal dot
2610 function REVERT_COMMA ($str) {
2611 // Default float is not a float... ;-)
2614 // Which language is selected?
2615 switch (GET_LANGUAGE()) {
2616 case "de": // German language
2617 // Remove german thousand dots first
2618 $str = str_replace(".", "", $str);
2620 // Replace german commata with decimal dot and cast it
2621 $float = (float)str_replace(",", ".", $str);
2624 default: // US and so on
2625 // Remove thousand dots first and cast
2626 $float = (float)str_replace(",", "", $str);
2634 // Handle menu-depending failed logins and return the rendered content
2635 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2636 // Default output is empty ;-)
2639 // Is the session data set?
2640 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failtures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2641 // Ignore zero values
2642 if (get_session('mxchange_'.$accessLevel.'_failtures') > 0) {
2643 // Non-guest has login failtures found, get both data and prepare it for template
2644 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2646 'login_failtures' => get_session('mxchange_'.$accessLevel.'_failtures'),
2647 'last_failture' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2651 $OUT = LOAD_TEMPLATE("login_failtures", true, $content);
2654 // Reset session data
2655 set_session('mxchange_'.$accessLevel.'_failtures', "");
2656 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2659 // Return rendered content
2664 function REBUILD_CACHE ($cache, $inc="") {
2665 global $cacheInstance, $CSS;
2667 // Shall I remove the cache file?
2668 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2670 if ($cacheInstance->loadCacheFile($cache)) {
2672 $cacheInstance->destroyCacheFile();
2675 // Include file given?
2678 $fqfn = sprintf("%sinc/loader/load_cache-%s.php", PATH, $inc);
2680 // Is the include there?
2681 if (FILE_READABLE($fqfn)) {
2682 // And rebuild it from scratch
2683 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2686 // Include not found!
2687 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2693 // Purge admin menu cache
2694 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2695 global $cacheInstance;
2697 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2698 if (!EXT_IS_ACTIVE("cache")) {
2699 // Cache extension not active
2701 } elseif (!is_object($cacheInstance)) {
2702 // No cache instance!
2703 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2705 } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2706 // Caching disabled (currently experiemental!)
2710 // Experiemental feature!
2711 trigger_error("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2714 // Translates the "pool type" into human-readable
2715 function TRANSLATE_POOL_TYPE ($type) {
2716 // Default type is unknown
2717 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2719 // Generate constant
2720 $constName = sprintf("POOL_TYPE_%s", $type);
2723 if (defined($constName)) {
2725 $translated = constant($constName);
2728 // Return "translation"
2732 // "Getter" for remote IP number
2733 function GET_REMOTE_ADDR () {
2734 // Get remote ip from environment
2735 $remoteAddr = getenv('REMOTE_ADDR');
2737 // Is removeip installed?
2738 if (EXT_IS_ACTIVE("removeip")) {
2739 // Then anonymize it
2740 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2746 // "Getter" for remote hostname
2747 function GET_REMOTE_HOST () {
2748 // Get remote ip from environment
2749 $remoteHost = getenv('REMOTE_HOST');
2751 // Is removeip installed?
2752 if (EXT_IS_ACTIVE("removeip")) {
2753 // Then anonymize it
2754 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2760 // "Getter" for user agent
2761 function GET_USER_AGENT () {
2762 // Get remote ip from environment
2763 $userAgent = getenv('HTTP_USER_AGENT');
2765 // Is removeip installed?
2766 if (EXT_IS_ACTIVE("removeip")) {
2767 // Then anonymize it
2768 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2774 // "Getter" for referer
2775 function GET_REFERER () {
2776 // Get remote ip from environment
2777 $referer = getenv('HTTP_REFERER');
2779 // Is removeip installed?
2780 if (EXT_IS_ACTIVE("removeip")) {
2781 // Then anonymize it
2782 $referer = GET_ANONYMOUS_REFERER($referer);
2789 // Adds a bonus mail to the queue
2790 // This is a high-level function!
2791 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2792 // Use mode from data if not set and availble ;-)
2793 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2795 // Generate receiver list
2796 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2799 if (!empty($RECEIVER)) {
2800 // Add bonus mail to queue
2801 ADD_BONUS_MAIL_TO_QUEUE(
2813 // Mail inserted into bonus pool
2814 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_BONUS_SEND);
2815 } elseif ($output) {
2816 // More entered than can be reached!
2817 LOAD_TEMPLATE("admin_settings_saved", false, ADMIN_MORE_SELECTED);
2820 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2823 // Determines referal id and sets it
2824 function DETERMINE_REFID () {
2825 global $CLICK, $_SERVER;
2827 // Check if refid is set
2828 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2829 // The variable user comes from the click-counter script click.php and we only accept this here
2830 $GLOBALS['refid'] = bigintval($_GET['user']);
2831 } elseif (!empty($_POST['refid'])) {
2832 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2833 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2834 } elseif (!empty($_GET['refid'])) {
2835 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2836 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2837 } elseif (!empty($_GET['ref'])) {
2838 // Set refid=ref (the referal link uses such variable)
2839 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2840 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2841 // Set session refid als global
2842 $GLOBALS['refid'] = bigintval(get_session('refid'));
2843 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2844 // Set default refid as refid in URL
2845 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2846 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2847 // Select a random user which has confirmed enougth mails
2848 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2850 // No default ID when sql_patches is not installed or none set
2851 $GLOBALS['refid'] = 0;
2854 // Set cookie when default refid > 0
2855 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2857 set_session('refid', $GLOBALS['refid']);
2860 // Return determined refid
2861 return $GLOBALS['refid'];
2864 // Destroys the admin session
2865 function DESTROY_ADMIN_SESSION ($destroy = true) {
2866 // Kill maybe existing session variables including array elements
2867 set_session('admin_login', "");
2868 set_session('admin_md5' , "");
2869 set_session('admin_last' , "");
2870 set_session('admin_to' , "");
2872 // Destroy session and return status
2874 return @session_destroy();
2877 // All fine if we shall not really destroy the session
2881 // Checks if a given apache module is loaded
2882 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2883 // Check it and return result
2884 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2887 // Getter for $_CONFIG entries
2888 function getConfig ($entry) {
2894 // Is the entry there?
2895 if (isset($_CONFIG[$entry])) {
2897 $value = $_CONFIG[$entry];
2904 // @TODO Rewrite all language constants to the function getLanguage().
2905 // "Getter" for language strings
2906 function getMessage ($messageId) {
2907 // Default is not found!
2908 $return = "!".$messageId."!";
2910 // Is the language string found?
2911 if (isset($GLOBALS['msg'][$messageId])) {
2912 // Language array element found
2913 $return = $GLOBALS['msg'][$messageId];
2914 } elseif (defined($messageId)) {
2915 // @DEPRECATED Deprecated constant found
2916 $return = constant($messageId);
2918 // Missing language constant
2919 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2922 // Return the string
2926 // Get current theme name
2927 function GET_CURR_THEME() {
2928 global $INC_POOL, $CSS, $cacheArray;
2930 // The default theme is 'default'... ;-)
2933 // Load default theme if not empty from configuration
2934 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2936 if (!isSessionVariableSet('mxchange_theme')) {
2937 // Set default theme
2938 set_session('mxchange_theme', $ret);
2939 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2940 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2941 // Get theme from cookie
2942 $ret = get_session('mxchange_theme');
2945 if (THEME_GET_ID($ret) == 0) {
2946 // Fix it to default
2949 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2950 // Prepare FQFN for checking
2951 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_GET['theme']));
2953 // Installation mode active
2954 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2955 // Set cookie from URL data
2956 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2957 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($_POST['theme'])))) {
2958 // Set cookie from posted data
2959 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2963 $ret = get_session('mxchange_theme');
2965 // Invalid design, reset cookie
2966 set_session('mxchange_theme', $ret);
2969 // Add (maybe) found theme.php file to inclusion list
2970 $theme = sprintf("%stheme/%s/theme.php", PATH, SQL_ESCAPE($ret));
2972 // Try to load the requested include file
2973 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2975 // Return theme value
2979 // Get id from theme
2980 function THEME_GET_ID ($name) {
2983 // Is the extension "theme" installed?
2984 if (!EXT_IS_ACTIVE("theme")) {
2992 // Is the cache entry there?
2993 if (isset($cacheArray['themes']['id'][$name])) {
2994 // Get the version from cache
2995 $id = $cacheArray['themes']['id'][$name];
2998 incrementConfigEntry('cache_hits');
2999 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
3000 // Check if current theme is already imported or not
3001 $result = SQL_QUERY_ESC("SELECT id FROM `"._MYSQL_PREFIX."_themes` WHERE theme_path='%s' LIMIT 1",
3002 array($name), __FILE__, __LINE__);
3005 if (SQL_NUMROWS($result) == 1) {
3007 list($id) = SQL_FETCHROW($result);
3011 SQL_FREERESULT($result);
3018 // Increment or init with given value or 1 as default the given config entry
3019 function incrementConfigEntry ($configEntry, $value=1) {
3022 // Increment it if set or init it with 1
3023 if (getConfig($configEntry) > 0) {
3024 $_CONFIG[$configEntry] += $value;
3026 $_CONFIG[$configEntry] = $value;
3030 // Read a given file
3031 function READ_FILE ($FQFN, $sqlPrepare = false) {
3033 if (function_exists('file_get_contents')) {
3035 $content = file_get_contents($FQFN);
3037 // Fall-back to implode-file chain
3038 $content = implode("", file($FQFN));
3041 // Prepare SQL queries?
3042 if ($sqlPrepare === true) {
3043 // Remove some unwanted chars
3044 $content = str_replace("\r", "", $content);
3045 $content = str_replace("\n\n", "\n", $content);
3048 // Return the content
3052 // Generates an error code from given account status
3053 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3054 // Default error code if unknown account status
3055 $ERROR = CODE_UNKNOWN_STATUS;
3057 // Generate constant name
3058 $constantName = sprintf("CODE_ID_%s", $status);
3060 // Is the constant there?
3061 if (defined($constantName)) {
3063 $ERROR = constant($constantName);
3066 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3069 // Return error code
3073 // Clears the output buffer. This function does *NOT* backup sent content.
3074 function clearOutputBuffer () {
3075 // Trigger an error on failure
3076 if (!ob_end_clean()) {
3078 trigger_error(__FUNCTION__.": Failed to clean output buffer.");
3082 //////////////////////////////////////////////////
3083 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3084 //////////////////////////////////////////////////
3086 if (!function_exists('html_entity_decode')) {
3087 // Taken from documentation on www.php.net
3088 function html_entity_decode ($string) {
3089 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3090 $trans_tbl = array_flip($trans_tbl);
3091 return strtr($string, $trans_tbl);