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 (constant('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 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid renderer %s detected.", constant('OUTPUT_MODE')));
83 app_die(__FUNCTION__, __LINE__, "<strong>{--FATAL_ERROR--}:</strong> {--LANG_NO_RENDER_DIRECT--}");
86 } elseif ((constant('_OB_CACHING') == "on") && (isset($GLOBALS['footer_sent'])) && ($GLOBALS['footer_sent'] == 1)) {
87 // Headers already sent?
90 DEBUG_LOG(__FUNCTION__, __LINE__, "Headers already sent! We need debug backtrace here.");
92 // Trigger an user error
93 debug_report_bug("Headers are already sent!");
96 // Output cached HTML code
97 $OUTPUT = ob_get_contents();
99 // Clear output buffer for later output if output is found
100 if (!empty($OUTPUT)) {
105 header("HTTP/1.1 200");
108 $now = gmdate('D, d M Y H:i:s') . ' GMT';
110 // General headers for no caching
111 header("Expired: " . $now); // RFC2616 - Section 14.21
112 header("Last-Modified: " . $now);
113 header("Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0"); // HTTP/1.1
114 header("Pragma: no-cache"); // HTTP/1.0
115 header("Connection: Close");
117 // Extension 'rewrite' installed?
118 if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
119 $OUTPUT = rewriteLinksInCode($OUTPUT);
122 // Compile and run finished rendered HTML code
123 while (strpos($OUTPUT, '{!') > 0) {
124 // Prepare the content and eval() it...
126 $eval = "\$newContent = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
129 // Was that eval okay?
130 if (empty($newContent)) {
131 // Something went wrong!
132 app_die(__FUNCTION__, __LINE__, "Evaluation error:<pre>".htmlentities($eval)."</pre>");
134 $OUTPUT = $newContent;
137 // Output code here, DO NOT REMOVE! ;-)
138 outputRawCode($OUTPUT);
139 } elseif ((constant('OUTPUT_MODE') == "render") && (!empty($OUTPUT))) {
140 // Rewrite links when rewrite extension is active
141 if ((EXT_IS_ACTIVE('rewrite')) && ($GLOBALS['output_mode'] != "1") && ($GLOBALS['output_mode'] != "-1")) {
142 $OUTPUT = rewriteLinksInCode($OUTPUT);
145 // Compile and run finished rendered HTML code
146 while (strpos($OUTPUT, '{!') > 0) {
147 $eval = "\$OUTPUT = \"".COMPILE_CODE(smartAddSlashes($OUTPUT))."\";";
151 // Output code here, DO NOT REMOVE! ;-)
152 outputRawCode($OUTPUT);
156 // Output the raw HTML code
157 function outputRawCode ($HTML) {
158 // Output stripped HTML code to avoid broken JavaScript code, etc.
159 echo stripslashes(stripslashes($HTML));
161 // Flush the output if only constant('_OB_CACHING') is not "on"
162 if (constant('_OB_CACHING') != "on") {
168 // Init fatal message array
169 function initFatalMessages () {
170 $GLOBALS['fatal_messages'] = array();
173 // Getter for whole fatal error messages
174 function getFatalArray () {
175 return $GLOBALS['fatal_messages'];
178 // Add a fatal error message to the queue array
179 function addFatalMessage ($F, $L, $message, $extra='') {
180 if (is_array($extra)) {
181 // Multiple extras for a message with masks
182 $message = call_user_func_array('sprintf', $extra);
183 } elseif (!empty($extra)) {
184 // $message is text with a mask plus extras to insert into the text
185 $message = sprintf($message, $extra);
188 // Add message to $GLOBALS['fatal_messages']
189 $GLOBALS['fatal_messages'][] = $message;
191 // Log fatal messages away
192 DEBUG_LOG($F, $L, " message={$message}");
195 // Getter for total fatal message count
196 function getTotalFatalErrors () {
200 // Do we have at least the first entry?
201 if (!empty($GLOBALS['fatal_messages'][0])) {
203 $count = count($GLOBALS['fatal_messages']);
210 // Load a template file and return it's content (only it's name; do not use ' or ")
211 function LOAD_TEMPLATE ($template, $return=false, $content=array()) {
212 // Add more variables which you want to use in your template files
213 global $DATA, $username;
215 // Get whole config array
216 $_CONFIG = getConfigArray();
218 // Make all template names lowercase
219 $template = strtolower($template);
221 // Count the template load
222 incrementConfigEntry('num_templates');
224 // Prepare IP number and User Agent
225 $REMOTE_ADDR = detectRemoteAddr();
226 if (!defined('REMOTE_ADDR')) define('REMOTE_ADDR', $REMOTE_ADDR);
227 $HTTP_USER_AGENT = detectUserAgent();
231 if (empty($GLOBALS['refid'])) $GLOBALS['refid'] = 0;
233 // @DEPRECATED Try to rewrite the if() condition
234 if ($template == "member_support_form") {
235 // Support request of a member
236 $result = SQL_QUERY_ESC("SELECT userid, gender, surname, family, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
237 array(getUserId()), __FUNCTION__, __LINE__);
239 // Is content an array?
240 if (is_array($content)) {
242 $content = merge_array($content, SQL_FETCHARRAY($result));
245 $content['gender'] = translateGender($content['gender']);
248 // @TODO Fine all templates which are using these direct variables and rewrite them.
249 // @TODO After this step is done, this else-block is history
250 list($gender, $surname, $family, $email) = SQL_FETCHROW($result);
253 $gender = translateGender($gender);
254 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("DEPRECATION-WARNING: content is not array (%s).", gettype($content)));
258 SQL_FREERESULT($result);
261 // Generate date/time string
262 $date_time = generateDateTime(time(), "1");
265 $basePath = sprintf("%stemplates/%s/html/", constant('PATH'), getLanguage());
268 // Check for admin/guest/member templates
269 if (strpos($template, "admin_") > -1) {
270 // Admin template found
272 } elseif (strpos($template, "guest_") > -1) {
273 // Guest template found
275 } elseif (strpos($template, "member_") > -1) {
276 // Member template found
278 } elseif (strpos($template, "install_") > -1) {
279 // Installation template found
281 } elseif (strpos($template, "ext_") > -1) {
282 // Extension template found
284 } elseif (strpos($template, "la_") > -1) {
285 // "Logical-area" template found
288 // Test for extension
289 $test = substr($template, 0, strpos($template, "_"));
290 if (EXT_IS_ACTIVE($test)) {
291 // Set extra path to extension's name
296 ////////////////////////
297 // Generate file name //
298 ////////////////////////
299 $FQFN = $basePath.$mode.$template.".tpl";
301 if ((!empty($GLOBALS['what'])) && ((strpos($template, "_header") > 0) || (strpos($template, "_footer") > 0)) && (($mode == "guest/") || ($mode == "member/") || ($mode == "admin/"))) {
302 // Select what depended header/footer template file for admin/guest/member area
303 $file2 = sprintf("%s%s%s_%s.tpl",
307 SQL_ESCAPE($GLOBALS['what'])
311 if (isFileReadable($file2)) $FQFN = $file2;
313 // Remove variable from memory
317 // Does the special template exists?
318 if (!isFileReadable($FQFN)) {
319 // Reset to default template
320 $FQFN = $basePath.$template.".tpl";
323 // Now does the final template exists?
324 if (isFileReadable($FQFN)) {
325 // The local file does exists so we load it. :)
326 $tmpl_file = readFromFile($FQFN);
328 // Replace ' to our own chars to preventing them being quoted
329 while (strpos($tmpl_file, "'") !== false) { $tmpl_file = str_replace("'", '{QUOT}', $tmpl_file); }
331 // Do we have to compile the code?
333 if ((strpos($tmpl_file, "\$") !== false) || (strpos($tmpl_file, '{--') !== false) || (strpos($tmpl_file, '--}') > 0)) {
335 $tmpl_file = "\$ret=\"".COMPILE_CODE(smartAddSlashes($tmpl_file))."\";";
338 // Simply return loaded code
342 // Add surrounding HTML comments to help finding bugs faster
343 $ret = "<!-- Template ".$template." - Start -->\n".$ret."<!-- Template ".$template." - End -->\n";
344 } elseif ((IS_ADMIN()) || ((isInstalling()) && (!isInstalled()))) {
345 // Only admins shall see this warning or when installation mode is active
346 $ret = "<br /><span class=\"guest_failed\">".TEMPLATE_404."</span><br />
347 (".basename($FQFN).")<br />
350 <pre>".print_r($content, true)."</pre>
352 <pre>".print_r($DATA, true)."</pre>
356 // Remove content and data
360 // Do we have some content to output or return?
362 // Not empty so let's put it out! ;)
363 if ($return === true) {
364 // Return the HTML code
370 } elseif (isDebugModeEnabled()) {
371 // Warning, empty output!
372 return "E:".$template."<br />\n";
376 // Send mail out to an email address
377 function sendEmail($toEmail, $subject, $message, $HTML = 'N', $mailHeader = '') {
378 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail},SUBJECT={$subject}<br />\n";
380 // Compile subject line (for POINTS constant etc.)
381 $eval = "\$subject = decodeEntities(\"".COMPILE_CODE(smartAddSlashes($subject))."\");";
385 if ((!eregi("@", $toEmail)) && ($toEmail > 0)) {
386 // Value detected, is the message extension installed?
387 if (EXT_IS_ACTIVE("msg")) {
388 ADD_MESSAGE_TO_BOX($toEmail, $subject, $message, $HTML);
391 // Load email address
392 $result_email = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1", array(bigintval($toEmail)), __FUNCTION__, __LINE__);
393 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):numRows=".SQL_NUMROWS($result_email)."<br />\n";
395 // Does the user exist?
396 if (SQL_NUMROWS($result_email)) {
397 // Load email address
398 list($toEmail) = SQL_FETCHROW($result_email);
401 $toEmail = constant('WEBMASTER');
405 SQL_FREERESULT($result_email);
407 } elseif ("$toEmail" == '0') {
409 $toEmail = constant('WEBMASTER');
411 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):TO={$toEmail}<br />\n";
413 // Check for PHPMailer or debug-mode
414 if (!CHECK_PHPMAILER_USAGE()) {
415 // Not in PHPMailer-Mode
416 if (empty($mailHeader)) {
417 // Load email header template
418 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
421 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
423 } elseif (isDebugModeEnabled()) {
424 if (empty($mailHeader)) {
425 // Load email header template
426 $mailHeader = LOAD_EMAIL_TEMPLATE("header");
429 $mailHeader .= LOAD_EMAIL_TEMPLATE("header");
434 $eval = "\$toEmail = \"".COMPILE_CODE(smartAddSlashes($toEmail))."\";";
438 $eval = "\$message = \"".COMPILE_CODE(smartAddSlashes($message))."\";";
441 // Fix HTML parameter (default is no!)
442 if (empty($HTML)) $HTML = 'N';
443 if (isDebugModeEnabled()) {
444 // In debug mode we want to display the mail instead of sending it away so we can debug this part
446 ".htmlentities(trim($mailHeader))."
448 Subject : ".$subject."
449 Message : ".$message."
451 } elseif (($HTML == 'Y') && (EXT_IS_ACTIVE('html_mail'))) {
452 // Send mail as HTML away
453 SEND_HTML_EMAIL($toEmail, $subject, $message, $mailHeader);
454 } elseif (!empty($toEmail)) {
456 SEND_RAW_EMAIL($toEmail, $subject, $message, $mailHeader);
457 } elseif ($HTML == 'N') {
459 SEND_RAW_EMAIL(constant('WEBMASTER'), "[PROBLEM:]".$subject, $message, $mailHeader);
463 // Check if legacy or PHPMailer command
464 // @TODO Rewrite this to an extension 'smtp'
466 function CHECK_PHPMAILER_USAGE() {
467 return ((defined('SMTP_HOSTNAME')) && (defined('SMTP_USER')) && (defined('SMTP_PASSWORD')) && (constant('SMTP_HOSTNAME') != '') && (constant('SMTP_USER') != ''));
471 * Send out a raw email with PHPMailer class or legacy mail() command
473 function SEND_RAW_EMAIL ($toEmail, $subject, $msg, $from) {
474 // Shall we use PHPMailer class or legacy mode?
475 if (CHECK_PHPMAILER_USAGE()) {
476 // Use PHPMailer class with SMTP enabled
477 loadIncludeOnce("inc/phpmailer/class.phpmailer.php");
478 loadIncludeOnce("inc/phpmailer/class.smtp.php");
481 $mail = new PHPMailer();
482 $mail->PluginDir = sprintf("%sinc/phpmailer/", constant('PATH'));
485 $mail->SMTPAuth = true;
486 $mail->Host = constant('SMTP_HOSTNAME');
488 $mail->Username = constant('SMTP_USER');
489 $mail->Password = constant('SMTP_PASSWORD');
491 $mail->From = constant('WEBMASTER');
495 $mail->FromName = constant('MAIN_TITLE');
496 $mail->Subject = $subject;
497 if ((EXT_IS_ACTIVE('html_mail')) && (strip_tags($msg) != $msg)) {
499 $mail->AltBody = "Your mail program required HTML support to read this mail!";
500 $mail->WordWrap = 70;
503 $mail->Body = decodeEntities($msg);
505 $mail->AddAddress($toEmail, '');
506 $mail->AddReplyTo(constant('WEBMASTER'), constant('MAIN_TITLE'));
507 $mail->AddCustomHeader("Errors-To:".constant('WEBMASTER'));
508 $mail->AddCustomHeader("X-Loop:".constant('WEBMASTER'));
511 // Use legacy mail() command
512 @mail($toEmail, $subject, decodeEntities($msg), $from);
516 // Generate a password in a specified length or use default password length
517 function generatePassword ($LEN = 0) {
518 // Auto-fix invalid length of zero
519 if ($LEN == 0) $LEN = getConfig('pass_len');
521 // Initialize array with all allowed chars
522 $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,-,+,_,/');
524 // Start creating password
526 for ($i = 0; $i < $LEN; $i++) {
527 $PASS .= $ABC[mt_rand(0, count($ABC) -1)];
530 // When the size is below 40 we can also add additional security by scrambling
531 // it. Otherwise we may corrupt hashes
532 if (strlen($PASS) <= 40) {
533 // Also scramble the password
534 $PASS = scrambleString($PASS);
537 // Return the password
541 // Generates a human-readable timestamp from the Uni* stamp
542 function generateDateTime ($time, $mode = '0') {
543 // Filter out numbers
544 $time = bigintval($time);
546 // If the stamp is zero it mostly didn't "happen"
549 return getMessage('NEVER_HAPPENED');
552 switch (getLanguage())
554 case 'de': // German date / time format
556 case '0': $ret = date("d.m.Y \u\m H:i \U\h\\r", $time); break;
557 case '1': $ret = strtolower(date("d.m.Y - H:i", $time)); break;
558 case '2': $ret = date("d.m.Y|H:i", $time); break;
559 case '3': $ret = date("d.m.Y", $time); break;
561 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
566 default: // Default is the US date / time format!
568 case '0': $ret = date("r", $time); break;
569 case '1': $ret = date("Y-m-d - g:i A", $time); break;
570 case '2': $ret = date("y-m-d|H:i", $time); break;
571 case '3': $ret = date("y-m-d", $time); break;
573 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Invalid date mode %s detected.", $mode));
580 // Translates Y/N to yes/no
581 function translateYesNo ($yn) {
583 $translated = "??? (".$yn.")";
585 case 'Y': $translated = getMessage('YES'); break;
586 case 'N': $translated = getMessage('NO'); break;
589 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown value %s. Expected Y/N!", $yn));
597 // Translates the "pool type" into human-readable
598 function translatePoolType ($type) {
599 // Default?type is unknown
600 $translated = sprintf(getMessage('POOL_TYPE_UNKNOWN'), $type);
603 $constName = sprintf("POOL_TYPE_%s", $type);
606 if (defined($constName)) {
608 $translated = getMessage($constName);
611 // Return "translation"
615 // Translates the american decimal dot into a german comma
616 function translateComma ($dotted, $cut = true, $max = 0) {
617 // Default is 3 you can change this in admin area "Misc -> Misc Options"
618 if (!isConfigEntrySet('max_comma')) setConfigEntry('max_comma', '3');
620 // Use from config is default
621 $maxComma = getConfig('max_comma');
623 // Use from parameter?
624 if ($max > 0) $maxComma = $max;
627 if (($cut) && ($max == 0)) {
628 // Test for commata if in cut-mode
629 $com = explode('.', $dotted);
630 if (count($com) < 2) {
631 // Don't display commatas even if there are none... ;-)
637 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "dotted={$dotted},maxComma={$maxComma}");
640 switch (getLanguage()) {
642 $dotted = number_format($dotted, $maxComma, ',', '.');
646 $dotted = number_format($dotted, $maxComma, '.', ',');
650 // Return translated value
654 // Translate Uni*-like gender to human-readable
655 function translateGender ($gender) {
657 $ret = '!' . $gender . '!';
659 // Male/female or company?
661 case 'M': $ret = getMessage('GENDER_M'); break;
662 case 'F': $ret = getMessage('GENDER_F'); break;
663 case 'C': $ret = getMessage('GENDER_C'); break;
665 // Log unknown gender
666 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown gender %s detected.", $gender));
670 // Return translated gender
674 // "Translates" the user status
675 function translateUserStatus ($status) {
681 $ret = getMessage(sprintf("ACCOUNT_%s", $status));
686 $ret = getMessage('ACCOUNT_DELETED');
690 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown status %s detected.", $status));
691 $ret = sprintf(getMessage('UNKNOWN_STATUS'), $status);
699 // Generates an URL for the dereferer
700 function DEREFERER ($URL) {
701 // Don't de-refer our own links!
702 if (substr($URL, 0, strlen(constant('URL'))) != constant('URL')) {
703 // De-refer this link
704 $URL = 'modules.php?module=loader&url=' . encodeString(compileUriCode($URL));
711 // Generates an URL for the frametester
712 function FRAMETESTER ($URL) {
713 // Prepare frametester URL
714 $frametesterUrl = sprintf("{!URL!}/modules.php?module=frametester&url=%s",
715 encodeString(compileUriCode($URL))
717 return $frametesterUrl;
720 // Count entries from e.g. a selection box
721 function countSelection ($array) {
723 if (is_array($array)) {
724 foreach ($array as $key => $selected) {
725 if (!empty($selected)) $ret++;
731 // Wrapper for $_POST['sel']
732 function countPostSelection () {
733 return countSelection(REQUEST_POST('sel'));
736 // Generate XHTML code for the CAPTCHA
737 function generateCaptchaCode ($code, $type, $DATA, $uid) {
738 return '<IMG border="0" alt="Code" src="{!URL!}/mailid_top.php?uid=' . $uid . '&' . $type . '=' . $DATA . '&mode=img&code=' . $code . '" />';
741 // "Getter" for language
742 function getLanguage () {
743 // Set default return value to default language from config
744 $ret = constant('DEFAULT_LANG');
749 // Is the variable set
750 if (REQUEST_ISSET_GET(('mx_lang'))) {
751 // Accept only first 2 chars
752 $lang = substr(REQUEST_GET('mx_lang'), 0, 2);
753 } elseif (isset($GLOBALS['cache_array']['language'])) {
755 $ret = $GLOBALS['cache_array']['language'];
756 } elseif (!empty($lang)) {
757 // Check if main language file does exist
758 if (isFileReadable(constant('PATH').'inc/language/'.$lang.'.php')) {
759 // Okay found, so let's update cookies
762 } elseif (!isSessionVariableSet('mx_lang')) {
763 // Return stored value from cookie
764 $ret = getSession('mx_lang');
766 // Fixes a warning before the session has the mx_lang constant
767 if (empty($ret)) $ret = constant('DEFAULT_LANG');
771 $GLOBALS['cache_array']['language'] = $ret;
777 // "Setter" for language
778 function setLanguage ($lang) {
779 // Accept only first 2 chars!
780 $lang = substr(SQL_ESCAPE(strip_tags($lang)), 0, 2);
783 setSession('mx_lang', $lang);
786 // Loads an email template and compiles it
787 function LOAD_EMAIL_TEMPLATE ($template, $content = array(), $UID = '0') {
788 global $DATA, $_CONFIG;
790 // Make sure all template names are lowercase!
791 $template = strtolower($template);
793 // Default 'nickname' if extension is not installed
796 // Prepare IP number and User Agent
797 $REMOTE_ADDR = detectRemoteAddr();
798 $HTTP_USER_AGENT = detectUserAgent();
801 $ADMIN = constant('MAIN_TITLE');
803 // Is the admin logged in?
806 $aid = getCurrentAdminId();
809 $ADMIN = getAdminEmail($aid);
812 // Neutral email address is default
813 $email = constant('WEBMASTER');
815 // Expiration in a nice output format
816 // NOTE: Use $content[expiration] in your templates instead of $EXPIRATION
817 if (getConfig('auto_purge') == 0) {
818 // Will never expire!
819 $EXPIRATION = getMessage('MAIL_WILL_NEVER_EXPIRE');
821 // Create nice date string
822 $EXPIRATION = createFancyTime(getConfig('auto_purge'));
825 // Is content an array?
826 if (is_array($content)) {
827 // Add expiration to array, $EXPIRATION is now deprecated!
828 $content['expiration'] = $EXPIRATION;
832 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):UID={$UID},template={$template},content[]=".gettype($content)."<br />\n";
833 if (($UID > 0) && (is_array($content))) {
834 // If nickname extension is installed, fetch nickname as well
835 if (EXT_IS_ACTIVE('nickname')) {
836 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NICKNAME!<br />\n";
838 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email, nickname FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
839 array(bigintval($UID)), __FUNCTION__, __LINE__);
841 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):NO-NICK!<br />\n";
843 $result = SQL_QUERY_ESC("SELECT surname, family, gender, email FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
844 array(bigintval($UID)), __FUNCTION__, __LINE__);
847 // Fetch and merge data
848 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - PRE<br />\n";
849 $content = merge_array($content, SQL_FETCHARRAY($result));
850 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):content()=".count($content)." - AFTER<br />\n";
853 SQL_FREERESULT($result);
856 // Translate M to male or F to female if present
857 if (isset($content['gender'])) $content['gender'] = translateGender($content['gender']);
859 // Overwrite email from data if present
860 if (isset($content['email'])) $email = $content['email'];
862 // Store email for some functions in global data array
863 $DATA['email'] = $email;
866 $basePath = sprintf("%stemplates/%s/emails/", constant('PATH'), getLanguage());
868 // Check for admin/guest/member templates
869 if (strpos($template, 'admin_') > -1) {
870 // Admin template found
871 $FQFN = $basePath.'admin/'.$template.'.tpl';
872 } elseif (strpos($template, 'guest_') > -1) {
873 // Guest template found
874 $FQFN = $basePath.'guest/'.$template.'.tpl';
875 } elseif (strpos($template, 'member_') > -1) {
876 // Member template found
877 $FQFN = $basePath.'member/'.$template.'.tpl';
879 // Test for extension
880 $test = substr($template, 0, strpos($template, '_'));
881 if (EXT_IS_ACTIVE($test)) {
882 // Set extra path to extension's name
883 $FQFN = $basePath.$test.'/'.$template.'.tpl';
885 // No special filename
886 $FQFN = $basePath.$template.'.tpl';
890 // Does the special template exists?
891 if (!isFileReadable($FQFN)) {
892 // Reset to default template
893 $FQFN = $basePath.$template.'.tpl';
896 // Now does the final template exists?
898 if (isFileReadable($FQFN)) {
899 // The local file does exists so we load it. :)
900 $tmpl_file = readFromFile($FQFN);
901 $tmpl_file = SQL_ESCAPE($tmpl_file);
904 $tmpl_file = "\$newContent = decodeEntities(\"".COMPILE_CODE($tmpl_file)."\");";
906 } elseif (!empty($template)) {
907 // Template file not found!
908 $newContent = "{--TEMPLATE_404--}: ".$template."<br />
909 {--TEMPLATE_CONTENT--}
910 <pre>".print_r($content, true)."</pre>
912 <pre>".print_r($DATA, true)."</pre>
915 // Debug mode not active? Then remove the HTML tags
916 if (!isDebugModeEnabled()) $newContent = strip_tags($newContent);
918 // No template name supplied!
919 $newContent = getMessage('NO_TEMPLATE_SUPPLIED');
922 // Is there some content?
923 if (empty($newContent)) {
925 $newContent = "Compiler error for template {$template}!\nUncompiled content:\n".$tmpl_file;
926 // Add last error if the required function exists
927 if (function_exists('error_get_last')) $newContent .= "\n--------------------------------------\nDebug:\n".print_r(error_get_last(), true)."--------------------------------------\nPlease don't alter these informations!\nThanx.";
930 // Remove content and data
934 // Return compiled content
935 return COMPILE_CODE($newContent);
938 // Generates a timestamp (wrapper for mktime())
939 function makeTime ($H, $M, $S, $stamp) {
940 // Extract day, month and year from given timestamp
941 $day = date('d', $stamp);
942 $month = date('m', $stamp);
943 $year = date('Y', $stamp);
945 // Create timestamp for wished time which depends on extracted date
946 return mktime($H, $M, $S, $month, $day, $year);
949 // Redirects to an URL and if neccessarry extends it with own base URL
950 function redirectToUrl ($URL, $addUrlData=true) {
951 // Compile out URI codes
952 $URL = compileUriCode($URL);
954 // Check if http(s):// is there
955 if ((substr($URL, 0, 7) != 'http://') && (substr($URL, 0, 8) != 'https://')) {
956 // Make all URLs full-qualified
957 $URL = constant('URL') . '/' . $URL;
960 // Three different debug ways...
961 //* DEBUG: */ debug_report_bug(sprintf("%s[%s:] URL=%s", __FUNCTION__, __LINE__, $URL));
962 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, $URL);
963 //* DEBUG: */ die($URL);
965 // Default 'rel' value is external, nofollow is evil from Google and hurts the Internet
966 $rel = ' rel="external"';
968 // Do we have internal or external URL?
969 if (substr($URL, 0, strlen(constant('URL'))) == constant('URL')) {
970 // Own (=internal) URL
975 $OUTPUT = ob_get_contents();
977 // Clear it only if there is content
978 if (!empty($OUTPUT)) {
982 // Add some data to URL if cookies are not accepted
983 if ((!isBooleanConstantAndTrue('__COOKIES')) && ($addUrlData === true)) $URL = addUrlData($URL);
985 // Secure the URL against bad things such als HTML insertions and so on...
986 $URL = htmlentities(strip_tags($URL), ENT_QUOTES);
988 // Simple probe for bots/spiders from search engines
989 if ((strpos(detectUserAgent(), 'spider') !== false) || (strpos(detectUserAgent(), 'bot') !== false)) {
990 // Output new location link as anchor
991 OUTPUT_HTML('<a href="' . $URL . '"' . $rel . '>' . $URL . '</a>');
992 } elseif (!headers_sent()) {
993 // Load URL when headers are not sent
994 //* DEBUG: */ debug_report_bug("URL={$URL}");
995 header ('Location: '.str_replace('&', '&', $URL));
997 // Output error message
998 loadInclude('inc/header.php');
999 LOAD_TEMPLATE('redirect_url', false, str_replace('&', '&', $URL));
1000 loadInclude('inc/footer.php');
1003 // Shut the mailer down here
1007 // Wrapper for redirectToUrl but URL comes from a configuration entry
1008 function LOAD_CONFIGURED_URL ($configEntry) {
1010 $URL = getConfig($configEntry);
1013 if (is_null($URL)) {
1015 trigger_error(sprintf("Configuration entry %s is not set!", $configEntry));
1019 redirectToUrl($URL);
1023 function COMPILE_CODE ($code, $simple = false, $constants = true, $full = true) {
1024 // Is the code a string?
1025 if (!is_string($code)) {
1026 // Silently return it
1030 // Init replacement-array with full security characters
1031 $secChars = $GLOBALS['security_chars'];
1033 // Select smaller set of chars to replace when we e.g. want to compile URLs
1034 if (!$full) $secChars = $GLOBALS['url_chars'];
1036 // Compile constants
1037 if ($constants === true) {
1038 // BEFORE 0.2.1 : Language and data constants
1039 // WITH 0.2.1+ : Only language constants
1040 $code = str_replace('{--','".', str_replace('--}','."', $code));
1042 // BEFORE 0.2.1 : Not used
1043 // WITH 0.2.1+ : Data constants
1044 $code = str_replace('{!','".', str_replace("!}", '."', $code));
1047 // Compile QUOT and other non-HTML codes
1048 foreach ($secChars['to'] as $k => $to) {
1049 // Do the reversed thing as in inc/libs/security_functions.php
1050 $code = str_replace($to, $secChars['from'][$k], $code);
1053 // But shall I keep simple quotes for later use?
1054 if ($simple) $code = str_replace("'", '{QUOT}', $code);
1056 // Find $content[bla][blub] entries
1057 preg_match_all('/\$(content|DATA)((\[([a-zA-Z0-9-_]+)\])*)/', $code, $matches);
1059 // Are some matches found?
1060 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
1061 // Replace all matches
1062 $matchesFound = array();
1063 foreach ($matches[0] as $key => $match) {
1064 // Fuzzy look has failed by default
1065 $fuzzyFound = false;
1067 // Fuzzy look on match if already found
1068 foreach ($matchesFound as $found => $set) {
1070 $test = substr($found, 0, strlen($match));
1072 // Does this entry exist?
1073 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):found={$found},match={$match},set={$set}<br />\n";
1074 if ($test == $match) {
1076 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):fuzzyFound!<br />\n";
1083 if ($fuzzyFound) continue;
1085 // Take all string elements
1086 if ((is_string($matches[4][$key])) && (!isset($matchesFound[$match])) && (!isset($matchesFound[$key."_".$matches[4][$key]]))) {
1087 // Replace it in the code
1088 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):key={$key},match={$match}<br />\n";
1089 $newMatch = str_replace("[".$matches[4][$key]."]", "['".$matches[4][$key]."']", $match);
1090 $code = str_replace($match, "\".".$newMatch.".\"", $code);
1091 $matchesFound[$key."_".$matches[4][$key]] = 1;
1092 $matchesFound[$match] = 1;
1093 } elseif (!isset($matchesFound[$match])) {
1094 // Not yet replaced!
1095 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):match={$match}<br />\n";
1096 $code = str_replace($match, "\".".$match.".\"", $code);
1097 $matchesFound[$match] = 1;
1102 // Return compiled code
1106 /************************************************************************
1108 * Gaenderter Sortier-Algorythmus, $array wird nach dem Array (!) *
1109 * $a_sort sortiert: *
1111 * $array - Das 3-dimensionale Array, das paralell sortiert werden soll *
1112 * $a_sort - Array, das die Sortiereihenfolge der ersten Elementeben *
1113 * $primary_key - Prim.rschl.ssel aus $a_sort, nach dem sortiert wird *
1114 * $order - Sortiereihenfolge: -1 = a-Z, 0 = keine, 1 = Z-a *
1115 * $nums - true = Als Zahlen sortieren, false = Als Zeichen sortieren *
1117 * $a_sort muss Elemente enthalten, deren Wert Schluessel von $array *
1118 * sind... Klingt kompliziert, suchen Sie mal mein Beispiel, dann sehen *
1119 * Sie, dass es doch nicht so schwer ist! :-) *
1121 ************************************************************************/
1122 function array_pk_sort (&$array, $a_sort, $primary_key = 0, $order = -1, $nums = false) {
1124 while ($primary_key < count($a_sort)) {
1125 foreach ($dummy[$a_sort[$primary_key]] as $key => $value) {
1126 foreach ($dummy[$a_sort[$primary_key]] as $key2 => $value2) {
1129 // Sort byte-by-byte (also numbers will be interpreted as chars! E.g.: "9" > "10")
1130 if (($key != $key2) && (strcmp(strtolower($dummy[$a_sort[$primary_key]][$key]), strtolower($dummy[$a_sort[$primary_key]][$key2])) == $order)) $match = true;
1131 } elseif ($key != $key2) {
1132 // Sort numbers (E.g.: 9 < 10)
1133 if (($dummy[$a_sort[$primary_key]][$key] < $dummy[$a_sort[$primary_key]][$key2]) && ($order == -1)) $match = true;
1134 if (($dummy[$a_sort[$primary_key]][$key] > $dummy[$a_sort[$primary_key]][$key2]) && ($order == 1)) $match = true;
1138 // We have found two different values, so let's sort whole array
1139 foreach ($dummy as $sort_key => $sort_val) {
1140 $t = $dummy[$sort_key][$key];
1141 $dummy[$sort_key][$key] = $dummy[$sort_key][$key2];
1142 $dummy[$sort_key][$key2] = $t;
1153 // Write back sorted array
1158 function ADD_SELECTION ($type, $default, $prefix = '', $id = '0') {
1161 if ($type == 'yn') {
1162 // This is a yes/no selection only!
1163 if ($id > 0) $prefix .= "[".$id."]";
1164 $OUT .= " <select name=\"".$prefix."\" class=\"register_select\" size=\"1\">\n";
1166 // Begin with regular selection box here
1167 if (!empty($prefix)) $prefix .= "_";
1169 if ($id > 0) $type2 .= "[".$id."]";
1170 $OUT .= " <select name=\"".strtolower($prefix.$type2)."\" class=\"register_select\" size=\"1\">\n";
1175 for ($idx = 1; $idx < 32; $idx++) {
1176 $OUT .= "<option value=\"".$idx."\"";
1177 if ($default == $idx) $OUT .= ' selected="selected"';
1178 $OUT .= ">".$idx."</option>\n";
1182 case "month": // Month
1183 foreach ($GLOBALS['month_descr'] as $month => $descr) {
1184 $OUT .= "<option value=\"".$month."\"";
1185 if ($default == $month) $OUT .= ' selected="selected"';
1186 $OUT .= ">".$descr."</option>\n";
1190 case "year": // Year
1192 $year = date('Y', time());
1194 // Use configured min age or fixed?
1195 if (GET_EXT_VERSION('other') >= '0.2.1') {
1197 $startYear = $year - getConfig('min_age');
1200 $startYear = $year - 16;
1203 // Calculate earliest year (100 years old people can still enter Internet???)
1204 $minYear = $year - 100;
1206 // Check if the default value is larger than minimum and bigger than actual year
1207 if (($default > $minYear) && ($default >= $year)) {
1208 for ($idx = $year; $idx < ($year + 11); $idx++) {
1209 $OUT .= "<option value=\"".$idx."\"";
1210 if ($default == $idx) $OUT .= ' selected="selected"';
1211 $OUT .= ">".$idx."</option>\n";
1213 } elseif ($default == -1) {
1214 // Current year minus 1
1215 for ($idx = $startYear; $idx <= ($year + 1); $idx++)
1217 $OUT .= "<option value=\"".$idx."\">".$idx."</option>\n";
1220 // Get current year and subtract the configured minimum age
1221 $OUT .= "<option value=\"".($minYear - 1)."\"><".$minYear."</option>\n";
1222 // Calculate earliest year depending on extension version
1223 if (GET_EXT_VERSION('other') >= '0.2.1') {
1224 // Use configured minimum age
1225 $year = date('Y', time()) - getConfig('min_age');
1227 // Use fixed 16 years age
1228 $year = date('Y', time()) - 16;
1231 // Construct year selection list
1232 for ($idx = $minYear; $idx <= $year; $idx++) {
1233 $OUT .= "<option value=\"".$idx."\"";
1234 if ($default == $idx) $OUT .= ' selected="selected"';
1235 $OUT .= ">".$idx."</option>\n";
1242 for ($idx = 0; $idx < 60; $idx+=5) {
1243 if (strlen($idx) == 1) $idx = '0'.$idx;
1244 $OUT .= "<option value=\"".$idx."\"";
1245 if ($default == $idx) $OUT .= ' selected="selected"';
1246 $OUT .= ">".$idx."</option>\n";
1251 for ($idx = 0; $idx < 24; $idx++) {
1252 if (strlen($idx) == 1) $idx = '0'.$idx;
1253 $OUT .= "<option value=\"".$idx."\"";
1254 if ($default == $idx) $OUT .= ' selected="selected"';
1255 $OUT .= ">".$idx."</option>\n";
1260 $OUT .= "<option value=\"Y\"";
1261 if ($default == 'Y') $OUT .= ' selected="selected"';
1262 $OUT .= ">{--YES--}</option>\n<option value=\"N\"";
1263 if ($default == 'N') $OUT .= ' selected="selected"';
1264 $OUT .= ">{--NO--}</option>\n";
1267 $OUT .= " </select>\n";
1272 // Deprecated : $length
1275 function generateRandomCodde ($length, $code, $uid, $DATA = '') {
1276 // Fix missing _MAX constant
1277 // @TODO Rewrite this unnice code
1278 if (!defined('_MAX')) define('_MAX', 15235);
1280 // Build server string
1281 $server = $_SERVER['PHP_SELF'].constant('ENCRYPT_SEPERATOR').detectUserAgent().constant('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').constant('ENCRYPT_SEPERATOR').detectRemoteAddr().":'.':".filemtime(constant('PATH')."inc/databases.php");
1284 $keys = constant('SITE_KEY').constant('ENCRYPT_SEPERATOR').constant('DATE_KEY');
1285 if (isConfigEntrySet('secret_key')) $keys .= constant('ENCRYPT_SEPERATOR').getConfig('secret_key');
1286 if (isConfigEntrySet('file_hash')) $keys .= constant('ENCRYPT_SEPERATOR').getConfig('file_hash');
1287 $keys .= constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime')));
1288 if (isConfigEntrySet('master_salt')) $keys .= constant('ENCRYPT_SEPERATOR').getConfig('master_salt');
1290 // Build string from misc data
1291 $data = $code.constant('ENCRYPT_SEPERATOR').$uid.constant('ENCRYPT_SEPERATOR').$DATA;
1293 // Add more additional data
1294 if (isSessionVariableSet('u_hash')) $data .= constant('ENCRYPT_SEPERATOR').getSession('u_hash');
1295 if (isUserIdSet()) $data .= constant('ENCRYPT_SEPERATOR').getUserId();
1296 if (isSessionVariableSet('mxchange_theme')) $data .= constant('ENCRYPT_SEPERATOR').getSession('mxchange_theme');
1297 if (isSessionVariableSet('mx_lang')) $data .= constant('ENCRYPT_SEPERATOR').getLanguage();
1298 if (isset($GLOBALS['refid'])) $data .= constant('ENCRYPT_SEPERATOR').$GLOBALS['refid'];
1300 // Calculate number for generating the code
1301 $a = $code + constant('_ADD') - 1;
1303 if (isConfigEntrySet('master_hash')) {
1304 // Generate hash with master salt from modula of number with the prime number and other data
1305 $saltedHash = generateHash(($a % constant('_PRIME')).constant('ENCRYPT_SEPERATOR').$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a, getConfig('master_salt'));
1307 // Create number from hash
1308 $rcode = hexdec(substr($saltedHash, strlen(getConfig('master_salt')), 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1310 // Generate hash with "hash of site key" from modula of number with the prime number and other data
1311 $saltedHash = generateHash(($a % constant('_PRIME')).constant('ENCRYPT_SEPERATOR').$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a, substr(sha1(constant('SITE_KEY')), 0, 8));
1313 // Create number from hash
1314 $rcode = hexdec(substr($saltedHash, 8, 9)) / abs(constant('_MAX') - $a + sqrt(constant('_ADD'))) / pi();
1317 // At least 10 numbers shall be secure enought!
1318 $len = getConfig('code_length');
1319 if ($len == 0) $len = $length;
1320 if ($len == 0) $len = 10;
1322 // Cut off requested counts of number
1323 $return = substr(str_replace('.', '', $rcode), 0, $len);
1325 // Done building code
1329 // Does only allow numbers
1330 function bigintval ($num, $castValue = true) {
1331 // Filter all numbers out
1332 $ret = preg_replace("/[^0123456789]/", '', $num);
1335 if ($castValue) $ret = (double)$ret;
1337 // Has the whole value changed?
1338 // @TODO Remove this if() block if all is working fine
1339 if ("".$ret."" != ''.$num."") {
1341 debug_report_bug("{$ret}<>{$num}");
1348 // Insert the code in $img_code into jpeg or PNG image
1349 function GENERATE_IMAGE ($img_code, $headerSent=true) {
1350 if ((strlen($img_code) > 6) || (empty($img_code)) || (getConfig('code_length') == 0)) {
1351 // Stop execution of function here because of over-sized code length
1353 } elseif (!$headerSent) {
1354 // Return in an HTML code code
1355 return "<img src=\"{!URL!}/img.php?code=".$img_code."\" alt=\"Image\" />\n";
1359 $img = sprintf("%s/theme/%s/images/code_bg.%s", constant('PATH'), getCurrentTheme(), getConfig('img_type'));
1360 if (isFileReadable($img)) {
1361 // Switch image type
1362 switch (getConfig('img_type'))
1365 // Okay, load image and hide all errors
1366 $image = @imagecreatefromjpeg($img);
1370 // Okay, load image and hide all errors
1371 $image = @imagecreatefrompng($img);
1375 // Exit function here
1376 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File for image type %s not found.", getConfig('img_type')));
1380 // Generate text color (red/green/blue; 0 = dark, 255 = bright)
1381 $text_color = imagecolorallocate($image, 0, 0, 0);
1383 // Insert code into image
1384 imagestring($image, 5, 14, 2, $img_code, $text_color);
1386 // Return to browser
1387 header ("Content-Type: image/".getConfig('img_type'));
1389 // Output image with matching image factory
1390 switch (getConfig('img_type')) {
1391 case "jpg": imagejpeg($image); break;
1392 case "png": imagepng($image); break;
1395 // Remove image from memory
1396 imagedestroy($image);
1398 // Create selection box or array of splitted timestamp
1399 function createTimeSelections ($timestamp, $prefix = '', $display = '', $align="center", $return_array=false) {
1400 // Calculate 2-seconds timestamp
1401 $stamp = round($timestamp);
1402 //* DEBUG: */ print("*".$stamp.'/'.$timestamp."*<br />");
1404 // Do we have a leap year?
1406 $TEST = date('Y', time()) / 4;
1407 $M1 = date('m', time());
1408 $M2 = date('m', (time() + $timestamp));
1410 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1411 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($M2 > "02")) $SWITCH = getConfig('one_day');
1413 // First of all years...
1414 $Y = abs(floor($timestamp / (31536000 + $SWITCH)));
1415 //* DEBUG: */ print("Y={$Y}<br />\n");
1417 $M = abs(floor($timestamp / 2628000 - $Y * 12));
1418 //* DEBUG: */ print("M={$M}<br />\n");
1420 $W = abs(floor($timestamp / 604800 - $Y * ((365 + $SWITCH / getConfig('one_day')) / 7) - ($M / 12 * (365 + $SWITCH / getConfig('one_day')) / 7)));
1421 //* DEBUG: */ print("W={$W}<br />\n");
1423 $D = abs(floor($timestamp / 86400 - $Y * (365 + $SWITCH / getConfig('one_day')) - ($M / 12 * (365 + $SWITCH / getConfig('one_day'))) - $W * 7));
1424 //* DEBUG: */ print("D={$D}<br />\n");
1426 $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));
1427 //* DEBUG: */ print("h={$h}<br />\n");
1429 $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));
1430 //* DEBUG: */ print("m={$m}<br />\n");
1431 // And at last seconds...
1432 $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));
1433 //* DEBUG: */ print("s={$s}<br />\n");
1435 // Is seconds zero and time is < 60 seconds?
1436 if (($s == 0) && ($timestamp < 60)) {
1438 $s = round($timestamp);
1442 // Now we convert them in seconds...
1444 if ($return_array) {
1445 // Just put all data in an array for later use
1457 $OUT = "<div align=\"".$align."\">\n";
1458 $OUT .= "<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" class=\"admin_table dashed\">\n";
1461 if (ereg('Y', $display) || (empty($display))) {
1462 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_YEARS--}</strong></td>\n";
1465 if (ereg("M", $display) || (empty($display))) {
1466 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MONTHS--}</strong></td>\n";
1469 if (ereg("W", $display) || (empty($display))) {
1470 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_WEEKS--}</strong></td>\n";
1473 if (ereg("D", $display) || (empty($display))) {
1474 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_DAYS--}</strong></td>\n";
1477 if (ereg("h", $display) || (empty($display))) {
1478 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_HOURS--}</strong></td>\n";
1481 if (ereg('m', $display) || (empty($display))) {
1482 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_MINUTES--}</strong></td>\n";
1485 if (ereg("s", $display) || (empty($display))) {
1486 $OUT .= " <td align=\"center\" class=\"admin_title bottom\"><div class=\"tiny\">{--_SECONDS--}</strong></td>\n";
1492 if (ereg('Y', $display) || (empty($display))) {
1493 // Generate year selection
1494 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ye\" size=\"1\">\n";
1495 for ($idx = 0; $idx <= 10; $idx++) {
1496 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1497 if ($idx == $Y) $OUT .= ' selected="selected"';
1498 $OUT .= ">".$idx."</option>\n";
1500 $OUT .= " </select></td>\n";
1502 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ye\" value=\"0\" />\n";
1505 if (ereg("M", $display) || (empty($display))) {
1506 // Generate month selection
1507 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mo\" size=\"1\">\n";
1508 for ($idx = 0; $idx <= 11; $idx++)
1510 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1511 if ($idx == $M) $OUT .= ' selected="selected"';
1512 $OUT .= ">".$idx."</option>\n";
1514 $OUT .= " </select></td>\n";
1516 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mo\" value=\"0\" />\n";
1519 if (ereg("W", $display) || (empty($display))) {
1520 // Generate week selection
1521 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_we\" size=\"1\">\n";
1522 for ($idx = 0; $idx <= 4; $idx++) {
1523 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1524 if ($idx == $W) $OUT .= ' selected="selected"';
1525 $OUT .= ">".$idx."</option>\n";
1527 $OUT .= " </select></td>\n";
1529 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_we\" value=\"0\" />\n";
1532 if (ereg("D", $display) || (empty($display))) {
1533 // Generate day selection
1534 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_da\" size=\"1\">\n";
1535 for ($idx = 0; $idx <= 31; $idx++) {
1536 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1537 if ($idx == $D) $OUT .= ' selected="selected"';
1538 $OUT .= ">".$idx."</option>\n";
1540 $OUT .= " </select></td>\n";
1542 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_da\" value=\"0\">\n";
1545 if (ereg("h", $display) || (empty($display))) {
1546 // Generate hour selection
1547 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_ho\" size=\"1\">\n";
1548 for ($idx = 0; $idx <= 23; $idx++) {
1549 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1550 if ($idx == $h) $OUT .= ' selected="selected"';
1551 $OUT .= ">".$idx."</option>\n";
1553 $OUT .= " </select></td>\n";
1555 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_ho\" value=\"0\">\n";
1558 if (ereg('m', $display) || (empty($display))) {
1559 // Generate minute selection
1560 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_mi\" size=\"1\">\n";
1561 for ($idx = 0; $idx <= 59; $idx++) {
1562 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1563 if ($idx == $m) $OUT .= ' selected="selected"';
1564 $OUT .= ">".$idx."</option>\n";
1566 $OUT .= " </select></td>\n";
1568 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_mi\" value=\"0\">\n";
1571 if (ereg("s", $display) || (empty($display))) {
1572 // Generate second selection
1573 $OUT .= " <td align=\"center\"><select class=\"mini_select\" name=\"".$prefix."_se\" size=\"1\">\n";
1574 for ($idx = 0; $idx <= 59; $idx++) {
1575 $OUT .= " <option class=\"mini_select\" value=\"".$idx."\"";
1576 if ($idx == $s) $OUT .= ' selected="selected"';
1577 $OUT .= ">".$idx."</option>\n";
1579 $OUT .= " </select></td>\n";
1581 $OUT .= "<INPUT type=\"hidden\" name=\"".$prefix."_se\" value=\"0\">\n";
1584 $OUT .= "</table>\n";
1586 // Return generated HTML code
1592 function createTimestampFromSelections ($prefix, $POST) {
1593 // Initial return value
1596 // Do we have a leap year?
1598 $TEST = date('Y', time()) / 4;
1599 $M1 = date('m', time());
1600 // If so and if current time is before 02/29 and estimated time is after 02/29 then add 86400 seconds (one day)
1601 if ((floor($TEST) == $TEST) && ($M1 == "02") && ($POST[$prefix."_mo"] > "02")) $SWITCH = getConfig('one_day');
1602 // First add years...
1603 $ret += $POST[$prefix."_ye"] * (31536000 + $SWITCH);
1605 $ret += $POST[$prefix."_mo"] * 2628000;
1607 $ret += $POST[$prefix."_we"] * 604800;
1609 $ret += $POST[$prefix."_da"] * 86400;
1611 $ret += $POST[$prefix."_ho"] * 3600;
1613 $ret += $POST[$prefix."_mi"] * 60;
1614 // And at last seconds...
1615 $ret += $POST[$prefix."_se"];
1616 // Return calculated value
1620 // Sends out mail to all administrators
1621 // IMPORTANT: Please use SEND_ADMIN_NOTIFCATION() for now!
1622 function SEND_ADMIN_EMAILS_PRO ($subj, $template, $content, $UID) {
1623 // Trim template name
1624 $template = trim($template);
1626 // Load email template
1627 $msg = LOAD_EMAIL_TEMPLATE($template, $content, $UID);
1629 // Check which admin shall receive this mail
1630 $result = SQL_QUERY_ESC("SELECT DISTINCT admin_id FROM `{!_MYSQL_PREFIX!}_admins_mails` WHERE mail_template='%s' ORDER BY admin_id",
1631 array($template), __FUNCTION__, __LINE__);
1632 if (SQL_NUMROWS($result) == 0) {
1633 // Create new entry (to all admins)
1634 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_admins_mails` (admin_id, mail_template) VALUES (0, '%s')",
1635 array($template), __FUNCTION__, __LINE__);
1637 // Load admin IDs...
1638 // @TODO This can be, somehow, rewritten
1639 $adminIds = array();
1640 while ($content = SQL_FETCHARRAY($result)) {
1641 $adminIds[] = $content['admin_id'];
1645 SQL_FREERESULT($result);
1650 // "implode" IDs and query string
1651 $aid = implode(",", $adminIds);
1653 if (EXT_IS_ACTIVE('events')) {
1654 // Add line to user events
1655 EVENTS_ADD_LINE($subj, $msg, $UID);
1657 // Log error for debug
1658 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension 'events' missing: tpl=%s,subj=%s,UID=%s",
1664 } elseif ($aid == '0') {
1665 // Select all email adresses
1666 $result = SQL_QUERY("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` ORDER BY `id`",
1667 __FUNCTION__, __LINE__);
1669 // If Admin-ID is not "to-all" select
1670 $result = SQL_QUERY_ESC("SELECT email FROM `{!_MYSQL_PREFIX!}_admins` WHERE id IN (%s) ORDER BY `id`",
1671 array($aid), __FUNCTION__, __LINE__);
1675 // Load email addresses and send away
1676 while ($content = SQL_FETCHARRAY($result)) {
1677 sendEmail($content['email'], $subj, $msg);
1681 SQL_FREERESULT($result);
1684 // Creates a 'fancy' human-readable timestamp from a Uni* stamp
1685 function createFancyTime ($stamp) {
1686 // Get data array with years/months/weeks/days/...
1687 $data = createTimeSelections($stamp, '', '', '', true);
1689 foreach($data as $k => $v) {
1691 // Value is greater than 0 "eval" data to return string
1692 $eval = "\$ret .= \", \".\$v.\" {--_".strtoupper($k)."--}\";";
1698 // Do we have something there?
1699 if (strlen($ret) > 0) {
1700 // Remove leading commata and space
1701 $ret = substr($ret, 2);
1704 $ret = "0 {--_SECONDS--}";
1707 // Return fancy time string
1712 function ADD_EMAIL_NAV ($PAGES, $offset, $show_form, $colspan, $return=false) {
1713 $SEP = ''; $TOP = '';
1716 $SEP = "<tr><td colspan=\"".$colspan."\" class=\"seperator\"> </td></tr>";
1720 for ($page = 1; $page <= $PAGES; $page++) {
1721 // Is the page currently selected or shall we generate a link to it?
1722 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == "1"))) {
1723 // Is currently selected, so only highlight it
1724 $NAV .= "<strong>-";
1726 // Open anchor tag and add base URL
1727 $NAV .= "<a href=\"{!URL!}/modules.php?module=admin&what=".$GLOBALS['what']."&page=".$page."&offset=".$offset;
1729 // Add userid when we shall show all mails from a single member
1730 if ((REQUEST_ISSET_GET('uid')) && (bigintval(REQUEST_GET('uid')) > 0)) $NAV .= "&uid=".bigintval(REQUEST_GET('uid'));
1732 // Close open anchor tag
1736 if (($page == REQUEST_GET('page')) || ((!REQUEST_ISSET_GET('page')) && ($page == "1"))) {
1737 // Is currently selected, so only highlight it
1738 $NAV .= "-</strong>";
1744 // Add seperator if we have not yet reached total pages
1745 if ($page < $PAGES) $NAV .= " | ";
1748 // Define constants only once
1749 if (!defined('__NAV_OUTPUT')) {
1750 define('__NAV_OUTPUT' , $NAV);
1751 define('__NAV_COLSPAN', $colspan);
1752 define('__NAV_TOP' , $TOP);
1753 define('__NAV_SEP' , $SEP);
1756 // Load navigation template
1757 $OUT = LOAD_TEMPLATE("admin_email_nav_row", true);
1759 if ($return === true) {
1760 // Return generated HTML-Code
1768 // Extract host from script name
1769 function extractHostnameFromUrl (&$script) {
1770 // Use default SERVER_URL by default... ;) So?
1771 $url = constant('SERVER_URL');
1773 // Is this URL valid?
1774 if (substr($script, 0, 7) == "http://") {
1775 // Use the hostname from script URL as new hostname
1776 $url = substr($script, 7);
1777 $extract = explode('/', $url);
1779 // Done extracting the URL :)
1782 // Extract host name
1783 $host = str_replace("http://", '', $url);
1784 if (ereg('/', $host)) $host = substr($host, 0, strpos($host, '/'));
1786 // Generate relative URL
1787 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1788 if (substr(strtolower($script), 0, 7) == "http://") {
1789 // But only if http:// is in front!
1790 $script = substr($script, (strlen($url) + 7));
1791 } elseif (substr(strtolower($script), 0, 8) == "https://") {
1793 $script = substr($script, (strlen($url) + 8));
1796 //* DEBUG: */ print("SCRIPT=".$script."<br />\n");
1797 if (substr($script, 0, 1) == '/') $script = substr($script, 1);
1803 // Send a GET request
1804 function sendGetRequest ($script) {
1805 // Compile the script name
1806 $script = COMPILE_CODE($script);
1808 // Extract host name from script
1809 $host = extractHostnameFromUrl($script);
1811 // Generate GET request header
1812 $request = "GET /" . trim($script) . " HTTP/1.1\r\n";
1813 $request .= "Host: " . $host . "\r\n";
1814 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1815 if (defined('FULL_VERSION')) {
1816 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1818 $request .= "User-Agent: " . constant('TITLE') . "/?.?.?\r\n";
1820 $request .= "Content-Type: text/plain\r\n";
1821 $request .= "Cache-Control: no-cache\r\n";
1822 $request .= "Connection: Close\r\n\r\n";
1824 // Send the raw request
1825 $response = sendRawRequest($host, $request);
1827 // Return the result to the caller function
1831 // Send a POST request
1832 function sendPostRequest ($script, $postData) {
1833 // Is postData an array?
1834 if (!is_array($postData)) {
1836 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("postData is not an array. Type: %s", gettype($postData)));
1837 return array('', '', '');
1840 // Compile the script name
1841 $script = COMPILE_CODE($script);
1843 // Extract host name from script
1844 $host = extractHostnameFromUrl($script);
1846 // Construct request
1847 $data = http_build_query($postData, '','&');
1849 // Generate POST request header
1850 $request = "POST /" . trim($script) . " HTTP/1.1\r\n";
1851 $request .= "Host: " . $host . "\r\n";
1852 $request .= "Referer: " . constant('URL') . "/admin.php\r\n";
1853 $request .= "User-Agent: " . constant('TITLE') . '/' . constant('FULL_VERSION') . "\r\n";
1854 $request .= "Content-type: application/x-www-form-urlencoded\r\n";
1855 $request .= "Content-length: " . strlen($data) . "\r\n";
1856 $request .= "Cache-Control: no-cache\r\n";
1857 $request .= "Connection: Close\r\n\r\n";
1860 // Send the raw request
1861 $response = sendRawRequest($host, $request);
1863 // Return the result to the caller function
1867 // Sends a raw request to another host
1868 function sendRawRequest ($host, $request) {
1870 $response = array('', '', '');
1872 // Default is not to use proxy
1875 // Are proxy settins set?
1876 if ((getConfig('proxy_host') != '') && (getConfig('proxy_port') > 0)) {
1882 //* DEBUG: */ die("SCRIPT=".$script."<br />\n");
1884 $fp = @fsockopen(COMPILE_CODE(getConfig('proxy_host')), getConfig('proxy_port'), $errno, $errdesc, 30);
1886 $fp = @fsockopen($host, 80, $errno, $errdesc, 30);
1890 if (!is_resource($fp)) {
1897 // Generate CONNECT request header
1898 $proxyTunnel = "CONNECT ".$host.":80 HTTP/1.1\r\n";
1899 $proxyTunnel .= "Host: ".$host."\r\n";
1901 // Use login data to proxy? (username at least!)
1902 if (getConfig('proxy_username') != '') {
1904 $encodedAuth = base64_encode(COMPILE_CODE(getConfig('proxy_username')).constant('ENCRYPT_SEPERATOR').COMPILE_CODE(getConfig('proxy_password')));
1905 $proxyTunnel .= "Proxy-Authorization: Basic ".$encodedAuth."\r\n";
1908 // Add last new-line
1909 $proxyTunnel .= "\r\n";
1910 //* DEBUG: */ print("<strong>proxyTunnel=</strong><pre>".$proxyTunnel."</pre>");
1913 fputs($fp, $proxyTunnel);
1917 // No response received
1921 // Read the first line
1922 $resp = trim(fgets($fp, 10240));
1923 $respArray = explode(' ', $resp);
1924 if ((strtolower($respArray[0]) !== 'http/1.0') || ($respArray[1] != '200')) {
1925 // Invalid response!
1931 fputs($fp, $request);
1934 while (!feof($fp)) {
1935 $response[] = trim(fgets($fp, 1024));
1941 // Skip first empty lines
1943 foreach ($resp as $idx => $line) {
1945 $line = trim($line);
1947 // Is this line empty?
1950 array_shift($response);
1952 // Abort on first non-empty line
1957 //* DEBUG: */ print("<strong>Response:</strong><pre>".print_r($response, true)."</pre>");
1959 // Proxy agent found?
1960 if ((substr(strtolower($response[0]), 0, 11) == 'proxy-agent') && ($useProxy)) {
1961 // Proxy header detected, so remove two lines
1962 array_shift($response);
1963 array_shift($response);
1966 // Was the request successfull?
1967 if ((!eregi('200 OK', $response[0])) || (empty($response[0]))) {
1968 // Not found / access forbidden
1969 $response = array('', '', '');
1976 // Taken from www.php.net eregi() user comments
1977 function VALIDATE_EMAIL ($email) {
1979 $email = COMPILE_CODE($email);
1981 // Check first part of email address
1982 $first = "[-a-z0-9!#$%&\'*+/=?^_<{|}~]+(\.[-a-zA-Z0-9!#$%&\'*+/=?^_<{|}~]+)*";
1985 $domain = "[a-z0-9-]+(\.[a-z0-9-]{2,5})+";
1988 $regex = '^'.$first.'@'.$domain.'$';
1990 // Return check result
1991 // @TODO eregi() should be rewritten here
1992 return eregi($regex, $email);
1995 // Function taken from user comments on www.php.net / function eregi()
1996 function isUrlValid ($URL, $compile=true) {
1997 // Trim URL a little
1998 $URL = trim(urldecode($URL));
1999 //* DEBUG: */ echo $URL."<br />";
2001 // Compile some chars out...
2002 if ($compile) $URL = compileUriCode($URL, false, false, false);
2003 //* DEBUG: */ echo $URL."<br />";
2005 // Check for the extension filter
2006 if (EXT_IS_ACTIVE('filter')) {
2007 // Use the extension's filter set
2008 return FILTER_isUrlValid($URL, false);
2011 // If not installed, perform a simple test. Just make it sure there is always a http:// or
2012 // https:// in front of the URLs
2013 return isUrlValidSimple($URL);
2016 // Generate a list of administrative links to a given userid
2017 function generateMemberAdminActionLinks ($uid, $status = '') {
2018 // Define all main targets
2019 $TARGETS = array('del_user', 'edit_user', 'lock_user', 'add_points', 'sub_points');
2021 // Begin of navigation links
2022 $eval = "\$OUT = \"[ ";
2024 foreach ($TARGETS as $tar) {
2025 $eval .= "<span class=\\\"admin_user_link\\\"><a href=\\\"{!URL!}/modules.php?module=admin&what=".$tar."&uid=".$uid."\\\" title=\\\"{--ADMIN_LINK_";
2026 //* DEBUG: */ echo "*".$tar.'/'.$status."*<br />\n";
2027 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2028 // Locked accounts shall be unlocked
2029 $eval .= "UNLOCK_USER";
2031 // All other status is fine
2032 $eval .= strtoupper($tar);
2034 $eval .= "_TITLE--}\\\">{--ADMIN_";
2035 if (($tar == "lock_user") && ($status == 'LOCKED')) {
2036 // Locked accounts shall be unlocked
2037 $eval .= "UNLOCK_USER";
2039 // All other status is fine
2040 $eval .= strtoupper($tar);
2042 $eval .= "--}</a></span> | ";
2045 // Finish navigation link
2046 $eval = substr($eval, 0, -7)."]\";";
2053 // Generate an email link
2054 function generateMemberEmailLink ($email, $table = 'admins') {
2055 // Default email link (INSECURE! Spammer can read this by harvester programs)
2056 $EMAIL = 'mailto:' . $email;
2058 // Check for several extensions
2059 if ((EXT_IS_ACTIVE('admins')) && ($table == 'admins')) {
2060 // Create email link for contacting admin in guest area
2061 $EMAIL = adminsCreateEmailLink($email);
2062 } elseif ((EXT_IS_ACTIVE('user')) && (GET_EXT_VERSION('user') >= '0.3.3') && ($table == 'user_data')) {
2063 // Create email link for contacting a member within admin area (or later in other areas, too?)
2064 $EMAIL = USER_generateMemberEmailLink($email);
2065 } elseif ((EXT_IS_ACTIVE('sponsor')) && ($table == 'sponsor_data')) {
2066 // Create email link to contact sponsor within admin area (or like the link above?)
2067 $EMAIL = SPONSOR_generateMemberEmailLink($email);
2070 // Shall I close the link when there is no admin?
2071 if ((!IS_ADMIN()) && ($EMAIL == $email)) $EMAIL = '#'; // Closed!
2073 // Return email link
2077 // Generate a hash for extra-security for all passwords
2078 function generateHash ($plainText, $salt = '') {
2079 // Is the required extension 'sql_patches' there and a salt is not given?
2080 if (((EXT_VERSION_IS_OLDER('sql_patches', '0.3.6')) || (!EXT_IS_ACTIVE('sql_patches'))) && (empty($salt))) {
2081 // Extension sql_patches is missing/outdated so we hash the plain text with MD5
2082 return md5($plainText);
2085 // Do we miss an arry element here?
2086 if (!isConfigEntrySet('file_hash')) {
2088 debug_report_bug('Missing file_hash in ' . __FUNCTION__ . '.');
2091 // When the salt is empty build a new one, else use the first x configured characters as the salt
2093 // Build server string (inc/databases.php is no longer updated with every commit)
2094 $server = $_SERVER['PHP_SELF'].constant('ENCRYPT_SEPERATOR').detectUserAgent().constant('ENCRYPT_SEPERATOR').getenv('SERVER_SOFTWARE').constant('ENCRYPT_SEPERATOR').detectRemoteAddr();
2097 $keys = constant('SITE_KEY').constant('ENCRYPT_SEPERATOR').constant('DATE_KEY').constant('ENCRYPT_SEPERATOR').getConfig('secret_key').constant('ENCRYPT_SEPERATOR').getConfig('file_hash').constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", getConfig(('patch_ctime'))).constant('ENCRYPT_SEPERATOR').getConfig('master_salt');
2100 $data = $plainText.constant('ENCRYPT_SEPERATOR').uniqid(mt_rand(), true).constant('ENCRYPT_SEPERATOR').time();
2102 // Calculate number for generating the code
2103 $a = time() + constant('_ADD') - 1;
2105 // Generate SHA1 sum from modula of number and the prime number
2106 $sha1 = sha1(($a % constant('_PRIME')).$server.constant('ENCRYPT_SEPERATOR').$keys.constant('ENCRYPT_SEPERATOR').$data.constant('ENCRYPT_SEPERATOR').date("d-m-Y (l-F-T)", time()).constant('ENCRYPT_SEPERATOR').$a);
2107 //* DEBUG: */ echo "SHA1=".$sha1." (".strlen($sha1).")<br />";
2108 $sha1 = scrambleString($sha1);
2109 //* DEBUG: */ echo "Scrambled=".$sha1." (".strlen($sha1).")<br />";
2110 //* DEBUG: */ $sha1b = descrambleString($sha1);
2111 //* DEBUG: */ echo "Descrambled=".$sha1b." (".strlen($sha1b).")<br />";
2113 // Generate the password salt string
2114 $salt = substr($sha1, 0, getConfig('salt_length'));
2115 //* DEBUG: */ echo $salt." (".strlen($salt).")<br />";
2118 $salt = substr($salt, 0, getConfig('salt_length'));
2119 //* DEBUG: */ echo "GIVEN={$salt}<br />\n";
2123 return $salt.sha1($salt.$plainText);
2126 // Scramble a string
2127 function scrambleString($str) {
2131 // Final check, in case of failture it will return unscrambled string
2132 if (strlen($str) > 40) {
2133 // The string is to long
2135 } elseif (strlen($str) == 40) {
2137 $scrambleNums = explode(':', getConfig('pass_scramble'));
2139 // Generate new numbers
2140 $scrambleNums = explode(':', genScrambleString(strlen($str)));
2143 // Scramble string here
2144 //* DEBUG: */ echo "***Original=".$str."***<br />";
2145 for ($idx = 0; $idx < strlen($str); $idx++) {
2146 // Get char on scrambled position
2147 $char = substr($str, $scrambleNums[$idx], 1);
2149 // Add it to final output string
2150 $scrambled .= $char;
2153 // Return scrambled string
2154 //* DEBUG: */ echo "***Scrambled=".$scrambled."***<br />";
2158 // De-scramble a string scrambled by scrambleString()
2159 function descrambleString($str) {
2160 // Scramble only 40 chars long strings
2161 if (strlen($str) != 40) return $str;
2163 // Load numbers from config
2164 $scrambleNums = explode(':', getConfig('pass_scramble'));
2167 if (count($scrambleNums) != 40) return $str;
2169 // Begin descrambling
2170 $orig = str_repeat(" ", 40);
2171 //* DEBUG: */ echo "+++Scrambled=".$str."+++<br />";
2172 for ($idx = 0; $idx < 40; $idx++) {
2173 $char = substr($str, $idx, 1);
2174 $orig = substr_replace($orig, $char, $scrambleNums[$idx], 1);
2177 // Return scrambled string
2178 //* DEBUG: */ echo "+++Original=".$orig."+++<br />";
2182 // Generated a "string" for scrambling
2183 function genScrambleString ($len) {
2184 // Prepare array for the numbers
2185 $scrambleNumbers = array();
2187 // First we need to setup randomized numbers from 0 to 31
2188 for ($idx = 0; $idx < $len; $idx++) {
2190 $rand = mt_rand(0, ($len -1));
2192 // Check for it by creating more numbers
2193 while (array_key_exists($rand, $scrambleNumbers)) {
2194 $rand = mt_rand(0, ($len -1));
2198 $scrambleNumbers[$rand] = $rand;
2201 // So let's create the string for storing it in database
2202 $scrambleString = implode(':', $scrambleNumbers);
2203 return $scrambleString;
2206 // Append data like session ID or referal ID to the given URL which would
2207 // normally be stored in cookies
2208 function addUrlData ($URL) {
2212 // Determine URL binder
2214 if (strpos($URL, '?') !== false) $BIND = '&';
2216 if ((!defined('__COOKIES')) || ((!constant('__COOKIES')))) {
2217 // Cookies are not accepted
2218 if ((REQUEST_ISSET_GET(('refid'))) && (strpos($URL, "refid=") == 0)) {
2219 // Cookie found in URL
2220 $add .= $BIND."refid=".bigintval(REQUEST_GET('refid'));
2221 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
2222 // Not found! So let's set default here
2223 $add .= $BIND."refid=".getConfig('def_refid');
2227 // Add all together and return it
2231 // Generate an PGP-like encrypted hash of given hash for e.g. cookies
2232 function generatePassString ($passHash) {
2233 // Return vanilla password hash
2236 // Is a secret key and master salt already initialized?
2237 if ((getConfig('secret_key') != '') && (getConfig('master_salt') != '')) {
2238 // Only calculate when the secret key is generated
2239 $newHash = ''; $start = 9;
2240 for ($idx = 0; $idx < 10; $idx++) {
2241 $part1 = hexdec(substr($passHash, $start, 4));
2242 $part2 = hexdec(substr(getConfig('secret_key'), $start, 4));
2243 $mod = dechex($idx);
2244 if ($part1 > $part2) {
2245 $mod = dechex(sqrt(($part1 - $part2) * constant('_PRIME') / pi()));
2246 } elseif ($part2 > $part1) {
2247 $mod = dechex(sqrt(($part2 - $part1) * constant('_PRIME') / pi()));
2249 $mod = substr(round($mod), 0, 4);
2250 $mod = str_repeat('0', 4-strlen($mod)).$mod;
2251 //* DEBUG: */ echo "*".$start.'='.$mod."*<br />";
2256 //* DEBUG: */ print($passHash."<br />".$newHash." (".strlen($newHash).")");
2257 $ret = generateHash($newHash, getConfig('master_salt'));
2258 //* DEBUG: */ print($ret."<br />\n");
2261 //* DEBUG: */ echo "--".$passHash."--<br />\n";
2262 $ret = md5($passHash);
2263 //* DEBUG: */ echo "++".$ret."++<br />\n";
2270 // Fix "deleted" cookies
2271 function fixDeletedCookies ($cookies) {
2272 // Is this an array with entries?
2273 if ((is_array($cookies)) && (count($cookies) > 0)) {
2274 // Then check all cookies if they are marked as deleted!
2275 foreach ($cookies as $cookieName) {
2276 // Is the cookie set to "deleted"?
2277 if (getSession($cookieName) == 'deleted') {
2278 setSession($cookieName, '');
2284 // Output error messages in a fasioned way and die...
2285 function app_die ($F, $L, $msg) {
2287 loadIncludeOnce('inc/header.php');
2289 // Prepare message for output
2290 $msg = sprintf(getMessage('MXCHANGE_HAS_DIED'), basename($F), $L, $msg);
2292 // Load the message template
2293 LOAD_TEMPLATE('admin_settings_saved', false, $msg);
2296 loadIncludeOnce('inc/footer.php');
2302 // Display parsing time and number of SQL queries in footer
2303 function displayParsingTime() {
2304 // Is the timer started?
2305 if (!isset($GLOBALS['startTime'])) {
2311 $endTime = microtime(true);
2313 // "Explode" both times
2314 $start = explode(' ', $GLOBALS['startTime']);
2315 $end = explode(' ', $endTime);
2316 $runTime = $end[0] - $start[0];
2317 if ($runTime < 0) $runTime = 0;
2318 $runTime = translateComma($runTime);
2322 'runtime' => $runTime,
2323 'numSQLs' => (getConfig('sql_count') + 1),
2324 'numTemplates' => (getConfig('num_templates') + 1)
2327 // Load the template
2328 LOAD_TEMPLATE('show_timings', false, $content);
2331 // Check wether a boolean constant is set
2332 // Taken from user comments in PHP documentation for function constant()
2333 function isBooleanConstantAndTrue ($constName) { // : Boolean
2334 // Failed by default
2338 if (isset($GLOBALS['cache_array']['const'][$constName])) {
2340 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-CACHE!<br />\n";
2341 $res = ($GLOBALS['cache_array']['const'][$constName] === true);
2344 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-RESOLVE!<br />\n";
2345 if (defined($constName)) {
2347 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ".$constName."-FOUND!<br />\n";
2348 $res = (constant($constName) === true);
2352 $GLOBALS['cache_array']['const'][$constName] = $res;
2354 //* DEBUG: */ var_dump($res);
2360 // Checks if a given apache module is loaded
2361 function isApacheModuleLoaded ($apacheModule) {
2362 // Check it and return result
2363 return (((function_exists('apache_get_modules')) && (in_array($apacheModule, apache_get_modules()))) || (!function_exists('apache_get_modules')));
2366 // "Getter" for language strings
2367 // @TODO Rewrite all language constants to this function.
2368 function getMessage ($messageId) {
2369 // Default is not found!
2370 $return = '!'.$messageId.'!';
2372 // Is the language string found?
2373 if (isset($GLOBALS['msg'][strtolower($messageId)])) {
2374 // Language array element found in small_letters
2375 $return = $GLOBALS['msg'][$messageId];
2376 } elseif (isset($GLOBALS['msg'][strtoupper($messageId)])) {
2377 // @DEPRECATED Language array element found in BIG_LETTERS
2378 $return = $GLOBALS['msg'][$messageId];
2379 } elseif (defined($messageId)) {
2380 // @DEPRECATED Deprecated constant found
2381 $return = constant($messageId);
2383 // Missing language constant
2384 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Missing message string %s detected.", $messageId));
2387 // Return the string
2391 // Get current theme name
2392 function getCurrentTheme() {
2393 // The default theme is 'default'... ;-)
2396 // Load default theme if not empty from configuration
2397 if (getConfig('default_theme') != '') $ret = getConfig('default_theme');
2399 if (!isSessionVariableSet('mxchange_theme')) {
2400 // Set default theme
2401 setSession('mxchange_theme', $ret);
2402 } elseif ((isSessionVariableSet('mxchange_theme')) && (GET_EXT_VERSION('sql_patches') >= '0.1.4')) {
2403 //die("<pre>".print_r($GLOBALS['cache_array']['themes'], true)."</pre>");
2404 // Get theme from cookie
2405 $ret = getSession('mxchange_theme');
2408 if (getThemeId($ret) == 0) {
2409 // Fix it to default
2412 } elseif ((!isInstalled()) && ((isInstalling()) || ($GLOBALS['output_mode'] == true)) && ((REQUEST_ISSET_GET('theme')) || (REQUEST_ISSET_POST('theme')))) {
2413 // Prepare FQFN for checking
2414 $theme = sprintf("%stheme/%s/theme.php", constant('PATH'), REQUEST_GET('theme'));
2416 // Installation mode active
2417 if ((REQUEST_ISSET_GET('theme')) && (isFileReadable($theme))) {
2418 // Set cookie from URL data
2419 setSession('mxchange_theme', REQUEST_GET('theme'));
2420 } elseif (isFileReadable(sprintf("%stheme/%s/theme.php", constant('PATH'), SQL_ESCAPE(REQUEST_POST('theme'))))) {
2421 // Set cookie from posted data
2422 setSession('mxchange_theme', SQL_ESCAPE(REQUEST_POST('theme')));
2426 $ret = getSession('mxchange_theme');
2428 // Invalid design, reset cookie
2429 setSession('mxchange_theme', $ret);
2432 // Add (maybe) found theme.php file to inclusion list
2433 $INC = sprintf("theme/%s/theme.php", SQL_ESCAPE($ret));
2435 // Try to load the requested include file
2436 if (isIncludeReadable($INC)) ADD_INC_TO_POOL($INC);
2438 // Return theme value
2442 // Get id from theme
2443 function getThemeId ($name) {
2444 // Is the extension 'theme' installed?
2445 if (!EXT_IS_ACTIVE('theme')) {
2453 // Is the cache entry there?
2454 if (isset($GLOBALS['cache_array']['themes']['id'][$name])) {
2455 // Get the version from cache
2456 $id = $GLOBALS['cache_array']['themes']['id'][$name];
2459 incrementConfigEntry('cache_hits');
2460 } elseif (GET_EXT_VERSION('cache') != '0.1.8') {
2461 // Check if current theme is already imported or not
2462 $result = SQL_QUERY_ESC("SELECT `id` FROM `{!_MYSQL_PREFIX!}_themes` WHERE theme_path='%s' LIMIT 1",
2463 array($name), __FUNCTION__, __LINE__);
2466 if (SQL_NUMROWS($result) == 1) {
2468 list($id) = SQL_FETCHROW($result);
2472 SQL_FREERESULT($result);
2479 // Read a given file
2480 function readFromFile ($FQFN, $sqlPrepare = false) {
2482 if (function_exists('file_get_contents')) {
2484 $content = file_get_contents($FQFN);
2486 // Fall-back to implode-file chain
2487 $content = implode('', file($FQFN));
2490 // Prepare SQL queries?
2491 if ($sqlPrepare === true) {
2492 // Remove some unwanted chars
2493 $content = str_replace("\r", '', $content);
2494 $content = str_replace("\n\n", "\n", $content);
2497 // Return the content
2501 // Writes content to a file
2502 function writeToFile ($FQFN, $content) {
2503 // Is the file writeable?
2504 if ((isFileReadable($FQFN)) && (!is_writeable($FQFN)) && (!chmod($FQFN, 0644))) {
2506 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("File %s not writeable.", basename($FQFN)));
2512 // By default all is failed...
2515 // Is the function there?
2516 if (function_exists('file_put_contents')) {
2517 // Write it directly
2518 $return = file_put_contents($FQFN, $content);
2520 // Write it with fopen
2521 $fp = fopen($FQFN, 'w') or app_die(__FUNCTION__, __LINE__, "Cannot write file ".basename($FQFN).'!');
2522 fwrite($fp, $content);
2526 $return = chmod($FQFN, 0644);
2533 // Generates an error code from given account status
2534 function generateErrorCodeFromUserStatus ($status) {
2535 // Default error code if unknown account status
2536 $errorCode = getCode('UNKNOWN_STATUS');
2538 // Generate constant name
2539 $constantName = sprintf("ID_%s", $status);
2541 // Is the constant there?
2542 if (isCodeSet($constantName)) {
2544 $errorCode = getCode($constantName);
2547 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Unknown error status %s detected.", $status));
2550 // Return error code
2554 // Clears the output buffer. This function does *NOT* backup sent content.
2555 function clearOutputBuffer () {
2556 // Trigger an error on failure
2557 if (!ob_end_clean()) {
2559 debug_report_bug(__FUNCTION__.': Failed to clean output buffer.');
2563 // Function to search for the last modifified file
2564 function searchDirsRecursive ($dir, &$last_changed) {
2566 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):dir=".$dir."<br />\n";
2567 // Does it match what we are looking for? (We skip a lot files already!)
2568 // RegexPattern to exclude ., .., .revision, .svn, debug.log or .cache in the filenames
2569 $excludePattern = '@(\.|\.\.|\.revision|\.svn|debug\.log|\.cache|config\.php)$@';
2570 $ds = getArrayFromDirectory($dir, '', true, false, $excludePattern);
2571 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ds[]=".count($ds)."<br />\n";
2573 // Walk through all entries
2574 foreach ($ds as $d) {
2575 // Generate proper FQFN
2576 $FQFN = str_replace("//", '/', constant('PATH') . $dir. '/'. $d);
2578 // Is it a file and readable?
2579 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):FQFN={$FQFN}<br />\n";
2580 if (isDirectory($FQFN)) {
2581 // $FQFN is a directory so also crawl into this directory
2583 if (!empty($dir)) $newDir = $dir . '/'. $d;
2584 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):DESCENT: ".$newDir."<br />\n";
2585 searchDirsRecursive($newDir, $last_changed);
2586 } elseif (isFileReadable($FQFN)) {
2587 // $FQFN is a filename and no directory
2588 $time = filemtime($FQFN);
2589 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):File: ".$d." found. (".($last_changed['time'] - $time).")<br />\n";
2590 if ($last_changed['time'] < $time) {
2591 // This file is newer as the file before
2592 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>) - NEWER!<br />\n";
2593 $last_changed['path_name'] = $FQFN;
2594 $last_changed['time'] = $time;
2600 // "Getter" for revision/version data
2601 function getActualVersion ($type = 'Revision') {
2602 // By default nothing is new... ;-)
2605 if (EXT_IS_ACTIVE('cache')) {
2606 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2607 if (REQUEST_ISSET_GET('check_revision_data') && REQUEST_GET('check_revision_data') == 'yes') $new = true;
2608 if (!isset($GLOBALS['cache_array']['revision'][$type])
2609 || count($GLOBALS['cache_array']['revision']) < 3
2610 || !$GLOBALS['cache_instance']->loadCacheFile('revision')) $new = true;
2612 // Is the cache file outdated/invalid?
2614 $GLOBALS['cache_instance']->destroyCacheFile(); // @TODO isn't it better to do $GLOBALS['cache_instance']->destroyCacheFile('revision')?
2616 // @TODO shouldn't do the unset and the reloading $GLOBALS['cache_instance']->destroyCacheFile() Or a new methode like forceCacheReload('revision')?
2617 unset($GLOBALS['cache_array']['revision']);
2619 // Reload load_cach-revison.php
2620 loadInclude('inc/loader/load_cache-revision.php');
2623 // Return found value
2624 return $GLOBALS['cache_array']['revision'][$type][0];
2627 // Old Version without ext-cache active (deprecated ?)
2629 // FQFN of revision file
2630 $FQFN = sprintf("%sinc/cache/.revision", constant('PATH'));
2632 // Check if REQUEST_GET('check_revision_data') is setted (switch for manually rewrite the .revision-File)
2633 if ((REQUEST_ISSET_GET('check_revision_data')) && (REQUEST_GET('check_revision_data') == 'yes')) {
2637 // Check for revision file
2638 if (!isFileReadable($FQFN)) {
2639 // Not found, so we need to create it
2642 // Revision file found
2643 $ins_vers = explode("\n", readFromFile($FQFN));
2645 // Get array for mapping information
2646 $mapper = array_flip(getSearchFor());
2647 //* DEBUG: */ print("<pre>".print_r($mapper, true).print_r($ins_vers, true)."</pre>");
2649 // Is the content valid?
2650 if ((!is_array($ins_vers)) || (count($ins_vers) <= 0) || (!isset($ins_vers[$mapper[$type]])) || (trim($ins_vers[$mapper[$type]]) == '') || ($ins_vers[0]) == "new") {
2651 // File needs update!
2654 // Return found value
2655 return trim($ins_vers[$mapper[$type]]);
2660 // Has it been updated?
2661 if ($new === true) {
2662 writeToFile($FQFN, implode("\n", getArrayFromActualVersion()));
2667 // Repares an array we are looking for
2668 // 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
2669 function getSearchFor () {
2670 // Add Revision, Date, Tag and Author
2671 $searchFor = array('Revision', 'Date', 'Tag', 'Author');
2673 // Return the created array
2677 // @TODO Please describe this function
2678 function getArrayFromActualVersion () {
2680 $next_dir = ''; // Directory to start with search
2681 $last_changed = array(
2685 $akt_vers = array(); // Init return array
2686 $res = 0; // Init value for counting the founded keywords
2688 // Searches all Files and there date of the last modifikation and puts the newest File in $last_changed.
2689 searchDirsRecursive($next_dir, $last_changed); // @TODO small change to API to $last_changed = searchDirsRecursive($next_dir, $time);
2692 $last_file = readFromFile($last_changed['path_name']);
2694 // Get all the keywords to search for
2695 $searchFor = getSearchFor();
2697 // This foreach loops the $searchFor-Tags (array('Revision', 'Date', 'Tag', 'Author') --> could easaly extended in the future)
2698 foreach ($searchFor as $search) {
2699 // Searches for "$search-tag:VALUE$" or "$search-tag::VALUE$"(the stylish keywordversion ;-)) in the lates modified file
2700 $res += preg_match('@\$'.$search.'(:|::) (.*) \$@U', $last_file, $t);
2701 // This trimms the search-result and puts it in the $akt_vers-return array
2702 if (isset($t[2])) $akt_vers[$search] = trim($t[2]);
2705 // Save the last-changed filename for debugging
2706 $akt_vers['File'] = $last_changed['path_name'];
2708 // at least 3 keyword-Tags are needed for propper values
2709 if ($res && $res >= 3
2710 && isset($akt_vers['Revision']) && $akt_vers['Revision'] != ''
2711 && isset($akt_vers['Date']) && $akt_vers['Date'] != ''
2712 && isset($akt_vers['Tag']) && $akt_vers['Tag'] != '') {
2713 // Prepare content witch need special treadment
2715 // Prepare timestamp for date
2716 preg_match('@(....)-(..)-(..) (..):(..):(..)@', $akt_vers['Date'], $match_d);
2717 $akt_vers['Date'] = mktime($match_d[4], $match_d[5], $match_d[6], $match_d[2], $match_d[3], $match_d[1]);
2719 // Add author to the Tag if the author is set and is not quix0r (lead coder)
2720 if ((isset($akt_vers['Author'])) && ($akt_vers['Author'] != "quix0r")) {
2721 $akt_vers['Tag'] .= '-'.strtoupper($akt_vers['Author']);
2725 // No valid Data from the last modificated file so read the Revision from the Server. Fallback-solution!! Should not be removed I think.
2726 $version = sendGetRequest('check-updates3.php');
2729 // Only sets not setted or not proper values to the Online-Server-Fallback-Solution
2730 if (!isset($akt_vers['Revision']) || $akt_vers['Revision'] == '') $akt_vers['Revision'] = trim($version[10]);
2731 if (!isset($akt_vers['Date']) || $akt_vers['Date'] == '') $akt_vers['Date'] = trim($version[9]);
2732 if (!isset($akt_vers['Tag']) || $akt_vers['Tag'] == '') $akt_vers['Tag'] = trim($version[8]);
2733 if (!isset($akt_vers['Author']) || $akt_vers['Author'] == '') $akt_vers['Author'] = "quix0r";
2736 // Return prepared array
2741 // Loads an include file and logs any missing files for debug purposes
2742 function loadInclude ($INC) {
2743 // Add the path. This is why we need a trailing slash in config.php
2744 $FQFN = constant('PATH') . $INC;
2746 // Is the include file there?
2747 if (!isIncludeReadable($INC)) {
2748 // Not there so log it
2749 debug_report_bug(sprintf("Include file %s not found.", $INC));
2757 // Loads an include file once
2758 function loadIncludeOnce ($INC) {
2759 // Is it not loaded?
2760 if (!isset($GLOBALS['load_once'][$INC])) {
2761 // Then try to load it
2764 // And mark it as loaded
2765 $GLOBALS['load_once'][$INC] = "loaded";
2769 // Back-ported from the new ship-simu engine. :-)
2770 function debug_get_printable_backtrace () {
2772 $backtrace = "<ol>\n";
2774 // Get and prepare backtrace for output
2775 $backtraceArray = debug_backtrace();
2776 foreach ($backtraceArray as $key => $trace) {
2777 if (!isset($trace['file'])) $trace['file'] = __FUNCTION__;
2778 if (!isset($trace['line'])) $trace['line'] = __LINE__;
2779 if (!isset($trace['args'])) $trace['args'] = array();
2780 $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";
2784 $backtrace .= "</ol>\n";
2786 // Return the backtrace
2790 // Output a debug backtrace to the user
2791 function debug_report_bug ($message = '') {
2794 // Is the optional message set?
2795 if (!empty($message)) {
2797 $debug = sprintf("Note: %s<br />\n",
2801 // @TODO Add a little more infos here
2802 DEBUG_LOG(__FUNCTION__, __LINE__, $message);
2806 $debug .= "Please report this bug at <a href=\"http://bugs.mxchange.org\" rel=\"external\" target=\"_blank\">bugs.mxchange.org</a>:<pre>";
2807 $debug .= debug_get_printable_backtrace();
2808 $debug .= "</pre>Request-URI: ".$_SERVER['REQUEST_URI']."<br />\n";
2809 $debug .= "Thank you for finding bugs.";
2812 // @TODO This cannot be rewritten to app_die(), try to find a solution for this.
2816 // Generates a ***weak*** seed (taken from de.php.net/mt_srand)
2817 function generateSeed () {
2818 list($usec, $sec) = explode(" ", microtime());
2819 return ((float)$sec + (float)$usec);
2822 // Converts a message code to a human-readable message
2823 function convertCodeToMessage ($code) {
2826 case getCode('LOGOUT_DONE') : $msg = getMessage('LOGOUT_DONE'); break;
2827 case getCode('LOGOUT_FAILED') : $msg = "<span class=\"guest_failed\">{--LOGOUT_FAILED--}</span>"; break;
2828 case getCode('DATA_INVALID') : $msg = getMessage('MAIL_DATA_INVALID'); break;
2829 case getCode('POSSIBLE_INVALID') : $msg = getMessage('MAIL_POSSIBLE_INVALID'); break;
2830 case getCode('ACCOUNT_LOCKED') : $msg = getMessage('MEMBER_ACCOUNT_LOCKED_UNC'); break;
2831 case getCode('USER_404') : $msg = getMessage('USER_NOT_FOUND'); break;
2832 case getCode('STATS_404') : $msg = getMessage('MAIL_STATS_404'); break;
2833 case getCode('ALREADY_CONFIRMED'): $msg = getMessage('MAIL_ALREADY_CONFIRMED'); break;
2835 case getCode('ERROR_MAILID'):
2836 if (EXT_IS_ACTIVE($ext, true)) {
2837 $msg = getMessage('ERROR_CONFIRMING_MAIL');
2839 $msg = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'mailid');
2843 case getCode('EXTENSION_PROBLEM'):
2844 if (REQUEST_ISSET_GET(('ext'))) {
2845 $msg = sprintf(getMessage('EXTENSION_PROBLEM_EXT_INACTIVE'), REQUEST_GET(('ext')));
2847 $msg = getMessage('EXTENSION_PROBLEM_UNSET_EXT');
2851 case getCode('COOKIES_DISABLED') : $msg = getMessage('LOGIN_NO_COOKIES'); break;
2852 case getCode('BEG_SAME_AS_OWN') : $msg = getMessage('BEG_SAME_UID_AS_OWN'); break;
2853 case getCode('LOGIN_FAILED') : $msg = getMessage('LOGIN_FAILED_GENERAL'); break;
2854 case getCode('MODULE_MEM_ONLY') : $msg = sprintf(getMessage('MODULE_MEM_ONLY'), REQUEST_GET('mod')); break;
2857 // Missing/invalid code
2858 $msg = sprintf(getMessage('UNKNOWN_MAILID_CODE'), $code);
2861 DEBUG_LOG(__FUNCTION__, __LINE__, $msg);
2865 // Return the message
2869 // Generate a "link" for the given admin id (aid)
2870 function generateAdminLink ($aid) {
2871 // No assigned admin is default
2872 $admin = "<span class=\"admin_note\">{--ADMIN_NO_ADMIN_ASSIGNED--}</span>";
2874 // Zero? = Not assigned
2875 if (bigintval($aid) > 0) {
2876 // Load admin's login
2877 $login = getAdminLogin($aid);
2879 // Is the login valid?
2880 if ($login != '***') {
2881 // Is the extension there?
2882 if (EXT_IS_ACTIVE('admins')) {
2884 $admin = "<a href=\"".adminsCreateEmailLink(getAdminEmail($aid))."\">".$login."</a>";
2886 // Extension not found
2887 $admin = sprintf(getMessage('EXTENSION_PROBLEM_NOT_INSTALLED'), 'admins');
2891 $admin = "<div class=\"admin_note\">".sprintf(getMessage('ADMIN_ID_404'), $aid)."</div>";
2899 // Checks wether an include file (non-FQFN better) is readable
2900 function isIncludeReadable ($INC) {
2902 $FQFN = constant('PATH') . $INC;
2905 return isFileReadable($FQFN);
2909 // @TODO Implement $compress
2910 function encodeString ($str, $compress=true) {
2911 $str = urlencode(base64_encode(compileUriCode($str)));
2915 // Decode strings encoded with encodeString()
2916 // @TODO Implement $decompress
2917 function decodeString ($str, $decompress=true) {
2918 $str = compileUriCode(base64_decode(urldecode(compileUriCode($str))));
2922 // Compile characters which are allowed in URLs
2923 function compileUriCode ($code, $simple=true) {
2924 // Compile constants
2925 if (!$simple) $code = str_replace("{--", '".', str_replace("--}", '."', $code));
2927 // Compile QUOT and other non-HTML codes
2928 $code = str_replace('{DOT}', '.',
2929 str_replace('{SLASH}', '/',
2930 str_replace('{QUOT}', "'",
2931 str_replace('{DOLLAR}', '$',
2932 str_replace('{OPEN_ANCHOR}', '(',
2933 str_replace('{CLOSE_ANCHOR}', ')',
2934 str_replace('{OPEN_SQR}', '[',
2935 str_replace('{CLOSE_SQR}', ']',
2936 str_replace('{PER}', '%',
2940 // Return compiled code
2944 // Function taken from user comments on www.php.net / function eregi()
2945 function isUrlValidSimple ($url) {
2947 $url = strip_tags(str_replace("\\", '', compileUriCode(urldecode($url))));
2949 // Allows http and https
2950 $http = "(http|https)+(:\/\/)";
2952 $domain1 = "([[:alnum:]]([-[:alnum:]])*\.)?([[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})?";
2953 // Test double-domains (e.g. .de.vu)
2954 $domain2 = "([-[:alnum:]])?(\.[[:alnum:]][-[:alnum:]\.]*[[:alnum:]])(\.[[:alpha:]]{2,5})(\.[[:alpha:]]{2,5})?";
2956 $ip = "([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})\.([[:digit:]]{1,3})";
2958 $dir = "((/)+([-_\.[:alnum:]])+)*";
2960 $page = "/([-_[:alnum:]][-\._[:alnum:]]*\.[[:alnum:]]{2,5})?";
2961 // ... and the string after and including question character
2962 $getstring1 = "([\?/]([[:alnum:]][-\._%[:alnum:]]*(=)?([-\@\._:%[:alnum:]])+)(&([[:alnum:]]([-_%[:alnum:]])*(=)?([-\@\[\._:%[:alnum:]])+(\])*))*)?";
2963 // Pattern for URLs like http://url/dir/doc.html?var=value
2964 $pattern['d1dpg1'] = $http.$domain1.$dir.$page.$getstring1;
2965 $pattern['d2dpg1'] = $http.$domain2.$dir.$page.$getstring1;
2966 $pattern['ipdpg1'] = $http.$ip.$dir.$page.$getstring1;
2967 // Pattern for URLs like http://url/dir/?var=value
2968 $pattern['d1dg1'] = $http.$domain1.$dir.'/'.$getstring1;
2969 $pattern['d2dg1'] = $http.$domain2.$dir.'/'.$getstring1;
2970 $pattern['ipdg1'] = $http.$ip.$dir.'/'.$getstring1;
2971 // Pattern for URLs like http://url/dir/page.ext
2972 $pattern['d1dp'] = $http.$domain1.$dir.$page;
2973 $pattern['d1dp'] = $http.$domain2.$dir.$page;
2974 $pattern['ipdp'] = $http.$ip.$dir.$page;
2975 // Pattern for URLs like http://url/dir
2976 $pattern['d1d'] = $http.$domain1.$dir;
2977 $pattern['d2d'] = $http.$domain2.$dir;
2978 $pattern['ipd'] = $http.$ip.$dir;
2979 // Pattern for URLs like http://url/?var=value
2980 $pattern['d1g1'] = $http.$domain1.'/'.$getstring1;
2981 $pattern['d2g1'] = $http.$domain2.'/'.$getstring1;
2982 $pattern['ipg1'] = $http.$ip.'/'.$getstring1;
2983 // Pattern for URLs like http://url?var=value
2984 $pattern['d1g12'] = $http.$domain1.$getstring1;
2985 $pattern['d2g12'] = $http.$domain2.$getstring1;
2986 $pattern['ipg12'] = $http.$ip.$getstring1;
2987 // Test all patterns
2989 foreach ($pattern as $key=>$pat) {
2991 if (defined('DEBUG_REGEX')) {
2992 $pat = str_replace("[:alnum:]", "0-9a-zA-Z", $pat);
2993 $pat = str_replace("[:alpha:]", "a-zA-Z", $pat);
2994 $pat = str_replace("[:digit:]", "0-9", $pat);
2995 $pat = str_replace('.', "\.", $pat);
2996 $pat = str_replace("@", "\@", $pat);
2997 echo $key."= ".$pat."<br />";
3000 // Check if expression matches
3001 $reg = ($reg || preg_match(("^".$pat."^"), $url));
3004 if ($reg === true) break;
3007 // Return true/false
3011 // Smartly adds slashes
3012 function smartAddSlashes ($unquoted) {
3013 $unquoted = str_replace("\\", '', $unquoted);
3014 return addslashes($unquoted);
3017 // Decode entities in a nicer way
3018 function decodeEntities ($str) {
3019 // Decode the entities to UTF-8 now
3020 $decodedString = html_entity_decode($str, ENT_NOQUOTES, "UTF-8");
3022 // Return decoded string
3023 return $decodedString;
3026 // Wtites data to a config.php-style file
3027 // @TODO Rewrite this function to use readFromFile() and writeToFile()
3028 function changeDataInFile ($FQFN, $comment, $prefix, $suffix, $DATA, $seek=0) {
3029 // Initialize some variables
3035 // Is the file there and read-/write-able?
3036 if ((isFileReadable($FQFN)) && (is_writeable($FQFN))) {
3037 $search = "CFG: ".$comment;
3038 $tmp = $FQFN.".tmp";
3040 // Open the source file
3041 $fp = fopen($FQFN, 'r') or OUTPUT_HTML("<strong>READ:</strong> ".$FQFN."<br />");
3043 // Is the resource valid?
3044 if (is_resource($fp)) {
3045 // Open temporary file
3046 $fp_tmp = fopen($tmp, 'w') or OUTPUT_HTML("<strong>WRITE:</strong> ".$tmp."<br />");
3048 // Is the resource again valid?
3049 if (is_resource($fp_tmp)) {
3050 while (!feof($fp)) {
3051 // Read from source file
3052 $line = fgets ($fp, 1024);
3054 if (strpos($line, $search) > -1) { $next = 0; $found = true; }
3057 if ($next === $seek) {
3059 $line = $prefix . $DATA . $suffix."\n";
3065 // Write to temp file
3066 fputs($fp_tmp, $line);
3072 // Finished writing tmp file
3076 // Close source file
3079 if (($done) && ($found)) {
3080 // Copy back tmp file and delete tmp :-)
3082 return unlink($tmp);
3083 } elseif (!$found) {
3084 OUTPUT_HTML("<strong>CHANGE:</strong> 404!");
3086 OUTPUT_HTML("<strong>TMP:</strong> UNDONE!");
3090 // File not found, not readable or writeable
3091 OUTPUT_HTML("<strong>404:</strong> ".$FQFN."<br />");
3094 // An error was detected!
3097 // Send notification to admin
3098 function sendAdminNotification ($subject, $templateName, $content=array(), $uid = '0') {
3099 if (GET_EXT_VERSION('admins') >= '0.4.1') {
3101 SEND_ADMIN_EMAILS_PRO($subject, $templateName, $content, $uid);
3103 // Send out out-dated way
3104 $msg = LOAD_EMAIL_TEMPLATE($templateName, $content, $uid);
3105 SEND_ADMIN_EMAILS($subject, $msg);
3109 // Merges an array together but only if both are arrays
3110 function merge_array ($array1, $array2) {
3111 // Are both an array?
3112 if ((is_array($array1)) && (is_array($array2))) {
3113 // Merge all together
3114 return array_merge($array1, $array2);
3115 } elseif (is_array($array1)) {
3116 // Return left array
3117 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array2 is not an array. array != %s", gettype($array2)));
3119 } elseif (is_array($array2)) {
3120 // Return right array
3121 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("array1 is not an array. array != %s", gettype($array1)));
3125 // Both are not arrays
3126 debug_report_bug(__FUNCTION__.": No arrays provided!");
3129 // Debug message logger
3130 function DEBUG_LOG ($funcFile, $line, $message, $force=true) {
3131 // Is debug mode enabled?
3132 if ((isDebugModeEnabled()) || ($force === true)) {
3134 $message = str_replace("\r", '', str_replace("\n", '', $message));
3136 // Log this message away
3137 $fp = fopen(constant('PATH')."inc/cache/debug.log", 'a') or app_die(__FUNCTION__, __LINE__, "Cannot write logfile debug.log!");
3138 fwrite($fp, date("d.m.Y|H:i:s", time())."|".$GLOBALS['module']."|".basename($funcFile)."|".$line."|".strip_tags($message)."\n");
3143 // Load more reset scripts
3144 function runResetIncludes () {
3145 // Is the reset set or old sql_patches?
3146 if ((!isResetModeEnabled()) || (EXT_VERSION_IS_OLDER('sql_patches', '0.4.5'))) {
3148 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot run reset! Please report this bug. Thanks");
3151 // Get more daily reset scripts
3152 SET_INC_POOL(getArrayFromDirectory('inc/reset/', 'reset_'));
3155 if (!defined('DEBUG_RESET')) updateConfiguration('last_update', time());
3157 // Is the config entry set?
3158 if (GET_EXT_VERSION('sql_patches') >= '0.4.2') {
3159 // Create current week mark
3160 $currWeek = date('W', time());
3163 if (getConfig('last_week') != $currWeek) {
3164 // Include weekly reset scripts
3165 MERGE_INC_POOL(getArrayFromDirectory('inc/weekly/', 'weekly_'));
3168 if (!defined('DEBUG_WEEKLY')) updateConfiguration('last_week', $currWeek);
3171 // Create current month mark
3172 $currMonth = date('m', time());
3175 if (getConfig('last_month') != $currMonth) {
3176 // Include monthly reset scripts
3177 MERGE_INC_POOL(getArrayFromDirectory('inc/monthly/', 'monthly_'));
3180 if (!defined('DEBUG_MONTHLY')) updateConfiguration('last_month', $currMonth);
3185 runFilterChain('load_includes');
3188 // Handle extra values
3189 function handleExtraValues ($filterFunction, $value, $extraValue) {
3190 // Default is the value itself
3193 // Do we have a special filter function?
3194 if (!empty($filterFunction)) {
3195 // Does the filter function exist?
3196 if (function_exists($filterFunction)) {
3197 // Do we have extra parameters here?
3198 if (!empty($extraValue)) {
3199 // Put both parameters in one new array by default
3200 $args = array($value, $extraValue);
3202 // If we have an array simply use it and pre-extend it with our value
3203 if (is_array($extraValue)) {
3204 // Make the new args array
3205 $args = merge_array(array($value), $extraValue);
3208 // Call the multi-parameter call-back
3209 $ret = call_user_func_array($filterFunction, $args);
3211 // One parameter call
3212 $ret = call_user_func($filterFunction, $value);
3221 // Check if given FQFN is a readable file
3222 function isFileReadable ($FQFN) {
3224 return ((file_exists($FQFN)) && (is_file($FQFN)) && (is_readable($FQFN)));
3227 // Converts timestamp selections into a timestamp
3228 function convertSelectionsToTimestamp (&$POST, &$DATA, &$id, &$skip) {
3229 // Init test variable
3232 // Get last three chars
3233 $test = substr($id, -3);
3235 // Improved way of checking! :-)
3236 if (in_array($test, array('_ye', '_mo', '_we', '_da', '_ho', '_mi', '_se'))) {
3237 // Found a multi-selection for timings?
3238 $test = substr($id, 0, -3);
3239 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)) {
3240 // Generate timestamp
3241 $POST[$test] = createTimestampFromSelections($test, $POST);
3242 $DATA[] = sprintf("%s='%s'", $test, $POST[$test]);
3244 // Remove data from array
3245 foreach (array('ye', 'mo', 'we', 'da', 'ho', 'mi', 'se') as $rem) {
3246 unset($POST[$test.'_'.$rem]);
3250 unset($id); $skip = true; $test2 = $test;
3253 // Process this entry
3259 // Reverts the german decimal comma into Computer decimal dot
3260 function convertCommaToDot ($str) {
3261 // Default float is not a float... ;-)
3264 // Which language is selected?
3265 switch (getLanguage()) {
3266 case 'de': // German language
3267 // Remove german thousand dots first
3268 $str = str_replace('.', '', $str);
3270 // Replace german commata with decimal dot and cast it
3271 $float = (float)str_replace(',', '.', $str);
3274 default: // US and so on
3275 // Remove thousand dots first and cast
3276 $float = (float)str_replace(',', '', $str);
3284 // Handle menu-depending failed logins and return the rendered content
3285 function HANDLE_LOGIN_FAILTURES ($accessLevel) {
3286 // Default output is empty ;-)
3289 // Is the session data set?
3290 if ((isSessionVariableSet('mxchange_'.$accessLevel.'_failures')) && (isSessionVariableSet('mxchange_'.$accessLevel.'_last_fail'))) {
3291 // Ignore zero values
3292 if (getSession('mxchange_'.$accessLevel.'_failures') > 0) {
3293 // Non-guest has login failures found, get both data and prepare it for template
3294 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):accessLevel={$accessLevel}<br />\n";
3296 'login_failures' => getSession('mxchange_'.$accessLevel.'_failures'),
3297 'last_failure' => generateDateTime(getSession('mxchange_'.$accessLevel.'_last_fail'), "2")
3301 $OUT = LOAD_TEMPLATE('login_failures', true, $content);
3304 // Reset session data
3305 setSession('mxchange_'.$accessLevel.'_failures', '');
3306 setSession('mxchange_'.$accessLevel.'_last_fail', '');
3309 // Return rendered content
3314 function rebuildCacheFiles ($cache, $inc = '') {
3315 // Shall I remove the cache file?
3316 if ((EXT_IS_ACTIVE('cache')) && (isCacheInstanceValid())) {
3318 if ($GLOBALS['cache_instance']->loadCacheFile($cache)) {
3320 $GLOBALS['cache_instance']->destroyCacheFile();
3323 // Include file given?
3326 $INC = sprintf("inc/loader/load_cache-%s.php", $inc);
3328 // Is the include there?
3329 if (isIncludeReadable($INC)) {
3330 // And rebuild it from scratch
3331 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): inc={$inc} - LOADED!<br />\n";
3334 // Include not found!
3335 DEBUG_LOG(__FUNCTION__, __LINE__, "Include {$inc} not found. cache={$cache}");
3341 // Purge admin menu cache
3342 function cachePurgeAdminMenu ($id=0, $action = '', $what = '', $str = '') {
3343 // Is the cache extension enabled or no cache instance or admin menu cache disabled?
3344 if (!EXT_IS_ACTIVE('cache')) {
3345 // Cache extension not active
3347 } elseif (!isCacheInstanceValid()) {
3348 // No cache instance!
3349 DEBUG_LOG(__FUNCTION__, __LINE__, " No cache instance found.");
3351 } elseif ((!isConfigEntrySet('cache_admin_menu')) || (getConfig('cache_admin_menu') != 'Y')) {
3352 // Caching disabled (currently experiemental!)
3356 // Experiemental feature!
3357 debug_report_bug("<strong>Experimental feature:</strong> You have to delete the admin_*.cache files by yourself at this point.");
3360 // Determines the real remote address
3361 function determineRealRemoteAddress () {
3362 // Is a proxy in use?
3363 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
3365 $address = $_SERVER['HTTP_X_FORWARDED_FOR'];
3366 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
3367 // Yet, another proxy
3368 $address = $_SERVER['HTTP_CLIENT_IP'];
3370 // The regular address when no proxy was used
3371 $address = $_SERVER['REMOTE_ADDR'];
3374 // This strips out the real address from proxy output
3375 if (strstr($address, ",")){
3376 $addressArray = explode(",", $address);
3377 $address = $addressArray[0];
3380 // Return the result
3384 // "Getter" for remote IP number
3385 function detectRemoteAddr () {
3386 // Get remote ip from environment
3387 $remoteAddr = determineRealRemoteAddress();
3389 // Is removeip installed?
3390 if (EXT_IS_ACTIVE('removeip')) {
3391 // Then anonymize it
3392 $remoteAddr = GET_ANONYMOUS_REMOTE_ADDR($remoteAddr);
3399 // "Getter" for remote hostname
3400 function detectRemoteHostname () {
3401 // Get remote ip from environment
3402 $remoteHost = getenv('REMOTE_HOST');
3404 // Is removeip installed?
3405 if (EXT_IS_ACTIVE('removeip')) {
3406 // Then anonymize it
3407 $remoteHost = GET_ANONYMOUS_REMOTE_HOST($remoteHost);
3414 // "Getter" for user agent
3415 function detectUserAgent () {
3416 // Get remote ip from environment
3417 $userAgent = getenv('HTTP_USER_AGENT');
3419 // Is removeip installed?
3420 if (EXT_IS_ACTIVE('removeip')) {
3421 // Then anonymize it
3422 $userAgent = GET_ANONYMOUS_USER_AGENT($userAgent);
3429 // "Getter" for referer
3430 function detectReferer () {
3431 // Get remote ip from environment
3432 $referer = getenv('HTTP_REFERER');
3434 // Is removeip installed?
3435 if (EXT_IS_ACTIVE('removeip')) {
3436 // Then anonymize it
3437 $referer = GET_ANONYMOUS_REFERER($referer);
3444 // Adds a bonus mail to the queue
3445 // This is a high-level function!
3446 function addNewBonusMail ($data, $mode = '', $output=true) {
3447 // Use mode from data if not set and availble ;-)
3448 if ((empty($mode)) && (isset($data['mode']))) $mode = $data['mode'];
3450 // Generate receiver list
3451 $RECEIVER = generateReceiverList($data['cat'], $data['receiver'], $mode);
3454 if (!empty($RECEIVER)) {
3455 // Add bonus mail to queue
3456 addBonusMailToQueue(
3468 // Mail inserted into bonus pool
3469 if ($output) LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_BONUS_SEND'));
3470 } elseif ($output) {
3471 // More entered than can be reached!
3472 LOAD_TEMPLATE('admin_settings_saved', false, getMessage('ADMIN_MORE_SELECTED'));
3475 DEBUG_LOG(__FUNCTION__, __LINE__, " cat={$data['cat']},receiver={$data['receiver']},data=".base64_encode(serialize($data))." More selected, than available!");
3479 // Determines referal id and sets it
3480 function DETERMINE_REFID () {
3481 // Check if refid is set
3482 if ((!empty($_GET['user'])) && (basename($_SERVER['PHP_SELF']) == "click.php")) {
3483 // The variable user comes from the click-counter script click.php and we only accept this here
3484 $GLOBALS['refid'] = bigintval($_GET['user']);
3485 } elseif (!empty($_POST['refid'])) {
3486 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3487 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_POST['refid']));
3488 } elseif (!empty($_GET['refid'])) {
3489 // Get referal id from variable refid (so I hope this makes my script more compatible to other scripts)
3490 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['refid']));
3491 } elseif (!empty($_GET['ref'])) {
3492 // Set refid=ref (the referal link uses such variable)
3493 $GLOBALS['refid'] = SQL_ESCAPE(strip_tags($_GET['ref']));
3494 } elseif ((isSessionVariableSet('refid')) && (getSession('refid') != 0)) {
3495 // Set session refid als global
3496 $GLOBALS['refid'] = bigintval(getSession('refid'));
3497 } elseif ((GET_EXT_VERSION('sql_patches') != '') && (getConfig('def_refid') > 0)) {
3498 // Set default refid as refid in URL
3499 $GLOBALS['refid'] = getConfig(('def_refid'));
3500 } elseif ((GET_EXT_VERSION('user') >= '0.3.4') && (getConfig('select_user_zero_refid')) == 'Y') {
3501 // Select a random user which has confirmed enougth mails
3502 $GLOBALS['refid'] = SELECT_RANDOM_REFID();
3504 // No default ID when sql_patches is not installed or none set
3505 $GLOBALS['refid'] = 0;
3508 // Set cookie when default refid > 0
3509 if (!isSessionVariableSet('refid') || (!empty($GLOBALS['refid'])) || ((getSession('refid') == '0') && (getConfig('def_refid') > 0))) {
3511 setSession('refid', $GLOBALS['refid']);
3514 // Return determined refid
3515 return $GLOBALS['refid'];
3518 // Check wether we are installing
3519 function isInstalling () {
3520 $installing = ((isset($GLOBALS['mxchange_installing'])) || (REQUEST_ISSET_GET('installing')));
3521 //* DEBUG: */ var_dump($installing);
3525 // Check wether this script is installed
3526 function isInstalled () {
3527 return isBooleanConstantAndTrue('mxchange_installed');
3530 // Check wether an admin is registered
3531 function isAdminRegistered () {
3532 return isBooleanConstantAndTrue('admin_registered');
3535 // Enables the reset mode. Only call this function if you really want the
3537 function enableResetMode () {
3538 // Enable the reset mode
3539 $GLOBALS['reset_enabled'] = true;
3542 runFilterChain('reset_enabled');
3545 // Checks wether the reset mode is active
3546 function isResetModeEnabled () {
3547 // Now simply check it
3548 return ((isset($GLOBALS['reset_enabled'])) && ($GLOBALS['reset_enabled'] === true));
3551 // Checks wether the debug mode is enabled
3552 function isDebugModeEnabled () {
3554 return isBooleanConstantAndTrue('DEBUG_MODE');
3557 // Checks wether the cache instance is valid
3558 function isCacheInstanceValid () {
3559 return ((isset($GLOBALS['cache_instance'])) && (is_object($GLOBALS['cache_instance'])));
3562 // Our shutdown-function
3563 function shutdown () {
3564 // Call the filter chain 'shutdown'
3565 runFilterChain('shutdown', null, false);
3567 if (SQL_IS_LINK_UP()) {
3569 SQL_CLOSE(__FILE__, __LINE__);
3570 } elseif ((!isInstalling()) && (isInstalled())) {
3572 addFatalMessage(__FILE__, __LINE__, getMessage('NO_DB_LINK_SHUTDOWN'));
3575 // Stop executing here
3579 // Setter for userid
3580 function setUserId ($userid) {
3581 $GLOBALS['userid'] = bigintval($userid);
3584 // Getter for userid or returns zero
3585 function getUserId () {
3589 // Is the userid set?
3590 if (isUserIdSet()) {
3592 $userid = $GLOBALS['userid'];
3599 // Checks ether the userid is set
3600 function isUserIdSet () {
3601 return (isset($GLOBALS['userid']));
3604 // Checks wether the given FQFN is a directory and not .,.. or .svn
3605 function isDirectory ($FQFN) {
3606 // Generate baseName
3607 $baseName = basename($FQFN);
3610 $isDirectory = ((is_dir($FQFN)) && ($baseName != '.') && ($baseName != '..') && ($baseName != ".svn"));
3612 // Return the result
3613 return $isDirectory;
3616 // Handle message codes from URL
3617 function handleCodeMessage () {
3618 if (REQUEST_ISSET_GET(('msg'))) {
3619 // Default extension is "unknown"
3622 // Is extension given?
3623 if (REQUEST_ISSET_GET(('ext'))) $ext = REQUEST_GET(('ext'));
3625 // Convert the 'msg' parameter from URL to a human-readable message
3626 $msg = convertCodeToMessage(REQUEST_GET('msg'));
3628 // Load message template
3629 LOAD_TEMPLATE("message", false, $msg);
3633 //////////////////////////////////////////////////
3634 // AUTOMATICALLY RE-GENERATED MISSING FUNCTIONS //
3635 //////////////////////////////////////////////////
3637 if (!function_exists('html_entity_decode')) {
3638 // Taken from documentation on www.php.net
3639 function html_entity_decode ($string) {
3640 $trans_tbl = get_html_translation_table(HTML_ENTITIES);
3641 $trans_tbl = array_flip($trans_tbl);
3642 return strtr($string, $trans_tbl);