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, $NEW_LINE = 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
73 // That's why you don't need any \n at the end of your HTML code... :-)
74 if (_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 ($NEW_LINE) 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 ($NEW_LINE) $OUTPUT .= "\n";
90 // If we are switching from render to direct output rendered code
91 if ((!empty($OUTPUT)) && (_OB_CACHING != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
93 // The same as above... ^
95 if ($NEW_LINE) echo "\n";
99 // Huh, something goes wrong or maybe you have edited config.php ???
100 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", OUTPUT_MODE));
101 mxchange_die("<strong>{!FATAL_ERROR!}:</strong> {!LANG_NO_RENDER_DIRECT!}");
104 } elseif ((_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 trigger_error("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 die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
150 $OUTPUT = $newContent;
153 // Output code here, DO NOT REMOVE! ;-)
155 } elseif ((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 _OB_CACHING is not "on"
178 if (_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(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 = SMTP_HOSTNAME;
490 $mail->Username = SMTP_USER;
491 $mail->Password = SMTP_PASSWORD;
493 $mail->From = constant('WEBMASTER');
497 $mail->FromName = 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(WEBMASTER,MAIN_TITLE);
509 $mail->AddCustomHeader("Errors-To:".WEBMASTER);
510 $mail->AddCustomHeader("X-Loop:".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 // Initialize randomizer
528 mt_srand((double) microtime() * 1000000);
530 // Start creating password
532 for ($i = 0; $i < $LEN; $i++) {
533 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
536 // When the size is below 40 we can also add additional security by scrambling it
537 if (strlen($PASS) <= 40) {
538 // Also scramble the password
539 $PASS = scrambleString($PASS);
542 // Return the password
546 function MAKE_DATETIME ($time, $mode="0")
550 return NEVER_HAPPENED;
552 // Filter out numbers
553 $time = bigintval($time);
556 switch (GET_LANGUAGE())
558 case "de": // German date / time format
560 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
561 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
562 case "2": $ret = date("d.m.Y|H:i", $time); break;
563 case "3": $ret = date("d.m.Y", $time); break;
565 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
570 default: // Default is the US date / time format!
572 case "0": $ret = date("r", $time); break;
573 case "1": $ret = date("Y-m-d - g:i A", $time); break;
574 case "2": $ret = date("y-m-d|H:i", $time); break;
575 case "3": $ret = date("y-m-d", $time); break;
577 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
584 // Translates the american decimal dot into a german comma
585 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
588 // Default is 3 you can change this in admin area "Misc -> Misc Options"
589 if (getConfig('max_comma') == null) $_CONFIG['max_comma'] = "3";
591 // Use from config is default
592 $maxComma = getConfig('max_comma');
594 // Use from parameter?
595 if ($max > 0) $maxComma = $max;
598 if (($cut) && ($max == 0)) {
599 // Test for commata if in cut-mode
600 $com = explode(".", $dotted);
601 if (count($com) < 2) {
602 // Don't display commatas even if there are none... ;-)
608 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
611 switch (GET_LANGUAGE()) {
613 $dotted = number_format($dotted, $maxComma, ",", ".");
617 $dotted = number_format($dotted, $maxComma, ".", ",");
621 // Return translated value
626 function DEREFERER ($URL) {
627 // Don't de-refer our own links!
628 if (substr($URL, 0, strlen(URL)) != URL) {
629 // De-refer this link
630 $URL = "modules.php?module=loader&url=".urlencode(base64_encode(gzcompress($URL)));
638 function TRANSLATE_GENDER ($gender) {
641 case "M": $ret = GENDER_M; break;
642 case "F": $ret = GENDER_F; break;
643 case "C": $ret = GENDER_C; break;
644 default : $ret = $gender; break;
649 function FRAMETESTER($URL) {
650 // Prepare frametester URL
651 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
653 urlencode(base64_encode(gzcompress(COMPILE_CODE($URL))))
655 return $frametesterUrl;
658 function SELECTION_COUNT($array) {
660 if (is_array($array)) {
661 foreach ($array as $key => $sel) {
662 if (!empty($sel)) $ret++;
668 function IMG_CODE ($code, $type, $DATA, $uid) {
669 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
672 function TRANSLATE_STATUS($status) {
676 $ret = ACCOUNT_UNCONFIRMED;
680 $ret = ACCOUNT_CONFIRMED;
684 $ret = ACCOUNT_LOCKED;
689 $ret = ACCOUNT_DELETED;
693 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
694 $ret = UNKNOWN_STATUS_1.$status.UNKNOWN_STATUS_2;
700 function GET_LANGUAGE() {
703 // Set default return value to default language from config
704 $ret = constant('DEFAULT_LANG');
709 // Is the variable set
710 if (!empty($_GET['mx_lang'])) {
711 // Accept only first 2 chars
712 $lang = substr($_GET['mx_lang'], 0, 2);
713 } elseif (isset($cacheArray['language'])) {
715 $ret = $cacheArray['language'];
716 } elseif (!empty($lang)) {
717 // Check if main language file does exist
718 if (FILE_READABLE(PATH."inc/language/".$lang.".php")) {
719 // Okay found, so let's update cookies
722 } elseif (!isSessionVariableSet('mx_lang')) {
723 // Return stored value from cookie
724 $ret = get_session('mx_lang');
726 // Fixes a warning before the session has the mx_lang constant
727 if (empty($ret)) $ret = constant('DEFAULT_LANG');
731 $cacheArray['language'] = $ret;
737 function SET_LANGUAGE ($lang) {
738 // Accept only first 2 chars!
739 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
742 set_session('mx_lang', $lang);
745 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
746 global $DATA, $REPLACER, $_CONFIG;
748 // Make sure all template names are lowercase!
749 $template = strtolower($template);
751 // Default "nickname" if extension is not installed
754 // Keept for backward-compatiblity (please replace these variables against our new {!CONST!} syntax!)
755 // No longer used: $MAIN_TITLE = MAIN_TITLE; $URL = constant('URL'); $WEBMASTER = constant('WEBMASTER');
757 // Prepare IP number and User Agent
758 $REMOTE_ADDR = GET_REMOTE_ADDR();
759 $HTTP_USER_AGENT = GET_USER_AGENT();
764 // Is the admin logged in?
767 $aid = GET_CURRENT_ADMIN_ID();
770 $ADMIN = GET_ADMIN_EMAIL($aid);
773 // Neutral email address is default
774 $email = constant('WEBMASTER');
776 // Expiration in a nice output format
777 if (getConfig('auto_purge') == 0) {
778 // Will never expire!
779 $EXPIRATION = MAIL_WILL_NEVER_EXPIRE;
781 // Create nice date string
782 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
785 // Is content an array?
786 if (is_array($content)) {
787 // Add expiration to array, $EXPIRATION is now deprecated!
788 $content['expiration'] = $EXPIRATION;
792 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
793 if (($UID > 0) && (is_array($content))) {
794 // If nickname extension is installed, fetch nickname as well
795 if (EXT_IS_ACTIVE("nickname")) {
796 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
798 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
799 array(bigintval($UID)), __FILE__, __LINE__);
801 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
803 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
804 array(bigintval($UID)), __FILE__, __LINE__);
807 // Fetch and merge data
808 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
809 $content = merge_array($content, SQL_FETCHARRAY($result));
810 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
813 SQL_FREERESULT($result);
816 // Translate M to male or F to female if present
817 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
819 // Overwrite email from data if present
820 if (isset($content['email'])) $email = $content['email'];
822 // Store email for some functions in global data array
823 $DATA['email'] = $email;
826 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
828 // Check for admin/guest/member templates
829 if (strpos($template, "admin_") > -1) {
830 // Admin template found
831 $file = $BASE."admin/".$template.".tpl";
832 } elseif (strpos($template, "guest_") > -1) {
833 // Guest template found
834 $file = $BASE."guest/".$template.".tpl";
835 } elseif (strpos($template, "member_") > -1) {
836 // Member template found
837 $file = $BASE."member/".$template.".tpl";
839 // Test for extension
840 $test = substr($template, 0, strpos($template, "_"));
841 if (EXT_IS_ACTIVE($test)) {
842 // Set extra path to extension's name
843 $file = $BASE.$test."/".$template.".tpl";
845 // No special filename
846 $file = $BASE.$template.".tpl";
850 // Does the special template exists?
851 if (!FILE_READABLE($file)) {
852 // Reset to default template
853 $file = $BASE.$template.".tpl";
856 // Now does the final template exists?
858 if (FILE_READABLE($file)) {
859 // The local file does exists so we load it. :)
860 $tmpl_file = READ_FILE($file);
861 $tmpl_file = addslashes($tmpl_file);
864 $tmpl_file = "\$newContent=html_entity_decode(\"".COMPILE_CODE($tmpl_file)."\");";
866 } elseif (!empty($template)) {
867 // Template file not found!
868 $newContent = TEMPLATE_404.": ".$template."<br />
870 <pre>".print_r($content, true)."</pre>
872 <pre>".print_r($DATA, true)."</pre>
875 // Debug mode not active? Then remove the HTML tags
876 if (!DEBUG_MODE) $newContent = strip_tags($newContent);
878 // No template name supplied!
879 $newContent = NO_TEMPLATE_SUPPLIED;
882 // Is there some content?
883 if (empty($newContent)) {
885 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
886 // Add last error if the required function exists
887 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
890 // Remove content and data
894 // Return compiled content
895 return COMPILE_CODE($newContent);
898 function MAKE_TIME($H, $M, $S, $stamp) {
899 // Extract day, month and year from given timestamp
900 $DAY = date("d", $stamp);
901 $MONTH = date("m", $stamp);
902 $YEAR = date('Y', $stamp);
904 // Create timestamp for wished time which depends on extracted date
905 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
908 function LOAD_URL($URL, $addUrlData=true) {
909 global $CSS, $footer;
911 // Compile out URI codes
912 $URL = COMPILE_CODE($URL);
914 // Check if http(s):// is there
915 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
916 // Make all URLs full-qualified
923 debug_print_backtrace();
926 $OUTPUT = ob_get_contents();
928 // Clear it only if there is content
929 if (!empty($OUTPUT)) {
933 // Add some data to URL if cookies are not accepted
934 if (((!defined('__COOKIES')) || (!__COOKIES)) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
936 // Probe for bot from search engine
937 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
938 // Search engine bot detected so let's rewrite many chars for the link
939 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
941 // Output new location link as anchor
942 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
943 } elseif (!headers_sent()) {
944 // Load URL when headers are not sent
947 debug_print_backtrace();
948 die("</pre>URL={$URL}");
950 header ("Location: ".str_replace("&", "&", $URL));
952 // Output error message
953 LOAD_INC("inc/header.php");
954 LOAD_TEMPLATE("redirect_url", false, str_replace("&", "&", $URL));
955 LOAD_INC("inc/footer.php");
960 // Wrapper for LOAD_URL but URL comes from a configuration entry
961 function LOAD_CONFIGURED_URL ($configEntry) {
963 $URL = getConfig($configEntry);
968 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
976 function COMPILE_CODE($code, $simple = false, $constants = true, $full = true) {
977 global $SEC_CHARS, $URL_CHARS;
978 // Is the code a string?
979 if (!is_string($code)) {
980 // Silently return it
986 // Select smaller set of chars to replace when we e.g. want to compile URLs
987 if (!$full) $ARRAY = $URL_CHARS;
991 // BEFORE 0.2.1 : Language and data constants
992 // WITH 0.2.1+ : Only language constants
993 $code = str_replace('{--','".', str_replace('--}','."', $code));
995 // BEFORE 0.2.1 : Not used
996 // WITH 0.2.1+ : Data constants
997 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1000 // Compile QUOT and other non-HTML codes
1001 foreach ($ARRAY['to'] as $k => $to) {
1002 // Do the reversed thing as in inc/libs/security_functions.php
1003 $code = str_replace($to, $ARRAY['from'][$k], $code);
1006 // But shall I keep simple quotes for later use?
1007 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1009 // Find $content[bla][blub] entries
1010 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1012 // Are some matches found?
1013 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1014 // Replace all matches
1015 $matchesFound = array();
1016 foreach ($matches[0] as $key => $match) {
1017 // Fuzzy look has failed by default
1018 $fuzzyFound = false;
1020 // Fuzzy look on match if already found
1021 foreach ($matchesFound as $found => $set) {
1023 $test = substr($found, 0, strlen($match));
1025 // Does this entry exist?
1026 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1027 if ($test == $match) {
1029 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1036 if ($fuzzyFound) continue;
1038 // Take all string elements
1039 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1040 // Replace it in the code
1041 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1042 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1043 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1044 $matchesFound[$key."_".$matches[4][$key]] = 1;
1045 $matchesFound[$match] = 1;
1046 } elseif (!isset($matchesFound[$match])) {
1047 // Not yet replaced!
1048 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1049 $code = str_replace($match, "\".".$match.".\"", $code);
1050 $matchesFound[$match] = 1;
1055 // Return compiled code
1059 /************************************************************************
1061 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1062 * $a_sort sortiert: *
1064 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1065 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1066 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1067 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1068 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1070 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1071 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1072 * Sie, dass es doch nicht so schwer ist! :-) *
1074 ************************************************************************/
1075 function array_pk_sort(&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false)
1078 while ($primary_key < count($a_sort)) {
1079 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1080 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1083 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1084 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1085 } elseif ($key != $key2) {
1086 // Sort numbers (E.g.: 9 < 10)
1087 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1088 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1092 // We have found two different values, so let's sort whole array
1093 foreach ($dummy as $sort_key => $sort_val) {
1094 $t = $dummy[$sort_key][$key];
1095 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1096 $dummy[$sort_key][$key2] = $t;
1107 // Write back sorted array
1111 function ADD_SELECTION($type, $DEFAULT, $prefix="", $id="0") {
1112 global $MONTH_DESCR;
1115 if ($type == "yn") {
1116 // This is a yes/no selection only!
1117 if ($id > 0) $prefix .= "[".$id."]";
1118 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1120 // Begin with regular selection box here
1121 if (!empty($prefix)) $prefix .= "_";
1123 if ($id > 0) $type2 .= "[".$id."]";
1124 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1129 for ($idx = 1; $idx < 32; $idx++) {
1130 $OUT .= "<option value=\"".$idx."\"";
1131 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1132 $OUT .= ">".$idx."</option>\n";
1136 case "month": // Month
1137 foreach ($MONTH_DESCR as $month => $descr) {
1138 $OUT .= "<option value=\"".$month."\"";
1139 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1140 $OUT .= ">".$descr."</option>\n";
1144 case "year": // Year
1146 $YEAR = date('Y', time());
1148 // Use configured min age or fixed?
1149 if (GET_EXT_VERSION("other") >= "0.2.1") {
1151 $startYear = $YEAR - getConfig('min_age');
1154 $startYear = $YEAR - 16;
1157 // Calculate earliest year (100 years old people can still enter Internet???)
1158 $minYear = $YEAR - 100;
1160 // Check if the default value is larger than minimum and bigger than actual year
1161 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1162 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1163 $OUT .= "<option value=\"".$idx."\"";
1164 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1165 $OUT .= ">".$idx."</option>\n";
1167 } elseif ($DEFAULT == -1) {
1168 // Current year minus 1
1169 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1171 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1174 // Get current year and subtract the configured minimum age
1175 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1176 // Calculate earliest year depending on extension version
1177 if (GET_EXT_VERSION("other") >= "0.2.1") {
1178 // Use configured minimum age
1179 $YEAR = date('Y', time()) - getConfig('min_age');
1181 // Use fixed 16 years age
1182 $YEAR = date('Y', time()) - 16;
1185 // Construct year selection list
1186 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1187 $OUT .= "<option value=\"".$idx."\"";
1188 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1189 $OUT .= ">".$idx."</option>\n";
1196 for ($idx = 0; $idx < 60; $idx+=5) {
1197 if (strlen($idx) == 1) $idx = "0".$idx;
1198 $OUT .= "<option value=\"".$idx."\"";
1199 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1200 $OUT .= ">".$idx."</option>\n";
1205 for ($idx = 0; $idx < 24; $idx++) {
1206 if (strlen($idx) == 1) $idx = "0".$idx;
1207 $OUT .= "<option value=\"".$idx."\"";
1208 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1209 $OUT .= ">".$idx."</option>\n";
1214 $OUT .= "<option value=\"Y\"";
1215 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1216 $OUT .= ">{!YES!}</option>\n<option value=\"N\"";
1217 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1218 $OUT .= ">{!NO!}</option>\n";
1221 $OUT .= " </select>\n";
1225 function TRANSLATE_YESNO($yn)
1229 case "Y": $yn = YES; break;
1230 case "N": $yn = NO; break;
1231 default : $yn = "??? (".$yn.")"; break;
1236 // Deprecated : $length
1239 function GEN_RANDOM_CODE($length, $code, $uid, $DATA="") {
1240 // Fix missing _MAX constant
1241 if (!defined('_MAX')) define('_MAX', 15235);
1243 // Build server string
1244 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
1247 $keys = SITE_KEY.":".DATE_KEY;
1248 if (getConfig('secret_key') != null) $keys .= ":".getConfig('secret_key');
1249 if (getConfig('file_hash') != null) $keys .= ":".getConfig('file_hash');
1250 $keys .= ":".date("d-m-Y (l-F-T)", bigintval(getConfig('patch_ctime')));
1251 if (getConfig('master_salt') != null) $keys .= ":".getConfig('master_salt');
1253 // Build string from misc data
1254 $data = $code.":".$uid.":".$DATA;
1256 // Add more additional data
1257 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1258 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1259 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1260 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1261 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1263 // Calculate number for generating the code
1264 $a = $code + _ADD - 1;
1266 if (getConfig('master_hash') != null) {
1267 // Generate hash with master salt from modula of number with the prime number and other data
1268 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1270 // Create number from hash
1271 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1273 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1274 $saltedHash = generateHash(($a % _PRIME).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(SITE_KEY), 0, 8));
1276 // Create number from hash
1277 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(_MAX - $a + sqrt(_ADD)) / pi();
1280 // At least 10 numbers shall be secure enought!
1281 $len = getConfig('code_length');
1282 if ($len == 0) $len = $length;
1283 if ($len == 0) $len = 10;
1285 // Cut off requested counts of number
1286 $return = substr(str_replace('.', "", $rcode), 0, $len);
1288 // Done building code
1291 // Does only allow numbers
1292 function bigintval($num, $castValue = true) {
1293 // Filter all numbers out
1294 $ret = preg_replace("/[^0123456789]/", "", $num);
1297 if ($castValue) $ret = (double)$ret;
1299 // Has the whole value changed?
1300 if ("".$ret."" != "".$num."") {
1303 debug_print_backtrace();
1305 DEBUG_LOG(__FUNCTION__, __LINE__, " num={$num},ret={$ret}");
1311 // Insert the code in $img_code into jpeg or PNG image
1312 function GENERATE_IMAGE($img_code, $header=true) {
1313 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1314 // Stop execution of function here because of over-sized code length
1316 } elseif (!$header) {
1317 // Return in an HTML code code
1318 return "<IMG src=\"{!URL!}/img.php?code=".$img_code."\">\n";
1322 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1323 if (FILE_READABLE($img)) {
1324 // Switch image type
1325 switch (getConfig('img_type'))
1328 // Okay, load image and hide all errors
1329 $image = @imagecreatefromjpeg($img);
1333 // Okay, load image and hide all errors
1334 $image = @imagecreatefrompng($img);
1338 // Exit function here
1342 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1343 $text_color = imagecolorallocate($image, 0, 0, 0);
1345 // Insert code into image
1346 imagestring($image, 5, 14, 2, $img_code, $text_color);
1348 // Return to browser
1349 header ("Content-Type: image/".getConfig('img_type'));
1351 // Output image with matching image factory
1352 switch (getConfig('img_type')) {
1353 case "jpg": imagejpeg($image); break;
1354 case "png": imagepng($image); break;
1357 // Remove image from memory
1358 imagedestroy($image);
1360 // Create selection box or array of splitted timestamp
1361 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1362 // Calculate 2-seconds timestamp
1363 $stamp = round($timestamp);
1364 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1366 // Do we have a leap year?
1368 $TEST = date('Y', time()) / 4;
1369 $M1 = date("m", time());
1370 $M2 = date("m", (time() + $timestamp));
1372 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1373 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1375 // First of all years...
1376 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1377 //* DEBUG: */ print("Y={$Y}<br />\n");
1379 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1380 //* DEBUG: */ print("M={$M}<br />\n");
1382 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1383 //* DEBUG: */ print("W={$W}<br />\n");
1385 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1386 //* DEBUG: */ print("D={$D}<br />\n");
1388 $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));
1389 //* DEBUG: */ print("h={$h}<br />\n");
1391 $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));
1392 //* DEBUG: */ print("m={$m}<br />\n");
1393 // And at last seconds...
1394 $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));
1395 //* DEBUG: */ print("s={$s}<br />\n");
1397 // Is seconds zero and time is < 60 seconds?
1398 if (($s == 0) && ($timestamp < 60)) {
1400 $s = round($timestamp);
1404 // Now we convert them in seconds...
1406 if ($return_array) {
1407 // Just put all data in an array for later use
1419 $OUT = "<div align=\"".$align."\">\n";
1420 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1423 if (ereg('Y', $display) || (empty($display))) {
1424 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._YEARS."</strong></td>\n";
1427 if (ereg("M", $display) || (empty($display))) {
1428 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MONTHS."</strong></td>\n";
1431 if (ereg("W", $display) || (empty($display))) {
1432 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._WEEKS."</strong></td>\n";
1435 if (ereg("D", $display) || (empty($display))) {
1436 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._DAYS."</strong></td>\n";
1439 if (ereg("h", $display) || (empty($display))) {
1440 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._HOURS."</strong></td>\n";
1443 if (ereg("m", $display) || (empty($display))) {
1444 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._MINUTES."</strong></td>\n";
1447 if (ereg("s", $display) || (empty($display))) {
1448 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">"._SECONDS."</strong></td>\n";
1454 if (ereg('Y', $display) || (empty($display))) {
1455 // Generate year selection
1456 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1457 for ($idx = 0; $idx <= 10; $idx++) {
1458 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1459 if ($idx == $Y) $OUT .= " selected default";
1460 $OUT .= ">".$idx."</option>\n";
1462 $OUT .= " </select></td>\n";
1464 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1467 if (ereg("M", $display) || (empty($display))) {
1468 // Generate month selection
1469 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1470 for ($idx = 0; $idx <= 11; $idx++)
1472 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1473 if ($idx == $M) $OUT .= " selected default";
1474 $OUT .= ">".$idx."</option>\n";
1476 $OUT .= " </select></td>\n";
1478 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1481 if (ereg("W", $display) || (empty($display))) {
1482 // Generate week selection
1483 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1484 for ($idx = 0; $idx <= 4; $idx++) {
1485 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1486 if ($idx == $W) $OUT .= " selected default";
1487 $OUT .= ">".$idx."</option>\n";
1489 $OUT .= " </select></td>\n";
1491 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1494 if (ereg("D", $display) || (empty($display))) {
1495 // Generate day selection
1496 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1497 for ($idx = 0; $idx <= 31; $idx++) {
1498 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1499 if ($idx == $D) $OUT .= " selected default";
1500 $OUT .= ">".$idx."</option>\n";
1502 $OUT .= " </select></td>\n";
1504 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1507 if (ereg("h", $display) || (empty($display))) {
1508 // Generate hour selection
1509 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1510 for ($idx = 0; $idx <= 23; $idx++) {
1511 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1512 if ($idx == $h) $OUT .= " selected default";
1513 $OUT .= ">".$idx."</option>\n";
1515 $OUT .= " </select></td>\n";
1517 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1520 if (ereg("m", $display) || (empty($display))) {
1521 // Generate minute selection
1522 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1523 for ($idx = 0; $idx <= 59; $idx++) {
1524 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1525 if ($idx == $m) $OUT .= " selected default";
1526 $OUT .= ">".$idx."</option>\n";
1528 $OUT .= " </select></td>\n";
1530 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1533 if (ereg("s", $display) || (empty($display))) {
1534 // Generate second selection
1535 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1536 for ($idx = 0; $idx <= 59; $idx++) {
1537 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1538 if ($idx == $s) $OUT .= " selected default";
1539 $OUT .= ">".$idx."</option>\n";
1541 $OUT .= " </select></td>\n";
1543 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1546 $OUT .= "</table>\n";
1548 // Return generated HTML code
1553 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1554 // Initial return value
1557 // Do we have a leap year?
1559 $TEST = date('Y', time()) / 4;
1560 $M1 = date("m", time());
1561 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1562 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1563 // First add years...
1564 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1566 $ret += $POST[$prefix."_mo"] * 2628000;
1568 $ret += $POST[$prefix."_we"] * 604800;
1570 $ret += $POST[$prefix."_da"] * 86400;
1572 $ret += $POST[$prefix."_ho"] * 3600;
1574 $ret += $POST[$prefix."_mi"] * 60;
1575 // And at last seconds...
1576 $ret += $POST[$prefix."_se"];
1577 // Return calculated value
1580 // Sends out mail to all administrators
1581 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1582 function SEND_ADMIN_EMAILS_PRO($subj, $template, $content, $UID) {
1583 // Trim template name
1584 $template = trim($template);
1586 // Load email template
1587 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1589 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1590 // Older version detected!
1591 return SEND_ADMIN_EMAILS($subj, $msg);
1594 // Check which admin shall receive this mail
1595 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1596 array($template), __FILE__, __LINE__);
1597 if (SQL_NUMROWS($result) == 0) {
1598 // Create new entry (to all admins)
1599 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1600 array($template), __FILE__, __LINE__);
1602 // Load admin IDs...
1604 while (list($aid) = SQL_FETCHROW($result)) {
1609 SQL_FREERESULT($result);
1611 // "implode" IDs and query string
1612 $aid = implode(",", $aids);
1614 // Add line to userlog
1615 USERLOG_ADD_LINE($subj, $msg, $UID);
1617 } elseif ($aid == "0") {
1618 // Select all email adresses
1619 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`", __FILE__, __LINE__);
1621 // If Admin-ID is not "to-all" select
1622 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`", array($aid), __FILE__, __LINE__);
1626 // Load email addresses and send away
1627 while (list($email) = SQL_FETCHROW($result)) {
1628 SEND_EMAIL($email, $subj, $msg);
1632 SQL_FREERESULT($result);
1635 function CREATE_FANCY_TIME ($stamp) {
1636 // Get data array with years/months/weeks/days/...
1637 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1639 foreach($data as $k => $v) {
1641 // Value is greater than 0 "eval" data to return string
1642 $eval = "\$ret .= \", \".\$v.\" \"._".strtoupper($k).";";
1648 // Do we have something there?
1649 if (strlen($ret) > 0) {
1650 // Remove leading commata and space
1651 $ret = substr($ret, 2);
1654 $ret = "0 "._SECONDS;
1657 // Return fancy time string
1661 function ADD_EMAIL_NAV($PAGES, $offset, $show_form, $colspan, $return=false) {
1662 $SEP = ""; $TOP = "";
1665 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1669 for ($page = 1; $page <= $PAGES; $page++) {
1670 // Is the page currently selected or shall we generate a link to it?
1671 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1672 // Is currently selected, so only highlight it
1673 $NAV .= "<strong>-";
1675 // Open anchor tag and add base URL
1676 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1678 // Add userid when we shall show all mails from a single member
1679 if ((isset($_GET['u_id'])) && (bigintval($_GET['u_id']) > 0)) $NAV .= "&u_id=".bigintval($_GET['u_id']);
1681 // Close open anchor tag
1685 if (($page == $_GET['page']) || ((empty($_GET['page'])) && ($page == "1"))) {
1686 // Is currently selected, so only highlight it
1687 $NAV .= "-</strong>";
1693 // Add seperator if we have not yet reached total pages
1694 if ($page < $PAGES) $NAV .= " | ";
1697 // Define constants only once
1698 if (!defined('__NAV_OUTPUT')) {
1699 define('__NAV_OUTPUT' , $NAV);
1700 define('__NAV_COLSPAN', $colspan);
1701 define('__NAV_TOP' , $TOP);
1702 define('__NAV_SEP' , $SEP);
1705 // Load navigation template
1706 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1709 // Return generated HTML-Code
1717 // Extract host from script name
1718 function EXTRACT_HOST (&$script) {
1719 // Use default SERVER_URL by default... ;) So?
1722 // Is this URL valid?
1723 if (substr($script, 0, 7) == "http://") {
1724 // Use the hostname from script URL as new hostname
1725 $url = substr($script, 7);
1726 $extract = explode("/", $url);
1728 // Done extracting the URL :)
1731 // Extract host name
1732 $host = str_replace("http://", "", $url);
1733 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1735 // Generate relative URL
1736 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1737 if (substr(strtolower($script), 0, 7) == "http://") {
1738 // But only if http:// is in front!
1739 $script = substr($script, (strlen($url) + 7));
1740 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1742 $script = substr($script, (strlen($url) + 8));
1745 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1746 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1752 // Send a GET request
1753 function GET_URL ($script) {
1754 // Compile the script name
1755 $script = COMPILE_CODE($script);
1757 // Extract host name from script
1758 $host = EXTRACT_HOST($script);
1760 // Generate GET request header
1761 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1762 $request .= "Host: " . $host . "\r\n";
1763 $request .= "Referer: " . URL . "/admin.php\r\n";
1764 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1765 $request .= "Content-Type: text/plain\r\n";
1766 $request .= "Cache-Control: no-cache\r\n";
1767 $request .= "Connection: Close\r\n\r\n";
1769 // Send the raw request
1770 $response = SEND_RAW_REQUEST($host, $request);
1772 // Return the result to the caller function
1776 // Send a POST request
1777 function POST_URL ($script, $postData) {
1778 // Is postData an array?
1779 if (!is_array($postData)) {
1781 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1782 return array("", "", "");
1785 // Compile the script name
1786 $script = COMPILE_CODE($script);
1788 // Extract host name from script
1789 $host = EXTRACT_HOST($script);
1791 // Construct request
1792 $data = http_build_query($postData, '','&');
1794 // Generate POST request header
1795 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1796 $request .= "Host: " . $host . "\r\n";
1797 $request .= "Referer: " . URL . "/admin.php\r\n";
1798 $request .= "User-Agent: " . TITLE . "/" . FULL_VERSION . "\r\n";
1799 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1800 $request .= "Content-length: " . strlen($data) . "\r\n";
1801 $request .= "Cache-Control: no-cache\r\n";
1802 $request .= "Connection: Close\r\n\r\n";
1805 // Send the raw request
1806 $response = SEND_RAW_REQUEST($host, $request);
1808 // Return the result to the caller function
1812 // Sends a raw request to another host
1813 function SEND_RAW_REQUEST ($host, $request) {
1815 $response = array("", "", "");
1817 // Default is not to use proxy
1820 // Are proxy settins set?
1821 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1827 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1829 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1831 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1835 if (!is_resource($fp)) {
1842 // Generate CONNECT request header
1843 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1844 $proxyTunnel .= "Host: ".$host."\r\n";
1846 // Use login data to proxy? (username at least!)
1847 if (getConfig('proxy_username') != "") {
1849 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1850 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1853 // Add last new-line
1854 $proxyTunnel .= "\r\n";
1855 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1858 fputs($fp, $proxyTunnel);
1862 // No response received
1866 // Read the first line
1867 $resp = trim(fgets($fp, 10240));
1868 $respArray = explode(" ", $resp);
1869 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1870 // Invalid response!
1876 fputs($fp, $request);
1880 $response[] = trim(fgets($fp, 1024));
1886 // Skip first empty lines
1888 foreach ($resp as $idx => $line) {
1890 $line = trim($line);
1892 // Is this line empty?
1895 array_shift($response);
1897 // Abort on first non-empty line
1902 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1904 // Proxy agent found?
1905 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1906 // Proxy header detected, so remove two lines
1907 array_shift($response);
1908 array_shift($response);
1911 // Was the request successfull?
1912 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1913 // Not found / access forbidden
1914 $response = array("", "", "");
1920 // Taken from www.php.net eregi() user comments
1921 function VALIDATE_EMAIL($email) {
1923 $email = COMPILE_CODE($email);
1925 // Check first part of email address
1926 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1929 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1932 $regex = "^".$first."@".$domain."$";
1934 // Return check result
1935 return eregi($regex, $email);
1937 // Function taken from user comments on www.php.net / function eregi()
1938 function VALIDATE_URL ($URL, $compile=true) {
1939 // Trim URL a little
1940 $URL = trim(urldecode($URL));
1941 //* DEBUG: */ echo $URL."<br />";
1943 // Compile some chars out...
1944 if ($compile) $URL = COMPILE_CODE($URL, false, false, false);
1945 //* DEBUG: */ echo $URL."<br />";
1947 // Check for the extension filter
1948 if (EXT_IS_ACTIVE("filter")) {
1949 // Use the extension's filter set
1950 return FILTER_VALIDATE_URL($URL, false);
1953 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1954 // https:// in front of the URLs
1955 return (((substr($URL, 0, 7) == "http://") || (substr($URL, 0, 8) == "https://")) && (strlen($URL) >= 12));
1958 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1959 // Define all main targets
1960 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1962 // Begin of navigation links
1963 $eval = "\$OUT = \"[ ";
1965 foreach ($TARGETS as $tar) {
1966 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&u_id=".$uid."\\\" title=\\\"{!ADMIN_LINK_";
1967 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1968 if (($tar == "lock_user") && ($status == "LOCKED")) {
1969 // Locked accounts shall be unlocked
1970 $eval .= "UNLOCK_USER";
1972 // All other status is fine
1973 $eval .= strtoupper($tar);
1975 $eval .= "_TITLE!}\\\">{!ADMIN_";
1976 if (($tar == "lock_user") && ($status == "LOCKED")) {
1977 // Locked accounts shall be unlocked
1978 $eval .= "UNLOCK_USER";
1980 // All other status is fine
1981 $eval .= strtoupper($tar);
1983 $eval .= "!}</a></span> | ";
1986 // Finish navigation link
1987 $eval = substr($eval, 0, -7)."]\";";
1993 // Function for backward-compatiblity
1994 function ADD_CATEGORY_table ($MODE, $return=false) {
1995 // Load it from the register extension
1996 return REGISTER_ADD_CATEGORY_table ($MODE, $return);
1998 // Generate an email link
1999 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2000 // Default email link (INSECURE! Spammer can read this by harvester programs)
2001 $EMAIL = "mailto:".$email;
2003 // Check for several extensions
2004 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2005 // Create email link for contacting admin in guest area
2006 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2007 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2008 // Create email link for contacting a member within admin area (or later in other areas, too?)
2009 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2010 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2011 // Create email link to contact sponsor within admin area (or like the link above?)
2012 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2015 // Shall I close the link when there is no admin?
2016 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2018 // Return email link
2021 // Generate a hash for extra-security for all passwords
2022 function generateHash ($plainText, $salt = "") {
2025 // Is the required extension "sql_patches" there and a salt is not given?
2026 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2027 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2028 return md5($plainText);
2031 // Do we miss an arry element here?
2032 if (getConfig('file_hash') == null) {
2034 print("Missing file_hash in ".__FUNCTION__.". Backtrace:<pre>");
2035 debug_print_backtrace();
2039 // When the salt is empty build a new one, else use the first x configured characters as the salt
2041 // Build server string
2042 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(PATH."inc/databases.php");
2045 $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');
2048 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2050 // Calculate number for generating the code
2051 $a = time() + _ADD - 1;
2053 // Generate SHA1 sum from modula of number and the prime number
2054 $sha1 = sha1(($a % _PRIME).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2055 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2056 $sha1 = scrambleString($sha1);
2057 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2058 //* DEBUG: */ $sha1b = descrambleString($sha1);
2059 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2061 // Generate the password salt string
2062 $salt = substr($sha1, 0, getConfig('salt_length'));
2063 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2066 $salt = substr($salt, 0, getConfig('salt_length'));
2067 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2071 return $salt.sha1($salt.$plainText);
2074 function scrambleString($str) {
2078 // Final check, in case of failture it will return unscrambled string
2079 if (strlen($str) > 40) {
2080 // The string is to long
2082 } elseif (strlen($str) == 40) {
2084 $scrambleNums = explode(":", getConfig('pass_scramble'));
2086 // Generate new numbers
2087 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2090 // Scramble string here
2091 //* DEBUG: */ echo "***Original=".$str."***<br />";
2092 for ($idx = 0; $idx < strlen($str); $idx++) {
2093 // Get char on scrambled position
2094 $char = substr($str, $scrambleNums[$idx], 1);
2096 // Add it to final output string
2097 $scrambled .= $char;
2100 // Return scrambled string
2101 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2105 function descrambleString($str) {
2106 // Scramble only 40 chars long strings
2107 if (strlen($str) != 40) return $str;
2109 // Load numbers from config
2110 $scrambleNums = explode(":", getConfig('pass_scramble'));
2113 if (count($scrambleNums) != 40) return $str;
2115 // Begin descrambling
2116 $orig = str_repeat(" ", 40);
2117 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2118 for ($idx = 0; $idx < 40; $idx++) {
2119 $char = substr($str, $idx, 1);
2120 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2123 // Return scrambled string
2124 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2128 function genScrambleString($len) {
2129 // Prepare randomizer and array for the numbers
2130 mt_srand((double) microtime() * 1000000);
2131 $scrambleNumbers = array();
2133 // First we need to setup randomized numbers from 0 to 31
2134 for ($idx = 0; $idx < $len; $idx++) {
2136 $rand = mt_rand(0, ($len -1));
2138 // Check for it by creating more numbers
2139 while (array_key_exists($rand, $scrambleNumbers)) {
2140 $rand = mt_rand(0, ($len -1));
2144 $scrambleNumbers[$rand] = $rand;
2147 // So let's create the string for storing it in database
2148 $scrambleString = implode(":", $scrambleNumbers);
2149 return $scrambleString;
2151 // Append data like session ID or referal ID to the given URL which would
2152 // normally be stored in cookies
2153 function ADD_URL_DATA ($URL) {
2157 // Determine URL binder
2159 if (strpos($URL, "?") !== false) $BIND = "&";
2161 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2162 // Cookies are not accepted
2163 if ((!empty($_GET['refid'])) && (strpos($URL, "refid=") == 0)) {
2164 // Cookie found in URL
2165 $ADD .= $BIND."refid=".bigintval($_GET['refid']);
2166 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2167 // Not found! So let's set default here
2168 $ADD .= $BIND."refid=".getConfig('def_refid');
2171 // Is there already added data? Then change the binder
2172 if (!empty($ADD)) $BIND = "&";
2175 if ((!empty($_GET['PHPSESSID'])) && (strpos($URL, "PHPSESSID=") == 0)) {
2176 // Add session from URL
2177 $ADD .= $BIND."PHPSESSID=".SQL_ESCAPE(strip_tags($_GET['PHPSESSID']));
2179 // Add current session
2180 $ADD .= $BIND."PHPSESSID=".session_id();
2184 // Add all together and return it
2187 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2188 function generatePassString($passHash) {
2189 // Return vanilla password hash
2192 // Is a secret key and master salt already initialized?
2193 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2194 // Only calculate when the secret key is generated
2195 $newHash = ""; $start = 9;
2196 for ($idx = 0; $idx < 10; $idx++) {
2197 $part1 = hexdec(substr($passHash, $start, 4));
2198 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2199 $mod = dechex($idx);
2200 if ($part1 > $part2) {
2201 $mod = dechex(sqrt(($part1 - $part2) * _PRIME / pi()));
2202 } elseif ($part2 > $part1) {
2203 $mod = dechex(sqrt(($part2 - $part1) * _PRIME / pi()));
2205 $mod = substr(round($mod), 0, 4);
2206 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2207 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2212 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2213 $ret = generateHash($newHash, getConfig('master_salt'));
2214 //* DEBUG: */ print($ret."<br />\n");
2217 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2218 $ret = md5($passHash);
2219 //* DEBUG: */ echo "++".$ret."++<br />\n";
2226 // Fix "deleted" cookies
2227 function FIX_DELETED_COOKIES ($cookies) {
2228 // Is this an array with entries?
2229 if ((is_array($cookies)) && (count($cookies) > 0)) {
2230 // Then check all cookies if they are marked as deleted!
2231 foreach ($cookies as $cookieName) {
2232 // Is the cookie set to "deleted"?
2233 if (get_session($cookieName) == "deleted") {
2234 set_session($cookieName, "");
2240 // Output error messages in a fasioned way and die...
2241 function mxchange_die ($msg) {
2243 LOAD_INC_ONCE("inc/header.php");
2245 // Load the message template
2246 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2249 LOAD_INC("inc/footer.php");
2255 // Display parsing time and number of SQL queries in footer
2256 function DISPLAY_PARSING_TIME_FOOTER() {
2257 // Is the timer started?
2258 if (!isset($GLOBALS['startTime'])) {
2264 $endTime = microtime(true);
2266 // "Explode" both times
2267 $start = explode(" ", $GLOBALS['startTime']);
2268 $end = explode(" ", $endTime);
2269 $runTime = $end[0] - $start[0];
2270 if ($runTime < 0) $runTime = 0;
2271 $runTime = TRANSLATE_COMMA($runTime);
2275 'runtime' => $runTime,
2276 'numSQLs' => (getConfig('sql_count') + 1),
2277 'numTemplates' => (getConfig('num_templates') + 1)
2280 // Load the template
2281 LOAD_TEMPLATE("show_timings", false, $content);
2284 // Unset/set session variables
2285 function set_session ($var, $value) {
2288 // Abort in CSS mode here
2289 if ($CSS == 1) return true;
2291 // Trim value and session variable
2292 $var = trim(SQL_ESCAPE($var)); $value = trim($value);
2294 // Is the session variable set?
2295 if (("".$value."" == "") && (isSessionVariableSet($var))) {
2296 // Remove the session
2297 //* DEBUG: */ echo "UNSET:".$var."=".get_session($var)."<br />\n";
2298 unset($_SESSION[$var]);
2299 return session_unregister($var);
2300 } elseif (("".$value."" != '') && (!isSessionVariableSet($var))) {
2302 //* DEBUG: */ echo "SET:".$var."=".$value."<br />\n";
2303 $_SESSION[$var] = $value;
2304 return session_register($var);
2305 } elseif (!empty($value)) {
2307 //* DEBUG: */ echo "UPDATE:".$var."=".$value."<br />\n";
2308 $_SESSION[$var] = $value;
2312 // Ignored (but valid)
2313 //* DEBUG: */ echo "IGNORED:".$var."=".$value."<br />\n";
2317 // Check wether a boolean constant is set
2318 // Taken from user comments in PHP documentation for function constant()
2319 function isBooleanConstantAndTrue($constName) { // : Boolean
2322 // Failed by default
2326 if (isset($cacheArray['const'][$constName])) {
2328 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2329 $res = $cacheArray['const'][$constName];
2332 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2333 if (defined($constName)) $res = (constant($constName) === true);
2336 $cacheArray['const'][$constName] = $res;
2338 //* DEBUG: */ var_dump($res);
2344 // Check wether a session variable is set
2345 function isSessionVariableSet ($var) {
2346 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):var={$var}<br />\n";
2347 return (isset($_SESSION[$var]));
2349 // Returns wether the value of the session variable or NULL if not set
2350 function get_session ($var) {
2353 // Default is not found! ;-)
2356 // Is the variable there or cached values?
2357 if (isset($cacheArray['session'][$var])) {
2358 // Get cached value (skips a lot SQL_ESCAPE() calles!
2359 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-CACHE!<br />\n";
2360 $value = $cacheArray['session'][$var];
2361 } elseif (isSessionVariableSet($var)) {
2362 // Then get it secured!
2363 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$var."-RESOLVE!<br />\n";
2364 $value = SQL_ESCAPE($_SESSION[$var]);
2367 $cacheArray['session'][$var] = $value;
2374 // Send notification to admin
2375 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2376 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2378 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2380 // Send outdated way
2381 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2382 SEND_ADMIN_EMAILS($subject, $msg);
2386 // Destroy user session
2387 function destroy_user_session () {
2389 $GLOBALS['userid'] = 0;
2391 // Remove all user data from session
2392 return ((set_session('userid', "")) && (set_session('u_hash', "")));
2395 // Merges an array together but only if both are arrays
2396 function merge_array ($array1, $array2) {
2397 // Are both an array?
2398 if ((is_array($array1)) && (is_array($array2))) {
2399 // Merge all together
2400 return array_merge($array1, $array2);
2401 } elseif (is_array($array1)) {
2402 // Return left array
2406 // Something wired happened here...
2407 print(__FUNCTION__.":<pre>");
2408 debug_print_backtrace();
2412 // Debug message logger
2413 function DEBUG_LOG ($file, $line, $message, $force=true) {
2414 // Is debug mode enabled?
2415 if ((isBooleanConstantAndTrue('DEBUG_MODE')) || ($force)) {
2416 // Log this message away
2417 $fp = fopen(PATH."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2418 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($file)."|".$line."|".strip_tags($message)."\n");
2423 // Reads a directory with PHP files in and gets only files back
2424 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2428 $dirPointer = opendir($baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2431 while ($baseFile = readdir($dirPointer)) {
2432 // Load file only if extension is active
2434 $file = $baseDir.$baseFile;
2436 // Is this a valid reset file?
2437 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2438 if ((FILE_READABLE($file)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2439 // Remove both for extension name
2440 $extName = substr($baseFile, strlen($prefix), -4);
2443 $extId = GET_EXT_ID($extName);
2445 // Is the extension valid and active?
2446 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2447 // Then add this file
2449 } elseif ($extId == 0) {
2450 // Add non-extension files as well
2457 closedir($dirPointer);
2462 // Return array with include files
2465 // Load more reset scripts
2466 function RESET_ADD_INCLUDES () {
2467 // Is the reset set or old sql_patches?
2468 if ((!defined('__DAILY_RESET')) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
2473 // Get more daily reset scripts
2474 $INC_POOL = GET_DIR_AS_ARRAY(PATH."inc/reset/", "reset_");
2477 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
2479 // Create current week mark
2480 $currWeek = date("W", time());
2483 if (getConfig('last_week') != $currWeek) {
2484 // Include weekly reset scripts
2485 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/weekly/", "weekly_"));
2488 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
2491 // Create current month mark
2492 $currMonth = date("m", time());
2495 if (getConfig('last_month') != $currMonth) {
2496 // Include monthly reset scripts
2497 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY(PATH."inc/monthly/", "monthly_"));
2500 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
2506 // Handle extra values
2507 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
2508 // Default is the value itself
2511 // Do we have a special filter function?
2512 if (!empty($filterFunction)) {
2513 // Does the filter function exist?
2514 if (function_exists($filterFunction)) {
2515 // Do we have extra parameters here?
2516 if (!empty($extraValue)) {
2517 // Put both parameters in one new array by default
2518 $args = array($value, $extraValue);
2520 // If we have an array simply use it and pre-extend it with our value
2521 if (is_array($extraValue)) {
2522 // Make the new args array
2523 $args = merge_array(array($value), $extraValue);
2526 // Call the multi-parameter call-back
2527 $ret = call_user_func_array($filterFunction, $args);
2529 // One parameter call
2530 $ret = call_user_func($filterFunction, $value);
2538 // Check if given FQFN is a readable file
2539 function FILE_READABLE($fqfn) {
2541 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
2543 // Converts timestamp selections into a timestamp
2544 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
2545 // Init test variable
2548 // Get last three chars
2549 $test = substr($id, -3);
2551 // Improved way of checking! :-)
2552 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
2553 // Found a multi-selection for timings?
2554 $test = substr($id, 0, -3);
2555 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)) {
2556 // Generate timestamp
2557 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
2558 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2560 // Remove data from array
2561 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
2562 unset($POST[$test."_".$rem]);
2566 unset($id); $skip = true; $test2 = $test;
2569 // Process this entry
2570 $skip = false; $test2 = "";
2573 // Reverts the german decimal comma into Computer decimal dot
2574 function REVERT_COMMA ($str) {
2575 // Default float is not a float... ;-)
2578 // Which language is selected?
2579 switch (GET_LANGUAGE()) {
2580 case "de": // German language
2581 // Remove german thousand dots first
2582 $str = str_replace(".", "", $str);
2584 // Replace german commata with decimal dot and cast it
2585 $float = (float)str_replace(",", ".", $str);
2588 default: // US and so on
2589 // Remove thousand dots first and cast
2590 $float = (float)str_replace(",", "", $str);
2598 // Handle menu-depending failed logins and return the rendered content
2599 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
2600 // Default output is empty ;-)
2603 // Is the session data set?
2604 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
2605 // Ignore zero values
2606 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
2607 // Non-guest has login failures found, get both data and prepare it for template
2608 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
2610 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
2611 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
2615 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
2618 // Reset session data
2619 set_session('mxchange_'.$accessLevel.'_failures', "");
2620 set_session('mxchange_'.$accessLevel.'_last_fail', "");
2623 // Return rendered content
2628 function REBUILD_CACHE ($cache, $inc="") {
2629 global $cacheInstance, $CSS;
2631 // Shall I remove the cache file?
2632 if ((EXT_IS_ACTIVE("cache")) && (is_object($cacheInstance))) {
2634 if ($cacheInstance->loadCacheFile($cache)) {
2636 $cacheInstance->destroyCacheFile();
2639 // Include file given?
2642 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
2644 // Is the include there?
2645 if (FILE_READABLE($INC)) {
2646 // And rebuild it from scratch
2647 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
2650 // Include not found!
2651 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
2657 // Purge admin menu cache
2658 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
2659 global $cacheInstance;
2661 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
2662 if (!EXT_IS_ACTIVE("cache")) {
2663 // Cache extension not active
2665 } elseif (!is_object($cacheInstance)) {
2666 // No cache instance!
2667 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
2669 } elseif ((getConfig('cache_admin_menu') == null) || (getConfig('cache_admin_menu') == "N")) {
2670 // Caching disabled (currently experiemental!)
2674 // Experiemental feature!
2675 trigger_error("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
2678 // Translates the "pool type" into human-readable
2679 function TRANSLATE_POOL_TYPE ($type) {
2680 // Default type is unknown
2681 $translated = sprintf(POOL_TYPE_UNKNOWN, $type);
2683 // Generate constant
2684 $constName = sprintf("POOL_TYPE_%s", $type);
2687 if (defined($constName)) {
2689 $translated = constant($constName);
2692 // Return "translation"
2696 // "Getter" for remote IP number
2697 function GET_REMOTE_ADDR () {
2698 // Get remote ip from environment
2699 $remoteAddr = getenv('REMOTE_ADDR');
2701 // Is removeip installed?
2702 if (EXT_IS_ACTIVE("removeip")) {
2703 // Then anonymize it
2704 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
2710 // "Getter" for remote hostname
2711 function GET_REMOTE_HOST () {
2712 // Get remote ip from environment
2713 $remoteHost = getenv('REMOTE_HOST');
2715 // Is removeip installed?
2716 if (EXT_IS_ACTIVE("removeip")) {
2717 // Then anonymize it
2718 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
2724 // "Getter" for user agent
2725 function GET_USER_AGENT () {
2726 // Get remote ip from environment
2727 $userAgent = getenv('HTTP_USER_AGENT');
2729 // Is removeip installed?
2730 if (EXT_IS_ACTIVE("removeip")) {
2731 // Then anonymize it
2732 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
2738 // "Getter" for referer
2739 function GET_REFERER () {
2740 // Get remote ip from environment
2741 $referer = getenv('HTTP_REFERER');
2743 // Is removeip installed?
2744 if (EXT_IS_ACTIVE("removeip")) {
2745 // Then anonymize it
2746 $referer = GET_ANONYMOUS_REFERER($referer);
2753 // Adds a bonus mail to the queue
2754 // This is a high-level function!
2755 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
2756 // Use mode from data if not set and availble ;-)
2757 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
2759 // Generate receiver list
2760 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
2763 if (!empty($RECEIVER)) {
2764 // Add bonus mail to queue
2765 ADD_BONUS_MAIL_TO_QUEUE(
2777 // Mail inserted into bonus pool
2778 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
2779 } elseif ($output) {
2780 // More entered than can be reached!
2781 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
2784 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
2787 // Determines referal id and sets it
2788 function DETERMINE_REFID () {
2789 global $CLICK, $_SERVER;
2791 // Check if refid is set
2792 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
2793 // The variable user comes from the click-counter script click.php and we only accept this here
2794 $GLOBALS['refid'] = bigintval($_GET['user']);
2795 } elseif (!empty($_POST['refid'])) {
2796 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2797 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
2798 } elseif (!empty($_GET['refid'])) {
2799 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
2800 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
2801 } elseif (!empty($_GET['ref'])) {
2802 // Set refid=ref (the referal link uses such variable)
2803 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
2804 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
2805 // Set session refid als global
2806 $GLOBALS['refid'] = bigintval(get_session('refid'));
2807 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
2808 // Set default refid as refid in URL
2809 $GLOBALS['refid'] = bigintval(getConfig('def_refid'));
2810 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
2811 // Select a random user which has confirmed enougth mails
2812 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
2814 // No default ID when sql_patches is not installed or none set
2815 $GLOBALS['refid'] = 0;
2818 // Set cookie when default refid > 0
2819 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
2821 set_session('refid', $GLOBALS['refid']);
2824 // Return determined refid
2825 return $GLOBALS['refid'];
2828 // Destroys the admin session
2829 function DESTROY_ADMIN_SESSION ($destroy = true) {
2830 // Kill maybe existing session variables including array elements
2831 set_session('admin_login', "");
2832 set_session('admin_md5' , "");
2833 set_session('admin_last' , "");
2834 set_session('admin_to' , "");
2836 // Destroy session and return status
2838 return @session_destroy();
2841 // All fine if we shall not really destroy the session
2845 // Checks if a given apache module is loaded
2846 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2847 // Check it and return result
2848 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2851 // Getter for $_CONFIG entries
2852 function getConfig ($entry) {
2858 // Is the entry there?
2859 if (isset($_CONFIG[$entry])) {
2861 $value = $_CONFIG[$entry];
2868 // @TODO Rewrite all language constants to this function.
2869 // "Getter" for language strings
2870 function getMessage ($messageId) {
2871 // Default is not found!
2872 $return = "!".$messageId."!";
2874 // Is the language string found?
2875 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2876 // Language array element found in small_letters
2877 $return = $GLOBALS['msg'][$messageId];
2878 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2879 // @DEPRECATED Language array element found in BIG_LETTERS
2880 $return = $GLOBALS['msg'][$messageId];
2881 } elseif (defined(strtoupper($messageId))) {
2882 // @DEPRECATED Deprecated constant found
2883 $return = constant($messageId);
2885 // Missing language constant
2886 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2889 // Return the string
2893 // Get current theme name
2894 function GET_CURR_THEME() {
2895 global $INC_POOL, $CSS, $cacheArray;
2897 // The default theme is 'default'... ;-)
2900 // Load default theme if not empty from configuration
2901 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2903 if (!isSessionVariableSet('mxchange_theme')) {
2904 // Set default theme
2905 set_session('mxchange_theme', $ret);
2906 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2907 //die("<pre>".print_r($cacheArray['themes'], true)."</pre>");
2908 // Get theme from cookie
2909 $ret = get_session('mxchange_theme');
2912 if (THEME_GET_ID($ret) == 0) {
2913 // Fix it to default
2916 } elseif ((!isBooleanConstantAndTrue('mxchange_installed')) && ((isBooleanConstantAndTrue('mxchange_installing')) || ($CSS == true)) && ((!empty($_GET['theme'])) || (!empty($_POST['theme'])))) {
2917 // Prepare FQFN for checking
2918 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_GET['theme']));
2920 // Installation mode active
2921 if ((!empty($_GET['theme'])) && (FILE_READABLE($theme))) {
2922 // Set cookie from URL data
2923 set_session('mxchange_theme', SQL_ESCAPE($_GET['theme']));
2924 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($_POST['theme'])))) {
2925 // Set cookie from posted data
2926 set_session('mxchange_theme', SQL_ESCAPE($_POST['theme']));
2930 $ret = get_session('mxchange_theme');
2932 // Invalid design, reset cookie
2933 set_session('mxchange_theme', $ret);
2936 // Add (maybe) found theme.php file to inclusion list
2937 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2939 // Try to load the requested include file
2940 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2942 // Return theme value
2946 // Get id from theme
2947 function THEME_GET_ID ($name) {
2950 // Is the extension "theme" installed?
2951 if (!EXT_IS_ACTIVE("theme")) {
2959 // Is the cache entry there?
2960 if (isset($cacheArray['themes']['id'][$name])) {
2961 // Get the version from cache
2962 $id = $cacheArray['themes']['id'][$name];
2965 incrementConfigEntry('cache_hits');
2966 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2967 // Check if current theme is already imported or not
2968 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2969 array($name), __FILE__, __LINE__);
2972 if (SQL_NUMROWS($result) == 1) {
2974 list($id) = SQL_FETCHROW($result);
2978 SQL_FREERESULT($result);
2985 // Increment or init with given value or 1 as default the given config entry
2986 function incrementConfigEntry ($configEntry, $value=1) {
2989 // Increment it if set or init it with 1
2990 if (getConfig($configEntry) > 0) {
2991 $_CONFIG[$configEntry] += $value;
2993 $_CONFIG[$configEntry] = $value;
2997 // Read a given file
2998 function READ_FILE ($FQFN, $sqlPrepare = false) {
3000 if (function_exists('file_get_contents')) {
3002 $content = file_get_contents($FQFN);
3004 // Fall-back to implode-file chain
3005 $content = implode("", file($FQFN));
3008 // Prepare SQL queries?
3009 if ($sqlPrepare === true) {
3010 // Remove some unwanted chars
3011 $content = str_replace("\r", "", $content);
3012 $content = str_replace("\n\n", "\n", $content);
3015 // Return the content
3019 // Writes content to a file
3020 function WRITE_FILE ($FQFN, $content) {
3021 // Is the function there?
3022 if (function_exists('file_put_contents')) {
3023 // Write it directly
3024 file_put_contents($FQFN, $content);
3026 // Write it with fopen
3027 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
3028 fwrite($fp, $content);
3036 // Generates an error code from given account status
3037 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
3038 // Default error code if unknown account status
3039 $ERROR = CODE_UNKNOWN_STATUS;
3041 // Generate constant name
3042 $constantName = sprintf("CODE_ID_%s", $status);
3044 // Is the constant there?
3045 if (defined($constantName)) {
3047 $ERROR = constant($constantName);
3050 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
3053 // Return error code
3057 // Clears the output buffer. This function does *NOT* backup sent content.
3058 function clearOutputBuffer () {
3059 // Trigger an error on failure
3060 if (!ob_end_clean()) {
3062 trigger_error(__FUNCTION__.": Failed to clean output buffer.");
3066 // "Getter" for revision/version data
3067 function getActualVersion ($type = 0) {
3068 // By default nothing is new... ;-)
3071 // FQFN of revision file
3072 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
3074 // Check for revision file
3075 if (!FILE_READABLE($FQFN)) {
3076 // Not found, so we need to create it
3079 // Revision file found
3080 $ins_vers = explode("\n", READ_FILE($FQFN));
3082 // Is the content valid?
3083 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
3084 // File needs update!
3087 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
3088 return trim($ins_vers[$type]);
3093 // no Revision-File or has no valid Data so read the Revision from the Server.
3094 $version = GET_URL("check-updates3.php");
3097 $akt_vers[] = trim($version[10]);
3098 $akt_vers[] = trim($version[9]);
3099 $akt_vers[] = trim($version[8]);
3102 WRITE_FILE($FQFN, implode("\n", $akt_vers));
3104 // Return requested content
3105 return trim($akt_vers[$type]);
3109 // Loads an include file and logs any missing files for debug purposes
3110 function LOAD_INC ($INC) {
3111 // Get constant path
3112 $PATH = constant('PATH');
3114 // Use the include file name directly
3115 // @TODO Try to find all locations where an FQFN is given to these two
3116 // @TODO functions and avoid it.
3119 // Check if PATH is in $INC
3120 if (substr($INC, 0, $PATH) != $PATH) {
3121 // Add it. This is why we need a trailing slash in config.php
3122 $FQFN = $PATH . $INC;
3125 // Is the include file there?
3126 if (!FILE_READABLE($FQFN)) {
3127 // Not there so log it
3128 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Include file %s not found.", basename($INC)));
3136 // Loads an include file once
3137 function LOAD_INC_ONCE ($INC) {
3140 // Is it not loaded?
3141 if (!isset($cacheArray['load_once'][$INC])) {
3142 // Then try to load it
3145 // And mark it as loaded
3146 $cacheArray['load_once'][$INC] = true;
3150 //////////////////////////////////////////////////
3151 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3152 //////////////////////////////////////////////////
3154 if (!function_exists('html_entity_decode')) {
3155 // Taken from documentation on www.php.net
3156 function html_entity_decode ($string) {
3157 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3158 $trans_tbl = array_flip($trans_tbl);
3159 return strtr($string, $trans_tbl);