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
67 // Nothing is added/remove by default
71 // Prepare SQL queries
72 $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES';
73 $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
75 // Write all filters to database
76 foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
77 // Walk through all filters
78 foreach ($filterArray as $filterFunction => $active) {
79 // Is this filter loaded?
80 //* DEBUG: */ debugOutput('FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
81 if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
82 // Add this filter (all filters are active by default)
83 //* DEBUG: */ debugOutput('ADD:'.$filterName.'/'.$filterFunction);
84 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
86 } elseif ($active == 'R') {
88 //* DEBUG: */ debugOutput('REMOVE:'.$filterName.'/'.$filterFunction);
89 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
95 // Something has been added?
97 // Finish SQL command and add it
98 addSql(substr($insertSQL, 0, -1));
101 // Something has been removed?
103 // Finish SQL command and add it
104 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
107 // Shall we update usage counters (ONLY FOR DEBUGGING!)
108 if (isFilterUsageUpdateEnabled()) {
109 // Update all counters
110 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
111 // Walk through all filters
112 foreach ($filterArray as $filterFunction => $count) {
113 // Construct and add the query
114 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
123 // Run the run_sqls filter in non-dry mode
124 runFilterChain('run_sqls');
126 // Should we rebuild cache?
127 if (($inserted > 0) || ($removed > 0)) {
129 rebuildCache('filter', 'filter');
133 // Filter for calling the handler for login failures
134 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
138 // Handle failed logins here if not in guest
139 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "type=".$data['type'].",action=".getAction().",what=".getWhat().",level=".$data['access_level']."<br />");
140 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')))) {
142 $content['content'] .= handleLoginFailures($data['access_level']);
145 // Return the content
149 // Filter for redirecting to logout if sql_patches has been installed
150 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
151 // Remove this filter
152 unregisterFilter(__FUNCTION__, __LINE__, 'shutdown', __FUNCTION__);
154 // Is the element set?
155 if (isset($GLOBALS['ext_load_mode'])) {
157 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
160 // This should not happen!
161 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
164 // Filter for auto-activation of a extension
165 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
167 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $data['ext_name'] . ',isExtensionAlwaysActive()=' . intval(isExtensionAlwaysActive()));
169 // Is this extension always activated?
170 if (isExtensionAlwaysActive()) {
171 // Then activate the extension
172 doActivateExtension($data['ext_name']);
179 // Filter for solving task given task
180 function FILTER_SOLVE_TASK ($data) {
181 // Don't solve anything if no admin!
182 if (!isAdmin()) return $data;
184 // Is this a direct task id or array element task_id is found?
187 adminSolveTask($data);
188 } elseif ((is_array($data)) && (isset($data['task_id']))) {
190 adminSolveTask($data['task_id']);
193 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
200 // Filter to load include files
201 function FILTER_LOAD_INCLUDES ($pool) {
203 if (is_null($pool)) {
204 // This should not happen!
205 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
208 // Is the pool an array and 'pool' set?
209 if ((is_array($pool)) && (isset($pool['pool']))) {
210 // Then use it as pool
211 $realPool = $pool['pool'];
213 // Default is $data as inclusion list
218 $data = getIncludePool($realPool);
221 if ((!isset($data)) || (!is_array($data))) {
223 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
224 } elseif (isset($data['inc_pool'])) {
225 // Use this as new inclusion pool!
226 setIncludePool($realPool, $data['inc_pool']);
229 // Check for added include files
230 if (countIncludePool($realPool) > 0) {
231 // Loads every include file
232 loadIncludePool($realPool);
235 initIncludePool($realPool);
238 // Continue with processing
242 // Filter for running SQL commands
243 function FILTER_RUN_SQLS ($data) {
245 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
247 // Is the array there?
248 if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
250 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
251 foreach (getSqls() as $mode=>$sqls) {
253 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
255 // New cache format...
256 foreach ($sqls as $sql) {
260 // Is 'enable_codes' not set? Then set it to true
261 if (!isset($data['enable_codes'])) {
262 $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']))) {
290 $GLOBALS['last_online'] = array();
293 // Recheck if logged in
299 setMemberId(getSession('userid'));
302 if (fetchUserData(getMemberId())) {
303 // Load last module and online time
304 $content = getUserDataArray();
306 // Maybe first login time?
307 if (empty($content['last_module'])) $content['last_module'] = 'login';
309 // This will be displayed on welcome page! :-)
310 if (empty($GLOBALS['last_online']['module'])) {
311 $GLOBALS['last_online']['module'] = $content['last_module'];
312 $GLOBALS['last_online']['online'] = $content['last_online'];
319 if (getIndexHome() != '') setWhatFromConfig('index_home');
322 // Update last module / online time
323 updateLastActivity(getMemberId());
325 // Destroy session, we cannot update!
326 destroyMemberSession();
330 // Filter for initializing randomizer
331 function FILTER_INIT_RANDOMIZER () {
332 // Only execute this filter if installed
333 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
337 // Take a prime number which is long (if you know a longer one please try it out!)
338 setConfigEntry('_PRIME', 591623);
340 // Calculate "entropy" with the prime number (for code generation)
341 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
343 // Simply init the randomizer with seed and _ADD value
344 mt_srand(generateSeed() + getConfig('_ADD'));
347 // Filter for removing updates
348 function FILTER_REMOVE_UPDATES ($data) {
350 initExtensionRemovalList();
352 // Add the current extension to it
353 addCurrentExtensionToRemovalList();
356 unsetExtensionSqls();
358 // Do we need to remove update depency?
359 if (countExtensionUpdateDependencies() > 0) {
360 // Then find all updates we shall no longer execute
361 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
362 // Shall we remove this update?
363 if (in_array($ext_name, getExtensionRemovalList())) {
364 // Then remove this extension!
365 removeExtensionDependency($ext_name);
374 // Determines username for current user state
375 function FILTER_DETERMINE_USERNAME () {
376 // Check if logged in
378 // Is still logged in so we welcome him with his name
379 if (fetchUserData(getMemberId())) {
380 // Load surname and family's name and build the username
381 $content = getUserDataArray();
384 setUsername($content['surname'] . ' ' . $content['family']);
386 // Additionally admin?
389 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
392 // Hmmm, logged in and no valid userid?
393 setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
396 destroyMemberSession();
398 } elseif (isAdmin()) {
400 setUsername('{--USERNAME_ADMIN--}');
402 // He's a guest, hello there... ;-)
403 setUsername('{--USERNAME_GUEST--}');
407 // Filter for compiling config entries
408 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
409 // Save the uncompiled code
413 if (!isset($GLOBALS['compiled_config'][$code])) {
414 // Compile {?some_var?} to getConfig('some_var')
415 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
417 // Some entries found?
418 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
419 // Replace all matches
420 foreach ($matches[0] as $key => $match) {
422 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
423 // Is the config valid?
424 if (isConfigEntrySet($matches[1][$key])) {
425 // Set it for caching
426 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
427 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
429 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
430 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
431 // No config, try the language system
432 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
435 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
439 // Use this for replacing
440 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
441 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
446 $GLOBALS['compiled_config'][$uncompiled] = $code;
449 // Should we compile it?
450 if ($compiled === true) {
452 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
453 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
457 // Return compiled code
458 return $GLOBALS['compiled_config'][$uncompiled];
461 // Filter for compiling expression code
462 function FILTER_COMPILE_EXPRESSION_CODE ($code) {
463 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
464 // See switch() command below for supported commands
465 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
466 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
468 // Default is from outputHtml()
469 $outputMode = getScriptOutputMode();
471 // Some entries found?
472 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
473 // Replace all matches
474 foreach ($matches[2] as $key => $cmd) {
475 // Init replacer/call-back variable
479 $extraFunction2 = '';
482 // Extract command and call-back
483 $cmdArray = explode(',', $cmd);
486 // Detect call-back function
487 if (isset($cmdArray[1])) {
488 // Call-back function detected
489 $callback = $cmdArray[1];
492 // Detect extra function
493 if (isset($cmdArray[2])) {
495 $extraFunction = $cmdArray[2];
498 // Detect extra function 2
499 if (isset($cmdArray[3])) {
501 $extraFunction2 = $cmdArray[3];
505 if (isset($matches[4][$key])) {
507 $value = $matches[4][$key];
510 // Construct call-back function name for the command
511 $commandFunction = 'doExpression' . capitalizeUnderscoreString($cmd);
513 // Is this function there?
514 if (function_exists($commandFunction)) {
515 // Prepare $matches, $key, $outputMode, etc.
517 'matches' => $matches,
519 'mode' => getScriptOutputMode(),
521 'callback' => $callback,
522 'extra_func' => $extraFunction,
523 'extra_func2' => $extraFunction2,
528 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
529 $code = call_user_func($commandFunction, $data);
531 // Unsupported command detected
532 logDebugMessage(__FUNCTION__, __LINE__, 'Command cmd=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
537 // Do we have non-HTML mode?
538 if (!isHtmlOutputMode()) {
539 $code = decodeEntities($code);
542 // Return compiled code
543 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($code).'</pre>');
547 // Runs some generic filter update steps
548 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
549 // Create task (we ignore the task id here)
550 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
552 // Update extension's version
553 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
554 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
558 unset($GLOBALS['update_ver'][$ext_name]);
561 // Load more hourly reset scripts
562 function FILTER_RUN_HOURLY_INCLUDES () {
563 // Is the reset set or old sql_patches?
564 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
566 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');
569 // Get more hourly reset scripts
570 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
573 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
574 updateConfiguration('last_hour', getHour());
578 runFilterChain('load_includes', 'hourly');
581 // Load more reset scripts
582 function FILTER_RUN_RESET_INCLUDES () {
583 // Is the reset set or old sql_patches?
584 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
586 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
589 // Get more daily reset scripts
590 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
593 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
594 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
597 // Is the config entry set?
598 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
599 // Create current week mark
600 $currWeek = getWeek();
603 if ((getConfig('last_week') != $currWeek) || (isWeeklyResetDebugEnabled())) {
604 // Include weekly reset scripts
605 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
607 // Update config if not in debug mode
608 if (!isWeeklyResetDebugEnabled()) updateConfiguration('last_week', $currWeek);
611 // Create current month mark
612 $currMonth = getMonth();
615 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
616 // Include monthly reset scripts
617 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
620 if (!isMonthlyResetDebugEnabled()) updateConfiguration('last_month', $currMonth);
625 runFilterChain('load_includes', 'reset');
628 // Filter for removing the given extension
629 function FILTER_REMOVE_EXTENSION () {
630 // Delete this extension (remember to remove it from your server *before* you click on welcome!
631 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
632 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
634 // Remove the extension from cache array as well
635 removeExtensionFromArray();
638 rebuildCache('extension', 'extension');
641 // Filter for flushing the output
642 function FILTER_FLUSH_OUTPUT () {
647 // Prepares an SQL statement part for HTML mail and/or holiday depency
648 function FILTER_HTML_INCLUDE_USERS ($mode) {
649 // Exclude no users by default
653 if ($mode == 'html') $MORE = " AND `html`='Y'";
654 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
655 // Add something for the holiday extension
656 $MORE .= " AND `holiday_active`='N'";
663 // Filter for determining what/action/module
664 function FILTER_DETERMINE_WHAT_ACTION () {
665 // In installation phase we don't have what/action
666 if (isInstallationPhase()) {
676 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
678 if (!isModuleSet()) {
679 // Is the request element set?
680 if (isGetRequestParameterSet('module')) {
681 // Set module from request
682 setModule(getRequestParameter('module'));
683 } elseif (isHtmlOutputMode()) {
684 // Set default module 'index'
688 setModule('unknown');
692 // Fix 'what' if not yet set
694 setWhat(getWhatFromModule(getModule()));
697 // Fix 'action' if not yet set
698 if (!isActionSet()) {
699 setAction(getActionFromModuleWhat(getModule(), getWhat()));
702 // Set action/what to empty
707 // Set default 'what' value
708 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
709 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
710 if (getModule() == 'admin') {
711 // Set 'action' value to 'login' in admin menu
712 setAction(getActionFromModuleWhat(getModule(), getWhat()));
713 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
714 // Set 'what' value to 'welcome' in guest and member menu
715 setWhatFromConfig('index_home');
717 // Anything else like begging link
723 // Sends out pooled mails
724 function FILTER_TRIGGER_SENDING_POOL () {
725 // Are we in normal output mode?
726 if (!isHtmlOutputMode()) {
727 // Only in normal output mode to prevent race-conditons!
731 $GLOBALS['pool_cnt'] = '0';
733 // Init & set the include pool
734 initIncludePool('pool');
735 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
738 runFilterChain('load_includes', 'pool');
740 // Remove the counter
741 unset($GLOBALS['pool_cnt']);
744 // Filter for checking and updating SVN revision
745 function FILTER_CHECK_REPOSITORY_REVISION () {
746 // Only execute this filter if installed and all config entries are there
747 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
749 // Check for patch level differences between database and current hard-coded
750 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
751 // Update database and CONFIG array
752 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
753 setConfigEntry('patch_level', getCurrentRepositoryRevision());
754 setConfigEntry('patch_ctime', time());
758 // Filter for running daily reset
759 function FILTER_RUN_DAILY_RESET () {
760 // Only execute this filter if installed
761 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
765 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
766 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
767 // Tell every module we are in reset-mode!
772 // Filter for running hourly reset
773 function FILTER_RUN_HOURLY_RESET () {
774 // Only execute this filter if installed
775 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
779 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
780 if (((getConfig('last_hour') != getHour()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
781 // Tell every module we are in reset-mode!
786 // Filter for loading more runtime includes (not for installation)
787 function FILTER_LOAD_RUNTIME_INCLUDES () {
788 // Load more includes
789 foreach (array('databases', 'session', 'versions') as $inc) {
791 loadIncludeOnce('inc/' . $inc . '.php');
795 // Filter for checking admin ACL
796 function FILTER_CHECK_ADMIN_ACL () {
797 // Extension not installed so it's always allowed to access everywhere!
800 // Ok, Cookie-Update done
801 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
802 // Check if action GET variable was set
803 $action = getAction();
805 // Get action value by what-value
806 $action = getActionFromModuleWhat('admin', getWhat());
809 // Check for access control line of current menu entry
810 $ret = adminsCheckAdminAcl($action, getWhat());
814 $GLOBALS['acl_allow'] = $ret;
817 // Init random number/cache buster
818 function FILTER_INIT_RANDOM_NUMBER () {
819 // Is the extension sql_patches installed and at least 0.3.6?
820 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
821 // Generate random number
822 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
824 // Generate *WEAK* code
825 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
828 // Copy it to CACHE_BUSTER
829 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
832 // Update module counter
833 function FILTER_COUNT_MODULE () {
834 // Do count all other modules but not accesses on CSS file css.php!
835 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
836 array(getModule()), __FUNCTION__, __LINE__);
839 // Handles fatal errors
840 function FILTER_HANDLE_FATAL_ERRORS () {
841 // Do we have errors to handle and right output mode?
842 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
843 // Abort executing here
848 setContentType('text/html');
851 loadIncludeOnce('inc/load_config.php');
853 // Set unset variable
854 if (empty($check)) $check = '';
859 // Installation phase or regular mode?
860 if ((isInstallationPhase())) {
861 // While we are installing ouput other header than while it is installed... :-)
863 foreach (getFatalArray() as $key => $value) {
864 // Prepare content for the template
871 $OUT .= loadTemplate('install_fatal_row', true, $content);
874 // Load main template
875 $content = loadTemplate('install_fatal_table', true, $OUT);
876 } elseif (isInstalled()) {
877 // Display all runtime fatal errors
879 foreach (getFatalArray() as $key => $value) {
880 // Prepare content for the template
887 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
890 // Load main template
891 $content = loadTemplate('runtime_fatal_table', true, $OUT);
894 // Message to regular users (non-admin)
895 $CORR = '{--FATAL_REPORT_ERRORS--}';
897 // PHP warnings fixed
898 if ($check == 'done') {
899 if (isAdmin()) $CORR = '{--FATAL_CORRECT_ERRORS--}';
902 // Remember all in array
909 loadIncludeOnce('inc/header.php');
911 // Load main template
912 loadTemplate('fatal_errors', false, $content);
914 // Delete all to prevent double-display
918 loadIncludeOnce('inc/footer.php');
924 // Filter for displaying copyright line
925 function FILTER_DISPLAY_COPYRIGHT () {
926 // Shall we display the copyright notice?
927 if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
929 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
930 // Copyright with backlink, thanks! :-)
931 $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
933 // No backlink in Copyright note
934 $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
939 // Filter for displaying parsing time
940 function FILTER_DISPLAY_PARSING_TIME () {
941 // Shall we display the parsing time and number of queries?
942 // 1234 5 54 4 5 5 4 4 5 543 3 4432 2 33 2 2 21
943 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
944 // Then display it here
945 displayParsingTime();
949 // Filter for flushing template cache
950 function FILTER_FLUSH_TEMPLATE_CACHE () {
951 // Do not flush when debugging the template cache
952 if (isDebuggingTemplateCache()) return;
954 // Do we have cached eval() data?
955 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
957 foreach ($GLOBALS['template_eval'] as $template => $eval) {
958 // Flush the cache (if not yet found)
959 flushTemplateCache($template, $eval);
964 // Filter for loading user data
965 function FILTER_FETCH_USER_DATA ($userid = 0) {
966 // Is the userid not set? Then use member id
967 if (($userid == '0') || (is_null($userid))) $userid = getMemberId();
970 if (!fetchUserData($userid)) {
971 // Userid is not valid
972 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
976 setMemberId($userid);
979 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
980 function FILTER_RESET_USER_LOGIN_FAILURE () {
981 // Is the user data valid?
983 // Do only run for logged in members
984 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
987 // Remmeber login failures if available
988 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
989 // Reset login failures
990 SQL_QUERY_ESC("UPDATE
991 `{?_MYSQL_PREFIX?}_user_data`
998 array(getMemberId()), __FUNCTION__, __LINE__);
1000 // Store it in session
1001 setSession('mailer_member_failures' , getUserData('login_failures'));
1002 setSession('mailer_member_last_failure', getUserData('last_failure'));
1006 // Try to login the admin by setting some session/cookie variables
1007 function FILTER_DO_LOGIN_ADMIN ($data) {
1008 // Now set all session variables and store the result for later processing
1009 $GLOBALS['admin_login_success'] = ((
1010 setAdminMd5(encodeHashForCookie($data['pass_hash']))
1012 setAdminId($data['id'])
1014 setAdminLast(time())
1017 // Return the data for further processing
1021 // Filter for loading page header, this should be ran first!
1022 function FILTER_LOAD_PAGE_HEADER () {
1023 // Output page header code
1024 $GLOBALS['page_header'] = loadTemplate('page_header', true);
1026 // Include meta data in 'guest' module
1027 if (getModule() == 'index') {
1028 // Load meta data template
1029 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
1031 // Add meta description to header
1032 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1033 // Add meta description not in admin and login module and when the script is installed
1034 generateMetaDescriptionCode();
1039 // Filter for adding style sheet, closing page header
1040 function FILTER_FINISH_PAGE_HEADER () {
1041 // Include stylesheet
1042 loadIncludeOnce('inc/stylesheet.php');
1045 $GLOBALS['page_header'] .= '</head>';
1048 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1049 function FILTER_CLEANUP_DNS_CACHE () {
1050 // Is the latest version installed?
1051 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1053 loadIncludeOnce('inc/classes/resolver.class.php');
1055 // Instance the resolver
1056 $resolver = new HostnameResolver();
1059 $resolver->purgeEntries();
1061 // Cute, isn't it? ;-)
1065 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1066 function FILTER_SET_CURRENT_DATE () {
1068 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1070 // Timestamp for yesterday, today ... all at 00:00 am
1071 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1072 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));