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 * -------------------------------------------------------------------- *
18 * Copyright (c) 2003 - 2009 by Roland Haeder *
19 * Copyright (c) 2009 - 2011 by Mailer Developer Team *
20 * For more information visit: http://www.mxchange.org *
22 * This program is free software; you can redistribute it and/or modify *
23 * it under the terms of the GNU General Public License as published by *
24 * the Free Software Foundation; either version 2 of the License, or *
25 * (at your option) any later version. *
27 * This program is distributed in the hope that it will be useful, *
28 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
29 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
30 * GNU General Public License for more details. *
32 * You should have received a copy of the GNU General Public License *
33 * along with this program; if not, write to the Free Software *
34 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
36 ************************************************************************/
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
43 // Filter for flushing all new filters to the database
44 function FILTER_FLUSH_FILTERS () {
45 // Clear all previous SQL queries
49 if ((isInstallationPhase())) {
50 // Then silently skip this filter
54 // Is a database link here and not in installation mode?
55 if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
57 addFatalMessage(__FUNCTION__, __LINE__, '{--FILTER_FLUSH_FAILED_NO_DATABASE--}');
61 // Is the extension sql_patches updated?
62 if ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) {
63 // Abort silently here
64 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot flush filters, sql_patches might be missing. isExtensionInstalled()=' . isExtensionInstalled('sql_patches') . ',isExtensionInstalledAndOlder()=' . isExtensionInstalledAndOlder('sql_patches', '0.5.9'));
68 // Nothing is added/remove by default
72 // Prepare SQL queries
73 $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES';
74 $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
76 // Write all filters to database
77 foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
78 // Walk through all filters
79 foreach ($filterArray as $filterFunction => $active) {
80 // Is this filter loaded?
81 //* DEBUG: */ debugOutput('FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
82 if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
83 // Add this filter (all filters are active by default)
84 //* DEBUG: */ debugOutput('ADD:'.$filterName.'/'.$filterFunction);
85 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
87 } elseif ($active == 'R') {
89 //* DEBUG: */ debugOutput('REMOVE:'.$filterName.'/'.$filterFunction);
90 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
96 // Something has been added?
98 // Finish SQL command and add it
99 addSql(substr($insertSQL, 0, -1));
102 // Something has been removed?
104 // Finish SQL command and add it
105 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
108 // Shall we update usage counters (ONLY FOR DEBUGGING!)
109 if (isFilterUsageUpdateEnabled()) {
110 // Update all counters
111 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
112 // Walk through all filters
113 foreach ($filterArray as $filterFunction => $count) {
114 // Construct and add the query
115 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
124 // Run the run_sqls filter in non-dry mode
125 runFilterChain('run_sqls');
127 // Should we rebuild cache?
128 if (($inserted > 0) || ($removed > 0)) {
130 rebuildCache('filter', 'filter');
134 // Filter for calling the handler for login failures
135 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
139 // Handle failed logins here if not in guest
140 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "type=".$data['type'].",action=".getAction().",what=".getWhat().",level=".$data['access_level']."<br />");
141 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.6')))) {
143 $content['content'] .= handleLoginFailures($data['access_level']);
146 // Return the content
150 // Filter for redirecting to logout if sql_patches has been installed
151 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
152 // Remove this filter
153 unregisterFilter(__FUNCTION__, __LINE__, 'shutdown', __FUNCTION__);
155 // Is the element set?
156 if (isset($GLOBALS['ext_load_mode'])) {
158 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
161 // This should not happen!
162 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
165 // Filter for auto-activation of a extension
166 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
168 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $data['ext_name'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
170 // Is this extension always activated?
171 if (isThisExtensionAlwaysActive()) {
172 // Then activate the extension
173 doActivateExtension($data['ext_name']);
180 // Filter for solving task given task
181 function FILTER_SOLVE_TASK ($data) {
182 // Don't solve anything if no admin!
183 if (!isAdmin()) return $data;
185 // Is this a direct task id or array element task_id is found?
188 adminSolveTask($data);
189 } elseif ((is_array($data)) && (isset($data['task_id']))) {
191 adminSolveTask($data['task_id']);
194 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
201 // Filter to load include files
202 function FILTER_LOAD_INCLUDES ($pool) {
204 if (is_null($pool)) {
205 // This should not happen!
206 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
209 // Is the pool an array and 'pool' set?
210 if ((is_array($pool)) && (isset($pool['pool']))) {
211 // Then use it as pool
212 $realPool = $pool['pool'];
214 // Default is $data as inclusion list
219 $data = getIncludePool($realPool);
222 if ((!isset($data)) || (!is_array($data))) {
224 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
225 } elseif (isset($data['inc_pool'])) {
226 // Use this as new inclusion pool!
227 setIncludePool($realPool, $data['inc_pool']);
230 // Check for added include files
231 if (countIncludePool($realPool) > 0) {
232 // Loads every include file
233 loadIncludePool($realPool);
236 initIncludePool($realPool);
239 // Continue with processing
243 // Filter for running SQL commands
244 function FILTER_RUN_SQLS ($data) {
246 //* DEBUG: */ die('getSqls()=<pre>'.print_r(getSqls(), true).'</pre>ext_update_depends=<pre>'.print_r($GLOBALS['ext_update_depends'], true).'</pre>');
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'])) {
264 $data['enable_codes'] = true;
267 // Is there still a query left?
269 // Do we have an "ALTER TABLE" command?
270 if (substr(strtolower($sql), 0, 11) == 'alter table') {
271 // Analyse the alteration command
272 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
273 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
275 // Run regular SQL command
276 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
277 SQL_QUERY($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
285 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
288 // Filter for updating/validating login data
289 function FILTER_UPDATE_LOGIN_DATA () {
291 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
292 $GLOBALS['last_online'] = array();
295 // Recheck if logged in
301 setMemberId(getSession('userid'));
304 if (fetchUserData(getMemberId())) {
305 // Load last module and online time
306 $content = getUserDataArray();
308 // Maybe first login time?
309 if (empty($content['last_module'])) {
310 $content['last_module'] = 'login';
313 // This will be displayed on welcome page! :-)
314 if (empty($GLOBALS['last_online']['module'])) {
315 $GLOBALS['last_online']['module'] = $content['last_module'];
316 $GLOBALS['last_online']['online'] = $content['last_online'];
323 if (getIndexHome() != '') {
324 setWhatFromConfig('index_home');
328 // Update last module / online time
329 updateLastActivity(getMemberId());
331 // Destroy session, we cannot update!
332 destroyMemberSession();
336 // Filter for initializing randomizer
337 function FILTER_INIT_RANDOMIZER () {
338 // Only execute this filter if installed
339 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
343 // Take a prime number which is long (if you know a longer one please try it out!)
344 setConfigEntry('_PRIME', 591623);
346 // Calculate "entropy" with the prime number (for code generation)
347 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
349 // Simply init the randomizer with seed and _ADD value
350 mt_srand(generateSeed() + getConfig('_ADD'));
353 // Filter for removing updates
354 function FILTER_REMOVE_UPDATES ($data) {
356 initExtensionRemovalList();
358 // Add the current extension to it
359 addCurrentExtensionToRemovalList();
362 unsetExtensionSqls();
364 // Do we need to remove update depency?
365 if (countExtensionUpdateDependencies() > 0) {
366 // Then find all updates we shall no longer execute
367 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
368 // Shall we remove this update?
369 if (in_array($ext_name, getExtensionRemovalList())) {
370 // Then remove this extension!
371 removeExtensionDependency($ext_name);
380 // Determines username for current user state
381 function FILTER_DETERMINE_USERNAME () {
382 // Check if logged in
384 // Is still logged in so we welcome him with his name
385 if (fetchUserData(getMemberId())) {
386 // Load surname and family's name and build the username
387 $content = getUserDataArray();
390 setUsername($content['surname'] . ' ' . $content['family']);
392 // Additionally admin?
395 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
398 // Hmmm, logged in and no valid userid?
399 setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
402 destroyMemberSession();
404 } elseif (isAdmin()) {
406 setUsername('{--USERNAME_ADMIN--}');
408 // He's a guest, hello there... ;-)
409 setUsername('{--USERNAME_GUEST--}');
413 // Filter for compiling config entries
414 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
415 // Save the uncompiled code
419 if (!isset($GLOBALS['compiled_config'][$code])) {
420 // Compile {?some_var?} to getConfig('some_var')
421 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
423 // Some entries found?
424 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
425 // Replace all matches
426 foreach ($matches[0] as $key => $match) {
428 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
429 // Is the config valid?
430 if (isConfigEntrySet($matches[1][$key])) {
431 // Set it for caching
432 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
433 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
435 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
436 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
437 // No config, try the language system
438 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
441 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
445 // Use this for replacing
446 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
447 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
452 $GLOBALS['compiled_config'][$uncompiled] = $code;
455 // Should we compile it?
456 if ($compiled === true) {
458 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
459 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
463 // Return compiled code
464 return $GLOBALS['compiled_config'][$uncompiled];
467 // Filter for compiling expression code
468 function FILTER_COMPILE_EXPRESSION_CODE ($code) {
469 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
470 // See switch() command below for supported commands
471 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
472 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
474 // Default is from outputHtml()
475 $outputMode = getScriptOutputMode();
477 // Some entries found?
478 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
479 // Replace all matches
480 foreach ($matches[2] as $key => $cmd) {
481 // Init replacer/call-back variable
485 $extraFunction2 = '';
488 // Extract command and call-back
489 $cmdArray = explode(',', $cmd);
492 // Detect call-back function
493 if (isset($cmdArray[1])) {
494 // Call-back function detected
495 $callback = $cmdArray[1];
498 // Detect extra function
499 if (isset($cmdArray[2])) {
501 $extraFunction = $cmdArray[2];
504 // Detect extra function 2
505 if (isset($cmdArray[3])) {
507 $extraFunction2 = $cmdArray[3];
511 if (isset($matches[4][$key])) {
513 $value = $matches[4][$key];
516 // Construct call-back function name for the command
517 $commandFunction = 'doExpression' . capitalizeUnderscoreString($cmd);
519 // Is this function there?
520 if (function_exists($commandFunction)) {
521 // Prepare $matches, $key, $outputMode, etc.
523 'matches' => $matches,
525 'mode' => getScriptOutputMode(),
527 'callback' => $callback,
528 'extra_func' => $extraFunction,
529 'extra_func2' => $extraFunction2,
534 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
535 $code = call_user_func($commandFunction, $data);
537 // Unsupported command detected
538 logDebugMessage(__FUNCTION__, __LINE__, 'Command cmd=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
543 // Do we have non-HTML mode?
544 if (!isHtmlOutputMode()) {
545 $code = decodeEntities($code);
548 // Return compiled code
549 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($code).'</pre>');
553 // Runs some generic filter update steps
554 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
555 // Create task (we ignore the task id here)
556 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
558 // Update extension's version
559 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
560 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
564 unset($GLOBALS['update_ver'][$ext_name]);
567 // Load more hourly reset scripts
568 function FILTER_RUN_HOURLY_INCLUDES () {
569 // Is the reset set or old sql_patches?
570 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
572 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isHourlyResetEnabled()).',ext_newer[sql_patches:0.7.5]='.intval(isExtensionInstalledAndNewer('sql_patches', '0.7.5')).' Please report this bug. Thanks');
575 // Get more hourly reset scripts
576 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
579 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
580 updateConfiguration('last_hour', getHour());
584 runFilterChain('load_includes', 'hourly');
587 // Load more reset scripts
588 function FILTER_RUN_RESET_INCLUDES () {
589 // Is the reset set or old sql_patches?
590 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
592 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
595 // Get more daily reset scripts
596 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
599 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
600 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
603 // Is the config entry set?
604 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
606 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
607 // Include weekly reset scripts
608 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
610 // Update config if not in debug mode
611 if (!isWeeklyResetDebugEnabled()) {
612 updateConfiguration('last_week', getWeek());
616 // Create current month mark
617 $currMonth = getMonth();
620 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
621 // Include monthly reset scripts
622 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
625 if (!isMonthlyResetDebugEnabled()) {
626 updateConfiguration('last_month', $currMonth);
632 runFilterChain('load_includes', 'reset');
635 // Filter for removing the given extension
636 function FILTER_REMOVE_EXTENSION () {
637 // Delete this extension (remember to remove it from your server *before* you click on welcome!
638 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
639 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
641 // Remove the extension from cache array as well
642 removeExtensionFromArray();
645 rebuildCache('extension', 'extension');
648 // Filter for flushing the output
649 function FILTER_FLUSH_OUTPUT () {
654 // Prepares an SQL statement part for HTML mail and/or holiday depency
655 function FILTER_HTML_INCLUDE_USERS ($mode) {
656 // Exclude no users by default
660 if ($mode == 'html') $MORE = " AND `html`='Y'";
661 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
662 // Add something for the holiday extension
663 $MORE .= " AND `holiday_active`='N'";
670 // Filter for determining what/action/module
671 function FILTER_DETERMINE_WHAT_ACTION () {
672 // In installation phase we don't have what/action
673 if (isInstallationPhase()) {
683 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
685 if (!isModuleSet()) {
686 // Is the request element set?
687 if (isGetRequestParameterSet('module')) {
688 // Set module from request
689 setModule(getRequestParameter('module'));
690 } elseif (isHtmlOutputMode()) {
691 // Set default module 'index'
695 setModule('unknown');
699 // Fix 'what' if not yet set
701 setWhat(getWhatFromModule(getModule()));
704 // Fix 'action' if not yet set
705 if (!isActionSet()) {
706 setAction(getActionFromModuleWhat(getModule(), getWhat()));
709 // Set action/what to empty
714 // Set default 'what' value
715 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
716 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
717 if (getModule() == 'admin') {
718 // Set 'action' value to 'login' in admin menu
719 setAction(getActionFromModuleWhat(getModule(), getWhat()));
720 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
721 // Set 'what' value to 'welcome' in guest and member menu
722 setWhatFromConfig('index_home');
724 // Anything else like begging link
730 // Sends out pooled mails
731 function FILTER_TRIGGER_SENDING_POOL () {
732 // Are we in normal output mode?
733 if (!isHtmlOutputMode()) {
734 // Only in normal output mode to prevent race-conditons!
738 $GLOBALS['pool_cnt'] = '0';
740 // Init & set the include pool
741 initIncludePool('pool');
742 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
745 runFilterChain('load_includes', 'pool');
747 // Remove the counter
748 unset($GLOBALS['pool_cnt']);
751 // Filter for checking and updating SVN revision
752 function FILTER_CHECK_REPOSITORY_REVISION () {
753 // Only execute this filter if installed and all config entries are there
754 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
756 // Check for patch level differences between database and current hard-coded
757 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
758 // Update database and CONFIG array
759 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
760 setConfigEntry('patch_level', getCurrentRepositoryRevision());
761 setConfigEntry('patch_ctime', time());
765 // Filter for running daily reset
766 function FILTER_RUN_DAILY_RESET () {
767 // Only execute this filter if installed
768 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
772 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
773 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
774 // Tell every module we are in reset-mode!
779 // Filter for running hourly reset
780 function FILTER_RUN_HOURLY_RESET () {
781 // Only execute this filter if installed
782 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
786 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
787 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
788 // Tell every module we are in reset-mode!
793 // Filter for loading more runtime includes (not for installation)
794 function FILTER_LOAD_RUNTIME_INCLUDES () {
795 // Load more includes
796 foreach (array('databases', 'session', 'versions') as $inc) {
798 loadIncludeOnce('inc/' . $inc . '.php');
802 // Filter for checking admin ACL
803 function FILTER_CHECK_ADMIN_ACL () {
804 // Extension not installed so it's always allowed to access everywhere!
807 // Ok, Cookie-Update done
808 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
809 // Check if action GET variable was set
810 $action = getAction();
812 // Get action value by what-value
813 $action = getActionFromModuleWhat('admin', getWhat());
816 // Check for access control line of current menu entry
817 $ret = isAdminsAllowedByAcl($action, getWhat());
821 $GLOBALS['acl_allow'] = $ret;
824 // Init random number/cache buster
825 function FILTER_INIT_RANDOM_NUMBER () {
826 // Is the extension sql_patches installed and at least 0.3.6?
827 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
828 // Generate random number
829 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
831 // Generate *WEAK* code
832 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
835 // Copy it to CACHE_BUSTER
836 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
839 // Update module counter
840 function FILTER_COUNT_MODULE () {
841 // Do count all other modules but not accesses on CSS file css.php!
842 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
843 array(getModule()), __FUNCTION__, __LINE__);
846 // Handles fatal errors
847 function FILTER_HANDLE_FATAL_ERRORS () {
848 // Do we have errors to handle and right output mode?
849 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
850 // Abort executing here
855 setContentType('text/html');
858 loadIncludeOnce('inc/load_config.php');
860 // Set unset variable
861 if (empty($check)) $check = '';
866 // Installation phase or regular mode?
867 if ((isInstallationPhase())) {
868 // While we are installing ouput other header than while it is installed... :-)
870 foreach (getFatalArray() as $key => $value) {
871 // Prepare content for the template
878 $OUT .= loadTemplate('install_fatal_row', true, $content);
881 // Load main template
882 $content = loadTemplate('install_fatal_table', true, $OUT);
883 } elseif (isInstalled()) {
884 // Display all runtime fatal errors
886 foreach (getFatalArray() as $key => $value) {
887 // Prepare content for the template
894 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
897 // Load main template
898 $content = loadTemplate('runtime_fatal_table', true, $OUT);
901 // Message to regular users (non-admin)
902 $CORR = '{--FATAL_REPORT_ERRORS--}';
904 // PHP warnings fixed
905 if ($check == 'done') {
906 if (isAdmin()) $CORR = '{--FATAL_CORRECT_ERRORS--}';
909 // Remember all in array
916 loadIncludeOnce('inc/header.php');
918 // Load main template
919 loadTemplate('fatal_errors', false, $content);
921 // Delete all to prevent double-display
925 loadIncludeOnce('inc/footer.php');
931 // Filter for displaying copyright line
932 function FILTER_DISPLAY_COPYRIGHT () {
933 // Shall we display the copyright notice?
934 if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
936 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
937 // Copyright with backlink, thanks! :-)
938 $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
940 // No backlink in Copyright note
941 $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
946 // Filter for displaying parsing time
947 function FILTER_DISPLAY_PARSING_TIME () {
948 // Shall we display the parsing time and number of queries?
949 // 1234 5 54 4 5 5 4 4 5 543 3 4432 2 33 2 2 21
950 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
951 // Then display it here
952 displayParsingTime();
956 // Filter for flushing template cache
957 function FILTER_FLUSH_TEMPLATE_CACHE () {
958 // Do not flush when debugging the template cache
959 if (isDebuggingTemplateCache()) return;
961 // Do we have cached eval() data?
962 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
964 foreach ($GLOBALS['template_eval'] as $template => $eval) {
965 // Flush the cache (if not yet found)
966 flushTemplateCache($template, $eval);
971 // Filter for loading user data
972 function FILTER_FETCH_USER_DATA ($userid = 0) {
973 // Is the userid not set? Then use member id
974 if (($userid == '0') || (is_null($userid))) $userid = getMemberId();
977 if (!fetchUserData($userid)) {
978 // Userid is not valid
979 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
983 setMemberId($userid);
986 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
987 function FILTER_RESET_USER_LOGIN_FAILURE () {
988 // Is the user data valid?
990 // Do only run for logged in members
991 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
994 // Remmeber login failures if available
995 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
996 // Reset login failures
997 SQL_QUERY_ESC("UPDATE
998 `{?_MYSQL_PREFIX?}_user_data`
1005 array(getMemberId()), __FUNCTION__, __LINE__);
1007 // Store it in session
1008 setSession('mailer_member_failures' , getUserData('login_failures'));
1009 setSession('mailer_member_last_failure', getUserData('last_failure'));
1013 // Try to login the admin by setting some session/cookie variables
1014 function FILTER_DO_LOGIN_ADMIN ($data) {
1015 // Now set all session variables and store the result for later processing
1016 $GLOBALS['admin_login_success'] = ((
1017 setAdminMd5(encodeHashForCookie($data['pass_hash']))
1019 setAdminId($data['id'])
1021 setAdminLast(time())
1024 // Return the data for further processing
1028 // Filter for loading page header, this should be ran first!
1029 function FILTER_LOAD_PAGE_HEADER () {
1030 // Output page header code
1031 $GLOBALS['page_header'] = loadTemplate('page_header', true);
1033 // Include meta data in 'guest' module
1034 if (getModule() == 'index') {
1035 // Load meta data template
1036 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
1038 // Add meta description to header
1039 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1040 // Add meta description not in admin and login module and when the script is installed
1041 generateMetaDescriptionCode();
1046 // Filter for adding style sheet, closing page header
1047 function FILTER_FINISH_PAGE_HEADER () {
1048 // Include stylesheet
1049 loadIncludeOnce('inc/stylesheet.php');
1052 $GLOBALS['page_header'] .= '</head>';
1055 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1056 function FILTER_CLEANUP_DNS_CACHE () {
1057 // Is the latest version installed?
1058 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1060 loadIncludeOnce('inc/classes/resolver.class.php');
1062 // Instance the resolver
1063 $resolver = new HostnameResolver();
1066 $resolver->purgeEntries();
1068 // Cute, isn't it? ;-)
1072 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1073 function FILTER_SET_CURRENT_DATE () {
1075 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1077 // Epoche time for yesterday, today ... all at 00:00 am
1078 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1079 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1082 // Filter for marking extension as installed
1083 function FILTER_EXTENSION_MARK_INSTALLED ($data) {
1084 // Mark it as installed
1085 $GLOBALS['ext_is_installed'][$data['ext_name']] = true;