2 /************************************************************************
3 * MXChange v0.2.1 Start: 08/25/2003 *
4 * =============== Last change: 11/29/2005 *
6 * -------------------------------------------------------------------- *
7 * File : functions.php *
8 * -------------------------------------------------------------------- *
9 * Short description : Many non-MySQL functions (also file access) *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Viele Nicht-MySQL-Funktionen (auch Dateizugriff) *
12 * -------------------------------------------------------------------- *
15 * $Tag:: 0.2.1-FINAL $ *
17 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2008 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
44 // Output HTML code directly or 'render' it. You addionally switch the new-line character off
45 function OUTPUT_HTML ($HTML, $newLine = true) {
46 // Some global variables
49 // Do we have HTML-Code here?
51 // Yes, so we handle it as you have configured
52 switch (getConfig('OUTPUT_MODE'))
55 // That's why you don't need any \n at the end of your HTML code... :-)
56 if (constant('_OB_CACHING') == 'on') {
57 // Output into PHP's internal buffer
60 // That's why you don't need any \n at the end of your HTML code... :-)
61 if ($newLine) echo "\n";
63 // Render mode for old or lame servers...
66 // That's why you don't need any \n at the end of your HTML code... :-)
67 if ($newLine) $OUTPUT .= "\n";
72 // If we are switching from render to direct output rendered code
73 if ((!empty($OUTPUT)) && (constant('_OB_CACHING') != 'on')) { outputRawCode($OUTPUT); $OUTPUT = ''; }
75 // The same as above... ^
77 if ($newLine) echo "\n";
81 // Huh, something goes wrong or maybe you have edited config.php ???
82 app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
85 } elseif ((constant('_OB_CACHING') == 'on') && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
86 // Headers already sent?
89 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
91 // Trigger an user error
92 debug_report_bug("Headers are already sent!");
95 // Output cached HTML code
96 $OUTPUT = ob_get_contents();
98 // Clear output buffer for later output if output is found
99 if (!empty($OUTPUT)) {
104 sendHeader('HTTP/1.1 200');
107 $now = gmdate('D, d M Y H:i:s') . ' GMT';
109 // General headers for no caching
110 sendHeader('Expired: ' . $now); // RFC2616 - Section 14.21
111 sendHeader('Last-Modified: ' . $now);
112 sendHeader('Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0'); // HTTP/1.1
113 sendHeader('Pragma: no-cache'); // HTTP/1.0
114 sendHeader('Connection: Close');
116 // Extension 'rewrite' installed?
117 if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != '1') && ($GLOBALS['output_mode'] != '-1')) {
118 $OUTPUT = rewriteLinksInCode($OUTPUT);
121 // Compile and run finished rendered HTML code
122 while (strpos($OUTPUT, '{!') > 0) {
123 // Prepare the content and eval() it...
125 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
128 // Was that eval okay?
129 if (empty($newContent)) {
130 // Something went wrong!
131 app_die(__FUNCTION__, __LINE__, "Evaluation error:<pre>".htmlentities($eval)."</pre>");
133 $OUTPUT = $newContent;
136 // Output code here, DO NOT REMOVE! ;-)
137 outputRawCode($OUTPUT);
138 } elseif ((getConfig('OUTPUT_MODE') == 'render') && (!empty($OUTPUT))) {
139 // Rewrite links when rewrite extension is active
140 if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != '1') && ($GLOBALS['output_mode'] != '-1')) {
141 $OUTPUT = rewriteLinksInCode($OUTPUT);
144 // Compile and run finished rendered HTML code
145 while (strpos($OUTPUT, '{!') > 0) {
146 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
150 // Output code here, DO NOT REMOVE! ;-)
151 outputRawCode($OUTPUT);
155 // Output the raw HTML code
156 function outputRawCode ($HTML) {
157 // Output stripped HTML code to avoid broken JavaScript code, etc.
158 echo stripslashes(stripslashes($HTML));
160 // Flush the output if only constant('_OB_CACHING') is not 'on'
161 if (constant('_OB_CACHING') != 'on') {
167 // Init fatal message array
168 function initFatalMessages () {
169 $GLOBALS['fatal_messages'] = array();
172 // Getter for whole fatal error messages
173 function getFatalArray () {
174 return $GLOBALS['fatal_messages'];
177 // Add a fatal error message to the queue array
178 function addFatalMessage ($F, $L, $message, $extra='') {
179 if (is_array($extra)) {
180 // Multiple extras for a message with masks
181 $message = call_user_func_array('sprintf', $extra);
182 } elseif (!empty($extra)) {
183 // $message is text with a mask plus extras to insert into the text
184 $message = sprintf($message, $extra);
187 // Add message to $GLOBALS['fatal_messages']
188 $GLOBALS['fatal_messages'][] = $message;
190 // Log fatal messages away
191 DEBUG_LOG($F, $L, " message={$message}");
194 // Getter for total fatal message count
195 function getTotalFatalErrors () {
199 // Do we have at least the first entry?
200 if (!empty($GLOBALS['fatal_messages'][0])) {
202 $count = count($GLOBALS['fatal_messages']);
209 // Load a template file and return it's content (only it's name; do not use ' or ")
210 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
211 // Add more variables which you want to use in your template files
212 global $DATA, $username;
214 // Get whole config array
215 $_CONFIG = getConfigArray();
217 // Make all template names lowercase
218 $template = strtolower($template);
220 // Count the template load
221 incrementConfigEntry('num_templates');
223 // Prepare IP number and User Agent
224 $REMOTE_ADDR = detectRemoteAddr();
225 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
226 $HTTP_USER_AGENT = detectUserAgent();
230 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
232 // @DEPRECATED Try to rewrite the if() condition
233 if ($template == "member_support_form") {
234 // Support request of a member
235 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
236 array(getUserId()), __FUNCTION__, __LINE__);
238 // Is content an array?
239 if (is_array($content)) {
241 $content = merge_array($content, SQL_FETCHARRAY($result));
244 $content['gender'] = translateGender($content['gender']);
247 // @TODO Fine all templates which are using these direct variables and rewrite them.
248 // @TODO After this step is done, this else-block is history
249 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
252 $gender = translateGender($gender);
253 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
257 SQL_FREERESULT($result);
260 // Generate date/time string
261 $date_time = generateDateTime(time(), '1');
264 $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
267 // Check for admin/guest/member templates
268 if (strpos($template, "admin_") > -1) {
269 // Admin template found
271 } elseif (strpos($template, "guest_") > -1) {
272 // Guest template found
274 } elseif (strpos($template, "member_") > -1) {
275 // Member template found
277 } elseif (strpos($template, "install_") > -1) {
278 // Installation template found
280 } elseif (strpos($template, "ext_") > -1) {
281 // Extension template found
283 } elseif (strpos($template, "la_") > -1) {
284 // "Logical-area" template found
287 // Test for extension
288 $test = substr($template, 0, strpos($template, "_"));
289 if (EXT_IS_ACTIVE($test)) {
290 // Set extra path to extension's name
295 ////////////////////////
296 // Generate file name //
297 ////////////////////////
298 $FQFN = $basePath.$mode.$template.".tpl";
300 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($mode == "guest/") || ($mode == "member/") || ($mode == "admin/"))) {
301 // Select what depended header/footer template file for admin/guest/member area
302 $file2 = sprintf("%s%s%s_%s.tpl",
306 SQL_ESCAPE($GLOBALS['what'])
310 if (isFileReadable($file2)) $FQFN = $file2;
312 // Remove variable from memory
316 // Does the special template exists?
317 if (!isFileReadable($FQFN)) {
318 // Reset to default template
319 $FQFN = $basePath.$template.".tpl";
322 // Now does the final template exists?
323 if (isFileReadable($FQFN)) {
324 // The local file does exists so we load it. :)
325 $tmpl_file = readFromFile($FQFN);
327 // Replace ' to our own chars to preventing them being quoted
328 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
330 // Do we have to compile the code?
332 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
334 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
337 // Simply return loaded code
341 // Add surrounding HTML comments to help finding bugs faster
342 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
343 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
344 // Only admins shall see this warning or when installation mode is active
345 $ret = "<br /><span class=\"guest_failed\">{--TEMPLATE_404--}</span><br />
346 (".basename($FQFN).")<br />
348 {--TEMPLATE_CONTENT--}
349 <pre>".print_r($content, true)."</pre>
351 <pre>".print_r($DATA, true)."</pre>
355 // Remove content and data
359 // Do we have some content to output or return?
361 // Not empty so let's put it out! ;)
362 if ($return === true) {
363 // Return the HTML code
369 } elseif (isDebugModeEnabled()) {
370 // Warning, empty output!
371 return "E:".$template."<br />\n";
375 // Send mail out to an email address
376 function sendEmail($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
377 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
379 // Compile subject line (for POINTS constant etc.)
380 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
384 if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
385 // Value detected, is the message extension installed?
386 if (EXT_IS_ACTIVE("msg")) {
387 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
390 // Load email address
391 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
392 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
394 // Does the user exist?
395 if (SQL_NUMROWS($result_email)) {
396 // Load email address
397 list($toEmail) = SQL_FETCHROW($result_email);
400 $toEmail = constant('WEBMASTER');
404 SQL_FREERESULT($result_email);
406 } elseif ("$toEmail" == '0') {
408 $toEmail = constant('WEBMASTER');
410 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
412 // Check for PHPMailer or debug-mode
413 if (!checkPhpMailerUsage()) {
414 // Not in PHPMailer-Mode
415 if (empty($mailHeader)) {
416 // Load email header template
417 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
420 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
422 } elseif (isDebugModeEnabled()) {
423 if (empty($mailHeader)) {
424 // Load email header template
425 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
428 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
433 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
437 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
440 // Fix HTML parameter (default is no!)
441 if (empty($HTML)) $HTML = 'N';
442 if (isDebugModeEnabled()) {
443 // In debug mode we want to display the mail instead of sending it away so we can debug this part
445 ".htmlentities(trim($mailHeader))."
447 Subject : ".$subject."
448 Message : ".$message."
450 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
451 // Send mail as HTML away
452 sendHtmlEmail($toEmail, $subject, $message, $mailHeader);
453 } elseif (!empty($toEmail)) {
455 sendRawEmail($toEmail, $subject, $message, $mailHeader);
456 } elseif ($HTML == 'N') {
458 sendRawEmail(constant('WEBMASTER'), '[PROBLEM:]' . $subject, $message, $mailHeader);
462 // Check if legacy or PHPMailer command
463 // @TODO Rewrite this to an extension 'smtp'
465 function checkPhpMailerUsage() {
466 return ((getConfig('SMTP_HOSTNAME') != '') && (getConfig('SMTP_USER') != ''));
469 // Send out a raw email with PHPMailer class or legacy mail() command
470 function sendRawEmail ($toEmail, $subject, $msg, $from) {
471 // Shall we use PHPMailer class or legacy mode?
472 if (checkPhpMailerUsage()) {
473 // Use PHPMailer class with SMTP enabled
474 loadIncludeOnce('inc/phpmailer/class.phpmailer.php');
475 loadIncludeOnce('inc/phpmailer/class.smtp.php');
478 $mail = new PHPMailer();
479 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
482 $mail->SMTPAuth = true;
483 $mail->Host = getConfig('SMTP_HOSTNAME');
485 $mail->Username = getConfig('SMTP_USER');
486 $mail->Password = getConfig('SMTP_PASSWORD');
488 $mail->From = constant('WEBMASTER');
492 $mail->FromName = constant('MAIN_TITLE');
493 $mail->Subject = $subject;
494 if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($msg) != $msg)) {
496 $mail->AltBody = 'Your mail program required HTML support to read this mail!';
497 $mail->WordWrap = 70;
500 $mail->Body = decodeEntities($msg);
502 $mail->AddAddress($toEmail, '');
503 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
504 $mail->AddCustomHeader('Errors-To:' . constant('WEBMASTER'));
505 $mail->AddCustomHeader('X-Loop:' . constant('WEBMASTER'));
508 // Use legacy mail() command
509 @mail($toEmail, $subject, decodeEntities($msg), $from);
513 // Generate a password in a specified length or use default password length
514 function generatePassword ($LEN = 0) {
515 // Auto-fix invalid length of zero
516 if ($LEN == 0) $LEN = getConfig('pass_len');
518 // Initialize array with all allowed chars
519 $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,-,+,_,/');
521 // Start creating password
523 for ($i = 0; $i < $LEN; $i++) {
524 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
527 // When the size is below 40 we can also add additional security by scrambling
528 // it. Otherwise we may corrupt hashes
529 if (strlen($PASS) <= 40) {
530 // Also scramble the password
531 $PASS = scrambleString($PASS);
534 // Return the password
538 // Generates a human-readable timestamp from the Uni* stamp
539 function generateDateTime ($time, $mode = '0') {
540 // Filter out numbers
541 $time = bigintval($time);
543 // If the stamp is zero it mostly didn't "happen"
546 return getMessage('NEVER_HAPPENED');
549 switch (getLanguage())
551 case 'de': // German date / time format
553 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
554 case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
555 case '2': $ret = date("d.m.Y|H:i", $time); break;
556 case '3': $ret = date("d.m.Y", $time); break;
558 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
563 default: // Default is the US date / time format!
565 case '0': $ret = date("r", $time); break;
566 case '1': $ret = date("Y-m-d - g:i A", $time); break;
567 case '2': $ret = date("y-m-d|H:i", $time); break;
568 case '3': $ret = date("y-m-d", $time); break;
570 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
577 // Translates Y/N to yes/no
578 function translateYesNo ($yn) {
580 $translated = "??? (".$yn.')';
582 case 'Y': $translated = getMessage('YES'); break;
583 case 'N': $translated = getMessage('NO'); break;
586 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
594 // Translates the "pool type" into human-readable
595 function translatePoolType ($type) {
596 // Default?type is unknown
597 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
600 $constName = sprintf("POOL_TYPE_%s", $type);
603 if (defined($constName)) {
605 $translated = getMessage($constName);
608 // Return "translation"
612 // Translates the american decimal dot into a german comma
613 function translateComma ($dotted, $cut = true, $max = 0) {
614 // Default is 3 you can change this in admin area "Misc -> Misc Options"
615 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
617 // Use from config is default
618 $maxComma = getConfig('max_comma');
620 // Use from parameter?
621 if ($max > 0) $maxComma = $max;
624 if (($cut) && ($max == 0)) {
625 // Test for commata if in cut-mode
626 $com = explode('.', $dotted);
627 if (count($com) < 2) {
628 // Don't display commatas even if there are none... ;-)
634 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
637 switch (getLanguage()) {
639 $dotted = number_format($dotted, $maxComma, ',', '.');
643 $dotted = number_format($dotted, $maxComma, '.', ',');
647 // Return translated value
651 // Translate Uni*-like gender to human-readable
652 function translateGender ($gender) {
654 $ret = '!' . $gender . '!';
656 // Male/female or company?
658 case 'M': $ret = getMessage('GENDER_M'); break;
659 case 'F': $ret = getMessage('GENDER_F'); break;
660 case 'C': $ret = getMessage('GENDER_C'); break;
662 // Log unknown gender
663 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
667 // Return translated gender
671 // "Translates" the user status
672 function translateUserStatus ($status) {
678 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
683 $ret = getMessage('ACCOUNT_DELETED');
687 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
688 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
696 // Generates an URL for the dereferer
697 function DEREFERER ($URL) {
698 // Don't de-refer our own links!
699 if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
700 // De-refer this link
701 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
708 // Generates an URL for the frametester
709 function FRAMETESTER ($URL) {
710 // Prepare frametester URL
711 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
712 encodeString(compileUriCode($URL))
714 return $frametesterUrl;
717 // Count entries from e.g. a selection box
718 function countSelection ($array) {
720 if (is_array($array)) {
721 foreach ($array as $key => $selected) {
722 if (!empty($selected)) $ret++;
728 // Generate XHTML code for the CAPTCHA
729 function generateCaptchaCode ($code, $type, $DATA, $uid) {
730 return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
733 // "Getter" for language
734 function getLanguage () {
735 // Set default return value to default language from config
736 $ret = getConfig('DEFAULT_LANG');
741 // Is the variable set
742 if (REQUEST_ISSET_GET('mx_lang')) {
743 // Accept only first 2 chars
744 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
745 } elseif (isset($GLOBALS['cache_array']['language'])) {
747 $ret = $GLOBALS['cache_array']['language'];
748 } elseif (!empty($lang)) {
749 // Check if main language file does exist
750 if (isFileReadable(constant('PATH') . 'inc/language/'.$lang.'.php')) {
751 // Okay found, so let's update cookies
754 } elseif (isSessionVariableSet('mx_lang')) {
755 // Return stored value from cookie
756 $ret = getSession('mx_lang');
758 // Fixes a warning before the session has the mx_lang constant
759 if (empty($ret)) $ret = getConfig('DEFAULT_LANG');
763 $GLOBALS['cache_array']['language'] = $ret;
769 // "Setter" for language
770 function setLanguage ($lang) {
771 // Accept only first 2 chars!
772 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
775 setSession('mx_lang', $lang);
778 // Loads an email template and compiles it
779 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
780 global $DATA, $_CONFIG;
782 // Make sure all template names are lowercase!
783 $template = strtolower($template);
785 // Default 'nickname' if extension is not installed
788 // Prepare IP number and User Agent
789 $REMOTE_ADDR = detectRemoteAddr();
790 $HTTP_USER_AGENT = detectUserAgent();
793 $ADMIN = constant('MAIN_TITLE');
795 // Is the admin logged in?
798 $aid = getCurrentAdminId();
801 $ADMIN = getAdminEmail($aid);
804 // Neutral email address is default
805 $email = constant('WEBMASTER');
807 // Expiration in a nice output format
808 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
809 if (getConfig('auto_purge') == 0) {
810 // Will never expire!
811 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
813 // Create nice date string
814 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
817 // Is content an array?
818 if (is_array($content)) {
819 // Add expiration to array, $EXPIRATION is now deprecated!
820 $content['expiration'] = $EXPIRATION;
824 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
825 if (($UID > 0) && (is_array($content))) {
826 // If nickname extension is installed, fetch nickname as well
827 if (EXT_IS_ACTIVE('nickname')) {
828 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
830 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
831 array(bigintval($UID)), __FUNCTION__, __LINE__);
833 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
835 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
836 array(bigintval($UID)), __FUNCTION__, __LINE__);
839 // Fetch and merge data
840 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
841 $content = merge_array($content, SQL_FETCHARRAY($result));
842 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
845 SQL_FREERESULT($result);
848 // Translate M to male or F to female if present
849 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
851 // Overwrite email from data if present
852 if (isset($content['email'])) $email = $content['email'];
854 // Store email for some functions in global data array
855 $DATA['email'] = $email;
858 $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
860 // Check for admin/guest/member templates
861 if (strpos($template, 'admin_') > -1) {
862 // Admin template found
863 $FQFN = $basePath.'admin/'.$template.'.tpl';
864 } elseif (strpos($template, 'guest_') > -1) {
865 // Guest template found
866 $FQFN = $basePath.'guest/'.$template.'.tpl';
867 } elseif (strpos($template, 'member_') > -1) {
868 // Member template found
869 $FQFN = $basePath.'member/'.$template.'.tpl';
871 // Test for extension
872 $test = substr($template, 0, strpos($template, '_'));
873 if (EXT_IS_ACTIVE($test)) {
874 // Set extra path to extension's name
875 $FQFN = $basePath.$test.'/'.$template.'.tpl';
877 // No special filename
878 $FQFN = $basePath.$template.'.tpl';
882 // Does the special template exists?
883 if (!isFileReadable($FQFN)) {
884 // Reset to default template
885 $FQFN = $basePath.$template.'.tpl';
888 // Now does the final template exists?
890 if (isFileReadable($FQFN)) {
891 // The local file does exists so we load it. :)
892 $tmpl_file = readFromFile($FQFN);
893 $tmpl_file = SQL_ESCAPE($tmpl_file);
896 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
898 } elseif (!empty($template)) {
899 // Template file not found!
900 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
901 {--TEMPLATE_CONTENT--}
902 <pre>".print_r($content, true)."</pre>
904 <pre>".print_r($DATA, true)."</pre>
907 // Debug mode not active? Then remove the HTML tags
908 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
910 // No template name supplied!
911 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
914 // Is there some content?
915 if (empty($newContent)) {
917 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
918 // Add last error if the required function exists
919 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
922 // Remove content and data
926 // Return compiled content
927 return COMPILE_CODE($newContent);
930 // Generates a timestamp (some wrapper for mktime())
931 function makeTime ($H, $M, $S, $stamp) {
932 // Extract day, month and year from given timestamp
933 $day = date('d', $stamp);
934 $month = date('m', $stamp);
935 $year = date('Y', $stamp);
937 // Create timestamp for wished time which depends on extracted date
938 return mktime($H, $M, $S, $month, $day, $year);
941 // Redirects to an URL and if neccessarry extends it with own base URL
942 function redirectToUrl ($URL) {
943 // Compile out URI codes
944 $URL = compileUriCode($URL);
946 // Check if http(s):// is there
947 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
948 // Make all URLs full-qualified
949 $URL = constant('URL') . '/' . $URL;
952 // Three different debug ways...
953 /* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
954 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
955 //* DEBUG: */ die($URL);
957 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
958 $rel = ' rel="external"';
960 // Do we have internal or external URL?
961 if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
962 // Own (=internal) URL
967 $OUTPUT = ob_get_contents();
969 // Clear it only if there is content
970 if (!empty($OUTPUT)) {
974 // Secure the URL against bad things such als HTML insertions and so on...
975 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
977 // Simple probe for bots/spiders from search engines
978 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
979 // Output new location link as anchor
980 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
981 } elseif (!headers_sent()) {
982 // Load URL when headers are not sent
983 //* DEBUG: */ debug_report_bug("URL={$URL}");
984 sendHeader('Location: '.str_replace('&', '&', $URL));
986 // Output error message
987 loadInclude('inc/header.php');
988 LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
989 loadInclude('inc/footer.php');
992 // Shut the mailer down here
996 // Wrapper for redirectToUrl but URL comes from a configuration entry
997 function redirectToConfiguredUrl ($configEntry) {
999 $URL = getConfig($configEntry);
1002 if (is_null($URL)) {
1004 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
1008 redirectToUrl($URL);
1012 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
1013 // Is the code a string?
1014 if (!is_string($code)) {
1015 // Silently return it
1019 // Init replacement-array with full security characters
1020 $secChars = $GLOBALS['security_chars'];
1022 // Select smaller set of chars to replace when we e.g. want to compile URLs
1023 if (!$full) $secChars = $GLOBALS['url_chars'];
1025 // Compile constants
1026 if ($constants === true) {
1027 // BEFORE 0.2.1 : Language and data constants
1028 // WITH 0.2.1+ : Only language constants
1029 $code = str_replace('{--','".', str_replace('--}','."', $code));
1031 // BEFORE 0.2.1 : Not used
1032 // WITH 0.2.1+ : Data constants
1033 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1036 // Compile QUOT and other non-HTML codes
1037 foreach ($secChars['to'] as $k => $to) {
1038 // Do the reversed thing as in inc/libs/security_functions.php
1039 $code = str_replace($to, $secChars['from'][$k], $code);
1042 // But shall I keep simple quotes for later use?
1043 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1045 // Find $content[bla][blub] entries
1046 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1048 // Are some matches found?
1049 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1050 // Replace all matches
1051 $matchesFound = array();
1052 foreach ($matches[0] as $key => $match) {
1053 // Fuzzy look has failed by default
1054 $fuzzyFound = false;
1056 // Fuzzy look on match if already found
1057 foreach ($matchesFound as $found => $set) {
1059 $test = substr($found, 0, strlen($match));
1061 // Does this entry exist?
1062 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1063 if ($test == $match) {
1065 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1072 if ($fuzzyFound) continue;
1074 // Take all string elements
1075 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1076 // Replace it in the code
1077 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1078 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1079 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1080 $matchesFound[$key."_".$matches[4][$key]] = 1;
1081 $matchesFound[$match] = 1;
1082 } elseif (!isset($matchesFound[$match])) {
1083 // Not yet replaced!
1084 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1085 $code = str_replace($match, "\".".$match.".\"", $code);
1086 $matchesFound[$match] = 1;
1091 // Return compiled code
1095 /************************************************************************
1097 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1098 * $a_sort sortiert: *
1100 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1101 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1102 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1103 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1104 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1106 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1107 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1108 * Sie, dass es doch nicht so schwer ist! :-) *
1110 ************************************************************************/
1111 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1113 while ($primary_key < count($a_sort)) {
1114 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1115 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1118 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1119 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1120 } elseif ($key != $key2) {
1121 // Sort numbers (E.g.: 9 < 10)
1122 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1123 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1127 // We have found two different values, so let's sort whole array
1128 foreach ($dummy as $sort_key => $sort_val) {
1129 $t = $dummy[$sort_key][$key];
1130 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1131 $dummy[$sort_key][$key2] = $t;
1142 // Write back sorted array
1147 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1150 if ($type == 'yn') {
1151 // This is a yes/no selection only!
1152 if ($id > 0) $prefix .= "[".$id."]";
1153 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1155 // Begin with regular selection box here
1156 if (!empty($prefix)) $prefix .= "_";
1158 if ($id > 0) $type2 .= "[".$id."]";
1159 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1164 for ($idx = 1; $idx < 32; $idx++) {
1165 $OUT .= "<option value=\"".$idx."\"";
1166 if ($default == $idx) $OUT .= ' selected="selected"';
1167 $OUT .= ">".$idx."</option>\n";
1171 case "month": // Month
1172 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1173 $OUT .= "<option value=\"".$month."\"";
1174 if ($default == $month) $OUT .= ' selected="selected"';
1175 $OUT .= ">".$descr."</option>\n";
1179 case "year": // Year
1181 $year = date('Y', time());
1183 // Use configured min age or fixed?
1184 if (GET_EXT_VERSION('other') >= '0.2.1') {
1186 $startYear = $year - getConfig('min_age');
1189 $startYear = $year - 16;
1192 // Calculate earliest year (100 years old people can still enter Internet???)
1193 $minYear = $year - 100;
1195 // Check if the default value is larger than minimum and bigger than actual year
1196 if (($default > $minYear) && ($default >= $year)) {
1197 for ($idx = $year; $idx < ($year + 11); $idx++) {
1198 $OUT .= "<option value=\"".$idx."\"";
1199 if ($default == $idx) $OUT .= ' selected="selected"';
1200 $OUT .= ">".$idx."</option>\n";
1202 } elseif ($default == -1) {
1203 // Current year minus 1
1204 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1206 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1209 // Get current year and subtract the configured minimum age
1210 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1211 // Calculate earliest year depending on extension version
1212 if (GET_EXT_VERSION('other') >= '0.2.1') {
1213 // Use configured minimum age
1214 $year = date('Y', time()) - getConfig('min_age');
1216 // Use fixed 16 years age
1217 $year = date('Y', time()) - 16;
1220 // Construct year selection list
1221 for ($idx = $minYear; $idx <= $year; $idx++) {
1222 $OUT .= "<option value=\"".$idx."\"";
1223 if ($default == $idx) $OUT .= ' selected="selected"';
1224 $OUT .= ">".$idx."</option>\n";
1231 for ($idx = 0; $idx < 60; $idx+=5) {
1232 if (strlen($idx) == 1) $idx = '0'.$idx;
1233 $OUT .= "<option value=\"".$idx."\"";
1234 if ($default == $idx) $OUT .= ' selected="selected"';
1235 $OUT .= ">".$idx."</option>\n";
1240 for ($idx = 0; $idx < 24; $idx++) {
1241 if (strlen($idx) == 1) $idx = '0'.$idx;
1242 $OUT .= "<option value=\"".$idx."\"";
1243 if ($default == $idx) $OUT .= ' selected="selected"';
1244 $OUT .= ">".$idx."</option>\n";
1249 $OUT .= "<option value=\"Y\"";
1250 if ($default == 'Y') $OUT .= ' selected="selected"';
1251 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1252 if ($default == 'N') $OUT .= ' selected="selected"';
1253 $OUT .= ">{--NO--}</option>\n";
1256 $OUT .= " </select>\n";
1261 // Deprecated : $length
1264 function generateRandomCodde ($length, $code, $uid, $DATA = '') {
1265 // Fix missing _MAX constant
1266 // @TODO Rewrite this unnice code
1267 if (!defined('_MAX')) define('_MAX', 15235);
1269 // Build server string
1270 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
1273 $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
1274 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1275 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1276 $keys .= getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1277 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1279 // Build string from misc data
1280 $data = $code.getConfig('ENCRYPT_SEPERATOR').$uid.getConfig('ENCRYPT_SEPERATOR').$DATA;
1282 // Add more additional data
1283 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
1284 if (isUserIdSet()) $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
1285 if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1286 if (isSessionVariableSet('mx_lang')) $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
1287 if (isset($GLOBALS['refid'])) $data .= getConfig('ENCRYPT_SEPERATOR').$GLOBALS['refid'];
1289 // Calculate number for generating the code
1290 $a = $code + getConfig('_ADD') - 1;
1292 if (isConfigEntrySet('master_hash')) {
1293 // Generate hash with master salt from modula of number with the prime number and other data
1294 $saltedHash = generateHash(($a % getConfig('_PRIME')).getConfig('ENCRYPT_SEPERATOR').$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a, getConfig('master_salt'));
1296 // Create number from hash
1297 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1299 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1300 $saltedHash = generateHash(($a % getConfig('_PRIME')).getConfig('ENCRYPT_SEPERATOR').$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a, substr(sha1(getConfig('SITE_KEY')), 0, 8));
1302 // Create number from hash
1303 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1306 // At least 10 numbers shall be secure enought!
1307 $len = getConfig('code_length');
1308 if ($len == 0) $len = $length;
1309 if ($len == 0) $len = 10;
1311 // Cut off requested counts of number
1312 $return = substr(str_replace('.', '', $rcode), 0, $len);
1314 // Done building code
1318 // Does only allow numbers
1319 function bigintval ($num, $castValue = true) {
1320 // Filter all numbers out
1321 $ret = preg_replace("/[^0123456789]/", '', $num);
1324 if ($castValue) $ret = (double)$ret;
1326 // Has the whole value changed?
1327 // @TODO Remove this if() block if all is working fine
1328 if ("".$ret."" != ''.$num."") {
1330 debug_report_bug("{$ret}<>{$num}");
1337 // Insert the code in $img_code into jpeg or PNG image
1338 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1339 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1340 // Stop execution of function here because of over-sized code length
1342 } elseif (!$headerSent) {
1343 // Return in an HTML code code
1344 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1348 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
1349 if (isFileReadable($img)) {
1350 // Switch image type
1351 switch (getConfig('img_type'))
1354 // Okay, load image and hide all errors
1355 $image = @imagecreatefromjpeg($img);
1359 // Okay, load image and hide all errors
1360 $image = @imagecreatefrompng($img);
1364 // Exit function here
1365 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1369 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1370 $text_color = imagecolorallocate($image, 0, 0, 0);
1372 // Insert code into image
1373 imagestring($image, 5, 14, 2, $img_code, $text_color);
1375 // Return to browser
1376 sendHeader('Content-Type: image/' . getConfig('img_type'));
1378 // Output image with matching image factory
1379 switch (getConfig('img_type')) {
1380 case 'jpg': imagejpeg($image); break;
1381 case 'png': imagepng($image); break;
1384 // Remove image from memory
1385 imagedestroy($image);
1387 // Create selection box or array of splitted timestamp
1388 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1389 // Calculate 2-seconds timestamp
1390 $stamp = round($timestamp);
1391 //* DEBUG: */ print("*".$stamp.'/'.$timestamp."*<br />");
1393 // Do we have a leap year?
1395 $TEST = date('Y', time()) / 4;
1396 $M1 = date('m', time());
1397 $M2 = date('m', (time() + $timestamp));
1399 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1400 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1402 // First of all years...
1403 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1404 //* DEBUG: */ print("Y={$Y}<br />\n");
1406 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1407 //* DEBUG: */ print("M={$M}<br />\n");
1409 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1410 //* DEBUG: */ print("W={$W}<br />\n");
1412 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1413 //* DEBUG: */ print("D={$D}<br />\n");
1415 $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));
1416 //* DEBUG: */ print("h={$h}<br />\n");
1418 $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));
1419 //* DEBUG: */ print("m={$m}<br />\n");
1420 // And at last seconds...
1421 $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));
1422 //* DEBUG: */ print("s={$s}<br />\n");
1424 // Is seconds zero and time is < 60 seconds?
1425 if (($s == 0) && ($timestamp < 60)) {
1427 $s = round($timestamp);
1431 // Now we convert them in seconds...
1433 if ($return_array) {
1434 // Just put all data in an array for later use
1446 $OUT = "<div align=\"".$align."\">\n";
1447 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1450 if (ereg('Y', $display) || (empty($display))) {
1451 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1454 if (ereg("M", $display) || (empty($display))) {
1455 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1458 if (ereg("W", $display) || (empty($display))) {
1459 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1462 if (ereg("D", $display) || (empty($display))) {
1463 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1466 if (ereg("h", $display) || (empty($display))) {
1467 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1470 if (ereg('m', $display) || (empty($display))) {
1471 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1474 if (ereg("s", $display) || (empty($display))) {
1475 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1481 if (ereg('Y', $display) || (empty($display))) {
1482 // Generate year selection
1483 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1484 for ($idx = 0; $idx <= 10; $idx++) {
1485 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1486 if ($idx == $Y) $OUT .= ' selected="selected"';
1487 $OUT .= ">".$idx."</option>\n";
1489 $OUT .= " </select></td>\n";
1491 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1494 if (ereg("M", $display) || (empty($display))) {
1495 // Generate month selection
1496 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1497 for ($idx = 0; $idx <= 11; $idx++)
1499 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1500 if ($idx == $M) $OUT .= ' selected="selected"';
1501 $OUT .= ">".$idx."</option>\n";
1503 $OUT .= " </select></td>\n";
1505 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1508 if (ereg("W", $display) || (empty($display))) {
1509 // Generate week selection
1510 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1511 for ($idx = 0; $idx <= 4; $idx++) {
1512 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1513 if ($idx == $W) $OUT .= ' selected="selected"';
1514 $OUT .= ">".$idx."</option>\n";
1516 $OUT .= " </select></td>\n";
1518 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1521 if (ereg("D", $display) || (empty($display))) {
1522 // Generate day selection
1523 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1524 for ($idx = 0; $idx <= 31; $idx++) {
1525 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1526 if ($idx == $D) $OUT .= ' selected="selected"';
1527 $OUT .= ">".$idx."</option>\n";
1529 $OUT .= " </select></td>\n";
1531 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1534 if (ereg("h", $display) || (empty($display))) {
1535 // Generate hour selection
1536 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1537 for ($idx = 0; $idx <= 23; $idx++) {
1538 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1539 if ($idx == $h) $OUT .= ' selected="selected"';
1540 $OUT .= ">".$idx."</option>\n";
1542 $OUT .= " </select></td>\n";
1544 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1547 if (ereg('m', $display) || (empty($display))) {
1548 // Generate minute selection
1549 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1550 for ($idx = 0; $idx <= 59; $idx++) {
1551 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1552 if ($idx == $m) $OUT .= ' selected="selected"';
1553 $OUT .= ">".$idx."</option>\n";
1555 $OUT .= " </select></td>\n";
1557 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1560 if (ereg("s", $display) || (empty($display))) {
1561 // Generate second selection
1562 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1563 for ($idx = 0; $idx <= 59; $idx++) {
1564 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1565 if ($idx == $s) $OUT .= ' selected="selected"';
1566 $OUT .= ">".$idx."</option>\n";
1568 $OUT .= " </select></td>\n";
1570 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1573 $OUT .= "</table>\n";
1575 // Return generated HTML code
1581 function createTimestampFromSelections ($prefix, $POST) {
1582 // Initial return value
1585 // Do we have a leap year?
1587 $TEST = date('Y', time()) / 4;
1588 $M1 = date('m', time());
1589 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1590 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1591 // First add years...
1592 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1594 $ret += $POST[$prefix."_mo"] * 2628000;
1596 $ret += $POST[$prefix."_we"] * 604800;
1598 $ret += $POST[$prefix."_da"] * 86400;
1600 $ret += $POST[$prefix."_ho"] * 3600;
1602 $ret += $POST[$prefix."_mi"] * 60;
1603 // And at last seconds...
1604 $ret += $POST[$prefix."_se"];
1605 // Return calculated value
1609 // Sends out mail to all administrators
1610 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1611 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1612 // Trim template name
1613 $template = trim($template);
1615 // Load email template
1616 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1618 // Check which admin shall receive this mail
1619 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1620 array($template), __FUNCTION__, __LINE__);
1621 if (SQL_NUMROWS($result) == 0) {
1622 // Create new entry (to all admins)
1623 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1624 array($template), __FUNCTION__, __LINE__);
1626 // Load admin IDs...
1627 // @TODO This can be, somehow, rewritten
1628 $adminIds = array();
1629 while ($content = SQL_FETCHARRAY($result)) {
1630 $adminIds[] = $content['admin_id'];
1634 SQL_FREERESULT($result);
1639 // "implode" IDs and query string
1640 $aid = implode(',', $adminIds);
1642 if (EXT_IS_ACTIVE('events')) {
1643 // Add line to user events
1644 EVENTS_ADD_LINE($subj, $msg, $UID);
1646 // Log error for debug
1647 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1653 } elseif ($aid == '0') {
1654 // Select all email adresses
1655 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1656 __FUNCTION__, __LINE__);
1658 // If Admin-ID is not "to-all" select
1659 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1660 array($aid), __FUNCTION__, __LINE__);
1664 // Load email addresses and send away
1665 while ($content = SQL_FETCHARRAY($result)) {
1666 sendEmail($content['email'], $subj, $msg);
1670 SQL_FREERESULT($result);
1673 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1674 function createFancyTime ($stamp) {
1675 // Get data array with years/months/weeks/days/...
1676 $data = createTimeSelections($stamp, '', '', '', true);
1678 foreach($data as $k => $v) {
1680 // Value is greater than 0 "eval" data to return string
1681 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1687 // Do we have something there?
1688 if (strlen($ret) > 0) {
1689 // Remove leading commata and space
1690 $ret = substr($ret, 2);
1693 $ret = "0 {--_SECONDS--}";
1696 // Return fancy time string
1701 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1702 $SEP = ''; $TOP = '';
1705 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1709 for ($page = 1; $page <= $PAGES; $page++) {
1710 // Is the page currently selected or shall we generate a link to it?
1711 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1712 // Is currently selected, so only highlight it
1713 $NAV .= "<strong>-";
1715 // Open anchor tag and add base URL
1716 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1718 // Add userid when we shall show all mails from a single member
1719 if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1721 // Close open anchor tag
1725 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1726 // Is currently selected, so only highlight it
1727 $NAV .= "-</strong>";
1733 // Add seperator if we have not yet reached total pages
1734 if ($page < $PAGES) $NAV .= " | ";
1737 // Define constants only once
1738 if (!defined('__NAV_OUTPUT')) {
1739 define('__NAV_OUTPUT' , $NAV);
1740 define('__NAV_COLSPAN', $colspan);
1741 define('__NAV_TOP' , $TOP);
1742 define('__NAV_SEP' , $SEP);
1745 // Load navigation template
1746 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1748 if ($return === true) {
1749 // Return generated HTML-Code
1757 // Extract host from script name
1758 function extractHostnameFromUrl (&$script) {
1759 // Use default SERVER_URL by default... ;) So?
1760 $url = constant('SERVER_URL');
1762 // Is this URL valid?
1763 if (substr($script, 0, 7) == "http://") {
1764 // Use the hostname from script URL as new hostname
1765 $url = substr($script, 7);
1766 $extract = explode('/', $url);
1768 // Done extracting the URL :)
1771 // Extract host name
1772 $host = str_replace("http://", '', $url);
1773 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1775 // Generate relative URL
1776 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1777 if (substr(strtolower($script), 0, 7) == "http://") {
1778 // But only if http:// is in front!
1779 $script = substr($script, (strlen($url) + 7));
1780 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1782 $script = substr($script, (strlen($url) + 8));
1785 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1786 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1792 // Send a GET request
1793 function sendGetRequest ($script) {
1794 // Compile the script name
1795 $script = COMPILE_CODE($script);
1797 // Extract host name from script
1798 $host = extractHostnameFromUrl($script);
1800 // Generate GET request header
1801 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1802 $request .= "Host: " . $host . "\r\n";
1803 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1804 if (defined('FULL_VERSION')) {
1805 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1807 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1809 $request .= "Content-Type: text/plain\r\n";
1810 $request .= "Cache-Control: no-cache\r\n";
1811 $request .= "Connection: Close\r\n\r\n";
1813 // Send the raw request
1814 $response = sendRawRequest($host, $request);
1816 // Return the result to the caller function
1820 // Send a POST request
1821 function sendPostRequest ($script, $postData) {
1822 // Is postData an array?
1823 if (!is_array($postData)) {
1825 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1826 return array('', '', '');
1829 // Compile the script name
1830 $script = COMPILE_CODE($script);
1832 // Extract host name from script
1833 $host = extractHostnameFromUrl($script);
1835 // Construct request
1836 $data = http_build_query($postData, '','&');
1838 // Generate POST request header
1839 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1840 $request .= "Host: " . $host . "\r\n";
1841 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1842 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1843 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1844 $request .= "Content-length: " . strlen($data) . "\r\n";
1845 $request .= "Cache-Control: no-cache\r\n";
1846 $request .= "Connection: Close\r\n\r\n";
1849 // Send the raw request
1850 $response = sendRawRequest($host, $request);
1852 // Return the result to the caller function
1856 // Sends a raw request to another host
1857 function sendRawRequest ($host, $request) {
1859 $response = array('', '', '');
1861 // Default is not to use proxy
1864 // Are proxy settins set?
1865 if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1871 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1873 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1875 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1879 if (!is_resource($fp)) {
1886 // Generate CONNECT request header
1887 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1888 $proxyTunnel .= "Host: ".$host."\r\n";
1890 // Use login data to proxy? (username at least!)
1891 if (getConfig('proxy_username') != '') {
1893 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).getConfig('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
1894 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1897 // Add last new-line
1898 $proxyTunnel .= "\r\n";
1899 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1902 fputs($fp, $proxyTunnel);
1906 // No response received
1910 // Read the first line
1911 $resp = trim(fgets($fp, 10240));
1912 $respArray = explode(' ', $resp);
1913 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1914 // Invalid response!
1920 fputs($fp, $request);
1923 while (!feof($fp)) {
1924 $response[] = trim(fgets($fp, 1024));
1930 // Skip first empty lines
1932 foreach ($resp as $idx => $line) {
1934 $line = trim($line);
1936 // Is this line empty?
1939 array_shift($response);
1941 // Abort on first non-empty line
1946 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1948 // Proxy agent found?
1949 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy)) {
1950 // Proxy header detected, so remove two lines
1951 array_shift($response);
1952 array_shift($response);
1955 // Was the request successfull?
1956 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1957 // Not found / access forbidden
1958 $response = array('', '', '');
1965 // Taken from www.php.net eregi() user comments
1966 function isEmailValid ($email) {
1968 $email = COMPILE_CODE($email);
1970 // Check first part of email address
1971 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1974 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1977 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1979 // Return check result
1980 // @NOTE altered the regex-pattern and added modificator i (match both upper and lower case letters) and U (PCRE_UNGREEDY) to work with preg_match the same way as eregi
1981 return preg_match($regex, $email);
1984 // Function taken from user comments on www.php.net / function eregi()
1985 function isUrlValid ($URL, $compile=true) {
1986 // Trim URL a little
1987 $URL = trim(urldecode($URL));
1988 //* DEBUG: */ echo $URL."<br />";
1990 // Compile some chars out...
1991 if ($compile) $URL = compileUriCode($URL, false, false, false);
1992 //* DEBUG: */ echo $URL."<br />";
1994 // Check for the extension filter
1995 if (EXT_IS_ACTIVE('filter')) {
1996 // Use the extension's filter set
1997 return FILTER_isUrlValid($URL, false);
2000 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2001 // https:// in front of the URLs
2002 return isUrlValidSimple($URL);
2005 // Generate a list of administrative links to a given userid
2006 function generateMemberAdminActionLinks ($uid, $status = '') {
2007 // Define all main targets
2008 $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2010 // Begin of navigation links
2011 $eval = "\$OUT = \"[ ";
2013 foreach ($TARGETS as $tar) {
2014 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
2015 //* DEBUG: */ echo "*".$tar.'/'.$status."*<br />\n";
2016 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2017 // Locked accounts shall be unlocked
2018 $eval .= "UNLOCK_USER";
2020 // All other status is fine
2021 $eval .= strtoupper($tar);
2023 $eval .= "_TITLE--}\\\">{--ADMIN_";
2024 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2025 // Locked accounts shall be unlocked
2026 $eval .= "UNLOCK_USER";
2028 // All other status is fine
2029 $eval .= strtoupper($tar);
2031 $eval .= "--}</a></span> | ";
2034 // Finish navigation link
2035 $eval = substr($eval, 0, -7)."]\";";
2042 // Generate an email link
2043 function generateMemberEmailLink ($email, $table = 'admins') {
2044 // Default email link (INSECURE! Spammer can read this by harvester programs)
2045 $EMAIL = 'mailto:' . $email;
2047 // Check for several extensions
2048 if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2049 // Create email link for contacting admin in guest area
2050 $EMAIL = adminsCreateEmailLink($email);
2051 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2052 // Create email link for contacting a member within admin area (or later in other areas, too?)
2053 $EMAIL = USER_generateMemberEmailLink($email);
2054 } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2055 // Create email link to contact sponsor within admin area (or like the link above?)
2056 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2059 // Shall I close the link when there is no admin?
2060 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2062 // Return email link
2066 // Generate a hash for extra-security for all passwords
2067 function generateHash ($plainText, $salt = '') {
2068 // Is the required extension 'sql_patches' there and a salt is not given?
2069 if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2070 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2071 return md5($plainText);
2074 // Do we miss an arry element here?
2075 if (!isConfigEntrySet('file_hash')) {
2077 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2080 // When the salt is empty build a new one, else use the first x configured characters as the salt
2082 // Build server string (inc/databases.php is no longer updated with every commit)
2083 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
2086 $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key').getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash').getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
2089 $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
2091 // Calculate number for generating the code
2092 $a = time() + getConfig('_ADD') - 1;
2094 // Generate SHA1 sum from modula of number and the prime number
2095 $sha1 = sha1(($a % getConfig('_PRIME')).$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a);
2096 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2097 $sha1 = scrambleString($sha1);
2098 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2099 //* DEBUG: */ $sha1b = descrambleString($sha1);
2100 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2102 // Generate the password salt string
2103 $salt = substr($sha1, 0, getConfig('salt_length'));
2104 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2107 $salt = substr($salt, 0, getConfig('salt_length'));
2108 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2112 return $salt.sha1($salt.$plainText);
2115 // Scramble a string
2116 function scrambleString($str) {
2120 // Final check, in case of failture it will return unscrambled string
2121 if (strlen($str) > 40) {
2122 // The string is to long
2124 } elseif (strlen($str) == 40) {
2126 $scrambleNums = explode(':', getConfig('pass_scramble'));
2128 // Generate new numbers
2129 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2132 // Scramble string here
2133 //* DEBUG: */ echo "***Original=".$str."***<br />";
2134 for ($idx = 0; $idx < strlen($str); $idx++) {
2135 // Get char on scrambled position
2136 $char = substr($str, $scrambleNums[$idx], 1);
2138 // Add it to final output string
2139 $scrambled .= $char;
2142 // Return scrambled string
2143 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2147 // De-scramble a string scrambled by scrambleString()
2148 function descrambleString($str) {
2149 // Scramble only 40 chars long strings
2150 if (strlen($str) != 40) return $str;
2152 // Load numbers from config
2153 $scrambleNums = explode(':', getConfig('pass_scramble'));
2156 if (count($scrambleNums) != 40) return $str;
2158 // Begin descrambling
2159 $orig = str_repeat(" ", 40);
2160 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2161 for ($idx = 0; $idx < 40; $idx++) {
2162 $char = substr($str, $idx, 1);
2163 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2166 // Return scrambled string
2167 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2171 // Generated a "string" for scrambling
2172 function genScrambleString ($len) {
2173 // Prepare array for the numbers
2174 $scrambleNumbers = array();
2176 // First we need to setup randomized numbers from 0 to 31
2177 for ($idx = 0; $idx < $len; $idx++) {
2179 $rand = mt_rand(0, ($len -1));
2181 // Check for it by creating more numbers
2182 while (array_key_exists($rand, $scrambleNumbers)) {
2183 $rand = mt_rand(0, ($len -1));
2187 $scrambleNumbers[$rand] = $rand;
2190 // So let's create the string for storing it in database
2191 $scrambleString = implode(':', $scrambleNumbers);
2192 return $scrambleString;
2195 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2196 function generatePassString ($passHash) {
2197 // Return vanilla password hash
2200 // Is a secret key and master salt already initialized?
2201 if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2202 // Only calculate when the secret key is generated
2203 $newHash = ''; $start = 9;
2204 for ($idx = 0; $idx < 10; $idx++) {
2205 $part1 = hexdec(substr($passHash, $start, 4));
2206 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2207 $mod = dechex($idx);
2208 if ($part1 > $part2) {
2209 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2210 } elseif ($part2 > $part1) {
2211 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2213 $mod = substr(round($mod), 0, 4);
2214 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2215 //* DEBUG: */ echo "*".$start.'='.$mod."*<br />";
2220 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).')');
2221 $ret = generateHash($newHash, getConfig('master_salt'));
2222 //* DEBUG: */ print($ret."<br />\n");
2225 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2226 $ret = md5($passHash);
2227 //* DEBUG: */ echo "++".$ret."++<br />\n";
2234 // Fix "deleted" cookies
2235 function fixDeletedCookies ($cookies) {
2236 // Is this an array with entries?
2237 if ((is_array($cookies)) && (count($cookies) > 0)) {
2238 // Then check all cookies if they are marked as deleted!
2239 foreach ($cookies as $cookieName) {
2240 // Is the cookie set to "deleted"?
2241 if (getSession($cookieName) == 'deleted') {
2242 setSession($cookieName, '');
2248 // Output error messages in a fasioned way and die...
2249 function app_die ($F, $L, $msg) {
2250 // Check if Script is already dieing and not let it kill itself another 1000 times
2251 if (!isset($GLOBALS['app_died'])) {
2252 // Make sure, that the script realy realy diese here and now
2253 $GLOBALS['app_died'] = true;
2256 loadIncludeOnce('inc/header.php');
2258 // Prepare message for output
2259 $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
2261 // Load the message template
2262 LOAD_TEMPLATE('admin_settings_saved', false, $msg);
2265 loadIncludeOnce('inc/footer.php');
2270 // Script tried to kill itself twice
2271 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $msg . ', file/function=' . $F . ', line=' . $L);
2275 // Display parsing time and number of SQL queries in footer
2276 function displayParsingTime() {
2277 // Is the timer started?
2278 if (!isset($GLOBALS['startTime'])) {
2284 $endTime = microtime(true);
2286 // "Explode" both times
2287 $start = explode(' ', $GLOBALS['startTime']);
2288 $end = explode(' ', $endTime);
2289 $runTime = $end[0] - $start[0];
2290 if ($runTime < 0) $runTime = 0;
2291 $runTime = translateComma($runTime);
2295 'runtime' => $runTime,
2296 'numSQLs' => (getConfig('sql_count') + 1),
2297 'numTemplates' => (getConfig('num_templates') + 1)
2300 // Load the template
2301 LOAD_TEMPLATE('show_timings', false, $content);
2304 // Check wether a boolean constant is set
2305 // Taken from user comments in PHP documentation for function constant()
2306 function isBooleanConstantAndTrue ($constName) { // : Boolean
2307 // Failed by default
2311 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2313 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2314 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2317 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2318 if (defined($constName)) {
2320 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2321 $res = (constant($constName) === true);
2325 $GLOBALS['cache_array']['const'][$constName] = $res;
2327 //* DEBUG: */ var_dump($res);
2333 // Checks if a given apache module is loaded
2334 function isApacheModuleLoaded ($apacheModule) {
2335 // Check it and return result
2336 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2339 // "Getter" for language strings
2340 // @TODO Rewrite all language constants to this function.
2341 function getMessage ($messageId) {
2342 // Default is not found!
2343 $return = '!'.$messageId.'!';
2345 // Is the language string found?
2346 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2347 // Language array element found in small_letters
2348 $return = $GLOBALS['msg'][$messageId];
2349 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2350 // @DEPRECATED Language array element found in BIG_LETTERS
2351 $return = $GLOBALS['msg'][$messageId];
2352 } elseif (defined($messageId)) {
2353 // @DEPRECATED Deprecated constant found
2354 $return = constant($messageId);
2356 // Missing language constant
2357 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2360 // Return the string
2364 // Get current theme name
2365 function getCurrentTheme() {
2366 // The default theme is 'default'... ;-)
2369 // Load default theme if not empty from configuration
2370 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2372 if (!isSessionVariableSet('mxchange_theme')) {
2373 // Set default theme
2374 setSession('mxchange_theme', $ret);
2375 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2376 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2377 // Get theme from cookie
2378 $ret = getSession('mxchange_theme');
2381 if (getThemeId($ret) == 0) {
2382 // Fix it to default
2385 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2386 // Prepare FQFN for checking
2387 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2389 // Installation mode active
2390 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2391 // Set cookie from URL data
2392 setSession('mxchange_theme', REQUEST_GET('theme'));
2393 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2394 // Set cookie from posted data
2395 setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2399 $ret = getSession('mxchange_theme');
2401 // Invalid design, reset cookie
2402 setSession('mxchange_theme', $ret);
2405 // Add (maybe) found theme.php file to inclusion list
2406 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2408 // Try to load the requested include file
2409 if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2411 // Return theme value
2415 // Get id from theme
2416 function getThemeId ($name) {
2417 // Is the extension 'theme' installed?
2418 if (!EXT_IS_ACTIVE('theme')) {
2426 // Is the cache entry there?
2427 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2428 // Get the version from cache
2429 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2432 incrementConfigEntry('cache_hits');
2433 } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2434 // Check if current theme is already imported or not
2435 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2436 array($name), __FUNCTION__, __LINE__);
2439 if (SQL_NUMROWS($result) == 1) {
2441 list($id) = SQL_FETCHROW($result);
2445 SQL_FREERESULT($result);
2452 // Generates an error code from given account status
2453 function generateErrorCodeFromUserStatus ($status) {
2454 // Default error code if unknown account status
2455 $errorCode = getCode('UNKNOWN_STATUS');
2457 // Generate constant name
2458 $constantName = sprintf("ID_%s", $status);
2460 // Is the constant there?
2461 if (isCodeSet($constantName)) {
2463 $errorCode = getCode($constantName);
2466 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2469 // Return error code
2473 // Function to search for the last modifified file
2474 function searchDirsRecursive ($dir, &$last_changed) {
2476 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2477 // Does it match what we are looking for? (We skip a lot files already!)
2478 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2479 $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2480 $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2481 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2483 // Walk through all entries
2484 foreach ($ds as $d) {
2485 // Generate proper FQFN
2486 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2488 // Is it a file and readable?
2489 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2490 if (isDirectory($FQFN)) {
2491 // $FQFN is a directory so also crawl into this directory
2493 if (!empty($dir)) $newDir = $dir . '/'. $d;
2494 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2495 searchDirsRecursive($newDir, $last_changed);
2496 } elseif (isFileReadable($FQFN)) {
2497 // $FQFN is a filename and no directory
2498 $time = filemtime($FQFN);
2499 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2500 if ($last_changed['time'] < $time) {
2501 // This file is newer as the file before
2502 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2503 $last_changed['path_name'] = $FQFN;
2504 $last_changed['time'] = $time;
2510 // "Getter" for revision/version data
2511 function getActualVersion ($type = 'Revision') {
2512 // By default nothing is new... ;-)
2515 if (EXT_IS_ACTIVE('cache')) {
2516 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2517 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
2518 if (!isset($GLOBALS['cache_array']['revision'][$type])
2519 || count($GLOBALS['cache_array']['revision']) < 3
2520 || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
2522 // Is the cache file outdated/invalid?
2524 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2526 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2527 unset($GLOBALS['cache_array']['revision']);
2529 // Reload load_cach-revison.php
2530 loadInclude('inc/loader/load_cache-revision.php');
2533 // Return found value
2534 return $GLOBALS['cache_array']['revision'][$type][0];
2537 // Old Version without ext-cache active (deprecated ?)
2539 // FQFN of revision file
2540 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2542 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2543 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2547 // Check for revision file
2548 if (!isFileReadable($FQFN)) {
2549 // Not found, so we need to create it
2552 // Revision file found
2553 $ins_vers = explode("\n", readFromFile($FQFN));
2555 // Get array for mapping information
2556 $mapper = array_flip(getSearchFor());
2557 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2559 // Is the content valid?
2560 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2561 // File needs update!
2564 // Return found value
2565 return trim($ins_vers[$mapper[$type]]);
2570 // Has it been updated?
2571 if ($new === true) {
2572 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2577 // Repares an array we are looking for
2578 // The returned Array is needed twice (in getArrayFromActualVersion() and in getActualVersion() in the old .revision-fallback) so I puted it in an extra function to not polute the global namespace
2579 function getSearchFor () {
2580 // Add Revision, Date, Tag and Author
2581 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2583 // Return the created array
2587 // @TODO Please describe this function
2588 function getArrayFromActualVersion () {
2590 $next_dir = ''; // Directory to start with search
2591 $last_changed = array(
2595 $akt_vers = array(); // Init return array
2596 $res = 0; // Init value for counting the founded keywords
2598 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2599 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2602 $last_file = readFromFile($last_changed['path_name']);
2604 // Get all the keywords to search for
2605 $searchFor = getSearchFor();
2607 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2608 foreach ($searchFor as $search) {
2609 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2610 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2611 // This trimms the search-result and puts it in the $akt_vers-return array
2612 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2615 // Save the last-changed filename for debugging
2616 $akt_vers['File'] = $last_changed['path_name'];
2618 // at least 3 keyword-Tags are needed for propper values
2619 if ($res && $res >= 3
2620 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2621 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2622 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2623 // Prepare content witch need special treadment
2625 // Prepare timestamp for date
2626 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2627 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2629 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2630 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2631 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2635 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2636 $version = sendGetRequest('check-updates3.php');
2639 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2640 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2641 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2642 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2643 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2646 // Return prepared array
2650 // Back-ported from the new ship-simu engine. :-)
2651 function debug_get_printable_backtrace () {
2653 $backtrace = "<ol>\n";
2655 // Get and prepare backtrace for output
2656 $backtraceArray = debug_backtrace();
2657 foreach ($backtraceArray as $key => $trace) {
2658 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2659 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2660 if (!isset($trace['args'])) $trace['args'] = array();
2661 $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";
2665 $backtrace .= "</ol>\n";
2667 // Return the backtrace
2671 // Output a debug backtrace to the user
2672 function debug_report_bug ($message = '') {
2675 // Is the optional message set?
2676 if (!empty($message)) {
2678 $debug = sprintf("Note: %s<br />\n",
2682 // @TODO Add a little more infos here
2683 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2687 $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2688 $debug .= debug_get_printable_backtrace();
2689 $debug .= "</pre>\nRequest-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2690 $debug .= "Thank you for finding bugs.";
2693 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2697 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2698 function generateSeed () {
2699 list($usec, $sec) = explode(" ", microtime());
2700 return ((float)$sec + (float)$usec);
2703 // Converts a message code to a human-readable message
2704 function convertCodeToMessage ($code) {
2707 case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2708 case getCode('LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2709 case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2710 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2711 case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2712 case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2713 case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2714 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2716 case getCode('ERROR_MAILID'):
2717 if (EXT_IS_ACTIVE($ext, true)) {
2718 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2720 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2724 case getCode('EXTENSION_PROBLEM'):
2725 if (REQUEST_ISSET_GET('ext')) {
2726 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET('ext'));
2728 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2732 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2733 case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2734 case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2735 case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2738 // Missing/invalid code
2739 $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2742 DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2746 // Return the message
2750 // Generate a "link" for the given admin id (aid)
2751 function generateAdminLink ($aid) {
2752 // No assigned admin is default
2753 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2755 // Zero? = Not assigned
2756 if (bigintval($aid) > 0) {
2757 // Load admin's login
2758 $login = getAdminLogin($aid);
2760 // Is the login valid?
2761 if ($login != '***') {
2762 // Is the extension there?
2763 if (EXT_IS_ACTIVE('admins')) {
2765 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">".$login."</a>";
2767 // Extension not found
2768 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2772 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2780 // Compile characters which are allowed in URLs
2781 function compileUriCode ($code, $simple=true) {
2782 // Compile constants
2783 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2785 // Compile QUOT and other non-HTML codes
2786 $code = str_replace('{DOT}', '.',
2787 str_replace('{SLASH}', '/',
2788 str_replace('{QUOT}', "'",
2789 str_replace('{DOLLAR}', '$',
2790 str_replace('{OPEN_ANCHOR}', '(',
2791 str_replace('{CLOSE_ANCHOR}', ')',
2792 str_replace('{OPEN_SQR}', '[',
2793 str_replace('{CLOSE_SQR}', ']',
2794 str_replace('{PER}', '%',
2798 // Return compiled code
2802 // Function taken from user comments on www.php.net / function eregi()
2803 function isUrlValidSimple ($url) {
2805 $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
2807 // Allows http and https
2808 $http = "(http|https)+(:\/\/)";
2810 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2811 // Test double-domains (e.g. .de.vu)
2812 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2814 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2816 $dir = "((/)+([-_\.[:alnum:]])+)*";
2818 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2819 // ... and the string after and including question character
2820 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2821 // Pattern for URLs like http://url/dir/doc.html?var=value
2822 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2823 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2824 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2825 // Pattern for URLs like http://url/dir/?var=value
2826 $pattern['d1dg1'] = $http.$domain1.$dir.'/'.$getstring1;
2827 $pattern['d2dg1'] = $http.$domain2.$dir.'/'.$getstring1;
2828 $pattern['ipdg1'] = $http.$ip.$dir.'/'.$getstring1;
2829 // Pattern for URLs like http://url/dir/page.ext
2830 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2831 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2832 $pattern['ipdp'] = $http.$ip.$dir.$page;
2833 // Pattern for URLs like http://url/dir
2834 $pattern['d1d'] = $http.$domain1.$dir;
2835 $pattern['d2d'] = $http.$domain2.$dir;
2836 $pattern['ipd'] = $http.$ip.$dir;
2837 // Pattern for URLs like http://url/?var=value
2838 $pattern['d1g1'] = $http.$domain1.'/'.$getstring1;
2839 $pattern['d2g1'] = $http.$domain2.'/'.$getstring1;
2840 $pattern['ipg1'] = $http.$ip.'/'.$getstring1;
2841 // Pattern for URLs like http://url?var=value
2842 $pattern['d1g12'] = $http.$domain1.$getstring1;
2843 $pattern['d2g12'] = $http.$domain2.$getstring1;
2844 $pattern['ipg12'] = $http.$ip.$getstring1;
2845 // Test all patterns
2847 foreach ($pattern as $key=>$pat) {
2849 if (defined('DEBUG_REGEX')) {
2850 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2851 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2852 $pat = str_replace("[:digit:]", "0-9", $pat);
2853 $pat = str_replace('.', "\.", $pat);
2854 $pat = str_replace("@", "\@", $pat);
2855 echo $key."= ".$pat."<br />";
2858 // Check if expression matches
2859 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2862 if ($reg === true) break;
2865 // Return true/false
2869 // Wtites data to a config.php-style file
2870 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2871 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2872 // Initialize some variables
2878 // Is the file there and read-/write-able?
2879 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2880 $search = "CFG: ".$comment;
2881 $tmp = $FQFN.".tmp";
2883 // Open the source file
2884 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
2886 // Is the resource valid?
2887 if (is_resource($fp)) {
2888 // Open temporary file
2889 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
2891 // Is the resource again valid?
2892 if (is_resource($fp_tmp)) {
2893 while (!feof($fp)) {
2894 // Read from source file
2895 $line = fgets ($fp, 1024);
2897 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2900 if ($next === $seek) {
2902 $line = $prefix . $DATA . $suffix."\n";
2908 // Write to temp file
2909 fputs($fp_tmp, $line);
2915 // Finished writing tmp file
2919 // Close source file
2922 if (($done) && ($found)) {
2923 // Copy back tmp file and delete tmp :-)
2925 return unlink($tmp);
2926 } elseif (!$found) {
2927 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
2929 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
2933 // File not found, not readable or writeable
2934 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
2937 // An error was detected!
2940 // Send notification to admin
2941 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
2942 if (GET_EXT_VERSION('admins') >= '0.4.1') {
2944 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2946 // Send out out-dated way
2947 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2948 SEND_ADMIN_EMAILS($subject, $msg);
2952 // Debug message logger
2953 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2954 // Is debug mode enabled?
2955 if ((isDebugModeEnabled()) || ($force === true)) {
2957 $message = str_replace("\r", '', str_replace("\n", '', $message));
2959 // Log this message away
2960 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
2961 fwrite($fp, date("d.m.Y|H:i:s", time())."|".$GLOBALS['module']."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
2966 // Load more reset scripts
2967 function runResetIncludes () {
2968 // Is the reset set or old sql_patches?
2969 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
2971 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
2974 // Get more daily reset scripts
2975 SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
2978 if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
2980 // Is the config entry set?
2981 if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
2982 // Create current week mark
2983 $currWeek = date('W', time());
2986 if (getConfig('last_week') != $currWeek) {
2987 // Include weekly reset scripts
2988 MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
2991 if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
2994 // Create current month mark
2995 $currMonth = date('m', time());
2998 if (getConfig('last_month') != $currMonth) {
2999 // Include monthly reset scripts
3000 MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
3003 if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
3008 runFilterChain('load_includes');
3011 // Handle extra values
3012 function handleExtraValues ($filterFunction, $value, $extraValue) {
3013 // Default is the value itself
3016 // Do we have a special filter function?
3017 if (!empty($filterFunction)) {
3018 // Does the filter function exist?
3019 if (function_exists($filterFunction)) {
3020 // Do we have extra parameters here?
3021 if (!empty($extraValue)) {
3022 // Put both parameters in one new array by default
3023 $args = array($value, $extraValue);
3025 // If we have an array simply use it and pre-extend it with our value
3026 if (is_array($extraValue)) {
3027 // Make the new args array
3028 $args = merge_array(array($value), $extraValue);
3031 // Call the multi-parameter call-back
3032 $ret = call_user_func_array($filterFunction, $args);
3034 // One parameter call
3035 $ret = call_user_func($filterFunction, $value);
3044 // Converts timestamp selections into a timestamp
3045 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
3046 // Init test variable
3049 // Get last three chars
3050 $test = substr($id, -3);
3052 // Improved way of checking! :-)
3053 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3054 // Found a multi-selection for timings?
3055 $test = substr($id, 0, -3);
3056 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)) {
3057 // Generate timestamp
3058 $POST[$test] = createTimestampFromSelections($test, $POST);
3059 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3061 // Remove data from array
3062 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3063 unset($POST[$test.'_'.$rem]);
3067 unset($id); $skip = true; $test2 = $test;
3070 // Process this entry
3076 // Reverts the german decimal comma into Computer decimal dot
3077 function convertCommaToDot ($str) {
3078 // Default float is not a float... ;-)
3081 // Which language is selected?
3082 switch (getLanguage()) {
3083 case 'de': // German language
3084 // Remove german thousand dots first
3085 $str = str_replace('.', '', $str);
3087 // Replace german commata with decimal dot and cast it
3088 $float = (float)str_replace(',', '.', $str);
3091 default: // US and so on
3092 // Remove thousand dots first and cast
3093 $float = (float)str_replace(',', '', $str);
3101 // Handle menu-depending failed logins and return the rendered content
3102 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3103 // Default output is empty ;-)
3106 // Is the session data set?
3107 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3108 // Ignore zero values
3109 if (getSession('mxchange_'.$accessLevel.'_failures') > 0) {
3110 // Non-guest has login failures found, get both data and prepare it for template
3111 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3113 'login_failures' => getSession('mxchange_'.$accessLevel.'_failures'),
3114 'last_failure' => generateDateTime(getSession('mxchange_'.$accessLevel.'_last_fail'), '2')
3118 $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3121 // Reset session data
3122 setSession('mxchange_'.$accessLevel.'_failures', '');
3123 setSession('mxchange_'.$accessLevel.'_last_fail', '');
3126 // Return rendered content
3131 function rebuildCacheFiles ($cache, $inc = '') {
3132 // Shall I remove the cache file?
3133 if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3135 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3137 $GLOBALS['cache_instance']->destroyCacheFile();
3140 // Include file given?
3143 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3145 // Is the include there?
3146 if (isIncludeReadable($INC)) {
3147 // And rebuild it from scratch
3148 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3151 // Include not found!
3152 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3158 // Purge admin menu cache
3159 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3160 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3161 if (!EXT_IS_ACTIVE('cache')) {
3162 // Cache extension not active
3164 } elseif (!isCacheInstanceValid()) {
3165 // No cache instance!
3166 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3168 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3169 // Caching disabled (currently experiemental!)
3173 // Experiemental feature!
3174 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3177 // Determines the real remote address
3178 function determineRealRemoteAddress () {
3179 // Is a proxy in use?
3180 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3182 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3183 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3184 // Yet, another proxy
3185 $address = $_SERVER['HTTP_CLIENT_IP'];
3187 // The regular address when no proxy was used
3188 $address = $_SERVER['REMOTE_ADDR'];
3191 // This strips out the real address from proxy output
3192 if (strstr($address, ',')){
3193 $addressArray = explode(',', $address);
3194 $address = $addressArray[0];
3197 // Return the result
3201 // Adds a bonus mail to the queue
3202 // This is a high-level function!
3203 function addNewBonusMail ($data, $mode = '', $output=true) {
3204 // Use mode from data if not set and availble ;-)
3205 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3207 // Generate receiver list
3208 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3211 if (!empty($RECEIVER)) {
3212 // Add bonus mail to queue
3213 addBonusMailToQueue(
3225 // Mail inserted into bonus pool
3226 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3227 } elseif ($output) {
3228 // More entered than can be reached!
3229 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3232 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3236 // Determines referal id and sets it
3237 function DETERMINE_REFID () {
3238 // Check if refid is set
3239 if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3240 // The variable user comes from the click-counter script click.php and we only accept this here
3241 $GLOBALS['refid'] = bigintval($_GET['user']);
3242 } elseif (!empty($_POST['refid'])) {
3243 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3244 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3245 } elseif (!empty($_GET['refid'])) {
3246 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3247 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3248 } elseif (!empty($_GET['ref'])) {
3249 // Set refid=ref (the referal link uses such variable)
3250 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3251 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3252 // Set session refid als global
3253 $GLOBALS['refid'] = bigintval(getSession('refid'));
3254 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3255 // Set default refid as refid in URL
3256 $GLOBALS['refid'] = getConfig(('def_refid'));
3257 } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3258 // Select a random user which has confirmed enougth mails
3259 $GLOBALS['refid'] = determineRandomReferalId();
3261 // No default ID when sql_patches is not installed or none set
3262 $GLOBALS['refid'] = 0;
3265 // Set cookie when default refid > 0
3266 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3268 setSession('refid', $GLOBALS['refid']);
3271 // Return determined refid
3272 return $GLOBALS['refid'];
3275 // Enables the reset mode. Only call this function if you really want the
3277 function enableResetMode () {
3278 // Enable the reset mode
3279 $GLOBALS['reset_enabled'] = true;
3282 runFilterChain('reset_enabled');
3285 // Our shutdown-function
3286 function shutdown () {
3287 // Call the filter chain 'shutdown'
3288 runFilterChain('shutdown', null, false);
3290 if (SQL_IS_LINK_UP()) {
3292 SQL_CLOSE(__FILE__, __LINE__);
3293 } elseif ((!isInstalling()) && (isInstalled())) {
3295 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3298 // Stop executing here
3302 // Setter for userid
3303 function setUserId ($userid) {
3304 $GLOBALS['userid'] = bigintval($userid);
3307 // Getter for userid or returns zero
3308 function getUserId () {
3312 // Is the userid set?
3313 if (isUserIdSet()) {
3315 $userid = $GLOBALS['userid'];
3322 // Checks ether the userid is set
3323 function isUserIdSet () {
3324 return (isset($GLOBALS['userid']));
3327 // Handle message codes from URL
3328 function handleCodeMessage () {
3329 if (REQUEST_ISSET_GET('msg')) {
3330 // Default extension is "unknown"
3333 // Is extension given?
3334 if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
3336 // Convert the 'msg' parameter from URL to a human-readable message
3337 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3339 // Load message template
3340 LOAD_TEMPLATE('message', false, $msg);
3344 // Setter for extra title
3345 function setExtraTitle ($extraTitle) {
3346 $GLOBALS['extra_title'] = $extraTitle;
3349 // Getter for extra title
3350 function getExtraTitle () {
3351 // Is the extra title set?
3352 if (!isExtraTitleSet()) {
3353 // No, then abort here
3354 debug_report_bug('extra_title is not set!');
3358 return $GLOBALS['extra_title'];
3361 // Checks if the extra title is set
3362 function isExtraTitleSet () {
3363 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3366 //////////////////////////////////////////////////
3367 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3368 //////////////////////////////////////////////////
3370 if (!function_exists('html_entity_decode')) {
3371 // Taken from documentation on www.php.net
3372 function html_entity_decode ($string) {
3373 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3374 $trans_tbl = array_flip($trans_tbl);
3375 return strtr($string, $trans_tbl);