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 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 // 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 ($filterData) {
137 $content = $filterData;
139 // Handle failed logins here if not in guest
140 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $filterData['type'] . ',action=' . getAction() . ',what=' . getWhat() . ',level=' . $filterData['access_level']);
141 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')))) {
143 $content['content'] .= handleLoginFailures($filterData['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 ($filterData) {
168 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $filterData['ext_name'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
170 // Is this extension always activated?
171 if (isThisExtensionAlwaysActive()) {
172 // Then activate the extension
173 doActivateExtension($filterData['ext_name']);
180 // Filter for solving task given task
181 function FILTER_SOLVE_TASK ($filterData) {
182 // Don't solve anything if no admin!
187 // Is this a direct task id or array element task_id is found?
188 if (is_int($filterData)) {
190 adminSolveTask($filterData);
191 } elseif ((is_array($filterData)) && (isset($filterData['task_id']))) {
193 adminSolveTask($filterData['task_id']);
196 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($filterData), print_r($filterData, true)));
203 // Filter to load include files
204 function FILTER_LOAD_INCLUDES ($filterData) {
206 if (is_null($filterData)) {
207 // This should not happen!
208 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
211 // Is the pool an array and 'pool' set?
212 if ((is_array($filterData)) && (isset($filterData['pool']))) {
213 // Then use it as pool
214 $realPool = $filterData['pool'];
216 // Default is $data as inclusion list
217 $realPool = $filterData;
221 $data = getIncludePool($realPool);
224 if ((!isset($data)) || (!is_array($data))) {
226 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
227 } elseif (isset($data['inc_pool'])) {
228 // Use this as new inclusion pool!
229 setIncludePool($realPool, $data['inc_pool']);
232 // Check for added include files
233 if (countIncludePool($realPool) > 0) {
234 // Loads every include file
235 loadIncludePool($realPool);
238 initIncludePool($realPool);
241 // Continue with processing
245 // Filter for running SQL commands
246 function FILTER_RUN_SQLS ($filterData) {
248 //* DEBUG: */ die('getSqls()=<pre>'.print_r(getSqls(), true).'</pre>ext_update_depends=<pre>'.print_r($GLOBALS['ext_update_depends'], true).'</pre>');
249 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
251 // Is the array there?
252 if ((isSqlsValid()) && ((!isset($filterData['dry_run'])) || ($filterData['dry_run'] == false))) {
254 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
255 foreach (getSqls() as $mode=>$sqls) {
257 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
259 // New cache format...
260 foreach ($sqls as $sql) {
264 // Is 'enable_codes' not set? Then set it to true
265 if (!isset($filterData['enable_codes'])) {
266 $filterData['enable_codes'] = true;
269 // Is there still a query left?
271 // Do we have an "ALTER TABLE" command?
272 if (substr(strtolower($sql), 0, 11) == 'alter table') {
273 // Analyse the alteration command
274 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
275 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
277 // Run regular SQL command
278 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
279 SQL_QUERY($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
287 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
290 // Filter for updating/validating login data
291 function FILTER_UPDATE_LOGIN_DATA () {
293 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
294 $GLOBALS['last_online'] = array();
297 // Recheck if logged in
298 if ((!isMember()) || ((isAdmin()) && (!isDebugModeEnabled()))) {
303 setMemberId(getSession('userid'));
306 if (fetchUserData(getMemberId())) {
307 // Load last module and online time
308 $content = getUserDataArray();
310 // Maybe first login time?
311 if (empty($content['last_module'])) {
312 $content['last_module'] = 'login';
315 // This will be displayed on welcome page! :-)
316 if (empty($GLOBALS['last_online']['module'])) {
317 $GLOBALS['last_online']['module'] = $content['last_module'];
318 $GLOBALS['last_online']['online'] = $content['last_online'];
325 if (getIndexHome() != '') {
326 setWhatFromConfig('index_home');
330 // Update last module / online time
331 updateLastActivity(getMemberId());
333 // Destroy session, we cannot update!
334 destroyMemberSession();
338 // Filter for initializing randomizer
339 function FILTER_INIT_RANDOMIZER () {
340 // Take a prime number which is long (if you know a longer one please try it out!)
341 setConfigEntry('_PRIME', 591623);
343 // Only execute this filter if installed
344 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
346 setConfigEntry('_ADD', 0);
350 // Calculate "entropy" with the prime number (for code generation)
351 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
353 // Simply init the randomizer with seed and _ADD value
354 mt_srand(generateSeed() + getConfig('_ADD'));
357 // Filter for removing updates
358 function FILTER_REMOVE_UPDATES ($filterData) {
360 initExtensionRemovalList();
362 // Add the current extension to it
363 addCurrentExtensionToRemovalList();
366 unsetExtensionSqls();
368 // Do we need to remove update depency?
369 if (countExtensionUpdateDependencies() > 0) {
370 // Then find all updates we shall no longer execute
371 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
372 // Shall we remove this update?
373 if (in_array($ext_name, getExtensionRemovalList())) {
374 // Then remove this extension!
375 removeExtensionDependency($ext_name);
384 // Determines username for current user state
385 function FILTER_DETERMINE_USERNAME () {
386 // Check if logged in
388 // Is still logged in so we welcome him with his name
389 if (fetchUserData(getMemberId())) {
390 // Load surname and family's name and build the username
391 $content = getUserDataArray();
394 setUsername($content['surname'] . ' ' . $content['family']);
396 // Additionally admin?
399 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
402 // Hmmm, logged in and no valid userid?
403 setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
406 destroyMemberSession();
408 } elseif (isAdmin()) {
410 setUsername('{--USERNAME_ADMIN--}');
412 // He's a guest, hello there... ;-)
413 setUsername('{--USERNAME_GUEST--}');
417 // Filter for compiling config entries
418 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
419 // Save the uncompiled code
423 if (!isset($GLOBALS['compiled_config'][$code])) {
424 // Compile {?some_var?} to getConfig('some_var')
425 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
427 // Some entries found?
428 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
429 // Replace all matches
430 foreach ($matches[0] as $key => $match) {
432 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
433 // Is the config valid?
434 if (isConfigEntrySet($matches[1][$key])) {
435 // Set it for caching
436 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
437 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
439 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
440 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
441 // No config, try the language system
442 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
445 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
449 // Use this for replacing
450 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
451 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
456 $GLOBALS['compiled_config'][$uncompiled] = $code;
459 // Should we compile it?
460 if ($compiled === true) {
462 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
463 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
467 // Return compiled code
468 return $GLOBALS['compiled_config'][$uncompiled];
471 // Filter for compiling expression code
472 function FILTER_COMPILE_EXPRESSION_CODE ($filterData) {
473 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
474 // See switch() command below for supported commands
475 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $filterData, $matches);
476 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
478 // Default is from outputHtml()
479 $outputMode = getScriptOutputMode();
481 // Some entries found?
482 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
483 // Replace all matches
484 foreach ($matches[2] as $key => $cmd) {
485 // Init replacer/call-back variable
489 $extraFunction2 = '';
492 // Extract command and call-back
493 $cmdArray = explode(',', $cmd);
496 // Detect call-back function
497 if (isset($cmdArray[1])) {
498 // Call-back function detected
499 $callback = $cmdArray[1];
502 // Detect extra function
503 if (isset($cmdArray[2])) {
505 $extraFunction = $cmdArray[2];
508 // Detect extra function 2
509 if (isset($cmdArray[3])) {
511 $extraFunction2 = $cmdArray[3];
515 if (isset($matches[4][$key])) {
517 $value = $matches[4][$key];
520 // Construct call-back function name for the command
521 $commandFunction = 'doExpression' . capitalizeUnderscoreString($cmd);
523 // Is this function there?
524 if (function_exists($commandFunction)) {
525 // Prepare $matches, $key, $outputMode, etc.
527 'matches' => $matches,
529 'mode' => getScriptOutputMode(),
530 'code' => $filterData,
531 'callback' => $callback,
532 'extra_func' => $extraFunction,
533 'extra_func2' => $extraFunction2,
538 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
539 $filterData = call_user_func($commandFunction, $data);
541 // Unsupported command detected
542 logDebugMessage(__FUNCTION__, __LINE__, 'Command cmd=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
547 // Do we have non-HTML mode?
548 if (!isHtmlOutputMode()) {
549 $filterData = decodeEntities($filterData);
552 // Return compiled code
553 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($filterData).'</pre>');
557 // Runs some generic filter update steps
558 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
559 // Create task (we ignore the task id here)
560 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
562 // Update extension's version
563 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
564 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
568 unset($GLOBALS['update_ver'][$ext_name]);
571 // Load more hourly reset scripts
572 function FILTER_RUN_HOURLY_INCLUDES () {
573 // Is the reset set or old sql_patches?
574 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
576 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');
579 // Get more hourly reset scripts
580 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
583 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
584 updateConfiguration('last_hour', getHour());
588 runFilterChain('load_includes', 'hourly');
591 // Load more reset scripts
592 function FILTER_RUN_RESET_INCLUDES () {
593 // Is the reset set or old sql_patches?
594 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
596 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
599 // Get more daily reset scripts
600 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
603 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
604 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
607 // Is the config entry set?
608 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
610 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
611 // Include weekly reset scripts
612 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
614 // Update config if not in debug mode
615 if (!isWeeklyResetDebugEnabled()) {
616 updateConfiguration('last_week', getWeek());
620 // Create current month mark
621 $currMonth = getMonth();
624 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
625 // Include monthly reset scripts
626 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
629 if (!isMonthlyResetDebugEnabled()) {
630 updateConfiguration('last_month', $currMonth);
636 runFilterChain('load_includes', 'reset');
639 // Filter for removing the given extension
640 function FILTER_REMOVE_EXTENSION () {
641 // Delete this extension (remember to remove it from your server *before* you click on welcome!
642 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
643 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
645 // Remove the extension from cache array as well
646 removeExtensionFromArray();
649 rebuildCache('extension', 'extension');
652 // Filter for flushing the output
653 function FILTER_FLUSH_OUTPUT () {
658 // Prepares an SQL statement part for HTML mail and/or holiday depency
659 function FILTER_HTML_INCLUDE_USERS ($mode) {
660 // Exclude no users by default
664 if ($mode == 'html') $MORE = " AND `html`='Y'";
665 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
666 // Add something for the holiday extension
667 $MORE .= " AND `holiday_active`='N'";
674 // Filter for determining what/action/module
675 function FILTER_DETERMINE_WHAT_ACTION () {
676 // In installation phase we don't have what/action
677 if (isInstallationPhase()) {
687 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
689 if (!isModuleSet()) {
690 // Is the request element set?
691 if (isGetRequestParameterSet('module')) {
692 // Set module from request
693 setModule(getRequestParameter('module'));
694 } elseif (isHtmlOutputMode()) {
695 // Set default module 'index'
699 setModule('unknown');
703 // Fix 'what' if not yet set
705 setWhat(getWhatFromModule(getModule()));
708 // Fix 'action' if not yet set
709 if (!isActionSet()) {
710 setAction(getActionFromModuleWhat(getModule(), getWhat()));
713 // Set action/what to empty
718 // Set default 'what' value
719 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
720 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
721 if (getModule() == 'admin') {
722 // Set 'action' value to 'login' in admin menu
723 setAction(getActionFromModuleWhat(getModule(), getWhat()));
724 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
725 // Set 'what' value to 'welcome' in guest and member menu
726 setWhatFromConfig('index_home');
728 // Anything else like begging link
734 // Sends out pooled mails
735 function FILTER_TRIGGER_SENDING_POOL () {
736 // Are we in normal output mode?
737 if (!isHtmlOutputMode()) {
738 // Only in normal output mode to prevent race-conditons!
742 $GLOBALS['pool_cnt'] = '0';
744 // Init & set the include pool
745 initIncludePool('pool');
746 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
749 runFilterChain('load_includes', 'pool');
751 // Remove the counter
752 unset($GLOBALS['pool_cnt']);
755 // Filter for checking and updating SVN revision
756 function FILTER_CHECK_REPOSITORY_REVISION () {
757 // Only execute this filter if installed and all config entries are there
758 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
760 // Check for patch level differences between database and current hard-coded
761 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
762 // Update database and CONFIG array
763 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
764 setConfigEntry('patch_level', getCurrentRepositoryRevision());
765 setConfigEntry('patch_ctime', time());
769 // Filter for running daily reset
770 function FILTER_RUN_DAILY_RESET () {
771 // Only execute this filter if installed
772 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
776 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
777 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
778 // Tell every module we are in reset-mode!
783 // Filter for running hourly reset
784 function FILTER_RUN_HOURLY_RESET () {
785 // Only execute this filter if installed
786 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
790 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
791 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
792 // Tell every module we are in reset-mode!
797 // Filter for loading more runtime includes (not for installation)
798 function FILTER_LOAD_RUNTIME_INCLUDES () {
799 // Load more includes
800 foreach (array('databases', 'session', 'versions') as $inc) {
802 loadIncludeOnce('inc/' . $inc . '.php');
806 // Filter for checking admin ACL
807 function FILTER_CHECK_ADMIN_ACL () {
808 // Extension not installed so it's always allowed to access everywhere!
811 // Ok, Cookie-Update done
812 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
813 // Check if action GET variable was set
814 $action = getAction();
816 // Get action value by what-value
817 $action = getActionFromModuleWhat('admin', getWhat());
820 // Check for access control line of current menu entry
821 $ret = isAdminsAllowedByAcl($action, getWhat());
825 $GLOBALS['acl_allow'] = $ret;
828 // Init random number/cache buster
829 function FILTER_INIT_RANDOM_NUMBER () {
830 // Is the extension ext-sql_patches installed and at least 0.3.6?
831 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
832 // Generate random number
833 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 99999), getMemberId(), ''));
835 // Generate *WEAK* code
836 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
839 // Copy it to CACHE_BUSTER
840 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
843 // Update module counter
844 function FILTER_COUNT_MODULE () {
845 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ' - ENTERED!');
846 // Do count all other modules but not accesses on CSS file css.php!
847 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
848 array(getModule()), __FUNCTION__, __LINE__);
849 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
852 // Handles fatal errors
853 function FILTER_HANDLE_FATAL_ERRORS () {
854 // Do we have errors to handle and right output mode?
855 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
856 // Abort executing here
861 setContentType('text/html');
864 loadIncludeOnce('inc/load_config.php');
866 // Default content is none
869 // Installation phase or regular mode?
870 if ((isInstallationPhase())) {
871 // While we are installing ouput other header than while it is installed... :-)
873 foreach (getFatalArray() as $key => $value) {
874 // Prepare content for the template
881 $OUT .= loadTemplate('install_fatal_row', true, $content);
884 // Load main template
885 $content = loadTemplate('install_fatal_table', true, $OUT);
886 } elseif (isInstalled()) {
887 // Display all runtime fatal errors
889 foreach (getFatalArray() as $key => $value) {
890 // Prepare content for the template
897 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
900 // Load main template
901 $content = loadTemplate('runtime_fatal_table', true, $OUT);
904 // Message to regular users (non-admin)
905 $CORR = '{--FATAL_REPORT_ERRORS--}';
907 // Maybe the admin wants to take a look?
909 $CORR = '{--FATAL_CORRECT_ERRORS--}';
912 // Remember all in array
919 loadIncludeOnce('inc/header.php');
921 // Load main template
922 loadTemplate('fatal_errors', false, $content);
924 // Delete all to prevent double-display
928 loadIncludeOnce('inc/footer.php');
934 // Filter for displaying copyright line
935 function FILTER_DISPLAY_COPYRIGHT () {
936 // Shall we display the copyright notice?
937 if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
939 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
940 // Copyright with backlink, thanks! :-)
941 $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
943 // No backlink in Copyright note
944 $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
949 // Filter for displaying parsing time
950 function FILTER_DISPLAY_PARSING_TIME () {
951 // Shall we display the parsing time and number of queries?
952 // 1234 5 54 4 5 5 4 4 5 543 3 4432 2 33 2 2 21
953 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
954 // Then display it here
955 displayParsingTime();
959 // Filter for flushing template cache
960 function FILTER_FLUSH_TEMPLATE_CACHE () {
961 // Do not flush when debugging the template cache
962 if (isDebuggingTemplateCache()) return;
964 // Do we have cached eval() data?
965 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
967 foreach ($GLOBALS['template_eval'] as $template => $eval) {
968 // Flush the cache (if not yet found)
969 flushTemplateCache($template, $eval);
974 // Filter for loading user data
975 function FILTER_FETCH_USER_DATA ($userid = NULL) {
976 // Is the userid not set? Then use member id
977 if (!isValidUserId($userid)) {
978 $userid = getMemberId();
982 if (!fetchUserData($userid)) {
983 // Userid is not valid
984 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
988 setMemberId($userid);
991 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
992 function FILTER_RESET_USER_LOGIN_FAILURE () {
993 // Is the user data valid?
995 // Do only run for logged in members
996 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
999 // Remmeber login failures if available
1000 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1001 // Reset login failures
1002 SQL_QUERY_ESC("UPDATE
1003 `{?_MYSQL_PREFIX?}_user_data`
1010 array(getMemberId()), __FUNCTION__, __LINE__);
1012 // Store it in session
1013 setSession('mailer_member_failures' , getUserData('login_failures'));
1014 setSession('mailer_member_last_failure', getUserData('last_failure'));
1018 // Try to login the admin by setting some session/cookie variables
1019 function FILTER_DO_LOGIN_ADMIN ($filterData) {
1020 // Now set all session variables and store the result for later processing
1021 $GLOBALS['admin_login_success'] = ((
1022 setAdminMd5(encodeHashForCookie($filterData['pass_hash']))
1024 setAdminId($filterData['id'])
1026 setAdminLast(time())
1029 // Return the data for further processing
1033 // Filter for loading page header, this should be ran first!
1034 function FILTER_LOAD_PAGE_HEADER () {
1035 // Output page header code
1036 $GLOBALS['page_header'] = loadTemplate('page_header', true);
1038 // Include meta data in 'guest' module
1039 if (getModule() == 'index') {
1040 // Load meta data template
1041 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
1043 // Add meta description to header
1044 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1045 // Add meta description not in admin and login module and when the script is installed
1046 generateMetaDescriptionCode();
1051 // Filter for adding style sheet, closing page header
1052 function FILTER_FINISH_PAGE_HEADER () {
1053 // Include stylesheet
1054 loadIncludeOnce('inc/stylesheet.php');
1057 $GLOBALS['page_header'] .= '</head>';
1060 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1061 function FILTER_CLEANUP_DNS_CACHE () {
1062 // Is the latest version installed?
1063 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1065 loadIncludeOnce('inc/classes/resolver.class.php');
1067 // Instance the resolver
1068 $resolver = new HostnameResolver();
1071 $resolver->purgeEntries();
1073 // Cute, isn't it? ;-)
1077 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1078 function FILTER_SET_CURRENT_DATE () {
1080 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1082 // Epoche time for yesterday, today ... all at 00:00 am
1083 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1084 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1087 // Filter for marking extension as installed
1088 function FILTER_EXTENSION_MARK_INSTALLED ($filterData) {
1089 // Mark it as installed
1090 $GLOBALS['ext_is_installed'][$filterData['ext_name']] = true;
1093 // Filter for generating mails links for 'pool' mails
1094 function FILTER_GENERATE_POOL_MAIL_LINKS ($filterData) {
1096 if ($filterData['type'] == 'mid') {
1098 $filterData['__output'] .= loadTemplate('admin_links_' . strtolower($filterData['mail_status']) . '_pool_mail', true, $filterData);
1105 // Filter to activate exchange
1106 function FILTER_ACTIVATE_EXCHANGE () {
1107 // Is the extension 'user' there?
1108 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1109 // Silently abort here
1113 // Check total amount of users
1114 if (getTotalConfirmedUser() >= getActivateXchange()) {
1116 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1");
1117 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1120 runFilterChain('run_sqls');
1122 // Update configuration
1123 updateConfiguration('activate_xchange' ,0);
1126 rebuildCache('modules', 'modules');
1130 // Filter to handle configuration
1131 function FILTER_HANDLE_HOME_IN_INDEX_SETTING ($filterData) {
1132 // Is ext-sql_patches up-to-date?
1133 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled())) {
1134 // Is 'search' as same as 'index_home'?
1135 if ($filterData['search'] == getIndexHome()) {
1136 // Then set 'content' to link to index.php
1137 $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>';
1145 // Filter to add history entry
1146 function FILTER_ADD_HISTORY_ENTRY ($filterData) {
1148 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_history` (`history_subject`,`history_userid`,`history_value`) VALUES('%s',%s,'%s')",
1150 __FUNCTION__, __LINE__);
1152 // Remember insert id for other filters
1153 $filterData['history_id'] = SQL_INSERTID();