2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Check if our config file is writeable or not
41 function IS_INC_WRITEABLE($inc) {
43 $fqfn = sprintf("%sinc/%s.php", constant('PATH'), $inc);
45 // Abort by simple test
46 if ((FILE_READABLE($fqfn)) && (!is_writeable($fqfn))) {
50 // Test if we can append data
51 $fp = fopen($fqfn, 'a');
52 if ($inc == "dummy") {
57 // Close all other files
62 // Output HTML code directly or "render" it. You addionally switch the new-line character off
63 function OUTPUT_HTML ($HTML, $newLine = true) {
64 // Some global variables
67 // Do we have HTML-Code here?
69 // Yes, so we handle it as you have configured
70 switch (constant('OUTPUT_MODE'))
73 // That's why you don't need any \n at the end of your HTML code... :-)
74 if (constant('_OB_CACHING') == "on") {
75 // Output into PHP's internal buffer
78 // That's why you don't need any \n at the end of your HTML code... :-)
79 if ($newLine) echo "\n";
81 // Render mode for old or lame servers...
84 // That's why you don't need any \n at the end of your HTML code... :-)
85 if ($newLine) $OUTPUT .= "\n";
90 // If we are switching from render to direct output rendered code
91 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != "on")) { OUTPUT_RAW($OUTPUT); $OUTPUT = ""; }
93 // The same as above... ^
95 if ($newLine) echo "\n";
99 // Huh, something goes wrong or maybe you have edited config.php ???
100 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
101 mxchange_die("<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
104 } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
105 // Headers already sent?
106 if (headers_sent()) {
108 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
110 // Trigger an user error
111 debug_report_bug("Headers are already sent!");
114 // Output cached HTML code
115 $OUTPUT = ob_get_contents();
117 // Clear output buffer for later output if output is found
118 if (!empty($OUTPUT)) {
123 header("HTTP/1.1 200");
126 $now = gmdate('D, d M Y H:i:s') . ' GMT';
128 // General headers for no caching
129 header("Expired: " . $now); // RFC2616 - Section 14.21
130 header("Last-Modified: " . $now);
131 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
132 header("Pragma: no-cache"); // HTTP/1.0
133 header("Connection: Close");
135 // Extension "rewrite" installed?
136 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
137 $OUTPUT = REWRITE_LINKS($OUTPUT);
140 // Compile and run finished rendered HTML code
141 while (strpos($OUTPUT, '{!') > 0) {
142 // Prepare the content and eval() it...
144 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
147 // Was that eval okay?
148 if (empty($newContent)) {
149 // Something went wrong!
150 mxchange_die("Evaluation error:<pre>".htmlentities($eval)."</pre>");
152 $OUTPUT = $newContent;
155 // Output code here, DO NOT REMOVE! ;-)
157 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
158 // Rewrite links when rewrite extension is active
159 if ((EXT_IS_ACTIVE("rewrite")) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
160 $OUTPUT = REWRITE_LINKS($OUTPUT);
163 // Compile and run finished rendered HTML code
164 while (strpos($OUTPUT, '{!') > 0) {
165 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
169 // Output code here, DO NOT REMOVE! ;-)
174 // Output the raw HTML code
175 function OUTPUT_RAW ($HTML) {
176 // Output stripped HTML code to avoid broken JavaScript code, etc.
177 echo stripslashes(stripslashes($HTML));
179 // Flush the output if only constant('_OB_CACHING') is not "on"
180 if (constant('_OB_CACHING') != "on") {
186 // Init fatal message array
187 function initFatalMessages () {
188 $GLOBALS['fatal_messages'] = array();
191 // Getter for whole fatal error messages
192 function getFatalArray () {
193 return $GLOBALS['fatal_messages'];
196 // Add a fatal error message to the queue array
197 function addFatalMessage ($F, $L, $message, $extra="") {
198 if (is_array($extra)) {
199 // Multiple extras for a message with masks
200 $message = call_user_func_array('sprintf', $extra);
201 } elseif (!empty($extra)) {
202 // $message is text with a mask plus extras to insert into the text
203 $message = sprintf($message, $extra);
206 // Add message to $GLOBALS['fatal_messages']
207 $GLOBALS['fatal_messages'][] = $message;
209 // Log fatal messages away
210 DEBUG_LOG($F, $L, " message={$message}");
213 // Getter for total fatal message count
214 function getTotalFatalErrors () {
218 // Do we have at least the first entry?
219 if (!empty($GLOBALS['fatal_messages'][0])) {
221 $count = count($GLOBALS['fatal_messages']);
228 // Load a template file and return it's content (only it's name; do not use ' or ")
229 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
230 // Add more variables which you want to use in your template files
231 global $DATA, $_CONFIG, $username;
233 // Make all template names lowercase
234 $template = strtolower($template);
236 // Count the template load
237 incrementConfigEntry('num_templates');
239 // Prepare IP number and User Agent
240 $REMOTE_ADDR = GET_REMOTE_ADDR();
241 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
242 $HTTP_USER_AGENT = GET_USER_AGENT();
246 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
248 // @DEPRECATED Try to rewrite the if() condition
249 if ($template == "member_support_form") {
250 // Support request of a member
251 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
252 array($GLOBALS['userid']), __FUNCTION__, __LINE__);
254 // Is content an array?
255 if (is_array($content)) {
257 $content = merge_array($content, SQL_FETCHARRAY($result));
260 $content['gender'] = TRANSLATE_GENDER($content['gender']);
263 // @TODO Fine all templates which are using these direct variables and rewrite them.
264 // @TODO After this step is done, this else-block is history
265 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
268 $gender = TRANSLATE_GENDER($gender);
269 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
273 SQL_FREERESULT($result);
276 // Generate date/time string
277 $date_time = MAKE_DATETIME(time(), "1");
280 $BASE = sprintf("%stemplates/%s/html/", constant('PATH'), GET_LANGUAGE());
283 // Check for admin/guest/member templates
284 if (strpos($template, "admin_") > -1) {
285 // Admin template found
287 } elseif (strpos($template, "guest_") > -1) {
288 // Guest template found
290 } elseif (strpos($template, "member_") > -1) {
291 // Member template found
293 } elseif (strpos($template, "install_") > -1) {
294 // Installation template found
296 } elseif (strpos($template, "ext_") > -1) {
297 // Extension template found
299 } elseif (strpos($template, "la_") > -1) {
300 // "Logical-area" template found
303 // Test for extension
304 $test = substr($template, 0, strpos($template, "_"));
305 if (EXT_IS_ACTIVE($test)) {
306 // Set extra path to extension's name
311 ////////////////////////
312 // Generate file name //
313 ////////////////////////
314 $FQFN = $BASE.$MODE.$template.".tpl";
316 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($MODE == "guest/") || ($MODE == "member/") || ($MODE == "admin/"))) {
317 // Select what depended header/footer template file for admin/guest/member area
318 $file2 = sprintf("%s%s%s_%s.tpl",
322 SQL_ESCAPE($GLOBALS['what'])
326 if (FILE_READABLE($file2)) $FQFN = $file2;
328 // Remove variable from memory
332 // Does the special template exists?
333 if (!FILE_READABLE($FQFN)) {
334 // Reset to default template
335 $FQFN = $BASE.$template.".tpl";
338 // Now does the final template exists?
339 if (FILE_READABLE($FQFN)) {
340 // The local file does exists so we load it. :)
341 $tmpl_file = READ_FILE($FQFN);
343 // Replace ' to our own chars to preventing them being quoted
344 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
346 // Do we have to compile the code?
348 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
350 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
353 // Simply return loaded code
357 // Add surrounding HTML comments to help finding bugs faster
358 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
359 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
360 // Only admins shall see this warning or when installation mode is active
361 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
362 (".basename($FQFN).")<br />
365 <pre>".print_r($content, true)."</pre>
367 <pre>".print_r($DATA, true)."</pre>
371 // Remove content and data
375 // Do we have some content to output or return?
377 // Not empty so let's put it out! ;)
379 // Return the HTML code
385 } elseif (isDebugModeEnabled()) {
386 // Warning, empty output!
387 return "E:".$template."<br />\n";
391 // Send mail out to an email address
392 function SEND_EMAIL($TO, $SUBJECT, $MSG, $HTML = "N", $FROM = "") {
393 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO},SUBJECT={$SUBJECT}<br />\n";
395 // Compile subject line (for POINTS constant etc.)
396 $eval = "\$SUBJECT = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($SUBJECT))."\");";
400 if ((!eregi("@", $TO)) && ($TO > 0)) {
401 // Value detected, is the message extension installed?
402 if (EXT_IS_ACTIVE("msg")) {
403 ADD_MESSAGE_TO_BOX($TO, $SUBJECT, $MSG, $HTML);
406 // Load email address
407 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($TO)), __FUNCTION__, __LINE__);
408 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
410 // Does the user exist?
411 if (SQL_NUMROWS($result_email)) {
412 // Load email address
413 list($TO) = SQL_FETCHROW($result_email);
416 $TO = constant('WEBMASTER');
420 SQL_FREERESULT($result_email);
422 } elseif ("$TO" == "0") {
424 $TO = constant('WEBMASTER');
426 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$TO}<br />\n";
428 // Check for PHPMailer or debug-mode
429 if (!CHECK_PHPMAILER_USAGE()) {
430 // Not in PHPMailer-Mode
432 // Load email header template
433 $FROM = LOAD_EMAIL_TEMPLATE("header");
436 $FROM .= LOAD_EMAIL_TEMPLATE("header");
438 } elseif (isDebugModeEnabled()) {
440 // Load email header template
441 $FROM = LOAD_EMAIL_TEMPLATE("header");
444 $FROM .= LOAD_EMAIL_TEMPLATE("header");
449 $eval = "\$TO = \"".COMPILE_CODE(smartAddSlashes($TO))."\";";
453 $eval = "\$MSG = \"".COMPILE_CODE(smartAddSlashes($MSG))."\";";
456 // Fix HTML parameter (default is no!)
457 if (empty($HTML)) $HTML = "N";
458 if (isDebugModeEnabled()) {
459 // In debug mode we want to display the mail instead of sending it away so we can debug this part
461 ".htmlentities(trim($FROM))."
463 Subject : ".$SUBJECT."
466 } elseif (($HTML == "Y") && (EXT_IS_ACTIVE("html_mail"))) {
467 // Send mail as HTML away
468 SEND_HTML_EMAIL($TO, $SUBJECT, $MSG, $FROM);
469 } elseif (!empty($TO)) {
471 SEND_RAW_EMAIL($TO, $SUBJECT, $MSG, $FROM);
472 } elseif ($HTML == "N") {
474 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$SUBJECT, $MSG, $FROM);
478 // Check if legacy or PHPMailer command
479 // @TODO Rewrite this to an extension 'smtp'
481 function CHECK_PHPMAILER_USAGE() {
482 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != "") && (constant('SMTP_USER') != ""));
486 * Send out a raw email with PHPMailer class or legacy mail() command
488 function SEND_RAW_EMAIL ($to, $subject, $msg, $from) {
489 // Shall we use PHPMailer class or legacy mode?
490 if (CHECK_PHPMAILER_USAGE()) {
491 // Use PHPMailer class with SMTP enabled
492 LOAD_INC_ONCE("inc/phpmailer/class.phpmailer.php");
493 LOAD_INC_ONCE("inc/phpmailer/class.smtp.php");
496 $mail = new PHPMailer();
497 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
500 $mail->SMTPAuth = true;
501 $mail->Host = constant('SMTP_HOSTNAME');
503 $mail->Username = constant('SMTP_USER');
504 $mail->Password = constant('SMTP_PASSWORD');
506 $mail->From = constant('WEBMASTER');
510 $mail->FromName = constant('MAIN_TITLE');
511 $mail->Subject = $subject;
512 if ((EXT_IS_ACTIVE("html_mail")) && (strip_tags($msg) != $msg)) {
514 $mail->AltBody = "Your mail program required HTML support to read this mail!";
515 $mail->WordWrap = 70;
518 $mail->Body = decodeEntities($msg);
520 $mail->AddAddress($to, "");
521 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
522 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
523 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
526 // Use legacy mail() command
527 @mail($to, $subject, decodeEntities($msg), $from);
532 // Generate a password in a specified length or use default password length
533 function GEN_PASS ($LEN = 0) {
534 // Auto-fix invalid length of zero
535 if ($LEN == 0) $LEN = getConfig('pass_len');
537 // Initialize array with all allowed chars
538 $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,-,+,_,/");
540 // Start creating password
542 for ($i = 0; $i < $LEN; $i++) {
543 $PASS .= $ABC[mt_rand(0, sizeof($ABC) -1)];
546 // When the size is below 40 we can also add additional security by scrambling it
547 if (strlen($PASS) <= 40) {
548 // Also scramble the password
549 $PASS = scrambleString($PASS);
552 // Return the password
556 function MAKE_DATETIME ($time, $mode="0")
560 return NEVER_HAPPENED;
562 // Filter out numbers
563 $time = bigintval($time);
566 switch (GET_LANGUAGE())
568 case "de": // German date / time format
570 case "0": $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
571 case "1": $ret = strtolower(date("d.m.Y - H:i", $time)); break;
572 case "2": $ret = date("d.m.Y|H:i", $time); break;
573 case "3": $ret = date("d.m.Y", $time); break;
575 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
580 default: // Default is the US date / time format!
582 case "0": $ret = date("r", $time); break;
583 case "1": $ret = date("Y-m-d - g:i A", $time); break;
584 case "2": $ret = date("y-m-d|H:i", $time); break;
585 case "3": $ret = date("y-m-d", $time); break;
587 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
594 // Translates the american decimal dot into a german comma
595 function TRANSLATE_COMMA ($dotted, $cut=true, $max=0) {
596 // Default is 3 you can change this in admin area "Misc -> Misc Options"
597 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', "3");
599 // Use from config is default
600 $maxComma = getConfig('max_comma');
602 // Use from parameter?
603 if ($max > 0) $maxComma = $max;
606 if (($cut) && ($max == 0)) {
607 // Test for commata if in cut-mode
608 $com = explode(".", $dotted);
609 if (count($com) < 2) {
610 // Don't display commatas even if there are none... ;-)
616 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
619 switch (GET_LANGUAGE()) {
621 $dotted = number_format($dotted, $maxComma, ",", ".");
625 $dotted = number_format($dotted, $maxComma, ".", ",");
629 // Return translated value
634 function DEREFERER ($URL) {
635 // Don't de-refer our own links!
636 if (substr($URL, 0, strlen(URL)) != URL) {
637 // De-refer this link
638 $URL = "modules.php?module=loader&url=".encodeString(compileUriCode($URL));
645 // Translate Uni*-like gender to human-readable
646 function TRANSLATE_GENDER ($gender) {
648 $ret = "!{$gender}!";
650 // Male/female or company?
652 case "M": $ret = getMessage('GENDER_M'); break;
653 case "F": $ret = getMessage('GENDER_F'); break;
654 case "C": $ret = getMessage('GENDER_C'); break;
656 // Log unknown gender
657 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
661 // Return translated gender
666 function FRAMETESTER ($URL) {
667 // Prepare frametester URL
668 $frametesterUrl = sprintf("%s/modules.php?module=frametester&url=%s",
670 encodeString(compileUriCode($URL))
672 return $frametesterUrl;
676 function SELECTION_COUNT ($array) {
678 if (is_array($array)) {
679 foreach ($array as $key => $selected) {
680 if (!empty($selected)) $ret++;
686 function IMG_CODE ($code, $type, $DATA, $uid) {
687 return "<IMG border=\"0\" alt=\"Code\" src=\"{!URL!}/mailid_top.php?uid=".$uid."&".$type."=".$DATA."&mode=img&code=".$code."\">";
690 function TRANSLATE_STATUS ($status) {
696 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
701 $ret = getMessage('ACCOUNT_DELETED');
705 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
706 $ret = sprintf(getMessage('UNKNOWN_STATUS"'), $status);
714 function GET_LANGUAGE() {
715 // Set default return value to default language from config
716 $ret = constant('DEFAULT_LANG');
721 // Is the variable set
722 if (REQUEST_ISSET_GET(('mx_lang'))) {
723 // Accept only first 2 chars
724 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
725 } elseif (isset($GLOBALS['cache_array']['language'])) {
727 $ret = $GLOBALS['cache_array']['language'];
728 } elseif (!empty($lang)) {
729 // Check if main language file does exist
730 if (FILE_READABLE(constant('PATH')."inc/language/".$lang.".php")) {
731 // Okay found, so let's update cookies
734 } elseif (!isSessionVariableSet('mx_lang')) {
735 // Return stored value from cookie
736 $ret = get_session('mx_lang');
738 // Fixes a warning before the session has the mx_lang constant
739 if (empty($ret)) $ret = constant('DEFAULT_LANG');
743 $GLOBALS['cache_array']['language'] = $ret;
749 function SET_LANGUAGE ($lang) {
750 // Accept only first 2 chars!
751 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
754 set_session('mx_lang', $lang);
757 function LOAD_EMAIL_TEMPLATE($template, $content=array(), $UID="0") {
758 global $DATA, $_CONFIG;
760 // Make sure all template names are lowercase!
761 $template = strtolower($template);
763 // Default "nickname" if extension is not installed
766 // Prepare IP number and User Agent
767 $REMOTE_ADDR = GET_REMOTE_ADDR();
768 $HTTP_USER_AGENT = GET_USER_AGENT();
771 $ADMIN = constant('MAIN_TITLE');
773 // Is the admin logged in?
776 $aid = GET_CURRENT_ADMIN_ID();
779 $ADMIN = GET_ADMIN_EMAIL($aid);
782 // Neutral email address is default
783 $email = constant('WEBMASTER');
785 // Expiration in a nice output format
786 if (getConfig('auto_purge') == 0) {
787 // Will never expire!
788 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
790 // Create nice date string
791 $EXPIRATION = CREATE_FANCY_TIME(getConfig('auto_purge'));
794 // Is content an array?
795 if (is_array($content)) {
796 // Add expiration to array, $EXPIRATION is now deprecated!
797 $content['expiration'] = $EXPIRATION;
801 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
802 if (($UID > 0) && (is_array($content))) {
803 // If nickname extension is installed, fetch nickname as well
804 if (EXT_IS_ACTIVE("nickname")) {
805 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
807 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
808 array(bigintval($UID)), __FUNCTION__, __LINE__);
810 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
812 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
813 array(bigintval($UID)), __FUNCTION__, __LINE__);
816 // Fetch and merge data
817 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
818 $content = merge_array($content, SQL_FETCHARRAY($result));
819 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
822 SQL_FREERESULT($result);
825 // Translate M to male or F to female if present
826 if (isset($content['gender'])) $content['gender'] = TRANSLATE_GENDER($content['gender']);
828 // Overwrite email from data if present
829 if (isset($content['email'])) $email = $content['email'];
831 // Store email for some functions in global data array
832 $DATA['email'] = $email;
835 $BASE = sprintf("%stemplates/%s/emails/", constant('PATH'), GET_LANGUAGE());
837 // Check for admin/guest/member templates
838 if (strpos($template, "admin_") > -1) {
839 // Admin template found
840 $FQFN = $BASE."admin/".$template.".tpl";
841 } elseif (strpos($template, "guest_") > -1) {
842 // Guest template found
843 $FQFN = $BASE."guest/".$template.".tpl";
844 } elseif (strpos($template, "member_") > -1) {
845 // Member template found
846 $FQFN = $BASE."member/".$template.".tpl";
848 // Test for extension
849 $test = substr($template, 0, strpos($template, "_"));
850 if (EXT_IS_ACTIVE($test)) {
851 // Set extra path to extension's name
852 $FQFN = $BASE.$test."/".$template.".tpl";
854 // No special filename
855 $FQFN = $BASE.$template.".tpl";
859 // Does the special template exists?
860 if (!FILE_READABLE($FQFN)) {
861 // Reset to default template
862 $FQFN = $BASE.$template.".tpl";
865 // Now does the final template exists?
867 if (FILE_READABLE($FQFN)) {
868 // The local file does exists so we load it. :)
869 $tmpl_file = READ_FILE($FQFN);
870 $tmpl_file = SQL_ESCAPE($tmpl_file);
873 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
875 } elseif (!empty($template)) {
876 // Template file not found!
877 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
878 {--TEMPLATE_CONTENT--}
879 <pre>".print_r($content, true)."</pre>
881 <pre>".print_r($DATA, true)."</pre>
884 // Debug mode not active? Then remove the HTML tags
885 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
887 // No template name supplied!
888 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
891 // Is there some content?
892 if (empty($newContent)) {
894 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
895 // Add last error if the required function exists
896 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
899 // Remove content and data
903 // Return compiled content
904 return COMPILE_CODE($newContent);
907 function MAKE_TIME ($H, $M, $S, $stamp) {
908 // Extract day, month and year from given timestamp
909 $DAY = date("d", $stamp);
910 $MONTH = date("m", $stamp);
911 $YEAR = date('Y', $stamp);
913 // Create timestamp for wished time which depends on extracted date
914 return mktime($H, $M, $S, $MONTH, $DAY, $YEAR);
917 function LOAD_URL ($URL, $addUrlData=true) {
918 // Compile out URI codes
919 $URL = compileUriCode($URL);
921 // Check if http(s):// is there
922 if ((substr($URL, 0, 7) != "http://") && (substr($URL, 0, 8) != "https://")) {
923 // Make all URLs full-qualified
928 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
929 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
930 $OUTPUT = ob_get_contents();
932 // Clear it only if there is content
933 if (!empty($OUTPUT)) {
937 // Add some data to URL if cookies are not accepted
938 if (((!defined('__COOKIES')) || (!constant('__COOKIES'))) && ($addUrlData)) $URL = ADD_URL_DATA($URL);
940 // Probe for bot from search engine
941 if ((eregi("spider", GET_USER_AGENT())) || (eregi("bot", GET_USER_AGENT()))) {
942 // Search engine bot detected so let's rewrite many chars for the link
943 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
945 // Output new location link as anchor
946 OUTPUT_HTML("<a href=\"".$URL."\">".$URL."</a>");
947 } elseif (!headers_sent()) {
948 // Load URL when headers are not sent
949 //* DEBUG: */ debug_report_bug("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 // Is the code a string?
978 if (!is_string($code)) {
979 // Silently return it
983 $ARRAY = $GLOBALS['security_chars'];
985 // Select smaller set of chars to replace when we e.g. want to compile URLs
986 if (!$full) $ARRAY = $GLOBALS['url_chars'];
990 // BEFORE 0.2.1 : Language and data constants
991 // WITH 0.2.1+ : Only language constants
992 $code = str_replace('{--','".', str_replace('--}','."', $code));
994 // BEFORE 0.2.1 : Not used
995 // WITH 0.2.1+ : Data constants
996 $code = str_replace('{!','".', str_replace("!}", '."', $code));
999 // Compile QUOT and other non-HTML codes
1000 foreach ($ARRAY['to'] as $k => $to) {
1001 // Do the reversed thing as in inc/libs/security_functions.php
1002 $code = str_replace($to, $ARRAY['from'][$k], $code);
1005 // But shall I keep simple quotes for later use?
1006 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1008 // Find $content[bla][blub] entries
1009 @preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1011 // Are some matches found?
1012 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1013 // Replace all matches
1014 $matchesFound = array();
1015 foreach ($matches[0] as $key => $match) {
1016 // Fuzzy look has failed by default
1017 $fuzzyFound = false;
1019 // Fuzzy look on match if already found
1020 foreach ($matchesFound as $found => $set) {
1022 $test = substr($found, 0, strlen($match));
1024 // Does this entry exist?
1025 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1026 if ($test == $match) {
1028 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1035 if ($fuzzyFound) continue;
1037 // Take all string elements
1038 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1039 // Replace it in the code
1040 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1041 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1042 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1043 $matchesFound[$key."_".$matches[4][$key]] = 1;
1044 $matchesFound[$match] = 1;
1045 } elseif (!isset($matchesFound[$match])) {
1046 // Not yet replaced!
1047 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1048 $code = str_replace($match, "\".".$match.".\"", $code);
1049 $matchesFound[$match] = 1;
1054 // Return compiled code
1058 /************************************************************************
1060 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1061 * $a_sort sortiert: *
1063 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1064 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1065 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1066 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1067 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1069 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1070 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1071 * Sie, dass es doch nicht so schwer ist! :-) *
1073 ************************************************************************/
1074 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1076 while ($primary_key < count($a_sort)) {
1077 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1078 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1081 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1082 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1083 } elseif ($key != $key2) {
1084 // Sort numbers (E.g.: 9 < 10)
1085 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1086 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1090 // We have found two different values, so let's sort whole array
1091 foreach ($dummy as $sort_key => $sort_val) {
1092 $t = $dummy[$sort_key][$key];
1093 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1094 $dummy[$sort_key][$key2] = $t;
1105 // Write back sorted array
1110 function ADD_SELECTION ($type, $DEFAULT, $prefix="", $id="0") {
1111 global $MONTH_DESCR;
1114 if ($type == "yn") {
1115 // This is a yes/no selection only!
1116 if ($id > 0) $prefix .= "[".$id."]";
1117 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1119 // Begin with regular selection box here
1120 if (!empty($prefix)) $prefix .= "_";
1122 if ($id > 0) $type2 .= "[".$id."]";
1123 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1128 for ($idx = 1; $idx < 32; $idx++) {
1129 $OUT .= "<option value=\"".$idx."\"";
1130 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1131 $OUT .= ">".$idx."</option>\n";
1135 case "month": // Month
1136 foreach ($MONTH_DESCR as $month => $descr) {
1137 $OUT .= "<option value=\"".$month."\"";
1138 if ($DEFAULT == $month) $OUT .= " selected=\"selected\"";
1139 $OUT .= ">".$descr."</option>\n";
1143 case "year": // Year
1145 $YEAR = date('Y', time());
1147 // Use configured min age or fixed?
1148 if (GET_EXT_VERSION("other") >= "0.2.1") {
1150 $startYear = $YEAR - getConfig('min_age');
1153 $startYear = $YEAR - 16;
1156 // Calculate earliest year (100 years old people can still enter Internet???)
1157 $minYear = $YEAR - 100;
1159 // Check if the default value is larger than minimum and bigger than actual year
1160 if (($DEFAULT > $minYear) && ($DEFAULT >= $YEAR)) {
1161 for ($idx = $YEAR; $idx < ($YEAR + 11); $idx++) {
1162 $OUT .= "<option value=\"".$idx."\"";
1163 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1164 $OUT .= ">".$idx."</option>\n";
1166 } elseif ($DEFAULT == -1) {
1167 // Current year minus 1
1168 for ($idx = $startYear; $idx <= ($YEAR + 1); $idx++)
1170 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1173 // Get current year and subtract the configured minimum age
1174 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1175 // Calculate earliest year depending on extension version
1176 if (GET_EXT_VERSION("other") >= "0.2.1") {
1177 // Use configured minimum age
1178 $YEAR = date('Y', time()) - getConfig('min_age');
1180 // Use fixed 16 years age
1181 $YEAR = date('Y', time()) - 16;
1184 // Construct year selection list
1185 for ($idx = $minYear; $idx <= $YEAR; $idx++) {
1186 $OUT .= "<option value=\"".$idx."\"";
1187 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1188 $OUT .= ">".$idx."</option>\n";
1195 for ($idx = 0; $idx < 60; $idx+=5) {
1196 if (strlen($idx) == 1) $idx = "0".$idx;
1197 $OUT .= "<option value=\"".$idx."\"";
1198 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1199 $OUT .= ">".$idx."</option>\n";
1204 for ($idx = 0; $idx < 24; $idx++) {
1205 if (strlen($idx) == 1) $idx = "0".$idx;
1206 $OUT .= "<option value=\"".$idx."\"";
1207 if ($DEFAULT == $idx) $OUT .= " selected=\"selected\"";
1208 $OUT .= ">".$idx."</option>\n";
1213 $OUT .= "<option value=\"Y\"";
1214 if ($DEFAULT == "Y") $OUT .= " selected=\"selected\"";
1215 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1216 if ($DEFAULT == "N") $OUT .= " selected=\"selected\"";
1217 $OUT .= ">{--NO--}</option>\n";
1220 $OUT .= " </select>\n";
1225 function TRANSLATE_YESNO ($yn) {
1227 $translated = "??? (".$yn.")";
1229 case "Y": $translated = getMessage('YES'); break;
1230 case "N": $translated = getMessage('NO'); break;
1232 // Log unknown value
1233 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
1242 // Deprecated : $length
1245 function generateRandomCodde ($length, $code, $uid, $DATA="") {
1246 // Fix missing _MAX constant
1247 // @TODO Rewrite this unnice code
1248 if (!defined('_MAX')) define('_MAX', 15235);
1250 // Build server string
1251 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
1254 $keys = constant('SITE_KEY').":".constant('DATE_KEY');
1255 if (isConfigEntrySet('secret_key')) $keys .= ":".getConfig('secret_key');
1256 if (isConfigEntrySet('file_hash')) $keys .= ":".getConfig('file_hash');
1257 $keys .= ":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1258 if (isConfigEntrySet('master_salt')) $keys .= ":".getConfig('master_salt');
1260 // Build string from misc data
1261 $data = $code.":".$uid.":".$DATA;
1263 // Add more additional data
1264 if (isSessionVariableSet('u_hash')) $data .= ":".get_session('u_hash');
1265 if (isset($GLOBALS['userid'])) $data .= ":".$GLOBALS['userid'];
1266 if (isSessionVariableSet('mxchange_theme')) $data .= ":".get_session('mxchange_theme');
1267 if (isSessionVariableSet('mx_lang')) $data .= ":".GET_LANGUAGE();
1268 if (isset($GLOBALS['refid'])) $data .= ":".$GLOBALS['refid'];
1270 // Calculate number for generating the code
1271 $a = $code + constant('_ADD') - 1;
1273 if (isConfigEntrySet('master_hash')) {
1274 // Generate hash with master salt from modula of number with the prime number and other data
1275 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, getConfig('master_salt'));
1277 // Create number from hash
1278 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1280 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1281 $saltedHash = generateHash(($a % constant('_PRIME')).":".$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1283 // Create number from hash
1284 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1287 // At least 10 numbers shall be secure enought!
1288 $len = getConfig('code_length');
1289 if ($len == 0) $len = $length;
1290 if ($len == 0) $len = 10;
1292 // Cut off requested counts of number
1293 $return = substr(str_replace('.', "", $rcode), 0, $len);
1295 // Done building code
1299 // Does only allow numbers
1300 function bigintval ($num, $castValue = true) {
1301 // Filter all numbers out
1302 $ret = preg_replace("/[^0123456789]/", "", $num);
1305 if ($castValue) $ret = (double)$ret;
1307 // Has the whole value changed?
1308 // @TODO Remove this if() block if all is working fine
1309 if ("".$ret."" != "".$num."") {
1311 debug_report_bug("{$ret}<>{$num}");
1318 // Insert the code in $img_code into jpeg or PNG image
1319 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1320 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1321 // Stop execution of function here because of over-sized code length
1323 } elseif (!$headerSent) {
1324 // Return in an HTML code code
1325 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1329 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), GET_CURR_THEME(), getConfig('img_type'));
1330 if (FILE_READABLE($img)) {
1331 // Switch image type
1332 switch (getConfig('img_type'))
1335 // Okay, load image and hide all errors
1336 $image = @imagecreatefromjpeg($img);
1340 // Okay, load image and hide all errors
1341 $image = @imagecreatefrompng($img);
1345 // Exit function here
1346 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1350 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1351 $text_color = imagecolorallocate($image, 0, 0, 0);
1353 // Insert code into image
1354 imagestring($image, 5, 14, 2, $img_code, $text_color);
1356 // Return to browser
1357 header ("Content-Type: image/".getConfig('img_type'));
1359 // Output image with matching image factory
1360 switch (getConfig('img_type')) {
1361 case "jpg": imagejpeg($image); break;
1362 case "png": imagepng($image); break;
1365 // Remove image from memory
1366 imagedestroy($image);
1368 // Create selection box or array of splitted timestamp
1369 function CREATE_TIME_SELECTIONS ($timestamp, $prefix="", $display="", $align="center", $return_array=false) {
1370 // Calculate 2-seconds timestamp
1371 $stamp = round($timestamp);
1372 //* DEBUG: */ print("*".$stamp."/".$timestamp."*<br />");
1374 // Do we have a leap year?
1376 $TEST = date('Y', time()) / 4;
1377 $M1 = date("m", time());
1378 $M2 = date("m", (time() + $timestamp));
1380 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1381 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1383 // First of all years...
1384 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1385 //* DEBUG: */ print("Y={$Y}<br />\n");
1387 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1388 //* DEBUG: */ print("M={$M}<br />\n");
1390 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1391 //* DEBUG: */ print("W={$W}<br />\n");
1393 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1394 //* DEBUG: */ print("D={$D}<br />\n");
1396 $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));
1397 //* DEBUG: */ print("h={$h}<br />\n");
1399 $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));
1400 //* DEBUG: */ print("m={$m}<br />\n");
1401 // And at last seconds...
1402 $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));
1403 //* DEBUG: */ print("s={$s}<br />\n");
1405 // Is seconds zero and time is < 60 seconds?
1406 if (($s == 0) && ($timestamp < 60)) {
1408 $s = round($timestamp);
1412 // Now we convert them in seconds...
1414 if ($return_array) {
1415 // Just put all data in an array for later use
1427 $OUT = "<div align=\"".$align."\">\n";
1428 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1431 if (ereg('Y', $display) || (empty($display))) {
1432 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1435 if (ereg("M", $display) || (empty($display))) {
1436 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1439 if (ereg("W", $display) || (empty($display))) {
1440 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1443 if (ereg("D", $display) || (empty($display))) {
1444 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1447 if (ereg("h", $display) || (empty($display))) {
1448 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1451 if (ereg("m", $display) || (empty($display))) {
1452 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1455 if (ereg("s", $display) || (empty($display))) {
1456 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1462 if (ereg('Y', $display) || (empty($display))) {
1463 // Generate year selection
1464 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1465 for ($idx = 0; $idx <= 10; $idx++) {
1466 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1467 if ($idx == $Y) $OUT .= " selected=\"selected\"";
1468 $OUT .= ">".$idx."</option>\n";
1470 $OUT .= " </select></td>\n";
1472 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1475 if (ereg("M", $display) || (empty($display))) {
1476 // Generate month selection
1477 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1478 for ($idx = 0; $idx <= 11; $idx++)
1480 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $M) $OUT .= " selected=\"selected\"";
1482 $OUT .= ">".$idx."</option>\n";
1484 $OUT .= " </select></td>\n";
1486 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1489 if (ereg("W", $display) || (empty($display))) {
1490 // Generate week selection
1491 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1492 for ($idx = 0; $idx <= 4; $idx++) {
1493 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1494 if ($idx == $W) $OUT .= " selected=\"selected\"";
1495 $OUT .= ">".$idx."</option>\n";
1497 $OUT .= " </select></td>\n";
1499 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1502 if (ereg("D", $display) || (empty($display))) {
1503 // Generate day selection
1504 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1505 for ($idx = 0; $idx <= 31; $idx++) {
1506 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1507 if ($idx == $D) $OUT .= " selected=\"selected\"";
1508 $OUT .= ">".$idx."</option>\n";
1510 $OUT .= " </select></td>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1515 if (ereg("h", $display) || (empty($display))) {
1516 // Generate hour selection
1517 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1518 for ($idx = 0; $idx <= 23; $idx++) {
1519 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1520 if ($idx == $h) $OUT .= " selected=\"selected\"";
1521 $OUT .= ">".$idx."</option>\n";
1523 $OUT .= " </select></td>\n";
1525 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1528 if (ereg("m", $display) || (empty($display))) {
1529 // Generate minute selection
1530 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1531 for ($idx = 0; $idx <= 59; $idx++) {
1532 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1533 if ($idx == $m) $OUT .= " selected=\"selected\"";
1534 $OUT .= ">".$idx."</option>\n";
1536 $OUT .= " </select></td>\n";
1538 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1541 if (ereg("s", $display) || (empty($display))) {
1542 // Generate second selection
1543 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1544 for ($idx = 0; $idx <= 59; $idx++) {
1545 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1546 if ($idx == $s) $OUT .= " selected=\"selected\"";
1547 $OUT .= ">".$idx."</option>\n";
1549 $OUT .= " </select></td>\n";
1551 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1554 $OUT .= "</table>\n";
1556 // Return generated HTML code
1562 function CREATE_TIMESTAMP_FROM_SELECTIONS ($prefix, $POST) {
1563 // Initial return value
1566 // Do we have a leap year?
1568 $TEST = date('Y', time()) / 4;
1569 $M1 = date("m", time());
1570 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1571 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1572 // First add years...
1573 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1575 $ret += $POST[$prefix."_mo"] * 2628000;
1577 $ret += $POST[$prefix."_we"] * 604800;
1579 $ret += $POST[$prefix."_da"] * 86400;
1581 $ret += $POST[$prefix."_ho"] * 3600;
1583 $ret += $POST[$prefix."_mi"] * 60;
1584 // And at last seconds...
1585 $ret += $POST[$prefix."_se"];
1586 // Return calculated value
1590 // Sends out mail to all administrators
1591 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1592 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1593 // Trim template name
1594 $template = trim($template);
1596 // Load email template
1597 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1599 if (EXT_VERSION_IS_OLDER("admins", "0.4.0")) {
1600 // Older version detected!
1601 return SEND_ADMIN_EMAILS($subj, $msg);
1604 // Check which admin shall receive this mail
1605 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1606 array($template), __FUNCTION__, __LINE__);
1607 if (SQL_NUMROWS($result) == 0) {
1608 // Create new entry (to all admins)
1609 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1610 array($template), __FUNCTION__, __LINE__);
1612 // Load admin IDs...
1614 while (list($aid) = SQL_FETCHROW($result)) {
1619 SQL_FREERESULT($result);
1624 // "implode" IDs and query string
1625 $aid = implode(",", $aids);
1627 if (EXT_IS_ACTIVE("events")) {
1628 // Add line to user events
1629 EVENTS_ADD_LINE($subj, $msg, $UID);
1631 // Log error for debug
1632 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1638 } elseif ($aid == "0") {
1639 // Select all email adresses
1640 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`", __FUNCTION__, __LINE__);
1642 // If Admin-ID is not "to-all" select
1643 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`", array($aid), __FUNCTION__, __LINE__);
1647 // Load email addresses and send away
1648 while (list($email) = SQL_FETCHROW($result)) {
1649 SEND_EMAIL($email, $subj, $msg);
1653 SQL_FREERESULT($result);
1657 function CREATE_FANCY_TIME ($stamp) {
1658 // Get data array with years/months/weeks/days/...
1659 $data = CREATE_TIME_SELECTIONS($stamp, "", "", "", true);
1661 foreach($data as $k => $v) {
1663 // Value is greater than 0 "eval" data to return string
1664 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1670 // Do we have something there?
1671 if (strlen($ret) > 0) {
1672 // Remove leading commata and space
1673 $ret = substr($ret, 2);
1676 $ret = "0 {--_SECONDS--}";
1679 // Return fancy time string
1684 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1685 $SEP = ""; $TOP = "";
1688 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1692 for ($page = 1; $page <= $PAGES; $page++) {
1693 // Is the page currently selected or shall we generate a link to it?
1694 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1695 // Is currently selected, so only highlight it
1696 $NAV .= "<strong>-";
1698 // Open anchor tag and add base URL
1699 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1701 // Add userid when we shall show all mails from a single member
1702 if ((REQUEST_ISSET_GET(('uid'))) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1704 // Close open anchor tag
1708 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET(('page'))) && ($page == "1"))) {
1709 // Is currently selected, so only highlight it
1710 $NAV .= "-</strong>";
1716 // Add seperator if we have not yet reached total pages
1717 if ($page < $PAGES) $NAV .= " | ";
1720 // Define constants only once
1721 if (!defined('__NAV_OUTPUT')) {
1722 define('__NAV_OUTPUT' , $NAV);
1723 define('__NAV_COLSPAN', $colspan);
1724 define('__NAV_TOP' , $TOP);
1725 define('__NAV_SEP' , $SEP);
1728 // Load navigation template
1729 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1732 // Return generated HTML-Code
1740 // Extract host from script name
1741 function EXTRACT_HOST (&$script) {
1742 // Use default SERVER_URL by default... ;) So?
1743 $url = constant('SERVER_URL');
1745 // Is this URL valid?
1746 if (substr($script, 0, 7) == "http://") {
1747 // Use the hostname from script URL as new hostname
1748 $url = substr($script, 7);
1749 $extract = explode("/", $url);
1751 // Done extracting the URL :)
1754 // Extract host name
1755 $host = str_replace("http://", "", $url);
1756 if (ereg("/", $host)) $host = substr($host, 0, strpos($host, "/"));
1758 // Generate relative URL
1759 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1760 if (substr(strtolower($script), 0, 7) == "http://") {
1761 // But only if http:// is in front!
1762 $script = substr($script, (strlen($url) + 7));
1763 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1765 $script = substr($script, (strlen($url) + 8));
1768 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1769 if (substr($script, 0, 1) == "/") $script = substr($script, 1);
1775 // Send a GET request
1776 function GET_URL ($script) {
1777 // Compile the script name
1778 $script = COMPILE_CODE($script);
1780 // Extract host name from script
1781 $host = EXTRACT_HOST($script);
1783 // Generate GET request header
1784 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1785 $request .= "Host: " . $host . "\r\n";
1786 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1787 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1788 $request .= "Content-Type: text/plain\r\n";
1789 $request .= "Cache-Control: no-cache\r\n";
1790 $request .= "Connection: Close\r\n\r\n";
1792 // Send the raw request
1793 $response = SEND_RAW_REQUEST($host, $request);
1795 // Return the result to the caller function
1799 // Send a POST request
1800 function POST_URL ($script, $postData) {
1801 // Is postData an array?
1802 if (!is_array($postData)) {
1804 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1805 return array("", "", "");
1808 // Compile the script name
1809 $script = COMPILE_CODE($script);
1811 // Extract host name from script
1812 $host = EXTRACT_HOST($script);
1814 // Construct request
1815 $data = http_build_query($postData, '','&');
1817 // Generate POST request header
1818 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1819 $request .= "Host: " . $host . "\r\n";
1820 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1821 $request .= "User-Agent: " . constant('TITLE') . "/" . constant('FULL_VERSION') . "\r\n";
1822 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1823 $request .= "Content-length: " . strlen($data) . "\r\n";
1824 $request .= "Cache-Control: no-cache\r\n";
1825 $request .= "Connection: Close\r\n\r\n";
1828 // Send the raw request
1829 $response = SEND_RAW_REQUEST($host, $request);
1831 // Return the result to the caller function
1835 // Sends a raw request to another host
1836 function SEND_RAW_REQUEST ($host, $request) {
1838 $response = array("", "", "");
1840 // Default is not to use proxy
1843 // Are proxy settins set?
1844 if ((getConfig('proxy_host') != "") && (getConfig('proxy_port') > 0)) {
1850 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1852 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1854 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1858 if (!is_resource($fp)) {
1865 // Generate CONNECT request header
1866 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1867 $proxyTunnel .= "Host: ".$host."\r\n";
1869 // Use login data to proxy? (username at least!)
1870 if (getConfig('proxy_username') != "") {
1872 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).":".COMPILE_CODE(getConfig('proxy_password')));
1873 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1876 // Add last new-line
1877 $proxyTunnel .= "\r\n";
1878 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1881 fputs($fp, $proxyTunnel);
1885 // No response received
1889 // Read the first line
1890 $resp = trim(fgets($fp, 10240));
1891 $respArray = explode(" ", $resp);
1892 if ((strtolower($respArray[0]) !== "http/1.0") || ($respArray[1] != "200")) {
1893 // Invalid response!
1899 fputs($fp, $request);
1903 $response[] = trim(fgets($fp, 1024));
1909 // Skip first empty lines
1911 foreach ($resp as $idx => $line) {
1913 $line = trim($line);
1915 // Is this line empty?
1918 array_shift($response);
1920 // Abort on first non-empty line
1925 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1927 // Proxy agent found?
1928 if ((substr(strtolower($response[0]), 0, 11) == "proxy-agent") && ($useProxy)) {
1929 // Proxy header detected, so remove two lines
1930 array_shift($response);
1931 array_shift($response);
1934 // Was the request successfull?
1935 if ((!eregi("200 OK", $response[0])) || (empty($response[0]))) {
1936 // Not found / access forbidden
1937 $response = array("", "", "");
1944 // Taken from www.php.net eregi() user comments
1945 function VALIDATE_EMAIL($email) {
1947 $email = COMPILE_CODE($email);
1949 // Check first part of email address
1950 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1953 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1956 $regex = "^".$first."@".$domain."$";
1958 // Return check result
1959 return eregi($regex, $email);
1962 // Function taken from user comments on www.php.net / function eregi()
1963 function VALIDATE_URL ($URL, $compile=true) {
1964 // Trim URL a little
1965 $URL = trim(urldecode($URL));
1966 //* DEBUG: */ echo $URL."<br />";
1968 // Compile some chars out...
1969 if ($compile) $URL = compileUriCode($URL, false, false, false);
1970 //* DEBUG: */ echo $URL."<br />";
1972 // Check for the extension filter
1973 if (EXT_IS_ACTIVE("filter")) {
1974 // Use the extension's filter set
1975 return FILTER_VALIDATE_URL($URL, false);
1978 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1979 // https:// in front of the URLs
1980 return isUrlValid($URL);
1983 // Generate a list of administrative links to a given userid
1984 function MEMBER_ACTION_LINKS ($uid, $status = "") {
1985 // Define all main targets
1986 $TARGETS = array("del_user", "edit_user", "lock_user", "add_points", "sub_points");
1988 // Begin of navigation links
1989 $eval = "\$OUT = \"[ ";
1991 foreach ($TARGETS as $tar) {
1992 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1993 //* DEBUG: */ echo "*".$tar."/".$status."*<br />\n";
1994 if (($tar == "lock_user") && ($status == "LOCKED")) {
1995 // Locked accounts shall be unlocked
1996 $eval .= "UNLOCK_USER";
1998 // All other status is fine
1999 $eval .= strtoupper($tar);
2001 $eval .= "_TITLE--}\\\">{--ADMIN_";
2002 if (($tar == "lock_user") && ($status == "LOCKED")) {
2003 // Locked accounts shall be unlocked
2004 $eval .= "UNLOCK_USER";
2006 // All other status is fine
2007 $eval .= strtoupper($tar);
2009 $eval .= "--}</a></span> | ";
2012 // Finish navigation link
2013 $eval = substr($eval, 0, -7)."]\";";
2020 // Generate an email link
2021 function CREATE_EMAIL_LINK ($email, $table = "admins") {
2022 // Default email link (INSECURE! Spammer can read this by harvester programs)
2023 $EMAIL = "mailto:".$email;
2025 // Check for several extensions
2026 if ((EXT_IS_ACTIVE("admins")) && ($table == "admins")) {
2027 // Create email link for contacting admin in guest area
2028 $EMAIL = ADMINS_CREATE_EMAIL_LINK($email);
2029 } elseif ((EXT_IS_ACTIVE("user")) && (GET_EXT_VERSION("user") >= "0.3.3") && ($table == "user_data")) {
2030 // Create email link for contacting a member within admin area (or later in other areas, too?)
2031 $EMAIL = USER_CREATE_EMAIL_LINK($email);
2032 } elseif ((EXT_IS_ACTIVE("sponsor")) && ($table == "sponsor_data")) {
2033 // Create email link to contact sponsor within admin area (or like the link above?)
2034 $EMAIL = SPONSOR_CREATE_EMAIL_LINK($email);
2037 // Shall I close the link when there is no admin?
2038 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = "#"; // Closed!
2040 // Return email link
2044 // Generate a hash for extra-security for all passwords
2045 function generateHash ($plainText, $salt = "") {
2048 // Is the required extension "sql_patches" there and a salt is not given?
2049 if (((EXT_VERSION_IS_OLDER("sql_patches", "0.3.6")) || (!EXT_IS_ACTIVE("sql_patches"))) && (empty($salt))) {
2050 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2051 return md5($plainText);
2054 // Do we miss an arry element here?
2055 if (!isConfigEntrySet('file_hash')) {
2057 debug_report_bug("Missing file_hash in ".__FUNCTION__.".");
2060 // When the salt is empty build a new one, else use the first x configured characters as the salt
2062 // Build server string
2063 $server = $_SERVER['PHP_SELF'].":".GET_USER_AGENT().":".getenv('SERVER_SOFTWARE').":".GET_REMOTE_ADDR().":".":".filemtime(constant('PATH')."inc/databases.php");
2066 $keys = constant('SITE_KEY').":".constant('DATE_KEY').":".getConfig('secret_key').":".getConfig('file_hash').":".date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).":".getConfig('master_salt');
2069 $data = $plainText.":".uniqid(mt_rand(), true).":".time();
2071 // Calculate number for generating the code
2072 $a = time() + constant('_ADD') - 1;
2074 // Generate SHA1 sum from modula of number and the prime number
2075 $sha1 = sha1(($a % constant('_PRIME')).$server.":".$keys.":".$data.":".date("d-m-Y (l-F-T)", time()).":".$a);
2076 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2077 $sha1 = scrambleString($sha1);
2078 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2079 //* DEBUG: */ $sha1b = descrambleString($sha1);
2080 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2082 // Generate the password salt string
2083 $salt = substr($sha1, 0, getConfig('salt_length'));
2084 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2087 $salt = substr($salt, 0, getConfig('salt_length'));
2088 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2092 return $salt.sha1($salt.$plainText);
2095 // Scramble a string
2096 function scrambleString($str) {
2100 // Final check, in case of failture it will return unscrambled string
2101 if (strlen($str) > 40) {
2102 // The string is to long
2104 } elseif (strlen($str) == 40) {
2106 $scrambleNums = explode(":", getConfig('pass_scramble'));
2108 // Generate new numbers
2109 $scrambleNums = explode(":", genScrambleString(strlen($str)));
2112 // Scramble string here
2113 //* DEBUG: */ echo "***Original=".$str."***<br />";
2114 for ($idx = 0; $idx < strlen($str); $idx++) {
2115 // Get char on scrambled position
2116 $char = substr($str, $scrambleNums[$idx], 1);
2118 // Add it to final output string
2119 $scrambled .= $char;
2122 // Return scrambled string
2123 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2127 // De-scramble a string scrambled by scrambleString()
2128 function descrambleString($str) {
2129 // Scramble only 40 chars long strings
2130 if (strlen($str) != 40) return $str;
2132 // Load numbers from config
2133 $scrambleNums = explode(":", getConfig('pass_scramble'));
2136 if (count($scrambleNums) != 40) return $str;
2138 // Begin descrambling
2139 $orig = str_repeat(" ", 40);
2140 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2141 for ($idx = 0; $idx < 40; $idx++) {
2142 $char = substr($str, $idx, 1);
2143 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2146 // Return scrambled string
2147 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2151 // Generated a "string" for scrambling
2152 function genScrambleString ($len) {
2153 // Prepare array for the numbers
2154 $scrambleNumbers = array();
2156 // First we need to setup randomized numbers from 0 to 31
2157 for ($idx = 0; $idx < $len; $idx++) {
2159 $rand = mt_rand(0, ($len -1));
2161 // Check for it by creating more numbers
2162 while (array_key_exists($rand, $scrambleNumbers)) {
2163 $rand = mt_rand(0, ($len -1));
2167 $scrambleNumbers[$rand] = $rand;
2170 // So let's create the string for storing it in database
2171 $scrambleString = implode(":", $scrambleNumbers);
2172 return $scrambleString;
2175 // Append data like session ID or referal ID to the given URL which would
2176 // normally be stored in cookies
2177 function ADD_URL_DATA ($URL) {
2181 // Determine URL binder
2183 if (strpos($URL, "?") !== false) $BIND = "&";
2185 if ((!defined('__COOKIES')) || ((!__COOKIES))) {
2186 // Cookies are not accepted
2187 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2188 // Cookie found in URL
2189 $ADD .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2190 } elseif ((GET_EXT_VERSION("sql_patches") != '') && (getConfig('def_refid') > 0)) {
2191 // Not found! So let's set default here
2192 $ADD .= $BIND."refid=".getConfig('def_refid');
2196 // Add all together and return it
2200 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2201 function generatePassString ($passHash) {
2202 // Return vanilla password hash
2205 // Is a secret key and master salt already initialized?
2206 if ((getConfig('secret_key') != "") && (getConfig('master_salt') != "")) {
2207 // Only calculate when the secret key is generated
2208 $newHash = ""; $start = 9;
2209 for ($idx = 0; $idx < 10; $idx++) {
2210 $part1 = hexdec(substr($passHash, $start, 4));
2211 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2212 $mod = dechex($idx);
2213 if ($part1 > $part2) {
2214 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2215 } elseif ($part2 > $part1) {
2216 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2218 $mod = substr(round($mod), 0, 4);
2219 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2220 //* DEBUG: */ echo "*".$start."=".$mod."*<br />";
2225 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2226 $ret = generateHash($newHash, getConfig('master_salt'));
2227 //* DEBUG: */ print($ret."<br />\n");
2230 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2231 $ret = md5($passHash);
2232 //* DEBUG: */ echo "++".$ret."++<br />\n";
2239 // Fix "deleted" cookies
2240 function FIX_DELETED_COOKIES ($cookies) {
2241 // Is this an array with entries?
2242 if ((is_array($cookies)) && (count($cookies) > 0)) {
2243 // Then check all cookies if they are marked as deleted!
2244 foreach ($cookies as $cookieName) {
2245 // Is the cookie set to "deleted"?
2246 if (get_session($cookieName) == "deleted") {
2247 set_session($cookieName, "");
2253 // Output error messages in a fasioned way and die...
2254 function mxchange_die ($msg) {
2256 LOAD_INC_ONCE("inc/header.php");
2258 // Load the message template
2259 LOAD_TEMPLATE("admin_settings_saved", false, $msg);
2262 LOAD_INC_ONCE("inc/footer.php");
2268 // Display parsing time and number of SQL queries in footer
2269 function DISPLAY_PARSING_TIME_FOOTER() {
2270 // Is the timer started?
2271 if (!isset($GLOBALS['startTime'])) {
2277 $endTime = microtime(true);
2279 // "Explode" both times
2280 $start = explode(" ", $GLOBALS['startTime']);
2281 $end = explode(" ", $endTime);
2282 $runTime = $end[0] - $start[0];
2283 if ($runTime < 0) $runTime = 0;
2284 $runTime = TRANSLATE_COMMA($runTime);
2288 'runtime' => $runTime,
2289 'numSQLs' => (getConfig('sql_count') + 1),
2290 'numTemplates' => (getConfig('num_templates') + 1)
2293 // Load the template
2294 LOAD_TEMPLATE("show_timings", false, $content);
2297 // Check wether a boolean constant is set
2298 // Taken from user comments in PHP documentation for function constant()
2299 function isBooleanConstantAndTrue ($constName) { // : Boolean
2300 // Failed by default
2304 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2306 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2307 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2310 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2311 if (defined($constName)) {
2313 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2314 $res = (constant($constName) === true);
2318 $GLOBALS['cache_array']['const'][$constName] = $res;
2320 //* DEBUG: */ var_dump($res);
2326 // Checks if a given apache module is loaded
2327 function IF_APACHE_MODULE_LOADED ($apacheModule) {
2328 // Check it and return result
2329 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2332 // "Getter" for language strings
2333 // @TODO Rewrite all language constants to this function.
2334 function getMessage ($messageId) {
2335 // Default is not found!
2336 $return = "!".$messageId."!";
2338 // Is the language string found?
2339 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2340 // Language array element found in small_letters
2341 $return = $GLOBALS['msg'][$messageId];
2342 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2343 // @DEPRECATED Language array element found in BIG_LETTERS
2344 $return = $GLOBALS['msg'][$messageId];
2345 } elseif (defined($messageId)) {
2346 // @DEPRECATED Deprecated constant found
2347 $return = constant($messageId);
2349 // Missing language constant
2350 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2353 // Return the string
2357 // Get current theme name
2358 function GET_CURR_THEME() {
2361 // The default theme is 'default'... ;-)
2364 // Load default theme if not empty from configuration
2365 if (getConfig('default_theme') != "") $ret = getConfig('default_theme');
2367 if (!isSessionVariableSet('mxchange_theme')) {
2368 // Set default theme
2369 set_session('mxchange_theme', $ret);
2370 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION("sql_patches") >= "0.1.4")) {
2371 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2372 // Get theme from cookie
2373 $ret = get_session('mxchange_theme');
2376 if (THEME_GET_ID($ret) == 0) {
2377 // Fix it to default
2380 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET(('theme'))) || (REQUEST_ISSET_POST(('theme'))))) {
2381 // Prepare FQFN for checking
2382 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET(('theme')));
2384 // Installation mode active
2385 if ((REQUEST_ISSET_GET(('theme'))) && (FILE_READABLE($theme))) {
2386 // Set cookie from URL data
2387 set_session('mxchange_theme', REQUEST_GET(('theme')));
2388 } elseif (FILE_READABLE(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2389 // Set cookie from posted data
2390 set_session('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2394 $ret = get_session('mxchange_theme');
2396 // Invalid design, reset cookie
2397 set_session('mxchange_theme', $ret);
2400 // Add (maybe) found theme.php file to inclusion list
2401 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE($ret));
2403 // Try to load the requested include file
2404 if (FILE_READABLE($theme)) $INC_POOL[] = $theme;
2406 // Return theme value
2410 // Get id from theme
2411 function THEME_GET_ID ($name) {
2412 // Is the extension "theme" installed?
2413 if (!EXT_IS_ACTIVE("theme")) {
2421 // Is the cache entry there?
2422 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2423 // Get the version from cache
2424 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2427 incrementConfigEntry('cache_hits');
2428 } elseif (GET_EXT_VERSION("cache") != "0.1.8") {
2429 // Check if current theme is already imported or not
2430 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2431 array($name), __FUNCTION__, __LINE__);
2434 if (SQL_NUMROWS($result) == 1) {
2436 list($id) = SQL_FETCHROW($result);
2440 SQL_FREERESULT($result);
2447 // Read a given file
2448 function READ_FILE ($FQFN, $sqlPrepare = false) {
2450 if (function_exists('file_get_contents')) {
2452 $content = file_get_contents($FQFN);
2454 // Fall-back to implode-file chain
2455 $content = implode("", file($FQFN));
2458 // Prepare SQL queries?
2459 if ($sqlPrepare === true) {
2460 // Remove some unwanted chars
2461 $content = str_replace("\r", "", $content);
2462 $content = str_replace("\n\n", "\n", $content);
2465 // Return the content
2469 // Writes content to a file
2470 function WRITE_FILE ($FQFN, $content) {
2471 // Is the file writeable?
2472 if ((FILE_READABLE($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2474 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2480 // By default all is failed...
2483 // Is the function there?
2484 if (function_exists('file_put_contents')) {
2485 // Write it directly
2486 $return = file_put_contents($FQFN, $content);
2488 // Write it with fopen
2489 $fp = fopen($FQFN, 'w') or mxchange_die("Cannot write file ".basename($FQFN)."!");
2490 fwrite($fp, $content);
2494 $return = chmod($FQFN, 0644);
2501 // Generates an error code from given account status
2502 function GEN_ERROR_CODE_FROM_ACCOUNT_STATUS ($status) {
2503 // Default error code if unknown account status
2504 $ERROR = constant('CODE_UNKNOWN_STATUS');
2506 // Generate constant name
2507 $constantName = sprintf("CODE_ID_%s", $status);
2509 // Is the constant there?
2510 if (defined($constantName)) {
2512 $ERROR = constant($constantName);
2515 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2518 // Return error code
2522 // Clears the output buffer. This function does *NOT* backup sent content.
2523 function clearOutputBuffer () {
2524 // Trigger an error on failure
2525 if (!ob_end_clean()) {
2527 debug_report_bug(__FUNCTION__.": Failed to clean output buffer.");
2531 // "Getter" for revision/version data
2532 function getActualVersion ($type = 0) {
2533 // By default nothing is new... ;-)
2536 // FQFN of revision file
2537 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2539 // Check for revision file
2540 if (!FILE_READABLE($FQFN)) {
2541 // Not found, so we need to create it
2544 // Revision file found
2545 $ins_vers = explode("\n", READ_FILE($FQFN));
2547 // Is the content valid?
2548 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$type])) || ($ins_vers[0]) == "new") {
2549 // File needs update!
2552 // Revision-File has valid Data and isn't 'new' so return the Rev-Number
2553 return trim($ins_vers[$type]);
2557 // Has it been updated?
2558 if ($new === true) {
2559 // No Revision-File or has no valid Data so read the Revision from the Server.
2560 $version = GET_URL("check-updates3.php");
2563 $akt_vers[] = trim($version[10]);
2564 $akt_vers[] = trim($version[9]);
2565 $akt_vers[] = trim($version[8]);
2568 WRITE_FILE($FQFN, implode("\n", $akt_vers));
2570 // Return requested content
2571 return trim($akt_vers[$type]);
2575 // Loads an include file and logs any missing files for debug purposes
2576 function LOAD_INC ($INC) {
2577 // Add the path. This is why we need a trailing slash in config.php
2578 $FQFN = constant('PATH') . $INC;
2580 // Is the include file there?
2581 if (!FILE_READABLE($FQFN)) {
2582 // Not there so log it
2583 debug_report_bug(sprintf("Include file %s not found.", $INC));
2591 // Loads an include file once
2592 function LOAD_INC_ONCE ($INC) {
2593 // Is it not loaded?
2594 if (!isset($GLOBALS['load_once'][$INC])) {
2595 // Then try to load it
2598 // And mark it as loaded
2599 $GLOBALS['load_once'][$INC] = "loaded";
2603 // Back-ported from the new ship-simu engine. :-)
2604 function debug_get_printable_backtrace () {
2606 $backtrace = "<ol>\n";
2608 // Get and prepare backtrace for output
2609 $backtraceArray = debug_backtrace();
2610 foreach ($backtraceArray as $key => $trace) {
2611 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2612 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2613 if (!isset($trace['args'])) $trace['args'] = array();
2614 $backtrace .= "<li class=\"debug_list\"><span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span></li>\n";
2618 $backtrace .= "</ol>\n";
2620 // Return the backtrace
2624 // Output a debug backtrace to the user
2625 function debug_report_bug ($message = "") {
2628 // Is the optional message set?
2629 if (!empty($message)) {
2631 $debug = sprintf("Note: %s<br />\n",
2635 // @TODO Add a little more infos here
2636 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2640 $debug .= ("Please report this error at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>");
2641 $debug .= (debug_get_printable_backtrace());
2642 $debug .= ("</pre>Thank you for your help finding bugs.");
2648 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2649 function generateSeed () {
2650 list($usec, $sec) = explode(" ", microtime());
2651 return ((float)$sec + (float)$usec);
2654 // Converts a message code to a human-readable message
2655 function convertCodeToMessage ($code) {
2658 case constant('CODE_LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2659 case constant('CODE_LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2660 case constant('CODE_DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2661 case constant('CODE_POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2662 case constant('CODE_ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2663 case constant('CODE_USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2664 case constant('CODE_STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2665 case constant('CODE_ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2667 case constant('CODE_ERROR_MAILID'):
2668 if (EXT_IS_ACTIVE($ext, true)) {
2669 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2671 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "mailid");
2675 case constant('CODE_EXTENSION_PROBLEM'):
2676 if (REQUEST_ISSET_GET(('ext'))) {
2677 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2679 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2683 case constant('CODE_COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2684 case constant('CODE_BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2685 case constant('CODE_LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2686 default : $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code); break;
2689 // Return the message
2693 // Checks wether the given extension is currently not installed
2694 // and redirects if so.
2695 function REDIRCT_ON_UNINSTALLED_EXTENSION ($ext_name) {
2696 // Is the extension uninstalled/inactive?
2697 if (!EXT_IS_ACTIVE($ext_name)) {
2698 // Redirect to index
2699 LOAD_URL("modules.php?module=index&msg=".constant('CODE_EXTENSION_PROBLEM')."&ext=".$ext_name);
2703 // Generate a "link" for the given admin id (aid)
2704 function GENERATE_AID_LINK ($aid) {
2705 // No assigned admin is default
2706 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2708 // Zero? = Not assigned
2710 // Load admin's login
2711 $login = GET_ADMIN_LOGIN($aid);
2712 if ($login != "***") {
2713 // Is the extension there?
2714 if (EXT_IS_ACTIVE("admins")) {
2716 $admin = "<a href=\"".ADMINS_CREATE_EMAIL_LINK(GET_ADMIN_EMAIL($aid))."\">".$login."</a>";
2718 // Extension not found
2719 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), "admins");
2723 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2731 // Checks wether an include file (non-FQFN better) is readable
2732 function INCLUDE_READABLE ($INC) {
2734 $FQFN = constant('PATH') . $INC;
2737 return FILE_READABLE($FQFN);
2741 // @TODO Implement $compress
2742 function encodeString ($str, $compress=true) {
2743 $str = urlencode(base64_encode(compileUriCode($str)));
2747 // Decode strings encoded with encodeString()
2748 // @TODO Implement $decompress
2749 function decodeString ($str, $decompress=true) {
2750 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2754 // Compile characters which are allowed in URLs
2755 function compileUriCode ($code, $simple=true) {
2756 // Compile constants
2757 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2759 // Compile QUOT and other non-HTML codes
2760 $code = str_replace("{DOT}", ".",
2761 str_replace("{SLASH}", "/",
2762 str_replace("{QUOT}", "'",
2763 str_replace("{DOLLAR}", "$",
2764 str_replace("{OPEN_ANCHOR}", "(",
2765 str_replace("{CLOSE_ANCHOR}", ")",
2766 str_replace("{OPEN_SQR}", "[",
2767 str_replace("{CLOSE_SQR}", "]",
2768 str_replace("{PER}", "%",
2772 // Return compiled code
2776 // Function taken from user comments on www.php.net / function eregi()
2777 function isUrlValid ($url) {
2779 $url = strip_tags(str_replace("\\", "", compileUriCode(urldecode($url))));
2781 // Allows http and https
2782 $http = "(http|https)+(:\/\/)";
2784 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2785 // Test double-domains (e.g. .de.vu)
2786 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2788 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2790 $dir = "((/)+([-_\.[:alnum:]])+)*";
2792 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2793 // ... and the string after and including question character
2794 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2795 // Pattern for URLs like http://url/dir/doc.html?var=value
2796 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2797 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2798 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2799 // Pattern for URLs like http://url/dir/?var=value
2800 $pattern['d1dg1'] = $http.$domain1.$dir."/".$getstring1;
2801 $pattern['d2dg1'] = $http.$domain2.$dir."/".$getstring1;
2802 $pattern['ipdg1'] = $http.$ip.$dir."/".$getstring1;
2803 // Pattern for URLs like http://url/dir/page.ext
2804 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2805 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2806 $pattern['ipdp'] = $http.$ip.$dir.$page;
2807 // Pattern for URLs like http://url/dir
2808 $pattern['d1d'] = $http.$domain1.$dir;
2809 $pattern['d2d'] = $http.$domain2.$dir;
2810 $pattern['ipd'] = $http.$ip.$dir;
2811 // Pattern for URLs like http://url/?var=value
2812 $pattern['d1g1'] = $http.$domain1."/".$getstring1;
2813 $pattern['d2g1'] = $http.$domain2."/".$getstring1;
2814 $pattern['ipg1'] = $http.$ip."/".$getstring1;
2815 // Pattern for URLs like http://url?var=value
2816 $pattern['d1g12'] = $http.$domain1.$getstring1;
2817 $pattern['d2g12'] = $http.$domain2.$getstring1;
2818 $pattern['ipg12'] = $http.$ip.$getstring1;
2819 // Test all patterns
2821 foreach ($pattern as $key=>$pat) {
2823 if (defined('DEBUG_REGEX')) {
2824 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2825 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2826 $pat = str_replace("[:digit:]", "0-9", $pat);
2827 $pat = str_replace(".", "\.", $pat);
2828 $pat = str_replace("@", "\@", $pat);
2829 echo $key."= ".$pat."<br />";
2832 // Check if expression matches
2833 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2836 if ($reg === true) break;
2839 // Return true/false
2843 // Smartly adds slashes
2844 function smartAddSlashes ($unquoted) {
2845 $unquoted = str_replace("\\", "", $unquoted);
2846 return addslashes($unquoted);
2849 // Decode entities in a nicer way
2850 function decodeEntities ($str) {
2851 // @TODO We may want to switch over to UTF-8 here!
2852 $decodedString = html_entity_decode($str, ENT_NOQUOTES, "ISO-8859-15");
2854 // Return decoded string
2855 return $decodedString;
2858 // Wtites data to a config.php-style file
2859 // @TODO Rewrite this function to use READ_FILE() and WRITE_FILE()
2860 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2861 // Initialize some variables
2867 // Is the file there and read-/write-able?
2868 if ((FILE_READABLE($FQFN)) && (is_writeable($FQFN))) {
2869 $search = "CFG: ".$comment;
2870 $tmp = $FQFN.".tmp";
2872 // Open the source file
2873 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2875 // Is the resource valid?
2876 if (is_resource($fp)) {
2877 // Open temporary file
2878 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
2880 // Is the resource again valid?
2881 if (is_resource($fp_tmp)) {
2882 while (!feof($fp)) {
2883 // Read from source file
2884 $line = fgets ($fp, 1024);
2886 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2889 if ($next === $seek) {
2891 $line = $prefix . $DATA . $suffix."\n";
2897 // Write to temp file
2898 fputs($fp_tmp, $line);
2904 // Finished writing tmp file
2908 // Close source file
2911 if (($done) && ($found)) {
2912 // Copy back tmp file and delete tmp :-)
2914 return unlink($tmp);
2915 } elseif (!$found) {
2916 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
2918 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
2922 // File not found, not readable or writeable
2923 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
2926 // An error was detected!
2929 // Send notification to admin
2930 function SEND_ADMIN_NOTIFICATION($subject, $templateName, $content=array(), $uid="0") {
2931 if (GET_EXT_VERSION("admins") >= "0.4.1") {
2933 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2935 // Send outdated way
2936 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2937 SEND_ADMIN_EMAILS($subject, $msg);
2941 // Merges an array together but only if both are arrays
2942 function merge_array ($array1, $array2) {
2943 // Are both an array?
2944 if ((is_array($array1)) && (is_array($array2))) {
2945 // Merge all together
2946 return array_merge($array1, $array2);
2947 } elseif (is_array($array1)) {
2948 // Return left array
2949 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
2951 } elseif (is_array($array2)) {
2952 // Return right array
2953 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
2957 // Both are not arrays
2958 debug_report_bug(__FUNCTION__.": No arrays provided!");
2961 // Debug message logger
2962 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2963 // Is debug mode enabled?
2964 if ((isDebugModeEnabled()) || ($force === true)) {
2965 // Log this message away
2966 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or mxchange_die("Cannot write logfile debug.log!");
2967 fwrite($fp, date("d.m.Y|H:i:s", time())."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
2972 // Reads a directory with PHP files in and gets only files back
2973 function GET_DIR_AS_ARRAY ($baseDir, $prefix) {
2977 $dirPointer = opendir(constant('PATH') . $baseDir) or mxchange_die("Cannot read ".basename($baseDir)." path!");
2980 while ($baseFile = readdir($dirPointer)) {
2981 // Load file only if extension is active
2982 $INC = $baseDir.$baseFile;
2983 $FQFN = constant('PATH') . $INC;
2985 // Is this a valid reset file?
2986 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):baseDir={$baseDir},prefix={$prefix},baseFile={$baseFile}<br />\n";
2987 if ((FILE_READABLE($FQFN)) && (substr($baseFile, 0, strlen($prefix)) == $prefix) && (substr($baseFile, -4, 4) == ".php")) {
2988 // Remove both for extension name
2989 $extName = substr($baseFile, strlen($prefix), -4);
2992 $extId = GET_EXT_ID($extName);
2994 // Is the extension valid and active?
2995 if (($extId > 0) && (EXT_IS_ACTIVE($extName))) {
2996 // Then add this file
2998 } elseif ($extId == 0) {
2999 // Add non-extension files as well
3006 closedir($dirPointer);
3011 // Return array with include files
3015 // Load more reset scripts
3016 function runResetIncludes () {
3017 // Is the reset set or old sql_patches?
3018 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER("sql_patches", "0.4.5"))) {
3020 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3023 // Get more daily reset scripts
3024 $INC_POOL = GET_DIR_AS_ARRAY("inc/reset/", "reset_");
3027 if (!defined('DEBUG_RESET')) UPDATE_CONFIG("last_update", time());
3029 // Create current week mark
3030 $currWeek = date("W", time());
3033 if (getConfig('last_week') != $currWeek) {
3034 // Include weekly reset scripts
3035 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY("inc/weekly/", "weekly_"));
3038 if (!defined('DEBUG_WEEKLY')) UPDATE_CONFIG("last_week", $currWeek);
3041 // Create current month mark
3042 $currMonth = date("m", time());
3045 if (getConfig('last_month') != $currMonth) {
3046 // Include monthly reset scripts
3047 $INC_POOL = merge_array($INC_POOL, GET_DIR_AS_ARRAY("inc/monthly/", "monthly_"));
3050 if (!defined('DEBUG_MONTHLY')) UPDATE_CONFIG("last_month", $currMonth);
3054 runFilterChain('load_includes', $INC_POOL);
3057 // Handle extra values
3058 function HANDLE_EXTRA_VALUES ($filterFunction, $value, $extraValue) {
3059 // Default is the value itself
3062 // Do we have a special filter function?
3063 if (!empty($filterFunction)) {
3064 // Does the filter function exist?
3065 if (function_exists($filterFunction)) {
3066 // Do we have extra parameters here?
3067 if (!empty($extraValue)) {
3068 // Put both parameters in one new array by default
3069 $args = array($value, $extraValue);
3071 // If we have an array simply use it and pre-extend it with our value
3072 if (is_array($extraValue)) {
3073 // Make the new args array
3074 $args = merge_array(array($value), $extraValue);
3077 // Call the multi-parameter call-back
3078 $ret = call_user_func_array($filterFunction, $args);
3080 // One parameter call
3081 $ret = call_user_func($filterFunction, $value);
3090 // Check if given FQFN is a readable file
3091 function FILE_READABLE($fqfn) {
3093 return ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn)));
3096 // Converts timestamp selections into a timestamp
3097 function CONVERT_SELECTIONS_TO_TIMESTAMP(&$POST, &$DATA, &$id, &$skip) {
3098 // Init test variable
3101 // Get last three chars
3102 $test = substr($id, -3);
3104 // Improved way of checking! :-)
3105 if (in_array($test, array("_ye", "_mo", "_we", "_da", "_ho", "_mi", "_se"))) {
3106 // Found a multi-selection for timings?
3107 $test = substr($id, 0, -3);
3108 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)) {
3109 // Generate timestamp
3110 $POST[$test] = CREATE_TIMESTAMP_FROM_SELECTIONS($test, $POST);
3111 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3113 // Remove data from array
3114 foreach (array("ye", "mo", "we", "da", "ho", "mi", "se") as $rem) {
3115 unset($POST[$test."_".$rem]);
3119 unset($id); $skip = true; $test2 = $test;
3122 // Process this entry
3128 // Reverts the german decimal comma into Computer decimal dot
3129 function REVERT_COMMA ($str) {
3130 // Default float is not a float... ;-)
3133 // Which language is selected?
3134 switch (GET_LANGUAGE()) {
3135 case "de": // German language
3136 // Remove german thousand dots first
3137 $str = str_replace(".", "", $str);
3139 // Replace german commata with decimal dot and cast it
3140 $float = (float)str_replace(",", ".", $str);
3143 default: // US and so on
3144 // Remove thousand dots first and cast
3145 $float = (float)str_replace(",", "", $str);
3153 // Handle menu-depending failed logins and return the rendered content
3154 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3155 // Default output is empty ;-)
3158 // Is the session data set?
3159 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3160 // Ignore zero values
3161 if (get_session('mxchange_'.$accessLevel.'_failures') > 0) {
3162 // Non-guest has login failures found, get both data and prepare it for template
3163 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3165 'login_failures' => get_session('mxchange_'.$accessLevel.'_failures'),
3166 'last_failure' => MAKE_DATETIME(get_session('mxchange_'.$accessLevel.'_last_fail'), "2")
3170 $OUT = LOAD_TEMPLATE("login_failures", true, $content);
3173 // Reset session data
3174 set_session('mxchange_'.$accessLevel.'_failures', "");
3175 set_session('mxchange_'.$accessLevel.'_last_fail', "");
3178 // Return rendered content
3183 function rebuildCacheFiles ($cache, $inc="") {
3184 // Shall I remove the cache file?
3185 if ((EXT_IS_ACTIVE("cache")) && (isCacheInstanceValid())) {
3187 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3189 $GLOBALS['cache_instance']->destroyCacheFile();
3192 // Include file given?
3195 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3197 // Is the include there?
3198 if (INCLUDE_READABLE($INC)) {
3199 // And rebuild it from scratch
3200 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3203 // Include not found!
3204 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3210 // Purge admin menu cache
3211 function CACHE_PURGE_ADMIN_MENU ($id=0, $action="", $what="", $str="") {
3212 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3213 if (!EXT_IS_ACTIVE("cache")) {
3214 // Cache extension not active
3216 } elseif (!isCacheInstanceValid()) {
3217 // No cache instance!
3218 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3220 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != "Y")) {
3221 // Caching disabled (currently experiemental!)
3225 // Experiemental feature!
3226 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3229 // Translates the "pool type" into human-readable
3230 function TRANSLATE_POOL_TYPE ($type) {
3231 // Default type is unknown
3232 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
3234 // Generate constant
3235 $constName = sprintf("POOL_TYPE_%s", $type);
3238 if (defined($constName)) {
3240 $translated = getMessage($constName);
3243 // Return "translation"
3247 // "Getter" for remote IP number
3248 function GET_REMOTE_ADDR () {
3249 // Get remote ip from environment
3250 $remoteAddr = getenv('REMOTE_ADDR');
3252 // Is removeip installed?
3253 if (EXT_IS_ACTIVE("removeip")) {
3254 // Then anonymize it
3255 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3262 // "Getter" for remote hostname
3263 function GET_REMOTE_HOST () {
3264 // Get remote ip from environment
3265 $remoteHost = getenv('REMOTE_HOST');
3267 // Is removeip installed?
3268 if (EXT_IS_ACTIVE("removeip")) {
3269 // Then anonymize it
3270 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3277 // "Getter" for user agent
3278 function GET_USER_AGENT () {
3279 // Get remote ip from environment
3280 $userAgent = getenv('HTTP_USER_AGENT');
3282 // Is removeip installed?
3283 if (EXT_IS_ACTIVE("removeip")) {
3284 // Then anonymize it
3285 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3292 // "Getter" for referer
3293 function GET_REFERER () {
3294 // Get remote ip from environment
3295 $referer = getenv('HTTP_REFERER');
3297 // Is removeip installed?
3298 if (EXT_IS_ACTIVE("removeip")) {
3299 // Then anonymize it
3300 $referer = GET_ANONYMOUS_REFERER($referer);
3307 // Adds a bonus mail to the queue
3308 // This is a high-level function!
3309 function ADD_NEW_BONUS_MAIL ($data, $mode="", $output=true) {
3310 // Use mode from data if not set and availble ;-)
3311 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3313 // Generate receiver list
3314 $RECEIVER = GENERATE_RECEIVER_LIST($data['cat'], $data['receiver'], $mode);
3317 if (!empty($RECEIVER)) {
3318 // Add bonus mail to queue
3319 ADD_BONUS_MAIL_TO_QUEUE(
3331 // Mail inserted into bonus pool
3332 if ($output) LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_BONUS_SEND'));
3333 } elseif ($output) {
3334 // More entered than can be reached!
3335 LOAD_TEMPLATE("admin_settings_saved", false, getMessage('ADMIN_MORE_SELECTED'));
3338 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3342 // Determines referal id and sets it
3343 function DETERMINE_REFID () {
3344 global $CLICK, $_SERVER;
3346 // Check if refid is set
3347 if ((!empty($_GET['user'])) && ($CLICK == 1) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3348 // The variable user comes from the click-counter script click.php and we only accept this here
3349 $GLOBALS['refid'] = bigintval($_GET['user']);
3350 } elseif (!empty($_POST['refid'])) {
3351 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3352 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3353 } elseif (!empty($_GET['refid'])) {
3354 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3355 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3356 } elseif (!empty($_GET['ref'])) {
3357 // Set refid=ref (the referal link uses such variable)
3358 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3359 } elseif ((isSessionVariableSet('refid')) && (get_session('refid') != 0)) {
3360 // Set session refid als global
3361 $GLOBALS['refid'] = bigintval(get_session('refid'));
3362 } elseif ((GET_EXT_VERSION("sql_patches") != "") && (getConfig('def_refid') > 0)) {
3363 // Set default refid as refid in URL
3364 $GLOBALS['refid'] = getConfig(('def_refid'));
3365 } elseif ((GET_EXT_VERSION("user") >= "0.3.4") && (getConfig('select_user_zero_refid')) == "Y") {
3366 // Select a random user which has confirmed enougth mails
3367 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3369 // No default ID when sql_patches is not installed or none set
3370 $GLOBALS['refid'] = 0;
3373 // Set cookie when default refid > 0
3374 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((get_session('refid') == "0") && (getConfig('def_refid') > 0))) {
3376 set_session('refid', $GLOBALS['refid']);
3379 // Return determined refid
3380 return $GLOBALS['refid'];
3383 // Check wether we are installing
3384 function isInstalling () {
3385 return (isset($GLOBALS['mxchange_installing']));
3388 // Check wether this script is installed
3389 function isInstalled () {
3390 return isBooleanConstantAndTrue('mxchange_installed');
3393 // Check wether an admin is registered
3394 function isAdminRegistered () {
3395 return isBooleanConstantAndTrue('admin_registered');
3398 // Enables the reset mode. Only call this function if you really want the
3400 function enableResetMode () {
3401 // Enable the reset mode
3402 $GLOBALS['reset_enabled'] = true;
3405 runFilterChain('reset_enabled');
3408 // Checks wether the reset mode is active
3409 function isResetModeEnabled () {
3410 // Now simply check it
3411 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3414 // Checks wether the debug mode is enabled
3415 function isDebugModeEnabled () {
3417 return isBooleanConstantAndTrue('DEBUG_MODE');
3420 // Checks wether the cache instance is valid
3421 function isCacheInstanceValid () {
3422 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3425 //////////////////////////////////////////////////
3426 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3427 //////////////////////////////////////////////////
3429 if (!function_exists('html_entity_decode')) {
3430 // Taken from documentation on www.php.net
3431 function html_entity_decode ($string) {
3432 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3433 $trans_tbl = array_flip($trans_tbl);
3434 return strtr($string, $trans_tbl);