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://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 debug_report_bug(__FUNCTION__, __LINE__, 'No database link is up. Cannot flush filters.');
61 // Is the extension ext-sql_patches updated?
62 if ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) {
63 // Log only in debug mode
64 if (isDebugModeEnabled()) {
65 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot flush filters, sql_patches might be missing. isExtensionInstalled()=' . intval(isExtensionInstalled('sql_patches')) . ',isExtensionInstalledAndOlder()=' . intval(isExtensionInstalledAndOlder('sql_patches', '0.5.9')));
68 // Abort silently here
72 // Nothing is added/remove by default
76 // Prepare SQL queries
77 $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES';
78 $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
80 // Write all filters to database
81 foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
82 // Walk through all filters
83 foreach ($filterArray as $filterFunction => $active) {
84 // Is this filter loaded?
85 //* DEBUG: */ debugOutput('FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
86 if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
87 // Add this filter (all filters are active by default)
88 //* DEBUG: */ debugOutput('ADD:'.$filterName.'/'.$filterFunction);
89 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
91 } elseif ($active == 'R') {
93 //* DEBUG: */ debugOutput('REMOVE:'.$filterName.'/'.$filterFunction);
94 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
100 // Something has been added?
102 // Finish SQL command and add it
103 addSql(substr($insertSQL, 0, -1));
106 // Something has been removed?
108 // Finish SQL command and add it
109 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
112 // Shall we update usage counters (ONLY FOR DEBUGGING!)
113 if (isFilterUsageUpdateEnabled()) {
114 // Update all counters
115 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
116 // Walk through all filters
117 foreach ($filterArray as $filterFunction => $count) {
118 // Construct and add the query
119 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
128 // Run the run_sqls filter in non-dry mode
129 runFilterChain('run_sqls');
131 // Should we rebuild cache?
132 if (($inserted > 0) || ($removed > 0)) {
134 rebuildCache('filter', 'filter');
138 // Filter for calling the handler for login failures
139 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($filterData) {
141 $content = $filterData;
143 // Handle failed logins here if not in guest
144 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $filterData['type'] . ',action=' . getAction() . ',what=' . getWhat() . ',level=' . $filterData['access_level']);
145 if ((($filterData['type'] == 'what') || ($filterData['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getIndexHome()))) && ($filterData['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.6')))) {
147 $content['content'] .= handleLoginFailures($filterData['access_level']);
150 // Return the content
154 // Filter for redirecting to logout if sql_patches has been installed
155 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
156 // Remove this filter
157 unregisterFilter(__FUNCTION__, __LINE__, 'shutdown', __FUNCTION__);
159 // Is the element set?
160 if (isset($GLOBALS['ext_load_mode'])) {
162 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
165 // This should not happen!
166 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
169 // Filter for auto-activation of a extension
170 function FILTER_AUTO_ACTIVATE_EXTENSION ($filterData) {
172 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $filterData['ext_name'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
174 // Is this extension always activated?
175 if (isThisExtensionAlwaysActive()) {
176 // Then activate the extension
177 doActivateExtension($filterData['ext_name']);
184 // Filter for solving task given task
185 function FILTER_SOLVE_TASK ($filterData) {
186 // Don't solve anything if no admin!
191 // Is this a direct task id or array element task_id is found?
192 if (is_int($filterData)) {
194 adminSolveTask($filterData);
195 } elseif ((is_array($filterData)) && (isset($filterData['task_id']))) {
197 adminSolveTask($filterData['task_id']);
200 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($filterData), print_r($filterData, true)));
207 // Filter to load include files
208 function FILTER_LOAD_INCLUDES ($filterData) {
210 if (is_null($filterData)) {
211 // This should not happen!
212 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
215 // Is the pool an array and 'pool' set?
216 if ((is_array($filterData)) && (isset($filterData['pool']))) {
217 // Then use it as pool
218 $realPool = $filterData['pool'];
220 // Default is $data as inclusion list
221 $realPool = $filterData;
225 $data = getIncludePool($realPool);
228 if ((!isset($data)) || (!is_array($data))) {
230 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
231 } elseif (isset($data['inc_pool'])) {
232 // Use this as new inclusion pool!
233 setIncludePool($realPool, $data['inc_pool']);
236 // Check for added include files
237 if (countIncludePool($realPool) > 0) {
238 // Loads every include file
239 loadIncludePool($realPool);
242 initIncludePool($realPool);
245 // Continue with processing
249 // Filter for running SQL commands
250 function FILTER_RUN_SQLS ($filterData) {
252 //* DEBUG: */ die('getSqls()=<pre>'.print_r(getSqls(), true).'</pre>ext_update_depends=<pre>'.print_r($GLOBALS['ext_update_depends'], true).'</pre>');
253 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
255 // Is the array there?
256 if ((isSqlsValid()) && ((!isset($filterData['dry_run'])) || ($filterData['dry_run'] == false))) {
258 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
259 foreach (getSqls() as $mode => $sqls) {
261 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
263 // New cache format...
264 foreach ($sqls as $sql) {
268 // Is 'enable_codes' not set? Then set it to true
269 if (!isset($filterData['enable_codes'])) {
270 $filterData['enable_codes'] = true;
273 // Is there still a query left?
275 // Do we have an "ALTER TABLE" command?
276 if (substr(strtolower($sql), 0, 11) == 'alter table') {
277 // Analyse the alteration command
278 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
279 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
281 // Run regular SQL command
282 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
283 SQL_QUERY($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
291 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
294 // Filter for updating/validating login data
295 function FILTER_UPDATE_LOGIN_DATA () {
297 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
298 $GLOBALS['last_online'] = array();
301 // Recheck if logged in
302 if ((!isMember()) || ((isAdmin()) && (!isDebugModeEnabled()))) {
307 setMemberId(getSession('userid'));
310 if (fetchUserData(getMemberId())) {
311 // Load last module and online time
312 $content = getUserDataArray();
314 // Maybe first login time?
315 if (empty($content['last_module'])) {
316 $content['last_module'] = 'login';
319 // This will be displayed on welcome page! :-)
320 if (empty($GLOBALS['last_online']['module'])) {
321 $GLOBALS['last_online']['module'] = $content['last_module'];
322 $GLOBALS['last_online']['online'] = $content['last_online'];
329 if (getIndexHome() != '') {
330 setWhatFromConfig('index_home');
334 // Update last module / online time
335 updateLastActivity(getMemberId());
337 // Destroy session, we cannot update!
338 destroyMemberSession();
342 // Filter for initializing randomizer
343 function FILTER_INIT_RANDOMIZER () {
344 // Take a prime number which is long (if you know a longer one please try it out!)
345 setConfigEntry('_PRIME', 591623);
347 // Only execute this filter if installed
348 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
350 setConfigEntry('_ADD', 0);
354 // Calculate "entropy" with the prime number (for code generation)
355 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
357 // Simply init the randomizer with seed and _ADD value
358 mt_srand(generateSeed() + getConfig('_ADD'));
361 // Filter for removing updates
362 function FILTER_REMOVE_UPDATES ($filterData) {
364 initExtensionRemovalList();
366 // Add the current extension to it
367 addCurrentExtensionToRemovalList();
370 unsetExtensionSqls();
372 // Do we need to remove update depency?
373 if (countExtensionUpdateDependencies() > 0) {
374 // Then find all updates we shall no longer execute
375 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
376 // Shall we remove this update?
377 if (in_array($ext_name, getExtensionRemovalList())) {
378 // Then remove this extension!
379 removeExtensionDependency($ext_name);
388 // Determines username for current user state
389 function FILTER_DETERMINE_USERNAME () {
390 // Check if logged in
392 // Is still logged in so we welcome him with his name
393 if (fetchUserData(getMemberId())) {
394 // Load surname and family's name and build the username
395 $content = getUserDataArray();
398 setUsername($content['surname'] . ' ' . $content['family']);
400 // Additionally admin?
403 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
406 // Hmmm, logged in and no valid userid?
407 setUsername('<span class="bad">{--USERNAME_UNKNOWN--}</span>');
410 destroyMemberSession();
412 } elseif (isAdmin()) {
414 setUsername('{--USERNAME_ADMIN--}');
416 // He's a guest, hello there... ;-)
417 setUsername('{--USERNAME_GUEST--}');
421 // Filter for compiling config entries
422 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
423 // Save the uncompiled code
427 if (!isset($GLOBALS['compiled_config'][$code])) {
428 // Compile {?some_var?} to getConfig('some_var')
429 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
431 // Some entries found?
432 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
433 // Replace all matches
434 foreach ($matches[0] as $key => $match) {
436 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
437 // Is the config valid?
438 if (isConfigEntrySet($matches[1][$key])) {
439 // Set it for caching
440 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
441 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
443 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
444 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
445 // No config, try the language system
446 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
449 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
453 // Use this for replacing
454 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
455 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
460 $GLOBALS['compiled_config'][$uncompiled] = $code;
463 // Should we compile it?
464 if ($compiled === true) {
466 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
467 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
471 // Return compiled code
472 return $GLOBALS['compiled_config'][$uncompiled];
475 // Filter for compiling expression code
476 function FILTER_COMPILE_EXPRESSION_CODE ($filterData) {
477 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
478 // See switch() command below for supported commands
479 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $filterData, $matches);
480 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
482 // Default is from outputHtml()
483 $outputMode = getScriptOutputMode();
485 // Some entries found?
486 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
487 // Replace all matches
488 foreach ($matches[2] as $key => $cmd) {
489 // Init replacer/call-back variable
493 $extraFunction2 = '';
496 // Extract command and call-back
497 $cmdArray = explode(',', $cmd);
500 // Detect call-back function
501 if (isset($cmdArray[1])) {
502 // Call-back function detected
503 $callback = $cmdArray[1];
506 // Detect extra function
507 if (isset($cmdArray[2])) {
509 $extraFunction = $cmdArray[2];
512 // Detect extra function 2
513 if (isset($cmdArray[3])) {
515 $extraFunction2 = $cmdArray[3];
519 if (isset($matches[4][$key])) {
521 $value = $matches[4][$key];
524 // Construct call-back function name for the command
525 $commandFunction = 'doExpression' . capitalizeUnderscoreString($cmd);
527 // Is this function there?
528 if (function_exists($commandFunction)) {
529 // Prepare $matches, $key, $outputMode, etc.
531 'matches' => $matches,
533 'mode' => getScriptOutputMode(),
534 'code' => $filterData,
535 'callback' => $callback,
536 'extra_func' => $extraFunction,
537 'extra_func2' => $extraFunction2,
542 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
543 $filterData = call_user_func($commandFunction, $data);
545 // Unsupported command detected
546 logDebugMessage(__FUNCTION__, __LINE__, 'Command cmd=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
551 // Do we have non-HTML mode?
552 if (!isHtmlOutputMode()) {
553 $filterData = decodeEntities($filterData);
556 // Return compiled code
557 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($filterData).'</pre>');
561 // Runs some generic filter update steps
562 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
563 // Create task (we ignore the task id here)
564 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
566 // Update extension's version
567 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
568 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
572 unset($GLOBALS['update_ver'][$ext_name]);
575 // Load more hourly reset scripts
576 function FILTER_RUN_HOURLY_INCLUDES () {
577 // Is the reset set or old sql_patches?
578 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
580 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');
583 // Get more hourly reset scripts
584 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
587 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
588 updateConfiguration('last_hour', getHour());
592 runFilterChain('load_includes', 'hourly');
595 // Load more reset scripts
596 function FILTER_RUN_RESET_INCLUDES () {
597 // Is the reset set or old sql_patches?
598 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
600 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
603 // Get more daily reset scripts
604 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
607 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
608 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
611 // Is the config entry set?
612 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
614 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
615 // Include weekly reset scripts
616 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
618 // Update config if not in debug mode
619 if (!isWeeklyResetDebugEnabled()) {
620 updateConfiguration('last_week', getWeek());
624 // Create current month mark
625 $currMonth = getMonth();
628 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
629 // Include monthly reset scripts
630 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
633 if (!isMonthlyResetDebugEnabled()) {
634 updateConfiguration('last_month', $currMonth);
640 runFilterChain('load_includes', 'reset');
643 // Filter for removing the given extension
644 function FILTER_REMOVE_EXTENSION () {
645 // Delete this extension (remember to remove it from your server *before* you click on welcome!
646 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
647 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
649 // Remove the extension from cache array as well
650 removeExtensionFromArray();
653 rebuildCache('extension', 'extension');
656 // Filter for flushing the output
657 function FILTER_FLUSH_OUTPUT () {
662 // Prepares an SQL statement part for HTML mail and/or holiday depency
663 function FILTER_HTML_INCLUDE_USERS ($mode) {
664 // Exclude no users by default
668 if ($mode == 'html') $MORE = " AND `html`='Y'";
669 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
670 // Add something for the holiday extension
671 $MORE .= " AND `holiday_active`='N'";
678 // Filter for determining what/action/module
679 function FILTER_DETERMINE_WHAT_ACTION () {
680 // In installation phase we don't have what/action
681 if (isInstallationPhase()) {
691 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
693 if (!isModuleSet()) {
694 // Is the request element set?
695 if (isGetRequestElementSet('module')) {
696 // Set module from request
697 setModule(getRequestElement('module'));
698 } elseif (isHtmlOutputMode()) {
699 // Set default module 'index'
703 setModule('unknown');
707 // Fix 'what' if not yet set
709 setWhat(getWhatFromModule(getModule()));
712 // Fix 'action' if not yet set
713 if (!isActionSet()) {
714 setAction(getActionFromModuleWhat(getModule(), getWhat()));
717 // Set action/what to empty
722 // Set default 'what' value
723 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
724 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
725 if (getModule() == 'admin') {
726 // Set 'action' value to 'login' in admin menu
727 setAction(getActionFromModuleWhat(getModule(), getWhat()));
728 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
729 // Set 'what' value to 'welcome' in guest and member menu
730 setWhatFromConfig('index_home');
732 // Anything else like begging link
738 // Sends out pooled mails
739 function FILTER_TRIGGER_SENDING_POOL () {
740 // Are we in normal output mode?
741 if (!isHtmlOutputMode()) {
742 // Only in normal output mode to prevent race-conditons!
746 $GLOBALS['pool_cnt'] = '0';
748 // Init & set the include pool
749 initIncludePool('pool');
750 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
753 runFilterChain('load_includes', 'pool');
755 // Remove the counter
756 unset($GLOBALS['pool_cnt']);
759 // Filter for checking and updating SVN revision
760 function FILTER_CHECK_REPOSITORY_REVISION () {
761 // Only execute this filter if installed and all config entries are there
762 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
764 // Check for patch level differences between database and current hard-coded
765 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
766 // Update database and CONFIG array
767 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
768 setConfigEntry('patch_level', getCurrentRepositoryRevision());
769 setConfigEntry('patch_ctime', time());
773 // Filter for running daily reset
774 function FILTER_RUN_DAILY_RESET () {
775 // Only execute this filter if installed
776 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
780 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
781 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
782 // Tell every module we are in reset-mode!
787 // Filter for running hourly reset
788 function FILTER_RUN_HOURLY_RESET () {
789 // Only execute this filter if installed
790 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
794 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
795 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
796 // Tell every module we are in reset-mode!
801 // Filter for loading more runtime includes (not for installation)
802 function FILTER_LOAD_RUNTIME_INCLUDES () {
803 // Load more includes
804 foreach (array('databases', 'session', 'versions') as $inc) {
806 loadIncludeOnce('inc/' . $inc . '.php');
810 // Filter for checking admin ACL
811 function FILTER_CHECK_ADMIN_ACL () {
812 // Extension not installed so it's always allowed to access everywhere!
815 // Ok, Cookie-Update done
816 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
817 // Check if action GET variable was set
818 $action = getAction();
820 // Get action value by what-value
821 $action = getActionFromModuleWhat('admin', getWhat());
824 // Check for access control line of current menu entry
825 $ret = isAdminsAllowedByAcl($action, getWhat());
829 $GLOBALS['acl_allow'] = $ret;
832 // Init random number/cache buster
833 function FILTER_INIT_RANDOM_NUMBER () {
834 // Is the extension ext-sql_patches installed and at least 0.3.6?
835 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
836 // Generate random number
837 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 99999), getMemberId(), ''));
839 // Generate *WEAK* code
840 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
843 // Copy it to CACHE_BUSTER
844 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
847 // Update module counter
848 function FILTER_COUNT_MODULE () {
849 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ' - ENTERED!');
850 // Do count all other modules but not accesses on CSS file css.php!
851 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
852 array(getModule()), __FUNCTION__, __LINE__);
853 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
856 // Handles fatal errors
857 function FILTER_HANDLE_FATAL_ERRORS () {
858 // Do we have errors to handle and right output mode?
859 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
860 // Abort executing here
865 setContentType('text/html');
868 loadIncludeOnce('inc/load_config.php');
870 // Default content is none
873 // Installation phase or regular mode?
874 if ((isInstallationPhase())) {
875 // While we are installing ouput other header than while it is installed... :-)
877 foreach (getFatalArray() as $key => $value) {
878 // Prepare content for the template
885 $OUT .= loadTemplate('install_fatal_row', true, $content);
888 // Load main template
889 $content = loadTemplate('install_fatal_table', true, $OUT);
890 } elseif (isInstalled()) {
891 // Display all runtime fatal errors
893 foreach (getFatalArray() as $key => $value) {
894 // Prepare content for the template
901 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
904 // Load main template
905 $content = loadTemplate('runtime_fatal_table', true, $OUT);
908 // Message to regular users (non-admin)
909 $CORR = '{--FATAL_REPORT_ERRORS--}';
911 // Maybe the admin wants to take a look?
913 $CORR = '{--FATAL_CORRECT_ERRORS--}';
916 // Remember all in array
923 loadIncludeOnce('inc/header.php');
925 // Load main template
926 loadTemplate('fatal_errors', false, $content);
928 // Delete all to prevent double-display
932 loadIncludeOnce('inc/footer.php');
938 // Filter for displaying copyright line
939 function FILTER_DISPLAY_COPYRIGHT () {
940 // Shall we display the copyright notice?
941 if ((!isGetRequestElementSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
943 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
944 // Copyright with backlink, thanks! :-)
945 $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
947 // No backlink in Copyright note
948 $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
953 // Filter for displaying parsing time
954 function FILTER_DISPLAY_PARSING_TIME () {
955 // Shall we display the parsing time and number of queries?
956 // 1234 5 54 4 5 5 4 4 5 543 3 4432 2 33 2 2 21
957 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestElementSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
958 // Then display it here
959 displayParsingTime();
963 // Filter for flushing template cache
964 function FILTER_FLUSH_TEMPLATE_CACHE () {
965 // Do not flush when debugging the template cache
966 if (isDebuggingTemplateCache()) return;
968 // Do we have cached eval() data?
969 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
971 foreach ($GLOBALS['template_eval'] as $template => $eval) {
972 // Flush the cache (if not yet found)
973 flushTemplateCache($template, $eval);
978 // Filter for loading user data
979 function FILTER_FETCH_USER_DATA ($userid = NULL) {
980 // Is the userid not set? Then use member id
981 if (!isValidUserId($userid)) {
982 $userid = getMemberId();
986 if (!fetchUserData($userid)) {
987 // Userid is not valid
988 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
992 setMemberId($userid);
995 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
996 function FILTER_RESET_USER_LOGIN_FAILURE () {
997 // Is the user data valid?
999 // Do only run for logged in members
1000 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
1003 // Remmeber login failures if available
1004 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1005 // Reset login failures
1006 SQL_QUERY_ESC("UPDATE
1007 `{?_MYSQL_PREFIX?}_user_data`
1014 array(getMemberId()), __FUNCTION__, __LINE__);
1016 // Store it in session
1017 setSession('mailer_member_failures' , getUserData('login_failures'));
1018 setSession('mailer_member_last_failure', getUserData('last_failure'));
1022 // Try to login the admin by setting some session/cookie variables
1023 function FILTER_DO_LOGIN_ADMIN ($filterData) {
1024 // Now set all session variables and store the result for later processing
1025 $GLOBALS['admin_login_success'] = ((
1026 setAdminMd5(encodeHashForCookie($filterData['pass_hash']))
1028 setAdminId($filterData['id'])
1030 setAdminLast(time())
1033 // Return the data for further processing
1037 // Filter for loading page header, this should be ran first!
1038 function FILTER_LOAD_PAGE_HEADER () {
1039 // Output page header code
1040 $GLOBALS['page_header'] = loadTemplate('page_header', true);
1042 // Include meta data in 'guest' module
1043 if (getModule() == 'index') {
1044 // Load meta data template
1045 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
1047 // Add meta description to header
1048 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1049 // Add meta description not in admin and login module and when the script is installed
1050 generateMetaDescriptionCode();
1055 // Filter for adding style sheet, closing page header
1056 function FILTER_FINISH_PAGE_HEADER () {
1057 // Include stylesheet
1058 loadIncludeOnce('inc/stylesheet.php');
1061 $GLOBALS['page_header'] .= '</head>';
1064 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1065 function FILTER_CLEANUP_DNS_CACHE () {
1066 // Is the latest version installed?
1067 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1069 loadIncludeOnce('inc/classes/resolver.class.php');
1071 // Instance the resolver
1072 $resolver = new HostnameResolver();
1075 $resolver->purgeEntries();
1077 // Cute, isn't it? ;-)
1081 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1082 function FILTER_SET_CURRENT_DATE () {
1084 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1086 // Epoche time for yesterday, today ... all at 00:00 am
1087 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1088 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1091 // Filter for marking extension as installed
1092 function FILTER_EXTENSION_MARK_INSTALLED ($filterData) {
1093 // Mark it as installed
1094 $GLOBALS['ext_is_installed'][$filterData['ext_name']] = true;
1097 // Filter for generating mails links for 'pool' mails
1098 function FILTER_GENERATE_POOL_MAIL_LINKS ($filterData) {
1100 if ($filterData['type'] == 'mid') {
1102 $filterData['__output'] .= loadTemplate('admin_links_' . strtolower($filterData['mail_status']) . '_pool_mail', true, $filterData);
1109 // Filter to activate exchange
1110 function FILTER_ACTIVATE_EXCHANGE () {
1111 // Is the extension 'user' there?
1112 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1113 // Silently abort here
1117 // Check total amount of users
1118 if (getTotalConfirmedUser() >= getActivateXchange()) {
1120 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N',`hidden`='N',`mem_only`='Y' WHERE `module`='order' LIMIT 1");
1121 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y',`locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1124 runFilterChain('run_sqls');
1126 // Update configuration
1127 updateConfiguration('activate_xchange' ,0);
1130 rebuildCache('modules', 'modules');
1134 // Filter to handle configuration
1135 function FILTER_HANDLE_HOME_IN_INDEX_SETTING ($filterData) {
1136 // Is ext-sql_patches up-to-date?
1137 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled())) {
1138 // Is 'search' as same as 'index_home'?
1139 if ($filterData['search'] == getIndexHome()) {
1140 // Then set 'content' to link to index.php
1141 $filterData['content'] = $filterData['prefix'] . '<strong><a class="you_are_here" href="{%url=index.php' . $filterData['link_add'] . '%}">' . getTitleFromMenu($filterData['access_level'], $filterData['search'], $filterData['type'], $filterData['add']) . '</a></strong>';
1149 // Filter to add history entry
1150 function FILTER_ADD_HISTORY_ENTRY ($filterData) {
1152 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_history` (`history_subject`,`history_userid`,`history_value`) VALUES ('%s',%s,'%s')",
1154 __FUNCTION__, __LINE__);
1156 // Remember insert id for other filters
1157 $filterData['history_id'] = SQL_INSERTID();