2 /************************************************************************
3 * Mailer v0.2.1-FINAL Start: 12/16/2008 *
4 * =================== Last change: 12/16/2008 *
6 * -------------------------------------------------------------------- *
8 * -------------------------------------------------------------------- *
9 * Short description : Generic filters *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Allgemeine Filter *
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 - 2009 by Roland Haeder *
21 * Copyright (c) 2009, 2010 by Mailer Developer Team *
22 * For more information visit: http://www.mxchange.org *
24 * This program is free software; you can redistribute it and/or modify *
25 * it under the terms of the GNU General Public License as published by *
26 * the Free Software Foundation; either version 2 of the License, or *
27 * (at your option) any later version. *
29 * This program is distributed in the hope that it will be useful, *
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
32 * GNU General Public License for more details. *
34 * You should have received a copy of the GNU General Public License *
35 * along with this program; if not, write to the Free Software *
36 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
38 ************************************************************************/
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
45 // Filter for flushing all new filters to the database
46 function FILTER_FLUSH_FILTERS () {
47 // Clear all previous SQL queries
51 if ((isInstallationPhase())) {
52 // Then silently skip this filter
56 // Is a database link here and not in installation mode?
57 if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
59 addFatalMessage(__FUNCTION__, __LINE__, '{--FILTER_FLUSH_FAILED_NO_DATABASE--}');
63 // Is the extension sql_patches updated?
64 if ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) {
65 // Abort silently here
69 // Nothing is added/remove by default
73 // Prepare SQL queries
74 $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES';
75 $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
77 // Write all filters to database
78 foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
79 // Walk through all filters
80 foreach ($filterArray as $filterFunction => $active) {
81 // Is this filter loaded?
82 //* DEBUG: */ debugOutput('FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
83 if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
84 // Add this filter (all filters are active by default)
85 //* DEBUG: */ debugOutput('ADD:'.$filterName.'/'.$filterFunction);
86 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
88 } elseif ($active == 'R') {
90 //* DEBUG: */ debugOutput('REMOVE:'.$filterName.'/'.$filterFunction);
91 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
97 // Something has been added?
99 // Finish SQL command and add it
100 addSql(substr($insertSQL, 0, -1));
103 // Something has been removed?
105 // Finish SQL command and add it
106 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
109 // Shall we update usage counters (ONLY FOR DEBUGGING!)
110 if (isFilterUsageUpdateEnabled()) {
111 // Update all counters
112 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
113 // Walk through all filters
114 foreach ($filterArray as $filterFunction => $cnt) {
115 // Construct and add the query
116 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
125 // Run the run_sqls filter in non-dry mode
126 runFilterChain('run_sqls');
128 // Should we rebuild cache?
129 if (($inserted > 0) || ($removed > 0)) {
131 rebuildCache('filter', 'filter');
135 // Filter for calling the handler for login failures
136 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
140 // Handle failed logins here if not in guest
141 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "type=".$data['type'].",action=".getAction().",what=".getWhat().",level=".$data['access_level']."<br />");
142 if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getIndexHome()))) && ($data['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.0')))) {
144 $content['content'] .= handleLoginFailures($data['access_level']);
147 // Return the content
151 // Filter for redirecting to logout if sql_patches has been installed
152 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
153 // Remove this filter
154 unregisterFilter(__FUNCTION__, __LINE__, 'shutdown', __FUNCTION__);
156 // Is the element set?
157 if (isset($GLOBALS['ext_load_mode'])) {
159 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
162 // This should not happen!
163 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
166 // Filter for auto-activation of a extension
167 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
169 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $data['ext_name'] . ',isExtensionAlwaysActive()=' . intval(isExtensionAlwaysActive()));
171 // Is this extension always activated?
172 if (isExtensionAlwaysActive()) {
173 // Then activate the extension
174 doActivateExtension($data['ext_name']);
181 // Filter for solving task given task
182 function FILTER_SOLVE_TASK ($data) {
183 // Don't solve anything if no admin!
184 if (!isAdmin()) return $data;
186 // Is this a direct task id or array element task_id is found?
189 adminSolveTask($data);
190 } elseif ((is_array($data)) && (isset($data['task_id']))) {
192 adminSolveTask($data['task_id']);
195 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
202 // Filter to load include files
203 function FILTER_LOAD_INCLUDES ($pool) {
205 if (is_null($pool)) {
206 // This should not happen!
207 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
210 // Is the pool an array and 'pool' set?
211 if ((is_array($pool)) && (isset($pool['pool']))) {
212 // Then use it as pool
213 $realPool = $pool['pool'];
215 // Default is $data as inclusion list
220 $data = getIncludePool($realPool);
223 if ((!isset($data)) || (!is_array($data))) {
225 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
226 } elseif (isset($data['inc_pool'])) {
227 // Use this as new inclusion pool!
228 setIncludePool($realPool, $data['inc_pool']);
231 // Check for added include files
232 if (countIncludePool($realPool) > 0) {
233 // Loads every include file
234 loadIncludePool($realPool);
237 initIncludePool($realPool);
240 // Continue with processing
244 // Filter for running SQL commands
245 function FILTER_RUN_SQLS ($data) {
247 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
249 // Is the array there?
250 if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
252 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
253 foreach (getSqls() as $mode=>$sqls) {
255 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
257 // New cache format...
258 foreach ($sqls as $sql) {
262 // Is 'enable_codes' not set? Then set it to true
263 if (!isset($data['enable_codes'])) $data['enable_codes'] = true;
265 // Is there still a query left?
267 // Do we have an "ALTER TABLE" command?
268 if (substr(strtolower($sql), 0, 11) == 'alter table') {
269 // Analyse the alteration command
270 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
271 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
273 // Run regular SQL command
274 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
275 SQL_QUERY($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
283 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
286 // Filter for updating/validating login data
287 function FILTER_UPDATE_LOGIN_DATA () {
289 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
291 // Recheck if logged in
292 if (!isMember()) return false;
295 setMemberId(getSession('userid'));
298 if (fetchUserData(getMemberId())) {
299 // Load last module and online time
300 $content = getUserDataArray();
302 // Maybe first login time?
303 if (empty($content['last_module'])) $content['last_module'] = 'login';
305 // This will be displayed on welcome page! :-)
306 if (empty($GLOBALS['last_online']['module'])) {
307 $GLOBALS['last_online']['module'] = $content['last_module'];
308 $GLOBALS['last_online']['online'] = $content['last_online'];
315 if (getIndexHome() != '') setWhatFromConfig('index_home');
318 // Update last module / online time
319 updateLastActivity(getMemberId());
321 // Destroy session, we cannot update!
322 destroyMemberSession();
326 // Filter for initializing randomizer
327 function FILTER_INIT_RANDOMIZER () {
328 // Only execute this filter if installed
329 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) return;
331 // Take a prime number which is long (if you know a longer one please try it out!)
332 setConfigEntry('_PRIME', 591623);
334 // Calculate "entropy" with the prime number (for code generation)
335 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getConfig('code_length') + 1)));
337 // Simply init the randomizer with seed and _ADD value
338 mt_srand(generateSeed() + getConfig('_ADD'));
341 // Filter for removing updates
342 function FILTER_REMOVE_UPDATES ($data) {
344 initExtensionRemovalList();
346 // Add the current extension to it
347 addCurrentExtensionToRemovalList();
350 unsetExtensionSqls();
352 // Do we need to remove update depency?
353 if (countExtensionUpdateDependencies() > 0) {
354 // Then find all updates we shall no longer execute
355 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
356 // Shall we remove this update?
357 if (in_array($ext_name, getExtensionRemovalList())) {
358 // Then remove this extension!
359 removeExtensionUpdateDependency($ext_name);
368 // Determines username for current user state
369 function FILTER_DETERMINE_USERNAME () {
370 // Check if logged in
372 // Is still logged in so we welcome him with his name
373 if (fetchUserData(getMemberId())) {
374 // Load surname and family's name and build the username
375 $content = getUserDataArray();
378 setUsername($content['surname'] . ' ' . $content['family']);
380 // Additionally admin?
383 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
386 // Hmmm, logged in and no valid userid?
387 setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
390 destroyMemberSession();
392 } elseif (isAdmin()) {
394 setUsername('{--USERNAME_ADMIN--}');
396 // He's a guest, hello there... ;-)
397 setUsername('{--USERNAME_GUEST--}');
401 // Filter for compiling config entries
402 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
403 // Save the uncompiled code
407 if (!isset($GLOBALS['compiled_config'][$code])) {
408 // Compile {?some_var?} to getConfig('some_var')
409 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
411 // Some entries found?
412 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
413 // Replace all matches
414 foreach ($matches[0] as $key => $match) {
416 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
417 // Is the config valid?
418 if (isConfigEntrySet($matches[1][$key])) {
419 // Set it for caching
420 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
421 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
423 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
424 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
425 // No config, try the language system
426 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
429 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
433 // Use this for replacing
434 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
435 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
440 $GLOBALS['compiled_config'][$uncompiled] = $code;
443 // Should we compile it?
444 if ($compiled === true) {
446 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
447 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
451 // Return compiled code
452 return $GLOBALS['compiled_config'][$uncompiled];
455 // Filter for compiling expression code
456 function FILTER_COMPILE_EXPRESSION_CODE ($code) {
457 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
458 // See switch() command below for supported commands
459 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
460 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
462 // Default is from outputHtml()
463 $outputMode = getScriptOutputMode();
465 // Some entries found?
466 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
467 // Replace all matches
468 foreach ($matches[2] as $key => $cmd) {
469 // Init replacer/call-back variable
473 $extraFunction2 = '';
476 // Extract command and call-back
477 $cmdArray = explode(',', $cmd);
480 // Detect call-back function
481 if (isset($cmdArray[1])) {
482 // Call-back function detected
483 $callback = $cmdArray[1];
486 // Detect extra function
487 if (isset($cmdArray[2])) {
489 $extraFunction = $cmdArray[2];
492 // Detect extra function 2
493 if (isset($cmdArray[3])) {
495 $extraFunction2 = $cmdArray[3];
499 if (isset($matches[4][$key])) {
501 $value = $matches[4][$key];
504 // Construct call-back function name for the command
505 $commandFunction = 'doExpression' . ucfirst(strtolower($cmd));
507 // Is this function there?
508 if (function_exists($commandFunction)) {
509 // Prepare $matches, $key, $outputMode, etc.
511 'matches' => $matches,
513 'mode' => $outputMode,
515 'callback' => $callback,
516 'extra_func' => $extraFunction,
517 'extra_func2' => $extraFunction2,
522 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
523 $code = call_user_func($commandFunction, $data);
525 // Unsupported command detected
526 debug_report_bug(__FUNCTION__, __LINE__, 'Command=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
531 // Do we have non-HTML mode?
532 if ((!isHtmlOutputMode()) || ($outputMode != '0')) $code = decodeEntities($code);
534 // Return compiled code
535 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($code).'</pre>');
539 // Runs some generic filter update steps
540 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
541 // Create task (we ignore the task id here)
542 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
544 // Update extension's version
545 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
546 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
550 unset($GLOBALS['update_ver'][$ext_name]);
553 // Load more reset scripts
554 function FILTER_RUN_RESET_INCLUDES () {
555 // Is the reset set or old sql_patches?
556 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
558 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
561 // Get more daily reset scripts
562 setIncludePool('reset', getArrayFromDirectory('inc/reset/', 'reset_'));
565 if ((!isConfigEntrySet('DEBUG_RESET')) || (getConfig('DEBUG_RESET') != 'Y')) updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
567 // Is the config entry set?
568 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
569 // Create current week mark
570 $currWeek = getWeek();
573 if ((getConfig('last_week') != $currWeek) || (isWeeklyResetDebugEnabled())) {
574 // Include weekly reset scripts
575 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
577 // Update config if not in debug mode
578 if (!isWeeklyResetDebugEnabled()) updateConfiguration('last_week', $currWeek);
581 // Create current month mark
582 $currMonth = getMonth();
585 if ((getConfig('last_month') != $currMonth) || (isMonthlyResetDebugEnabled())) {
586 // Include monthly reset scripts
587 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
590 if (!isMonthlyResetDebugEnabled()) updateConfiguration('last_month', $currMonth);
595 runFilterChain('load_includes', 'reset');
598 // Filter for removing the given extension
599 function FILTER_REMOVE_EXTENSION () {
600 // Delete this extension (remember to remove it from your server *before* you click on welcome!
601 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
602 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
604 // Remove the extension from cache array as well
605 removeExtensionFromArray();
608 rebuildCache('extension', 'extension');
611 // Filter for flushing the output
612 function FILTER_FLUSH_OUTPUT () {
617 // Prepares an SQL statement part for HTML mail and/or holiday depency
618 function FILTER_HTML_INCLUDE_USERS ($mode) {
619 // Exclude no users by default
623 if ($mode == 'html') $MORE = " AND `html`='Y'";
624 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
625 // Add something for the holiday extension
626 $MORE .= " AND `holiday_active`='N'";
633 // Filter for determining what/action/module
634 function FILTER_DETERMINE_WHAT_ACTION () {
635 // In installation phase we don't have what/action
636 if (isInstallationPhase()) {
646 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
648 if (!isModuleSet()) {
649 // Is the request element set?
650 if (isGetRequestParameterSet('module')) {
651 // Set module from request
652 setModule(getRequestParameter('module'));
653 } elseif (isHtmlOutputMode()) {
654 // Set default module 'index'
658 setModule('unknown');
662 // Fix 'what' if not yet set
664 setWhat(getWhatFromModule(getModule()));
667 // Fix 'action' if not yet set
668 if (!isActionSet()) {
669 setAction(getActionFromModuleWhat(getModule(), getWhat()));
672 // Set action/what to empty
677 // Set default 'what' value
678 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
679 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
680 if (getModule() == 'admin') {
681 // Set 'action' value to 'login' in admin menu
682 setAction(getActionFromModuleWhat(getModule(), getWhat()));
683 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
684 // Set 'what' value to 'welcome' in guest and member menu
685 setWhatFromConfig('index_home');
687 // Anything else like begging link
693 // Sends out pooled mails
694 function FILTER_TRIGGER_SENDING_POOL () {
695 // Are we in normal output mode?
696 if (!isHtmlOutputMode()) {
697 // Only in normal output mode to prevent race-conditons!
701 $GLOBALS['pool_cnt'] = '0';
703 // Init & set the include pool
704 initIncludePool('pool');
705 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
708 runFilterChain('load_includes', 'pool');
710 // Remove the counter
711 unset($GLOBALS['pool_cnt']);
714 // Filter for checking and updating SVN revision
715 function FILTER_CHECK_SVN_REVISION () {
716 // Only execute this filter if installed and all config entries are there
717 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
719 // Check for patch level differences between databases and current hard-coded
720 if ((getCurrSvnRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURR_SVN_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
721 // Update database and CONFIG array
722 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrSvnRevision(), 'UNIX_TIMESTAMP()'));
723 setConfigEntry('patch_level', getCurrSvnRevision());
724 setConfigEntry('patch_ctime', time());
728 // Filter for running daily reset
729 function FILTER_RUN_DAILY_RESET () {
730 // Only execute this filter if installed
731 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) return;
733 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
734 if (((getDay(getConfig('last_update')) != getDay()) || ((isConfigEntrySet('DEBUG_RESET')) && (getConfig('DEBUG_RESET') == 'Y'))) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
735 // Tell every module we are in reset-mode!
740 // Filter for loading more runtime includes (not for installation)
741 function FILTER_LOAD_RUNTIME_INCLUDES () {
742 // Load more includes
743 foreach (array('inc/databases.php','inc/session.php','inc/versions.php') as $inc) {
745 loadIncludeOnce($inc);
749 // Filter for checking admin ACL
750 function FILTER_CHECK_ADMIN_ACL () {
751 // Extension not installed so it's always allowed to access everywhere!
754 // Ok, Cookie-Update done
755 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
756 // Check if action GET variable was set
757 $action = getAction();
759 // Get action value by what-value
760 $action = getActionFromModuleWhat('admin', getWhat());
763 // Check for access control line of current menu entry
764 $ret = adminsCheckAdminAcl($action, getWhat());
768 $GLOBALS['acl_allow'] = $ret;
771 // Init random number/cache buster
772 function FILTER_INIT_RANDOM_NUMBER () {
773 // Is the extension sql_patches installed and at least 0.3.6?
774 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
775 // Generate random number
776 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
778 // Generate weak (!!!) code
779 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
782 // Copy it to CACHE_BUSTER
783 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
786 // Update module counter
787 function FILTER_COUNT_MODULE () {
788 // Do count all other modules but not accesses on CSS file css.php!
789 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
790 array(getModule()), __FUNCTION__, __LINE__);
793 // Handles fatal errors
794 function FILTER_HANDLE_FATAL_ERRORS () {
795 // Do we have errors to handle and right output mode?
796 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
797 // Abort executing here
802 setContentType('text/html');
805 loadIncludeOnce('inc/load_config.php');
807 // Set unset variable
808 if (empty($check)) $check = '';
813 // Installation phase or regular mode?
814 if ((isInstallationPhase())) {
815 // While we are installing ouput other header than while it is installed... :-)
817 foreach (getFatalArray() as $key => $value) {
818 // Prepare content for the template
825 $OUT .= loadTemplate('install_fatal_row', true, $content);
828 // Load main template
829 $content = loadTemplate('install_fatal_table', true, $OUT);
830 } elseif (isInstalled()) {
831 // Display all runtime fatal errors
833 foreach (getFatalArray() as $key => $value) {
834 // Prepare content for the template
841 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
844 // Load main template
845 $content = loadTemplate('runtime_fatal_table', true, $OUT);
848 // Message to regular users (non-admin)
849 $CORR = '{--FATAL_REPORT_ERRORS--}';
851 // PHP warnings fixed
852 if ($check == 'done') {
853 if (isAdmin()) $CORR = '{--FATAL_CORRECT_ERRORS--}';
856 // Remember all in array
863 loadIncludeOnce('inc/header.php');
865 // Load main template
866 loadTemplate('fatal_errors', false, $content);
868 // Delete all to prevent double-display
872 loadIncludeOnce('inc/footer.php');
878 // Filter for displaying copyright line
879 function FILTER_DISPLAY_COPYRIGHT () {
880 // Shall we display the copyright notice?
881 if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
883 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
884 // Copyright with backlink, thanks! :-)
885 $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
887 // No backlink in Copyright note
888 $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
893 // Filter for displaying parsing time
894 function FILTER_DISPLAY_PARSING_TIME () {
895 // Shall we display the parsing time and number of queries?
896 // 1234 5 54 4 5 5 4 4 5 543 3 4432 2 33 2 2 21
897 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
898 // Then display it here
899 displayParsingTime();
903 // Filter for flushing template cache
904 function FILTER_FLUSH_TEMPLATE_CACHE () {
905 // Do not flush when debugging the template cache
906 if (isDebuggingTemplateCache()) return;
908 // Do we have cached eval() data?
909 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
911 foreach ($GLOBALS['template_eval'] as $template => $eval) {
912 // Flush the cache (if not yet found)
913 flushTemplateCache($template, $eval);
918 // Filter for loading user data
919 function FILTER_FETCH_USER_DATA ($userid = 0) {
920 // Is the userid not set? Then use member id
921 if (($userid == '0') || (is_null($userid))) $userid = getMemberId();
924 if (!fetchUserData($userid)) {
925 // Userid is not valid
926 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
930 setMemberId($userid);
933 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
934 function FILTER_RESET_USER_LOGIN_FAILURE () {
935 // Is the user data valid?
937 // Do only run for logged in members
938 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
941 // Remmeber login failures if available
942 if (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
943 // Reset login failures
944 SQL_QUERY_ESC("UPDATE
945 `{?_MYSQL_PREFIX?}_user_data`
948 `last_failure`='0000-00-00 00:00:00'
952 array(getMemberId()), __FUNCTION__, __LINE__);
954 // Store it in session
955 setSession('mailer_member_failures' , getUserData('login_failures'));
956 setSession('mailer_member_last_failure', getUserData('last_failure'));
960 // Try to login the admin by setting some session/cookie variables
961 function FILTER_DO_LOGIN_ADMIN ($data) {
962 // Now set all session variables and store the result for later processing
963 $GLOBALS['admin_login_success'] = ((
964 setSession('admin_md5', encodeHashForCookie($data['pass_hash']))
966 setSession('admin_id', $data['id'])
968 setSession('admin_last', time())
971 // Return the data for further processing
975 // Filter for loading page header, this should be ran first!
976 function FILTER_LOAD_PAGE_HEADER () {
977 // Determine the page title
978 $content['header_title'] = determinePageTitle();
980 // Output page header code
981 $GLOBALS['page_header'] = loadTemplate('page_header', true, $content);
983 // Include meta data in 'guest' module
984 if (getModule() == 'index') {
985 // Load meta data template
986 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
988 // Add meta description to header
989 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
990 // Add meta description not in admin and login module and when the script is installed
991 generateMetaDescriptionCode();
996 // Filter for adding style sheet, closing page header
997 function FILTER_FINISH_PAGE_HEADER () {
998 // Include stylesheet
999 loadIncludeOnce('inc/stylesheet.php');
1002 $GLOBALS['page_header'] .= '</head>';
1005 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1006 function FILTER_CLEANUP_DNS_CACHE () {
1007 // Is the latest version installed?
1008 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1010 loadIncludeOnce('inc/classes/resolver.class.php');
1012 // Instance the resolver
1013 $resolver = new HostnameResolver();
1016 $resolver->purgeEntries();
1018 // Cute, isn't it? ;-)