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 // Loads an email template and compiles it
734 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
735 global $DATA, $_CONFIG;
737 // Make sure all template names are lowercase!
738 $template = strtolower($template);
740 // Default 'nickname' if extension is not installed
743 // Prepare IP number and User Agent
744 $REMOTE_ADDR = detectRemoteAddr();
745 $HTTP_USER_AGENT = detectUserAgent();
748 $ADMIN = constant('MAIN_TITLE');
750 // Is the admin logged in?
753 $aid = getCurrentAdminId();
756 $ADMIN = getAdminEmail($aid);
759 // Neutral email address is default
760 $email = constant('WEBMASTER');
762 // Expiration in a nice output format
763 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
764 if (getConfig('auto_purge') == 0) {
765 // Will never expire!
766 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
768 // Create nice date string
769 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
772 // Is content an array?
773 if (is_array($content)) {
774 // Add expiration to array, $EXPIRATION is now deprecated!
775 $content['expiration'] = $EXPIRATION;
779 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
780 if (($UID > 0) && (is_array($content))) {
781 // If nickname extension is installed, fetch nickname as well
782 if (EXT_IS_ACTIVE('nickname')) {
783 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
785 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
786 array(bigintval($UID)), __FUNCTION__, __LINE__);
788 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
790 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
791 array(bigintval($UID)), __FUNCTION__, __LINE__);
794 // Fetch and merge data
795 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
796 $content = merge_array($content, SQL_FETCHARRAY($result));
797 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
800 SQL_FREERESULT($result);
803 // Translate M to male or F to female if present
804 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
806 // Overwrite email from data if present
807 if (isset($content['email'])) $email = $content['email'];
809 // Store email for some functions in global data array
810 $DATA['email'] = $email;
813 $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
815 // Check for admin/guest/member templates
816 if (strpos($template, 'admin_') > -1) {
817 // Admin template found
818 $FQFN = $basePath.'admin/'.$template.'.tpl';
819 } elseif (strpos($template, 'guest_') > -1) {
820 // Guest template found
821 $FQFN = $basePath.'guest/'.$template.'.tpl';
822 } elseif (strpos($template, 'member_') > -1) {
823 // Member template found
824 $FQFN = $basePath.'member/'.$template.'.tpl';
826 // Test for extension
827 $test = substr($template, 0, strpos($template, '_'));
828 if (EXT_IS_ACTIVE($test)) {
829 // Set extra path to extension's name
830 $FQFN = $basePath.$test.'/'.$template.'.tpl';
832 // No special filename
833 $FQFN = $basePath.$template.'.tpl';
837 // Does the special template exists?
838 if (!isFileReadable($FQFN)) {
839 // Reset to default template
840 $FQFN = $basePath.$template.'.tpl';
843 // Now does the final template exists?
845 if (isFileReadable($FQFN)) {
846 // The local file does exists so we load it. :)
847 $tmpl_file = readFromFile($FQFN);
848 $tmpl_file = SQL_ESCAPE($tmpl_file);
851 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
853 } elseif (!empty($template)) {
854 // Template file not found!
855 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
856 {--TEMPLATE_CONTENT--}
857 <pre>".print_r($content, true)."</pre>
859 <pre>".print_r($DATA, true)."</pre>
862 // Debug mode not active? Then remove the HTML tags
863 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
865 // No template name supplied!
866 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
869 // Is there some content?
870 if (empty($newContent)) {
872 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
873 // Add last error if the required function exists
874 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
877 // Remove content and data
881 // Return compiled content
882 return COMPILE_CODE($newContent);
885 // Generates a timestamp (some wrapper for mktime())
886 function makeTime ($H, $M, $S, $stamp) {
887 // Extract day, month and year from given timestamp
888 $day = date('d', $stamp);
889 $month = date('m', $stamp);
890 $year = date('Y', $stamp);
892 // Create timestamp for wished time which depends on extracted date
893 return mktime($H, $M, $S, $month, $day, $year);
896 // Redirects to an URL and if neccessarry extends it with own base URL
897 function redirectToUrl ($URL) {
898 // Compile out URI codes
899 $URL = compileUriCode($URL);
901 // Check if http(s):// is there
902 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
903 // Make all URLs full-qualified
904 $URL = constant('URL') . '/' . $URL;
907 // Three different debug ways...
908 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
909 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
910 //* DEBUG: */ die($URL);
912 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
913 $rel = ' rel="external"';
915 // Do we have internal or external URL?
916 if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
917 // Own (=internal) URL
922 $OUTPUT = ob_get_contents();
924 // Clear it only if there is content
925 if (!empty($OUTPUT)) {
929 // Secure the URL against bad things such als HTML insertions and so on...
930 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
932 // Simple probe for bots/spiders from search engines
933 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
934 // Output new location link as anchor
935 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
936 } elseif (!headers_sent()) {
937 // Load URL when headers are not sent
938 //* DEBUG: */ debug_report_bug("URL={$URL}");
939 sendHeader('Location: '.str_replace('&', '&', $URL));
941 // Output error message
942 loadInclude('inc/header.php');
943 LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
944 loadInclude('inc/footer.php');
947 // Shut the mailer down here
951 // Wrapper for redirectToUrl but URL comes from a configuration entry
952 function redirectToConfiguredUrl ($configEntry) {
954 $URL = getConfig($configEntry);
959 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
967 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
968 // Is the code a string?
969 if (!is_string($code)) {
970 // Silently return it
974 // Init replacement-array with full security characters
975 $secChars = $GLOBALS['security_chars'];
977 // Select smaller set of chars to replace when we e.g. want to compile URLs
978 if (!$full) $secChars = $GLOBALS['url_chars'];
981 if ($constants === true) {
982 // BEFORE 0.2.1 : Language and data constants
983 // WITH 0.2.1+ : Only language constants
984 $code = str_replace('{--','".', str_replace('--}','."', $code));
986 // BEFORE 0.2.1 : Not used
987 // WITH 0.2.1+ : Data constants
988 $code = str_replace('{!','".', str_replace("!}", '."', $code));
991 // Compile QUOT and other non-HTML codes
992 foreach ($secChars['to'] as $k => $to) {
993 // Do the reversed thing as in inc/libs/security_functions.php
994 $code = str_replace($to, $secChars['from'][$k], $code);
997 // But shall I keep simple quotes for later use?
998 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1000 // Find $content[bla][blub] entries
1001 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1003 // Are some matches found?
1004 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1005 // Replace all matches
1006 $matchesFound = array();
1007 foreach ($matches[0] as $key => $match) {
1008 // Fuzzy look has failed by default
1009 $fuzzyFound = false;
1011 // Fuzzy look on match if already found
1012 foreach ($matchesFound as $found => $set) {
1014 $test = substr($found, 0, strlen($match));
1016 // Does this entry exist?
1017 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1018 if ($test == $match) {
1020 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1027 if ($fuzzyFound) continue;
1029 // Take all string elements
1030 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1031 // Replace it in the code
1032 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1033 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1034 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1035 $matchesFound[$key."_".$matches[4][$key]] = 1;
1036 $matchesFound[$match] = 1;
1037 } elseif (!isset($matchesFound[$match])) {
1038 // Not yet replaced!
1039 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1040 $code = str_replace($match, "\".".$match.".\"", $code);
1041 $matchesFound[$match] = 1;
1046 // Return compiled code
1050 /************************************************************************
1052 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1053 * $a_sort sortiert: *
1055 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1056 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1057 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1058 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1059 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1061 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1062 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1063 * Sie, dass es doch nicht so schwer ist! :-) *
1065 ************************************************************************/
1066 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1068 while ($primary_key < count($a_sort)) {
1069 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1070 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1073 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1074 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1075 } elseif ($key != $key2) {
1076 // Sort numbers (E.g.: 9 < 10)
1077 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1078 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1082 // We have found two different values, so let's sort whole array
1083 foreach ($dummy as $sort_key => $sort_val) {
1084 $t = $dummy[$sort_key][$key];
1085 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1086 $dummy[$sort_key][$key2] = $t;
1097 // Write back sorted array
1102 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1105 if ($type == 'yn') {
1106 // This is a yes/no selection only!
1107 if ($id > 0) $prefix .= "[".$id."]";
1108 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1110 // Begin with regular selection box here
1111 if (!empty($prefix)) $prefix .= "_";
1113 if ($id > 0) $type2 .= "[".$id."]";
1114 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1119 for ($idx = 1; $idx < 32; $idx++) {
1120 $OUT .= "<option value=\"".$idx."\"";
1121 if ($default == $idx) $OUT .= ' selected="selected"';
1122 $OUT .= ">".$idx."</option>\n";
1126 case "month": // Month
1127 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1128 $OUT .= "<option value=\"".$month."\"";
1129 if ($default == $month) $OUT .= ' selected="selected"';
1130 $OUT .= ">".$descr."</option>\n";
1134 case "year": // Year
1136 $year = date('Y', time());
1138 // Use configured min age or fixed?
1139 if (GET_EXT_VERSION('other') >= '0.2.1') {
1141 $startYear = $year - getConfig('min_age');
1144 $startYear = $year - 16;
1147 // Calculate earliest year (100 years old people can still enter Internet???)
1148 $minYear = $year - 100;
1150 // Check if the default value is larger than minimum and bigger than actual year
1151 if (($default > $minYear) && ($default >= $year)) {
1152 for ($idx = $year; $idx < ($year + 11); $idx++) {
1153 $OUT .= "<option value=\"".$idx."\"";
1154 if ($default == $idx) $OUT .= ' selected="selected"';
1155 $OUT .= ">".$idx."</option>\n";
1157 } elseif ($default == -1) {
1158 // Current year minus 1
1159 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1161 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1164 // Get current year and subtract the configured minimum age
1165 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1166 // Calculate earliest year depending on extension version
1167 if (GET_EXT_VERSION('other') >= '0.2.1') {
1168 // Use configured minimum age
1169 $year = date('Y', time()) - getConfig('min_age');
1171 // Use fixed 16 years age
1172 $year = date('Y', time()) - 16;
1175 // Construct year selection list
1176 for ($idx = $minYear; $idx <= $year; $idx++) {
1177 $OUT .= "<option value=\"".$idx."\"";
1178 if ($default == $idx) $OUT .= ' selected="selected"';
1179 $OUT .= ">".$idx."</option>\n";
1186 for ($idx = 0; $idx < 60; $idx+=5) {
1187 if (strlen($idx) == 1) $idx = '0'.$idx;
1188 $OUT .= "<option value=\"".$idx."\"";
1189 if ($default == $idx) $OUT .= ' selected="selected"';
1190 $OUT .= ">".$idx."</option>\n";
1195 for ($idx = 0; $idx < 24; $idx++) {
1196 if (strlen($idx) == 1) $idx = '0'.$idx;
1197 $OUT .= "<option value=\"".$idx."\"";
1198 if ($default == $idx) $OUT .= ' selected="selected"';
1199 $OUT .= ">".$idx."</option>\n";
1204 $OUT .= "<option value=\"Y\"";
1205 if ($default == 'Y') $OUT .= ' selected="selected"';
1206 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1207 if ($default == 'N') $OUT .= ' selected="selected"';
1208 $OUT .= ">{--NO--}</option>\n";
1211 $OUT .= " </select>\n";
1216 // Deprecated : $length
1219 function generateRandomCode ($length, $code, $uid, $DATA = '') {
1220 // Fix missing _MAX constant
1221 // @TODO Rewrite this unnice code
1222 if (!defined('_MAX')) define('_MAX', 15235);
1224 // Build server string
1225 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH').'inc/databases.php');
1228 $keys = getConfig('SITE_KEY').getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY');
1229 if (isConfigEntrySet('secret_key')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('secret_key');
1230 if (isConfigEntrySet('file_hash')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('file_hash');
1231 $keys .= getConfig('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1232 if (isConfigEntrySet('master_salt')) $keys .= getConfig('ENCRYPT_SEPERATOR').getConfig('master_salt');
1234 // Build string from misc data
1235 $data = $code.getConfig('ENCRYPT_SEPERATOR').$uid.getConfig('ENCRYPT_SEPERATOR').$DATA;
1237 // Add more additional data
1238 if (isSessionVariableSet('u_hash')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('u_hash');
1239 if (isUserIdSet()) $data .= getConfig('ENCRYPT_SEPERATOR').getUserId();
1240 if (isSessionVariableSet('mxchange_theme')) $data .= getConfig('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1241 if (isSessionVariableSet('mx_lang')) $data .= getConfig('ENCRYPT_SEPERATOR').getLanguage();
1242 if (isset($GLOBALS['refid'])) $data .= getConfig('ENCRYPT_SEPERATOR').$GLOBALS['refid'];
1244 // Calculate number for generating the code
1245 $a = $code + getConfig('_ADD') - 1;
1247 if (isConfigEntrySet('master_hash')) {
1248 // Generate hash with master salt from modula of number with the prime number and other data
1249 $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'));
1251 // Create number from hash
1252 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1254 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1255 $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));
1257 // Create number from hash
1258 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(getConfig('_ADD'))) / pi();
1261 // At least 10 numbers shall be secure enought!
1262 $len = getConfig('code_length');
1263 if ($len == 0) $len = $length;
1264 if ($len == 0) $len = 10;
1266 // Cut off requested counts of number
1267 $return = substr(str_replace('.', '', $rcode), 0, $len);
1269 // Done building code
1273 // Does only allow numbers
1274 function bigintval ($num, $castValue = true) {
1275 // Filter all numbers out
1276 $ret = preg_replace("/[^0123456789]/", '', $num);
1279 if ($castValue) $ret = (double)$ret;
1281 // Has the whole value changed?
1282 // @TODO Remove this if() block if all is working fine
1283 if ("".$ret."" != ''.$num."") {
1285 debug_report_bug("{$ret}<>{$num}");
1292 // Insert the code in $img_code into jpeg or PNG image
1293 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1294 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1295 // Stop execution of function here because of over-sized code length
1297 } elseif (!$headerSent) {
1298 // Return in an HTML code code
1299 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1303 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
1304 if (isFileReadable($img)) {
1305 // Switch image type
1306 switch (getConfig('img_type'))
1309 // Okay, load image and hide all errors
1310 $image = @imagecreatefromjpeg($img);
1314 // Okay, load image and hide all errors
1315 $image = @imagecreatefrompng($img);
1319 // Exit function here
1320 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1324 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1325 $text_color = imagecolorallocate($image, 0, 0, 0);
1327 // Insert code into image
1328 imagestring($image, 5, 14, 2, $img_code, $text_color);
1330 // Return to browser
1331 sendHeader('Content-Type: image/' . getConfig('img_type'));
1333 // Output image with matching image factory
1334 switch (getConfig('img_type')) {
1335 case 'jpg': imagejpeg($image); break;
1336 case 'png': imagepng($image); break;
1339 // Remove image from memory
1340 imagedestroy($image);
1342 // Create selection box or array of splitted timestamp
1343 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align = 'center', $return_array=false) {
1344 // Calculate 2-seconds timestamp
1345 $stamp = round($timestamp);
1346 //* DEBUG: */ print("*".$stamp.'/'.$timestamp."*<br />");
1348 // Do we have a leap year?
1350 $TEST = date('Y', time()) / 4;
1351 $M1 = date('m', time());
1352 $M2 = date('m', (time() + $timestamp));
1354 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1355 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1357 // First of all years...
1358 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1359 //* DEBUG: */ print("Y={$Y}<br />\n");
1361 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1362 //* DEBUG: */ print("M={$M}<br />\n");
1364 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1365 //* DEBUG: */ print("W={$W}<br />\n");
1367 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1368 //* DEBUG: */ print("D={$D}<br />\n");
1370 $h = abs(floor($timestamp / 3600 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24) - $W * 7 * 24 - $D * 24));
1371 //* DEBUG: */ print("h={$h}<br />\n");
1373 $m = abs(floor($timestamp / 60 - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 60 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 60) - $W * 7 * 24 * 60 - $D * 24 * 60 - $h * 60));
1374 //* DEBUG: */ print("m={$m}<br />\n");
1375 // And at last seconds...
1376 $s = abs(floor($timestamp - $Y * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600 - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) * 24 * 3600) - $W * 7 * 24 * 3600 - $D * 24 * 3600 - $h * 3600 - $m * 60));
1377 //* DEBUG: */ print("s={$s}<br />\n");
1379 // Is seconds zero and time is < 60 seconds?
1380 if (($s == 0) && ($timestamp < 60)) {
1382 $s = round($timestamp);
1386 // Now we convert them in seconds...
1388 if ($return_array) {
1389 // Just put all data in an array for later use
1401 $OUT = "<div align=\"".$align."\">\n";
1402 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1405 if (ereg('Y', $display) || (empty($display))) {
1406 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1409 if (ereg("M", $display) || (empty($display))) {
1410 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1413 if (ereg("W", $display) || (empty($display))) {
1414 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1417 if (ereg("D", $display) || (empty($display))) {
1418 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1421 if (ereg("h", $display) || (empty($display))) {
1422 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1425 if (ereg('m', $display) || (empty($display))) {
1426 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1429 if (ereg("s", $display) || (empty($display))) {
1430 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1436 if (ereg('Y', $display) || (empty($display))) {
1437 // Generate year selection
1438 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1439 for ($idx = 0; $idx <= 10; $idx++) {
1440 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1441 if ($idx == $Y) $OUT .= ' selected="selected"';
1442 $OUT .= ">".$idx."</option>\n";
1444 $OUT .= " </select></td>\n";
1446 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1449 if (ereg("M", $display) || (empty($display))) {
1450 // Generate month selection
1451 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1452 for ($idx = 0; $idx <= 11; $idx++)
1454 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1455 if ($idx == $M) $OUT .= ' selected="selected"';
1456 $OUT .= ">".$idx."</option>\n";
1458 $OUT .= " </select></td>\n";
1460 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1463 if (ereg("W", $display) || (empty($display))) {
1464 // Generate week selection
1465 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1466 for ($idx = 0; $idx <= 4; $idx++) {
1467 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1468 if ($idx == $W) $OUT .= ' selected="selected"';
1469 $OUT .= ">".$idx."</option>\n";
1471 $OUT .= " </select></td>\n";
1473 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1476 if (ereg("D", $display) || (empty($display))) {
1477 // Generate day selection
1478 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1479 for ($idx = 0; $idx <= 31; $idx++) {
1480 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1481 if ($idx == $D) $OUT .= ' selected="selected"';
1482 $OUT .= ">".$idx."</option>\n";
1484 $OUT .= " </select></td>\n";
1486 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1489 if (ereg("h", $display) || (empty($display))) {
1490 // Generate hour selection
1491 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1492 for ($idx = 0; $idx <= 23; $idx++) {
1493 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1494 if ($idx == $h) $OUT .= ' selected="selected"';
1495 $OUT .= ">".$idx."</option>\n";
1497 $OUT .= " </select></td>\n";
1499 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1502 if (ereg('m', $display) || (empty($display))) {
1503 // Generate minute selection
1504 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1505 for ($idx = 0; $idx <= 59; $idx++) {
1506 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1507 if ($idx == $m) $OUT .= ' selected="selected"';
1508 $OUT .= ">".$idx."</option>\n";
1510 $OUT .= " </select></td>\n";
1512 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1515 if (ereg("s", $display) || (empty($display))) {
1516 // Generate second selection
1517 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1518 for ($idx = 0; $idx <= 59; $idx++) {
1519 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1520 if ($idx == $s) $OUT .= ' selected="selected"';
1521 $OUT .= ">".$idx."</option>\n";
1523 $OUT .= " </select></td>\n";
1525 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1528 $OUT .= "</table>\n";
1530 // Return generated HTML code
1536 function createTimestampFromSelections ($prefix, $POST) {
1537 // Initial return value
1540 // Do we have a leap year?
1542 $TEST = date('Y', time()) / 4;
1543 $M1 = date('m', time());
1544 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1545 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1546 // First add years...
1547 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1549 $ret += $POST[$prefix."_mo"] * 2628000;
1551 $ret += $POST[$prefix."_we"] * 604800;
1553 $ret += $POST[$prefix."_da"] * 86400;
1555 $ret += $POST[$prefix."_ho"] * 3600;
1557 $ret += $POST[$prefix."_mi"] * 60;
1558 // And at last seconds...
1559 $ret += $POST[$prefix."_se"];
1560 // Return calculated value
1564 // Sends out mail to all administrators
1565 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1566 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1567 // Trim template name
1568 $template = trim($template);
1570 // Load email template
1571 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1573 // Check which admin shall receive this mail
1574 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1575 array($template), __FUNCTION__, __LINE__);
1576 if (SQL_NUMROWS($result) == 0) {
1577 // Create new entry (to all admins)
1578 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1579 array($template), __FUNCTION__, __LINE__);
1581 // Load admin IDs...
1582 // @TODO This can be, somehow, rewritten
1583 $adminIds = array();
1584 while ($content = SQL_FETCHARRAY($result)) {
1585 $adminIds[] = $content['admin_id'];
1589 SQL_FREERESULT($result);
1594 // "implode" IDs and query string
1595 $aid = implode(',', $adminIds);
1597 if (EXT_IS_ACTIVE('events')) {
1598 // Add line to user events
1599 EVENTS_ADD_LINE($subj, $msg, $UID);
1601 // Log error for debug
1602 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1608 } elseif ($aid == '0') {
1609 // Select all email adresses
1610 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1611 __FUNCTION__, __LINE__);
1613 // If Admin-ID is not "to-all" select
1614 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1615 array($aid), __FUNCTION__, __LINE__);
1619 // Load email addresses and send away
1620 while ($content = SQL_FETCHARRAY($result)) {
1621 sendEmail($content['email'], $subj, $msg);
1625 SQL_FREERESULT($result);
1628 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1629 function createFancyTime ($stamp) {
1630 // Get data array with years/months/weeks/days/...
1631 $data = createTimeSelections($stamp, '', '', '', true);
1633 foreach($data as $k => $v) {
1635 // Value is greater than 0 "eval" data to return string
1636 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1642 // Do we have something there?
1643 if (strlen($ret) > 0) {
1644 // Remove leading commata and space
1645 $ret = substr($ret, 2);
1648 $ret = "0 {--_SECONDS--}";
1651 // Return fancy time string
1656 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1657 $SEP = ''; $TOP = '';
1660 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1664 for ($page = 1; $page <= $PAGES; $page++) {
1665 // Is the page currently selected or shall we generate a link to it?
1666 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1667 // Is currently selected, so only highlight it
1668 $NAV .= "<strong>-";
1670 // Open anchor tag and add base URL
1671 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1673 // Add userid when we shall show all mails from a single member
1674 if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1676 // Close open anchor tag
1680 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == '1'))) {
1681 // Is currently selected, so only highlight it
1682 $NAV .= "-</strong>";
1688 // Add seperator if we have not yet reached total pages
1689 if ($page < $PAGES) $NAV .= " | ";
1692 // Define constants only once
1693 if (!defined('__NAV_OUTPUT')) {
1694 define('__NAV_OUTPUT' , $NAV);
1695 define('__NAV_COLSPAN', $colspan);
1696 define('__NAV_TOP' , $TOP);
1697 define('__NAV_SEP' , $SEP);
1700 // Load navigation template
1701 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1703 if ($return === true) {
1704 // Return generated HTML-Code
1712 // Extract host from script name
1713 function extractHostnameFromUrl (&$script) {
1714 // Use default SERVER_URL by default... ;) So?
1715 $url = constant('SERVER_URL');
1717 // Is this URL valid?
1718 if (substr($script, 0, 7) == 'http://') {
1719 // Use the hostname from script URL as new hostname
1720 $url = substr($script, 7);
1721 $extract = explode('/', $url);
1723 // Done extracting the URL :)
1726 // Extract host name
1727 $host = str_replace('http://', '', $url);
1728 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1730 // Generate relative URL
1731 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1732 if (substr(strtolower($script), 0, 7) == 'http://') {
1733 // But only if http:// is in front!
1734 $script = substr($script, (strlen($url) + 7));
1735 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1737 $script = substr($script, (strlen($url) + 8));
1740 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1741 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1747 // Send a GET request
1748 function sendGetRequest ($script) {
1749 // Compile the script name
1750 $script = COMPILE_CODE($script);
1752 // Extract host name from script
1753 $host = extractHostnameFromUrl($script);
1755 // Generate GET request header
1756 $request = "GET /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1757 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1758 $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
1759 if (defined('FULL_VERSION')) {
1760 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
1762 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?" . getConfig('HTTP_EOL');
1764 $request .= "Content-Type: text/plain" . getConfig('HTTP_EOL');
1765 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1766 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1768 // Send the raw request
1769 $response = sendRawRequest($host, $request);
1771 // Return the result to the caller function
1775 // Send a POST request
1776 function sendPostRequest ($script, $postData) {
1777 // Is postData an array?
1778 if (!is_array($postData)) {
1780 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1781 return array('', '', '');
1784 // Compile the script name
1785 $script = COMPILE_CODE($script);
1787 // Extract host name from script
1788 $host = extractHostnameFromUrl($script);
1790 // Construct request
1791 $data = http_build_query($postData, '','&');
1793 // Generate POST request header
1794 $request = "POST /" . trim($script) . " HTTP/1.1" . getConfig('HTTP_EOL');
1795 $request .= "Host: " . $host . getConfig('HTTP_EOL');
1796 $request .= "Referer: " . constant('URL') . "/admin.php" . getConfig('HTTP_EOL');
1797 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . getConfig('HTTP_EOL');
1798 $request .= "Content-type: application/x-www-form-urlencoded" . getConfig('HTTP_EOL');
1799 $request .= "Content-length: " . strlen($data) . getConfig('HTTP_EOL');
1800 $request .= "Cache-Control: no-cache" . getConfig('HTTP_EOL');
1801 $request .= "Connection: Close" . getConfig('HTTP_EOL') . getConfig('HTTP_EOL');
1804 // Send the raw request
1805 $response = sendRawRequest($host, $request);
1807 // Return the result to the caller function
1811 // Sends a raw request to another host
1812 function sendRawRequest ($host, $request) {
1813 // Init errno and errdesc with 'all fine' values
1814 $errno = 0; $errdesc = '';
1817 $response = array('', '', '');
1819 // Default is not to use proxy
1822 // Are proxy settins set?
1823 if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1829 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1830 if ($useProxy === true) {
1831 // Connect to host through proxy connection
1832 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), bigintval(getConfig('proxy_port')), $errno, $errdesc, 30);
1834 // Connect to host directly
1835 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1839 if (!is_resource($fp)) {
1845 if ($useProxy === true) {
1846 // Generate CONNECT request header
1847 $proxyTunnel = "CONNECT " . $host . ":80 HTTP/1.1" . getConfig('HTTP_EOL');
1848 $proxyTunnel .= "Host: " . $host . getConfig('HTTP_EOL');
1850 // Use login data to proxy? (username at least!)
1851 if (getConfig('proxy_username') != '') {
1853 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')) . getConfig('ENCRYPT_SEPERATOR') . COMPILE_CODE(getConfig('proxy_password')));
1854 $proxyTunnel .= "Proxy-Authorization: Basic " . $encodedAuth . getConfig('HTTP_EOL');
1857 // Add last new-line
1858 $proxyTunnel .= getConfig('HTTP_EOL');
1859 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1862 fputs($fp, $proxyTunnel);
1866 // No response received
1870 // Read the first line
1871 $resp = trim(fgets($fp, 10240));
1872 $respArray = explode(' ', $resp);
1873 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1874 // Invalid response!
1880 fputs($fp, $request);
1883 while (!feof($fp)) {
1884 $response[] = trim(fgets($fp, 1024));
1890 // Skip first empty lines
1892 foreach ($resp as $idx => $line) {
1894 $line = trim($line);
1896 // Is this line empty?
1899 array_shift($response);
1901 // Abort on first non-empty line
1906 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1908 // Proxy agent found?
1909 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy === true)) {
1910 // Proxy header detected, so remove two lines
1911 array_shift($response);
1912 array_shift($response);
1915 // Was the request successfull?
1916 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1917 // Not found / access forbidden
1918 $response = array('', '', '');
1925 // Taken from www.php.net eregi() user comments
1926 function isEmailValid ($email) {
1928 $email = COMPILE_CODE($email);
1930 // Check first part of email address
1931 $first = '[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*';
1934 $domain = '[a-z0-9-]+(\.[a-z0-9-]{2,5})+';
1937 $regex = '@^' . $first . '\@' . $domain . '$@iU';
1939 // Return check result
1940 // @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
1941 return preg_match($regex, $email);
1944 // Function taken from user comments on www.php.net / function eregi()
1945 function isUrlValid ($URL, $compile=true) {
1946 // Trim URL a little
1947 $URL = trim(urldecode($URL));
1948 //* DEBUG: */ echo $URL."<br />";
1950 // Compile some chars out...
1951 if ($compile) $URL = compileUriCode($URL, false, false, false);
1952 //* DEBUG: */ echo $URL."<br />";
1954 // Check for the extension filter
1955 if (EXT_IS_ACTIVE('filter')) {
1956 // Use the extension's filter set
1957 return FILTER_isUrlValid($URL, false);
1960 // If not installed, perform a simple test. Just make it sure there is always a http:// or
1961 // https:// in front of the URLs
1962 return isUrlValidSimple($URL);
1965 // Generate a list of administrative links to a given userid
1966 function generateMemberAdminActionLinks ($uid, $status = '') {
1967 // Define all main targets
1968 $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
1970 // Begin of navigation links
1971 $eval = "\$OUT = \"[ ";
1973 foreach ($TARGETS as $tar) {
1974 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
1975 //* DEBUG: */ echo "*".$tar.'/'.$status."*<br />\n";
1976 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1977 // Locked accounts shall be unlocked
1978 $eval .= "UNLOCK_USER";
1980 // All other status is fine
1981 $eval .= strtoupper($tar);
1983 $eval .= "_TITLE--}\\\">{--ADMIN_";
1984 if (($tar == "lock_user") && ($status == 'LOCKED')) {
1985 // Locked accounts shall be unlocked
1986 $eval .= "UNLOCK_USER";
1988 // All other status is fine
1989 $eval .= strtoupper($tar);
1991 $eval .= "--}</a></span> | ";
1994 // Finish navigation link
1995 $eval = substr($eval, 0, -7)."]\";";
2002 // Generate an email link
2003 function generateMemberEmailLink ($email, $table = 'admins') {
2004 // Default email link (INSECURE! Spammer can read this by harvester programs)
2005 $EMAIL = 'mailto:' . $email;
2007 // Check for several extensions
2008 if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2009 // Create email link for contacting admin in guest area
2010 $EMAIL = adminsCreateEmailLink($email);
2011 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2012 // Create email link for contacting a member within admin area (or later in other areas, too?)
2013 $EMAIL = USER_generateMemberEmailLink($email);
2014 } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2015 // Create email link to contact sponsor within admin area (or like the link above?)
2016 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2019 // Shall I close the link when there is no admin?
2020 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2022 // Return email link
2026 // Generate a hash for extra-security for all passwords
2027 function generateHash ($plainText, $salt = '') {
2028 // Is the required extension 'sql_patches' there and a salt is not given?
2029 if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2030 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2031 return md5($plainText);
2034 // Do we miss an arry element here?
2035 if (!isConfigEntrySet('file_hash')) {
2037 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2040 // When the salt is empty build a new one, else use the first x configured characters as the salt
2042 // Build server string (inc/databases.php is no longer updated with every commit)
2043 $server = $_SERVER['PHP_SELF'].getConfig('ENCRYPT_SEPERATOR').detectUserAgent().getConfig('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').getConfig('ENCRYPT_SEPERATOR').detectRemoteAddr();
2046 $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');
2049 $data = $plainText.getConfig('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).getConfig('ENCRYPT_SEPERATOR').time();
2051 // Calculate number for generating the code
2052 $a = time() + getConfig('_ADD') - 1;
2054 // Generate SHA1 sum from modula of number and the prime number
2055 $sha1 = sha1(($a % getConfig('_PRIME')).$server.getConfig('ENCRYPT_SEPERATOR').$keys.getConfig('ENCRYPT_SEPERATOR').$data.getConfig('ENCRYPT_SEPERATOR').getConfig('DATE_KEY').getConfig('ENCRYPT_SEPERATOR').$a);
2056 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2057 $sha1 = scrambleString($sha1);
2058 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2059 //* DEBUG: */ $sha1b = descrambleString($sha1);
2060 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2062 // Generate the password salt string
2063 $salt = substr($sha1, 0, getConfig('salt_length'));
2064 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2067 $salt = substr($salt, 0, getConfig('salt_length'));
2068 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2072 return $salt.sha1($salt.$plainText);
2075 // Scramble a string
2076 function scrambleString($str) {
2080 // Final check, in case of failture it will return unscrambled string
2081 if (strlen($str) > 40) {
2082 // The string is to long
2084 } elseif (strlen($str) == 40) {
2086 $scrambleNums = explode(':', getConfig('pass_scramble'));
2088 // Generate new numbers
2089 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2092 // Scramble string here
2093 //* DEBUG: */ echo "***Original=".$str."***<br />";
2094 for ($idx = 0; $idx < strlen($str); $idx++) {
2095 // Get char on scrambled position
2096 $char = substr($str, $scrambleNums[$idx], 1);
2098 // Add it to final output string
2099 $scrambled .= $char;
2102 // Return scrambled string
2103 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2107 // De-scramble a string scrambled by scrambleString()
2108 function descrambleString($str) {
2109 // Scramble only 40 chars long strings
2110 if (strlen($str) != 40) return $str;
2112 // Load numbers from config
2113 $scrambleNums = explode(':', getConfig('pass_scramble'));
2116 if (count($scrambleNums) != 40) return $str;
2118 // Begin descrambling
2119 $orig = str_repeat(" ", 40);
2120 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2121 for ($idx = 0; $idx < 40; $idx++) {
2122 $char = substr($str, $idx, 1);
2123 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2126 // Return scrambled string
2127 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2131 // Generated a "string" for scrambling
2132 function genScrambleString ($len) {
2133 // Prepare array for the numbers
2134 $scrambleNumbers = array();
2136 // First we need to setup randomized numbers from 0 to 31
2137 for ($idx = 0; $idx < $len; $idx++) {
2139 $rand = mt_rand(0, ($len -1));
2141 // Check for it by creating more numbers
2142 while (array_key_exists($rand, $scrambleNumbers)) {
2143 $rand = mt_rand(0, ($len -1));
2147 $scrambleNumbers[$rand] = $rand;
2150 // So let's create the string for storing it in database
2151 $scrambleString = implode(':', $scrambleNumbers);
2152 return $scrambleString;
2155 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2156 function generatePassString ($passHash) {
2157 // Return vanilla password hash
2160 // Is a secret key and master salt already initialized?
2161 if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2162 // Only calculate when the secret key is generated
2163 $newHash = ''; $start = 9;
2164 for ($idx = 0; $idx < 10; $idx++) {
2165 $part1 = hexdec(substr($passHash, $start, 4));
2166 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2167 $mod = dechex($idx);
2168 if ($part1 > $part2) {
2169 $mod = dechex(sqrt(($part1 - $part2) * getConfig('_PRIME') / pi()));
2170 } elseif ($part2 > $part1) {
2171 $mod = dechex(sqrt(($part2 - $part1) * getConfig('_PRIME') / pi()));
2173 $mod = substr(round($mod), 0, 4);
2174 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2175 //* DEBUG: */ echo "*".$start.'='.$mod."*<br />";
2180 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).')');
2181 $ret = generateHash($newHash, getConfig('master_salt'));
2182 //* DEBUG: */ print($ret."<br />\n");
2185 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2186 $ret = md5($passHash);
2187 //* DEBUG: */ echo "++".$ret."++<br />\n";
2194 // Fix "deleted" cookies
2195 function fixDeletedCookies ($cookies) {
2196 // Is this an array with entries?
2197 if ((is_array($cookies)) && (count($cookies) > 0)) {
2198 // Then check all cookies if they are marked as deleted!
2199 foreach ($cookies as $cookieName) {
2200 // Is the cookie set to "deleted"?
2201 if (getSession($cookieName) == 'deleted') {
2202 setSession($cookieName, '');
2208 // Output error messages in a fasioned way and die...
2209 function app_die ($F, $L, $msg) {
2210 // Check if Script is already dieing and not let it kill itself another 1000 times
2211 if (!isset($GLOBALS['app_died'])) {
2212 // Make sure, that the script realy realy diese here and now
2213 $GLOBALS['app_died'] = true;
2216 loadIncludeOnce('inc/header.php');
2218 // Prepare message for output
2219 $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
2221 // Load the message template
2222 LOAD_TEMPLATE('admin_settings_saved', false, $msg);
2225 loadIncludeOnce('inc/footer.php');
2227 // Script tried to kill itself twice
2228 debug_report_bug('Script wanted to kill itself more than once! Raw message=' . $msg . ', file/function=' . $F . ', line=' . $L);
2232 // Display parsing time and number of SQL queries in footer
2233 function displayParsingTime() {
2234 // Is the timer started?
2235 if (!isset($GLOBALS['startTime'])) {
2241 $endTime = microtime(true);
2243 // "Explode" both times
2244 $start = explode(' ', $GLOBALS['startTime']);
2245 $end = explode(' ', $endTime);
2246 $runTime = $end[0] - $start[0];
2247 if ($runTime < 0) $runTime = 0;
2248 $runTime = translateComma($runTime);
2252 'runtime' => $runTime,
2253 'numSQLs' => (getConfig('sql_count') + 1),
2254 'numTemplates' => (getConfig('num_templates') + 1)
2257 // Load the template
2258 LOAD_TEMPLATE('show_timings', false, $content);
2261 // Check wether a boolean constant is set
2262 // Taken from user comments in PHP documentation for function constant()
2263 function isBooleanConstantAndTrue ($constName) { // : Boolean
2264 // Failed by default
2268 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2270 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2271 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2274 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2275 if (defined($constName)) {
2277 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2278 $res = (constant($constName) === true);
2282 $GLOBALS['cache_array']['const'][$constName] = $res;
2284 //* DEBUG: */ var_dump($res);
2290 // Checks if a given apache module is loaded
2291 function isApacheModuleLoaded ($apacheModule) {
2292 // Check it and return result
2293 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2296 // Get current theme name
2297 function getCurrentTheme() {
2298 // The default theme is 'default'... ;-)
2301 // Load default theme if not empty from configuration
2302 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2304 if (!isSessionVariableSet('mxchange_theme')) {
2305 // Set default theme
2306 setSession('mxchange_theme', $ret);
2307 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2308 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2309 // Get theme from cookie
2310 $ret = getSession('mxchange_theme');
2313 if (getThemeId($ret) == 0) {
2314 // Fix it to default
2317 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2318 // Prepare FQFN for checking
2319 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2321 // Installation mode active
2322 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2323 // Set cookie from URL data
2324 setSession('mxchange_theme', REQUEST_GET('theme'));
2325 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2326 // Set cookie from posted data
2327 setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2331 $ret = getSession('mxchange_theme');
2333 // Invalid design, reset cookie
2334 setSession('mxchange_theme', $ret);
2337 // Add (maybe) found theme.php file to inclusion list
2338 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2340 // Try to load the requested include file
2341 if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2343 // Return theme value
2347 // Get id from theme
2348 function getThemeId ($name) {
2349 // Is the extension 'theme' installed?
2350 if (!EXT_IS_ACTIVE('theme')) {
2358 // Is the cache entry there?
2359 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2360 // Get the version from cache
2361 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2364 incrementConfigEntry('cache_hits');
2365 } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2366 // Check if current theme is already imported or not
2367 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2368 array($name), __FUNCTION__, __LINE__);
2371 if (SQL_NUMROWS($result) == 1) {
2373 list($id) = SQL_FETCHROW($result);
2377 SQL_FREERESULT($result);
2384 // Generates an error code from given account status
2385 function generateErrorCodeFromUserStatus ($status) {
2386 // Default error code if unknown account status
2387 $errorCode = getCode('UNKNOWN_STATUS');
2389 // Generate constant name
2390 $constantName = sprintf("ID_%s", $status);
2392 // Is the constant there?
2393 if (isCodeSet($constantName)) {
2395 $errorCode = getCode($constantName);
2398 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2401 // Return error code
2405 // Function to search for the last modifified file
2406 function searchDirsRecursive ($dir, &$last_changed) {
2408 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2409 // Does it match what we are looking for? (We skip a lot files already!)
2410 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2411 $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2412 $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2413 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2415 // Walk through all entries
2416 foreach ($ds as $d) {
2417 // Generate proper FQFN
2418 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2420 // Is it a file and readable?
2421 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2422 if (isDirectory($FQFN)) {
2423 // $FQFN is a directory so also crawl into this directory
2425 if (!empty($dir)) $newDir = $dir . '/'. $d;
2426 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2427 searchDirsRecursive($newDir, $last_changed);
2428 } elseif (isFileReadable($FQFN)) {
2429 // $FQFN is a filename and no directory
2430 $time = filemtime($FQFN);
2431 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2432 if ($last_changed['time'] < $time) {
2433 // This file is newer as the file before
2434 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2435 $last_changed['path_name'] = $FQFN;
2436 $last_changed['time'] = $time;
2442 // "Getter" for revision/version data
2443 function getActualVersion ($type = 'Revision') {
2444 // By default nothing is new... ;-)
2447 if (EXT_IS_ACTIVE('cache')) {
2448 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2449 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
2450 if (!isset($GLOBALS['cache_array']['revision'][$type])
2451 || count($GLOBALS['cache_array']['revision']) < 3
2452 || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
2454 // Is the cache file outdated/invalid?
2456 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2458 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2459 unset($GLOBALS['cache_array']['revision']);
2461 // Reload load_cach-revison.php
2462 loadInclude('inc/loader/load_cache-revision.php');
2465 // Return found value
2466 return $GLOBALS['cache_array']['revision'][$type][0];
2469 // Old Version without ext-cache active (deprecated ?)
2471 // FQFN of revision file
2472 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2474 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2475 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2479 // Check for revision file
2480 if (!isFileReadable($FQFN)) {
2481 // Not found, so we need to create it
2484 // Revision file found
2485 $ins_vers = explode("\n", readFromFile($FQFN));
2487 // Get array for mapping information
2488 $mapper = array_flip(getSearchFor());
2489 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2491 // Is the content valid?
2492 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2493 // File needs update!
2496 // Return found value
2497 return trim($ins_vers[$mapper[$type]]);
2502 // Has it been updated?
2503 if ($new === true) {
2504 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2509 // Repares an array we are looking for
2510 // 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
2511 function getSearchFor () {
2512 // Add Revision, Date, Tag and Author
2513 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2515 // Return the created array
2519 // @TODO Please describe this function
2520 function getArrayFromActualVersion () {
2522 $next_dir = ''; // Directory to start with search
2523 $last_changed = array(
2527 $akt_vers = array(); // Init return array
2528 $res = 0; // Init value for counting the founded keywords
2530 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2531 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2534 $last_file = readFromFile($last_changed['path_name']);
2536 // Get all the keywords to search for
2537 $searchFor = getSearchFor();
2539 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2540 foreach ($searchFor as $search) {
2541 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2542 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2543 // This trimms the search-result and puts it in the $akt_vers-return array
2544 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2547 // Save the last-changed filename for debugging
2548 $akt_vers['File'] = $last_changed['path_name'];
2550 // at least 3 keyword-Tags are needed for propper values
2551 if ($res && $res >= 3
2552 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2553 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2554 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2555 // Prepare content witch need special treadment
2557 // Prepare timestamp for date
2558 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2559 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2561 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2562 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2563 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2567 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2568 $version = sendGetRequest('check-updates3.php');
2571 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2572 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2573 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2574 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2575 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2578 // Return prepared array
2582 // Back-ported from the new ship-simu engine. :-)
2583 function debug_get_printable_backtrace () {
2585 $backtrace = "<ol>\n";
2587 // Get and prepare backtrace for output
2588 $backtraceArray = debug_backtrace();
2589 foreach ($backtraceArray as $key => $trace) {
2590 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2591 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2592 if (!isset($trace['args'])) $trace['args'] = array();
2593 $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";
2597 $backtrace .= "</ol>\n";
2599 // Return the backtrace
2603 // Output a debug backtrace to the user
2604 function debug_report_bug ($message = '') {
2607 // Is the optional message set?
2608 if (!empty($message)) {
2610 $debug = sprintf("Note: %s<br />\n",
2614 // @TODO Add a little more infos here
2615 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2619 $debug .= "Please report this bug at <a title=\"Direct link to the bug-tracker\" href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a> and include the logfile from <strong>inc/cache/debug.log</strong> in your report (you cannot attach files!):<pre>";
2620 $debug .= debug_get_printable_backtrace();
2621 $debug .= "</pre>\nRequest-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2622 $debug .= "Thank you for finding bugs.";
2625 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2629 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2630 function generateSeed () {
2631 list($usec, $sec) = explode(" ", microtime());
2632 return ((float)$sec + (float)$usec);
2635 // Converts a message code to a human-readable message
2636 function convertCodeToMessage ($code) {
2639 case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2640 case getCode('LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2641 case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2642 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2643 case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2644 case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2645 case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2646 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2648 case getCode('ERROR_MAILID'):
2649 if (EXT_IS_ACTIVE($ext, true)) {
2650 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2652 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2656 case getCode('EXTENSION_PROBLEM'):
2657 if (REQUEST_ISSET_GET('ext')) {
2658 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET('ext'));
2660 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2664 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2665 case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2666 case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2667 case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2670 // Missing/invalid code
2671 $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2674 DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2678 // Return the message
2682 // Generate a "link" for the given admin id (aid)
2683 function generateAdminLink ($aid) {
2684 // No assigned admin is default
2685 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2687 // Zero? = Not assigned
2688 if (bigintval($aid) > 0) {
2689 // Load admin's login
2690 $login = getAdminLogin($aid);
2692 // Is the login valid?
2693 if ($login != '***') {
2694 // Is the extension there?
2695 if (EXT_IS_ACTIVE('admins')) {
2697 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">".$login."</a>";
2699 // Extension not found
2700 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2704 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2712 // Compile characters which are allowed in URLs
2713 function compileUriCode ($code, $simple=true) {
2714 // Compile constants
2715 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2717 // Compile QUOT and other non-HTML codes
2718 $code = str_replace('{DOT}', '.',
2719 str_replace('{SLASH}', '/',
2720 str_replace('{QUOT}', "'",
2721 str_replace('{DOLLAR}', '$',
2722 str_replace('{OPEN_ANCHOR}', '(',
2723 str_replace('{CLOSE_ANCHOR}', ')',
2724 str_replace('{OPEN_SQR}', '[',
2725 str_replace('{CLOSE_SQR}', ']',
2726 str_replace('{PER}', '%',
2730 // Return compiled code
2734 // Function taken from user comments on www.php.net / function eregi()
2735 function isUrlValidSimple ($url) {
2737 $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
2739 // Allows http and https
2740 $http = "(http|https)+(:\/\/)";
2742 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2743 // Test double-domains (e.g. .de.vu)
2744 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2746 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2748 $dir = "((/)+([-_\.[:alnum:]])+)*";
2750 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2751 // ... and the string after and including question character
2752 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2753 // Pattern for URLs like http://url/dir/doc.html?var=value
2754 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2755 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2756 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2757 // Pattern for URLs like http://url/dir/?var=value
2758 $pattern['d1dg1'] = $http.$domain1.$dir.'/'.$getstring1;
2759 $pattern['d2dg1'] = $http.$domain2.$dir.'/'.$getstring1;
2760 $pattern['ipdg1'] = $http.$ip.$dir.'/'.$getstring1;
2761 // Pattern for URLs like http://url/dir/page.ext
2762 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2763 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2764 $pattern['ipdp'] = $http.$ip.$dir.$page;
2765 // Pattern for URLs like http://url/dir
2766 $pattern['d1d'] = $http.$domain1.$dir;
2767 $pattern['d2d'] = $http.$domain2.$dir;
2768 $pattern['ipd'] = $http.$ip.$dir;
2769 // Pattern for URLs like http://url/?var=value
2770 $pattern['d1g1'] = $http.$domain1.'/'.$getstring1;
2771 $pattern['d2g1'] = $http.$domain2.'/'.$getstring1;
2772 $pattern['ipg1'] = $http.$ip.'/'.$getstring1;
2773 // Pattern for URLs like http://url?var=value
2774 $pattern['d1g12'] = $http.$domain1.$getstring1;
2775 $pattern['d2g12'] = $http.$domain2.$getstring1;
2776 $pattern['ipg12'] = $http.$ip.$getstring1;
2777 // Test all patterns
2779 foreach ($pattern as $key=>$pat) {
2781 if (defined('DEBUG_REGEX')) {
2782 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2783 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2784 $pat = str_replace("[:digit:]", "0-9", $pat);
2785 $pat = str_replace('.', "\.", $pat);
2786 $pat = str_replace("@", "\@", $pat);
2787 echo $key."= ".$pat."<br />";
2790 // Check if expression matches
2791 $reg = ($reg || preg_match(("^".$pat."^"), $url));
2794 if ($reg === true) break;
2797 // Return true/false
2801 // Wtites data to a config.php-style file
2802 // @TODO Rewrite this function to use readFromFile() and writeToFile()
2803 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
2804 // Initialize some variables
2810 // Is the file there and read-/write-able?
2811 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
2812 $search = 'CFG: ' . $comment;
2813 $tmp = $FQFN . '.tmp';
2815 // Open the source file
2816 $fp = fopen($FQFN, 'r') or OUTPUT_HTML('<strong>READ:</strong> ' . $FQFN . "<br />\n");
2818 // Is the resource valid?
2819 if (is_resource($fp)) {
2820 // Open temporary file
2821 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML('<strong>WRITE:</strong> ' . $tmp . "<br />\n");
2823 // Is the resource again valid?
2824 if (is_resource($fp_tmp)) {
2825 while (!feof($fp)) {
2826 // Read from source file
2827 $line = fgets ($fp, 1024);
2829 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
2832 if ($next === $seek) {
2834 $line = $prefix . $DATA . $suffix . "\n";
2840 // Write to temp file
2841 fputs($fp_tmp, $line);
2847 // Finished writing tmp file
2851 // Close source file
2854 if (($done === true) && ($found === true)) {
2855 // Copy back tmp file and delete tmp :-)
2856 copyFileVerified($tmp, $FQFN, 0644);
2857 return removeFile($tmp);
2858 } elseif ($found === false) {
2859 OUTPUT_HTML('<strong>CHANGE:</strong> 404!');
2861 OUTPUT_HTML('<strong>TMP:</strong> UNDONE!');
2865 // File not found, not readable or writeable
2866 OUTPUT_HTML('<strong>404:</strong> ' . $FQFN . '<br />');
2869 // An error was detected!
2872 // Send notification to admin
2873 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
2874 if (GET_EXT_VERSION('admins') >= '0.4.1') {
2876 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
2878 // Send out out-dated way
2879 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
2880 SEND_ADMIN_EMAILS($subject, $msg);
2884 // Debug message logger
2885 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
2886 // Is debug mode enabled?
2887 if ((isDebugModeEnabled()) || ($force === true)) {
2889 $message = str_replace("\r", '', str_replace("\n", '', $message));
2891 // Log this message away
2892 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
2893 fwrite($fp, date("d.m.Y|H:i:s", time())."|".$GLOBALS['module']."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
2898 // Load more reset scripts
2899 function runResetIncludes () {
2900 // Is the reset set or old sql_patches?
2901 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
2903 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
2906 // Get more daily reset scripts
2907 SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
2910 if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
2912 // Is the config entry set?
2913 if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
2914 // Create current week mark
2915 $currWeek = date('W', time());
2918 if (getConfig('last_week') != $currWeek) {
2919 // Include weekly reset scripts
2920 MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
2923 if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
2926 // Create current month mark
2927 $currMonth = date('m', time());
2930 if (getConfig('last_month') != $currMonth) {
2931 // Include monthly reset scripts
2932 MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
2935 if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
2940 runFilterChain('load_includes');
2943 // Handle extra values
2944 function handleExtraValues ($filterFunction, $value, $extraValue) {
2945 // Default is the value itself
2948 // Do we have a special filter function?
2949 if (!empty($filterFunction)) {
2950 // Does the filter function exist?
2951 if (function_exists($filterFunction)) {
2952 // Do we have extra parameters here?
2953 if (!empty($extraValue)) {
2954 // Put both parameters in one new array by default
2955 $args = array($value, $extraValue);
2957 // If we have an array simply use it and pre-extend it with our value
2958 if (is_array($extraValue)) {
2959 // Make the new args array
2960 $args = merge_array(array($value), $extraValue);
2963 // Call the multi-parameter call-back
2964 $ret = call_user_func_array($filterFunction, $args);
2966 // One parameter call
2967 $ret = call_user_func($filterFunction, $value);
2976 // Converts timestamp selections into a timestamp
2977 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
2978 // Init test variable
2981 // Get last three chars
2982 $test = substr($id, -3);
2984 // Improved way of checking! :-)
2985 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
2986 // Found a multi-selection for timings?
2987 $test = substr($id, 0, -3);
2988 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)) {
2989 // Generate timestamp
2990 $POST[$test] = createTimestampFromSelections($test, $POST);
2991 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
2993 // Remove data from array
2994 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
2995 unset($POST[$test.'_'.$rem]);
2999 unset($id); $skip = true; $test2 = $test;
3002 // Process this entry
3008 // Reverts the german decimal comma into Computer decimal dot
3009 function convertCommaToDot ($str) {
3010 // Default float is not a float... ;-)
3013 // Which language is selected?
3014 switch (getLanguage()) {
3015 case 'de': // German language
3016 // Remove german thousand dots first
3017 $str = str_replace('.', '', $str);
3019 // Replace german commata with decimal dot and cast it
3020 $float = (float)str_replace(',', '.', $str);
3023 default: // US and so on
3024 // Remove thousand dots first and cast
3025 $float = (float)str_replace(',', '', $str);
3033 // Handle menu-depending failed logins and return the rendered content
3034 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3035 // Default output is empty ;-)
3038 // Is the session data set?
3039 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3040 // Ignore zero values
3041 if (getSession('mxchange_'.$accessLevel.'_failures') > 0) {
3042 // Non-guest has login failures found, get both data and prepare it for template
3043 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3045 'login_failures' => getSession('mxchange_'.$accessLevel.'_failures'),
3046 'last_failure' => generateDateTime(getSession('mxchange_'.$accessLevel.'_last_fail'), '2')
3050 $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3053 // Reset session data
3054 setSession('mxchange_'.$accessLevel.'_failures', '');
3055 setSession('mxchange_'.$accessLevel.'_last_fail', '');
3058 // Return rendered content
3063 function rebuildCacheFiles ($cache, $inc = '') {
3064 // Shall I remove the cache file?
3065 if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3067 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3069 $GLOBALS['cache_instance']->destroyCacheFile();
3072 // Include file given?
3075 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3077 // Is the include there?
3078 if (isIncludeReadable($INC)) {
3079 // And rebuild it from scratch
3080 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3083 // Include not found!
3084 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3090 // Purge admin menu cache
3091 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3092 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3093 if (!EXT_IS_ACTIVE('cache')) {
3094 // Cache extension not active
3096 } elseif (!isCacheInstanceValid()) {
3097 // No cache instance!
3098 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3100 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3101 // Caching disabled (currently experiemental!)
3105 // Experiemental feature!
3106 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3109 // Determines the real remote address
3110 function determineRealRemoteAddress () {
3111 // Is a proxy in use?
3112 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3114 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3115 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3116 // Yet, another proxy
3117 $address = $_SERVER['HTTP_CLIENT_IP'];
3119 // The regular address when no proxy was used
3120 $address = $_SERVER['REMOTE_ADDR'];
3123 // This strips out the real address from proxy output
3124 if (strstr($address, ',')){
3125 $addressArray = explode(',', $address);
3126 $address = $addressArray[0];
3129 // Return the result
3133 // Adds a bonus mail to the queue
3134 // This is a high-level function!
3135 function addNewBonusMail ($data, $mode = '', $output=true) {
3136 // Use mode from data if not set and availble ;-)
3137 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3139 // Generate receiver list
3140 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3143 if (!empty($RECEIVER)) {
3144 // Add bonus mail to queue
3145 addBonusMailToQueue(
3157 // Mail inserted into bonus pool
3158 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3159 } elseif ($output) {
3160 // More entered than can be reached!
3161 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3164 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3168 // Determines referal id and sets it
3169 function DETERMINE_REFID () {
3170 // Check if refid is set
3171 if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3172 // The variable user comes from the click-counter script click.php and we only accept this here
3173 $GLOBALS['refid'] = bigintval($_GET['user']);
3174 } elseif (!empty($_POST['refid'])) {
3175 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3176 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3177 } elseif (!empty($_GET['refid'])) {
3178 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3179 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3180 } elseif (!empty($_GET['ref'])) {
3181 // Set refid=ref (the referal link uses such variable)
3182 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3183 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3184 // Set session refid als global
3185 $GLOBALS['refid'] = bigintval(getSession('refid'));
3186 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3187 // Set default refid as refid in URL
3188 $GLOBALS['refid'] = getConfig(('def_refid'));
3189 } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3190 // Select a random user which has confirmed enougth mails
3191 $GLOBALS['refid'] = determineRandomReferalId();
3193 // No default ID when sql_patches is not installed or none set
3194 $GLOBALS['refid'] = 0;
3197 // Set cookie when default refid > 0
3198 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3200 setSession('refid', $GLOBALS['refid']);
3203 // Return determined refid
3204 return $GLOBALS['refid'];
3207 // Enables the reset mode. Only call this function if you really want the
3209 function enableResetMode () {
3210 // Enable the reset mode
3211 $GLOBALS['reset_enabled'] = true;
3214 runFilterChain('reset_enabled');
3217 // Our shutdown-function
3218 function shutdown () {
3219 // Call the filter chain 'shutdown'
3220 runFilterChain('shutdown', null, false);
3222 if (SQL_IS_LINK_UP()) {
3224 SQL_CLOSE(__FILE__, __LINE__);
3225 } elseif ((!isInstalling()) && (isInstalled())) {
3227 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3230 // Stop executing here
3234 // Setter for userid
3235 function setUserId ($userid) {
3236 $GLOBALS['userid'] = bigintval($userid);
3239 // Getter for userid or returns zero
3240 function getUserId () {
3244 // Is the userid set?
3245 if (isUserIdSet()) {
3247 $userid = $GLOBALS['userid'];
3254 // Checks ether the userid is set
3255 function isUserIdSet () {
3256 return (isset($GLOBALS['userid']));
3259 // Handle message codes from URL
3260 function handleCodeMessage () {
3261 if (REQUEST_ISSET_GET('msg')) {
3262 // Default extension is "unknown"
3265 // Is extension given?
3266 if (REQUEST_ISSET_GET('ext')) $ext = REQUEST_GET('ext');
3268 // Convert the 'msg' parameter from URL to a human-readable message
3269 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3271 // Load message template
3272 LOAD_TEMPLATE('message', false, $msg);
3276 // Setter for extra title
3277 function setExtraTitle ($extraTitle) {
3278 $GLOBALS['extra_title'] = $extraTitle;
3281 // Getter for extra title
3282 function getExtraTitle () {
3283 // Is the extra title set?
3284 if (!isExtraTitleSet()) {
3285 // No, then abort here
3286 debug_report_bug('extra_title is not set!');
3290 return $GLOBALS['extra_title'];
3293 // Checks if the extra title is set
3294 function isExtraTitleSet () {
3295 return ((isset($GLOBALS['extra_title'])) && (!empty($GLOBALS['extra_title'])));
3298 //////////////////////////////////////////////////
3299 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3300 //////////////////////////////////////////////////
3302 if (!function_exists('html_entity_decode')) {
3303 // Taken from documentation on www.php.net
3304 function html_entity_decode ($string) {
3305 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3306 $trans_tbl = array_flip($trans_tbl);
3307 return strtr($string, $trans_tbl);