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 ($data) {
139 // Handle failed logins here if not in guest
140 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $data['type'] . ',action=' . getAction() . ',what=' . getWhat() . ',level=' . $data['access_level']);
141 if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getIndexHome()))) && ($data['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.6')))) {
143 $content['content'] .= handleLoginFailures($data['access_level']);
146 // Return the content
150 // Filter for redirecting to logout if sql_patches has been installed
151 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
152 // Remove this filter
153 unregisterFilter(__FUNCTION__, __LINE__, 'shutdown', __FUNCTION__);
155 // Is the element set?
156 if (isset($GLOBALS['ext_load_mode'])) {
158 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
161 // This should not happen!
162 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
165 // Filter for auto-activation of a extension
166 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
168 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $data['ext_name'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
170 // Is this extension always activated?
171 if (isThisExtensionAlwaysActive()) {
172 // Then activate the extension
173 doActivateExtension($data['ext_name']);
180 // Filter for solving task given task
181 function FILTER_SOLVE_TASK ($data) {
182 // Don't solve anything if no admin!
183 if (!isAdmin()) return $data;
185 // Is this a direct task id or array element task_id is found?
188 adminSolveTask($data);
189 } elseif ((is_array($data)) && (isset($data['task_id']))) {
191 adminSolveTask($data['task_id']);
194 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
201 // Filter to load include files
202 function FILTER_LOAD_INCLUDES ($pool) {
204 if (is_null($pool)) {
205 // This should not happen!
206 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
209 // Is the pool an array and 'pool' set?
210 if ((is_array($pool)) && (isset($pool['pool']))) {
211 // Then use it as pool
212 $realPool = $pool['pool'];
214 // Default is $data as inclusion list
219 $data = getIncludePool($realPool);
222 if ((!isset($data)) || (!is_array($data))) {
224 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
225 } elseif (isset($data['inc_pool'])) {
226 // Use this as new inclusion pool!
227 setIncludePool($realPool, $data['inc_pool']);
230 // Check for added include files
231 if (countIncludePool($realPool) > 0) {
232 // Loads every include file
233 loadIncludePool($realPool);
236 initIncludePool($realPool);
239 // Continue with processing
243 // Filter for running SQL commands
244 function FILTER_RUN_SQLS ($data) {
246 //* DEBUG: */ die('getSqls()=<pre>'.print_r(getSqls(), true).'</pre>ext_update_depends=<pre>'.print_r($GLOBALS['ext_update_depends'], true).'</pre>');
247 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
249 // Is the array there?
250 if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
252 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
253 foreach (getSqls() as $mode=>$sqls) {
255 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
257 // New cache format...
258 foreach ($sqls as $sql) {
262 // Is 'enable_codes' not set? Then set it to true
263 if (!isset($data['enable_codes'])) {
264 $data['enable_codes'] = true;
267 // Is there still a query left?
269 // Do we have an "ALTER TABLE" command?
270 if (substr(strtolower($sql), 0, 11) == 'alter table') {
271 // Analyse the alteration command
272 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
273 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
275 // Run regular SQL command
276 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
277 SQL_QUERY($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
285 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
288 // Filter for updating/validating login data
289 function FILTER_UPDATE_LOGIN_DATA () {
291 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
292 $GLOBALS['last_online'] = array();
295 // Recheck if logged in
301 setMemberId(getSession('userid'));
304 if (fetchUserData(getMemberId())) {
305 // Load last module and online time
306 $content = getUserDataArray();
308 // Maybe first login time?
309 if (empty($content['last_module'])) {
310 $content['last_module'] = 'login';
313 // This will be displayed on welcome page! :-)
314 if (empty($GLOBALS['last_online']['module'])) {
315 $GLOBALS['last_online']['module'] = $content['last_module'];
316 $GLOBALS['last_online']['online'] = $content['last_online'];
323 if (getIndexHome() != '') {
324 setWhatFromConfig('index_home');
328 // Update last module / online time
329 updateLastActivity(getMemberId());
331 // Destroy session, we cannot update!
332 destroyMemberSession();
336 // Filter for initializing randomizer
337 function FILTER_INIT_RANDOMIZER () {
338 // Take a prime number which is long (if you know a longer one please try it out!)
339 setConfigEntry('_PRIME', 591623);
341 // Only execute this filter if installed
342 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
344 setConfigEntry('_ADD', 0);
348 // Calculate "entropy" with the prime number (for code generation)
349 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
351 // Simply init the randomizer with seed and _ADD value
352 mt_srand(generateSeed() + getConfig('_ADD'));
355 // Filter for removing updates
356 function FILTER_REMOVE_UPDATES ($data) {
358 initExtensionRemovalList();
360 // Add the current extension to it
361 addCurrentExtensionToRemovalList();
364 unsetExtensionSqls();
366 // Do we need to remove update depency?
367 if (countExtensionUpdateDependencies() > 0) {
368 // Then find all updates we shall no longer execute
369 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
370 // Shall we remove this update?
371 if (in_array($ext_name, getExtensionRemovalList())) {
372 // Then remove this extension!
373 removeExtensionDependency($ext_name);
382 // Determines username for current user state
383 function FILTER_DETERMINE_USERNAME () {
384 // Check if logged in
386 // Is still logged in so we welcome him with his name
387 if (fetchUserData(getMemberId())) {
388 // Load surname and family's name and build the username
389 $content = getUserDataArray();
392 setUsername($content['surname'] . ' ' . $content['family']);
394 // Additionally admin?
397 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
400 // Hmmm, logged in and no valid userid?
401 setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
404 destroyMemberSession();
406 } elseif (isAdmin()) {
408 setUsername('{--USERNAME_ADMIN--}');
410 // He's a guest, hello there... ;-)
411 setUsername('{--USERNAME_GUEST--}');
415 // Filter for compiling config entries
416 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
417 // Save the uncompiled code
421 if (!isset($GLOBALS['compiled_config'][$code])) {
422 // Compile {?some_var?} to getConfig('some_var')
423 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
425 // Some entries found?
426 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
427 // Replace all matches
428 foreach ($matches[0] as $key => $match) {
430 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
431 // Is the config valid?
432 if (isConfigEntrySet($matches[1][$key])) {
433 // Set it for caching
434 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
435 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
437 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
438 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
439 // No config, try the language system
440 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
443 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
447 // Use this for replacing
448 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
449 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
454 $GLOBALS['compiled_config'][$uncompiled] = $code;
457 // Should we compile it?
458 if ($compiled === true) {
460 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
461 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
465 // Return compiled code
466 return $GLOBALS['compiled_config'][$uncompiled];
469 // Filter for compiling expression code
470 function FILTER_COMPILE_EXPRESSION_CODE ($code) {
471 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
472 // See switch() command below for supported commands
473 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
474 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
476 // Default is from outputHtml()
477 $outputMode = getScriptOutputMode();
479 // Some entries found?
480 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
481 // Replace all matches
482 foreach ($matches[2] as $key => $cmd) {
483 // Init replacer/call-back variable
487 $extraFunction2 = '';
490 // Extract command and call-back
491 $cmdArray = explode(',', $cmd);
494 // Detect call-back function
495 if (isset($cmdArray[1])) {
496 // Call-back function detected
497 $callback = $cmdArray[1];
500 // Detect extra function
501 if (isset($cmdArray[2])) {
503 $extraFunction = $cmdArray[2];
506 // Detect extra function 2
507 if (isset($cmdArray[3])) {
509 $extraFunction2 = $cmdArray[3];
513 if (isset($matches[4][$key])) {
515 $value = $matches[4][$key];
518 // Construct call-back function name for the command
519 $commandFunction = 'doExpression' . capitalizeUnderscoreString($cmd);
521 // Is this function there?
522 if (function_exists($commandFunction)) {
523 // Prepare $matches, $key, $outputMode, etc.
525 'matches' => $matches,
527 'mode' => getScriptOutputMode(),
529 'callback' => $callback,
530 'extra_func' => $extraFunction,
531 'extra_func2' => $extraFunction2,
536 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
537 $code = call_user_func($commandFunction, $data);
539 // Unsupported command detected
540 logDebugMessage(__FUNCTION__, __LINE__, 'Command cmd=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
545 // Do we have non-HTML mode?
546 if (!isHtmlOutputMode()) {
547 $code = decodeEntities($code);
550 // Return compiled code
551 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($code).'</pre>');
555 // Runs some generic filter update steps
556 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
557 // Create task (we ignore the task id here)
558 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
560 // Update extension's version
561 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
562 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
566 unset($GLOBALS['update_ver'][$ext_name]);
569 // Load more hourly reset scripts
570 function FILTER_RUN_HOURLY_INCLUDES () {
571 // Is the reset set or old sql_patches?
572 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
574 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');
577 // Get more hourly reset scripts
578 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
581 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
582 updateConfiguration('last_hour', getHour());
586 runFilterChain('load_includes', 'hourly');
589 // Load more reset scripts
590 function FILTER_RUN_RESET_INCLUDES () {
591 // Is the reset set or old sql_patches?
592 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
594 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
597 // Get more daily reset scripts
598 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
601 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
602 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
605 // Is the config entry set?
606 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
608 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
609 // Include weekly reset scripts
610 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
612 // Update config if not in debug mode
613 if (!isWeeklyResetDebugEnabled()) {
614 updateConfiguration('last_week', getWeek());
618 // Create current month mark
619 $currMonth = getMonth();
622 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
623 // Include monthly reset scripts
624 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
627 if (!isMonthlyResetDebugEnabled()) {
628 updateConfiguration('last_month', $currMonth);
634 runFilterChain('load_includes', 'reset');
637 // Filter for removing the given extension
638 function FILTER_REMOVE_EXTENSION () {
639 // Delete this extension (remember to remove it from your server *before* you click on welcome!
640 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
641 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
643 // Remove the extension from cache array as well
644 removeExtensionFromArray();
647 rebuildCache('extension', 'extension');
650 // Filter for flushing the output
651 function FILTER_FLUSH_OUTPUT () {
656 // Prepares an SQL statement part for HTML mail and/or holiday depency
657 function FILTER_HTML_INCLUDE_USERS ($mode) {
658 // Exclude no users by default
662 if ($mode == 'html') $MORE = " AND `html`='Y'";
663 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
664 // Add something for the holiday extension
665 $MORE .= " AND `holiday_active`='N'";
672 // Filter for determining what/action/module
673 function FILTER_DETERMINE_WHAT_ACTION () {
674 // In installation phase we don't have what/action
675 if (isInstallationPhase()) {
685 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
687 if (!isModuleSet()) {
688 // Is the request element set?
689 if (isGetRequestParameterSet('module')) {
690 // Set module from request
691 setModule(getRequestParameter('module'));
692 } elseif (isHtmlOutputMode()) {
693 // Set default module 'index'
697 setModule('unknown');
701 // Fix 'what' if not yet set
703 setWhat(getWhatFromModule(getModule()));
706 // Fix 'action' if not yet set
707 if (!isActionSet()) {
708 setAction(getActionFromModuleWhat(getModule(), getWhat()));
711 // Set action/what to empty
716 // Set default 'what' value
717 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
718 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
719 if (getModule() == 'admin') {
720 // Set 'action' value to 'login' in admin menu
721 setAction(getActionFromModuleWhat(getModule(), getWhat()));
722 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
723 // Set 'what' value to 'welcome' in guest and member menu
724 setWhatFromConfig('index_home');
726 // Anything else like begging link
732 // Sends out pooled mails
733 function FILTER_TRIGGER_SENDING_POOL () {
734 // Are we in normal output mode?
735 if (!isHtmlOutputMode()) {
736 // Only in normal output mode to prevent race-conditons!
740 $GLOBALS['pool_cnt'] = '0';
742 // Init & set the include pool
743 initIncludePool('pool');
744 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
747 runFilterChain('load_includes', 'pool');
749 // Remove the counter
750 unset($GLOBALS['pool_cnt']);
753 // Filter for checking and updating SVN revision
754 function FILTER_CHECK_REPOSITORY_REVISION () {
755 // Only execute this filter if installed and all config entries are there
756 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
758 // Check for patch level differences between database and current hard-coded
759 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
760 // Update database and CONFIG array
761 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
762 setConfigEntry('patch_level', getCurrentRepositoryRevision());
763 setConfigEntry('patch_ctime', time());
767 // Filter for running daily reset
768 function FILTER_RUN_DAILY_RESET () {
769 // Only execute this filter if installed
770 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
774 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
775 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
776 // Tell every module we are in reset-mode!
781 // Filter for running hourly reset
782 function FILTER_RUN_HOURLY_RESET () {
783 // Only execute this filter if installed
784 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
788 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
789 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
790 // Tell every module we are in reset-mode!
795 // Filter for loading more runtime includes (not for installation)
796 function FILTER_LOAD_RUNTIME_INCLUDES () {
797 // Load more includes
798 foreach (array('databases', 'session', 'versions') as $inc) {
800 loadIncludeOnce('inc/' . $inc . '.php');
804 // Filter for checking admin ACL
805 function FILTER_CHECK_ADMIN_ACL () {
806 // Extension not installed so it's always allowed to access everywhere!
809 // Ok, Cookie-Update done
810 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
811 // Check if action GET variable was set
812 $action = getAction();
814 // Get action value by what-value
815 $action = getActionFromModuleWhat('admin', getWhat());
818 // Check for access control line of current menu entry
819 $ret = isAdminsAllowedByAcl($action, getWhat());
823 $GLOBALS['acl_allow'] = $ret;
826 // Init random number/cache buster
827 function FILTER_INIT_RANDOM_NUMBER () {
828 // Is the extension ext-sql_patches installed and at least 0.3.6?
829 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
830 // Generate random number
831 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
833 // Generate *WEAK* code
834 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
837 // Copy it to CACHE_BUSTER
838 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
841 // Update module counter
842 function FILTER_COUNT_MODULE () {
843 // Do count all other modules but not accesses on CSS file css.php!
844 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
845 array(getModule()), __FUNCTION__, __LINE__);
848 // Handles fatal errors
849 function FILTER_HANDLE_FATAL_ERRORS () {
850 // Do we have errors to handle and right output mode?
851 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
852 // Abort executing here
857 setContentType('text/html');
860 loadIncludeOnce('inc/load_config.php');
862 // Set unset variable
863 if (empty($check)) $check = '';
868 // Installation phase or regular mode?
869 if ((isInstallationPhase())) {
870 // While we are installing ouput other header than while it is installed... :-)
872 foreach (getFatalArray() as $key => $value) {
873 // Prepare content for the template
880 $OUT .= loadTemplate('install_fatal_row', true, $content);
883 // Load main template
884 $content = loadTemplate('install_fatal_table', true, $OUT);
885 } elseif (isInstalled()) {
886 // Display all runtime fatal errors
888 foreach (getFatalArray() as $key => $value) {
889 // Prepare content for the template
896 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
899 // Load main template
900 $content = loadTemplate('runtime_fatal_table', true, $OUT);
903 // Message to regular users (non-admin)
904 $CORR = '{--FATAL_REPORT_ERRORS--}';
906 // PHP warnings fixed
907 if ($check == 'done') {
908 if (isAdmin()) $CORR = '{--FATAL_CORRECT_ERRORS--}';
911 // Remember all in array
918 loadIncludeOnce('inc/header.php');
920 // Load main template
921 loadTemplate('fatal_errors', false, $content);
923 // Delete all to prevent double-display
927 loadIncludeOnce('inc/footer.php');
933 // Filter for displaying copyright line
934 function FILTER_DISPLAY_COPYRIGHT () {
935 // Shall we display the copyright notice?
936 if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
938 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
939 // Copyright with backlink, thanks! :-)
940 $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
942 // No backlink in Copyright note
943 $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
948 // Filter for displaying parsing time
949 function FILTER_DISPLAY_PARSING_TIME () {
950 // Shall we display the parsing time and number of queries?
951 // 1234 5 54 4 5 5 4 4 5 543 3 4432 2 33 2 2 21
952 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
953 // Then display it here
954 displayParsingTime();
958 // Filter for flushing template cache
959 function FILTER_FLUSH_TEMPLATE_CACHE () {
960 // Do not flush when debugging the template cache
961 if (isDebuggingTemplateCache()) return;
963 // Do we have cached eval() data?
964 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
966 foreach ($GLOBALS['template_eval'] as $template => $eval) {
967 // Flush the cache (if not yet found)
968 flushTemplateCache($template, $eval);
973 // Filter for loading user data
974 function FILTER_FETCH_USER_DATA ($userid = NULL) {
975 // Is the userid not set? Then use member id
976 if (!isValidUserId($userid)) {
977 $userid = getMemberId();
981 if (!fetchUserData($userid)) {
982 // Userid is not valid
983 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
987 setMemberId($userid);
990 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
991 function FILTER_RESET_USER_LOGIN_FAILURE () {
992 // Is the user data valid?
994 // Do only run for logged in members
995 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
998 // Remmeber login failures if available
999 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1000 // Reset login failures
1001 SQL_QUERY_ESC("UPDATE
1002 `{?_MYSQL_PREFIX?}_user_data`
1009 array(getMemberId()), __FUNCTION__, __LINE__);
1011 // Store it in session
1012 setSession('mailer_member_failures' , getUserData('login_failures'));
1013 setSession('mailer_member_last_failure', getUserData('last_failure'));
1017 // Try to login the admin by setting some session/cookie variables
1018 function FILTER_DO_LOGIN_ADMIN ($data) {
1019 // Now set all session variables and store the result for later processing
1020 $GLOBALS['admin_login_success'] = ((
1021 setAdminMd5(encodeHashForCookie($data['pass_hash']))
1023 setAdminId($data['id'])
1025 setAdminLast(time())
1028 // Return the data for further processing
1032 // Filter for loading page header, this should be ran first!
1033 function FILTER_LOAD_PAGE_HEADER () {
1034 // Output page header code
1035 $GLOBALS['page_header'] = loadTemplate('page_header', true);
1037 // Include meta data in 'guest' module
1038 if (getModule() == 'index') {
1039 // Load meta data template
1040 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
1042 // Add meta description to header
1043 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1044 // Add meta description not in admin and login module and when the script is installed
1045 generateMetaDescriptionCode();
1050 // Filter for adding style sheet, closing page header
1051 function FILTER_FINISH_PAGE_HEADER () {
1052 // Include stylesheet
1053 loadIncludeOnce('inc/stylesheet.php');
1056 $GLOBALS['page_header'] .= '</head>';
1059 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1060 function FILTER_CLEANUP_DNS_CACHE () {
1061 // Is the latest version installed?
1062 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1064 loadIncludeOnce('inc/classes/resolver.class.php');
1066 // Instance the resolver
1067 $resolver = new HostnameResolver();
1070 $resolver->purgeEntries();
1072 // Cute, isn't it? ;-)
1076 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1077 function FILTER_SET_CURRENT_DATE () {
1079 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1081 // Epoche time for yesterday, today ... all at 00:00 am
1082 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1083 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1086 // Filter for marking extension as installed
1087 function FILTER_EXTENSION_MARK_INSTALLED ($data) {
1088 // Mark it as installed
1089 $GLOBALS['ext_is_installed'][$data['ext_name']] = true;
1092 // Filter for generating mails links for 'pool' mails
1093 function FILTER_GENERATE_POOL_MAIL_LINKS ($data) {
1095 if ($data['type'] == 'mid') {
1097 $data['__output'] .= loadTemplate('admin_links_' . strtolower($data['mail_status']) . '_pool_mail', true, $data);
1104 // Filter to activate exchange
1105 function FILTER_ACTIVATE_EXCHANGE () {
1106 // Is the extension 'user' there?
1107 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1108 // Silently abort here
1112 // Check total amount of users
1113 if (getTotalConfirmedUser() >= getActivateXchange()) {
1115 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N', `hidden`='N', `mem_only`='Y' WHERE `module`='order' LIMIT 1");
1116 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y', `locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1119 runFilterChain('run_sqls');
1121 // Update configuration
1122 updateConfiguration('activate_xchange' ,0);
1125 rebuildCache('modules', 'modules');