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 - 2012 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 reportBug(__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() == 'welcome') || (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 reportBug(__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 reportBug(__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 reportBug(__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) {
255 //* DEBUG: */ die('getSqls()=<pre>'.print_r(getSqls(), true).'</pre>ext_update_depends=<pre>'.print_r($GLOBALS['ext_update_depends'], true).'</pre>');
256 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
258 // Is the array there?
259 if ((isSqlsValid()) && ((!isset($filterData['dry_run'])) || ($filterData['dry_run'] == false))) {
261 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
262 foreach (getSqls() as $mode => $sqls) {
264 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
266 // New cache format...
267 foreach ($sqls as $sql) {
271 // Is 'enable_codes' not set? Then set it to true
272 if (!isset($filterData['enable_codes'])) {
273 $filterData['enable_codes'] = true;
276 // Is there still a query left?
278 // Do we have an "ALTER TABLE" command?
279 if (substr(strtolower($sql), 0, 11) == 'alter table') {
280 // Analyse the alteration command
281 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
282 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
284 // Run regular SQL command
285 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
286 SQL_QUERY($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
289 // Has a line changed?
290 if (!SQL_HASZEROAFFECTED()) {
291 // Add it to total account
292 $count += SQL_AFFECTEDROWS();
300 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
302 // Clear any SQL queries
309 // Filter for updating/validating login data
310 function FILTER_UPDATE_LOGIN_DATA () {
312 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
313 $GLOBALS['last_online'] = array();
316 // Recheck if logged in
317 if ((!isMember()) || ((isAdmin()) && (!isDebugModeEnabled()))) {
322 setMemberId(getSession('userid'));
325 if (fetchUserData(getMemberId())) {
326 // Load last module and online time
327 $content = getUserDataArray();
329 // Maybe first login time?
330 if (empty($content[getUserLastWhatName()])) {
331 $content[getUserLastWhatName()] = 'login';
334 // This will be displayed on welcome page! :-)
335 if (empty($GLOBALS['last_online']['module'])) {
336 $GLOBALS['last_online']['module'] = $content[getUserLastWhatName()];
337 $GLOBALS['last_online']['online'] = $content['last_online'];
344 if (getIndexHome() != '') {
345 setWhatFromConfig('index_home');
349 // Update last module / online time
350 updateLastActivity(getMemberId());
352 // Destroy session, we cannot update!
353 destroyMemberSession();
357 // Filter for initializing randomizer
358 function FILTER_INIT_RANDOMIZER () {
359 // Take a prime number which is long (if you know a longer one please try it out!)
360 setConfigEntry('_PRIME', 591623);
362 // Only execute this filter if installed
363 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
365 setConfigEntry('_ADD', 0);
369 // Calculate "entropy" with the prime number (for code generation)
370 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
372 // Simply init the randomizer with seed and _ADD value
373 mt_srand(generateSeed() + getConfig('_ADD'));
376 // Filter for removing updates
377 function FILTER_REMOVE_UPDATES ($filterData) {
379 initExtensionRemovalList();
381 // Add the current extension to it
382 addCurrentExtensionToRemovalList();
385 unsetExtensionSqls();
387 // Do we need to remove update depency?
388 if (countExtensionUpdateDependencies() > 0) {
389 // Then find all updates we shall no longer execute
390 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
391 // Shall we remove this update?
392 if (in_array($ext_name, getExtensionRemovalList())) {
393 // Then remove this extension!
394 removeExtensionDependency($ext_name);
403 // Determines username for current user state
404 function FILTER_DETERMINE_USERNAME () {
405 // Check if logged in
407 // Is still logged in so we welcome him with his name
408 if (fetchUserData(getMemberId())) {
409 // Load surname and family's name and build the username
410 $content = getUserDataArray();
413 setUsername($content['surname'] . ' ' . $content['family']);
415 // Additionally admin?
418 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
421 // Hmmm, logged in and no valid userid?
422 setUsername('<span class="bad">{--USERNAME_UNKNOWN--}</span>');
425 destroyMemberSession();
427 } elseif (isAdmin()) {
429 setUsername('{--USERNAME_ADMIN--}');
431 // He's a guest, hello there... ;-)
432 setUsername('{--USERNAME_GUEST--}');
436 // Filter for compiling config entries
437 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
438 // Save the uncompiled code
442 if (!isset($GLOBALS['compiled_config'][$code])) {
443 // Compile {?some_var?} to getConfig('some_var')
444 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
446 // Some entries found?
447 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
448 // Replace all matches
449 foreach ($matches[0] as $key => $match) {
451 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
452 // Is the config valid?
453 if (isConfigEntrySet($matches[1][$key])) {
454 // Set it for caching
455 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
456 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
458 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
459 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
460 // No config, try the language system
461 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
464 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
468 // Use this for replacing
469 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
470 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
475 $GLOBALS['compiled_config'][$uncompiled] = $code;
478 // Should we compile it?
479 if ($compiled === true) {
481 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
482 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
486 // Return compiled code
487 return $GLOBALS['compiled_config'][$uncompiled];
490 // Filter for compiling expression code
491 function FILTER_COMPILE_EXPRESSION_CODE ($filterData) {
492 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
493 // See switch() command below for supported commands
494 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $filterData, $matches);
495 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
497 // Default is from outputHtml()
498 $outputMode = getScriptOutputMode();
500 // Some entries found?
501 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
502 // Replace all matches
503 foreach ($matches[2] as $key => $eti) {
504 // Init replacer/call-back variable
508 $extraFunction2 = '';
511 // Extract command and call-back
512 $etiArray = explode(',', $eti);
515 // Detect call-back function
516 if (isset($etiArray[1])) {
517 // Call-back function detected
518 $callback = $etiArray[1];
521 // Detect extra function
522 if (isset($etiArray[2])) {
524 $extraFunction = $etiArray[2];
527 // Detect extra function 2
528 if (isset($etiArray[3])) {
530 $extraFunction2 = $etiArray[3];
534 if (isset($matches[4][$key])) {
536 $value = $matches[4][$key];
539 // Construct call-back function name for the command
540 $etiFunction = 'doExpression' . capitalizeUnderscoreString($eti);
542 // Is this function there?
543 if (function_exists($etiFunction)) {
544 // Prepare $matches, $key, $outputMode, etc.
546 'matches' => $matches,
548 'output_mode' => getScriptOutputMode(),
549 'code' => $filterData,
550 'callback' => $callback,
551 'extra_func' => $extraFunction,
552 'extra_func2' => $extraFunction2,
557 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: etiFunction=' . $etiFunction);
558 $filterData = call_user_func($etiFunction, $data);
560 // Unsupported command detected
561 logDebugMessage(__FUNCTION__, __LINE__, 'eti=' . $eti . ', callback=' . $callback . ', extra=' . $extraFunction . ' - unsupported');
566 // Do we have non-HTML mode?
567 if (!isHtmlOutputMode()) {
568 $filterData = decodeEntities($filterData);
571 // Return compiled code
572 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($filterData).'</pre>');
576 // Runs some generic filter update steps
577 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
578 // Create task (we ignore the task id here)
579 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
581 // Update extension's version
582 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
583 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
587 unset($GLOBALS['update_ver'][$ext_name]);
590 // Load more hourly reset scripts
591 function FILTER_RUN_HOURLY_INCLUDES () {
592 // Is the reset set or old sql_patches?
593 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
595 reportBug(__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');
598 // Get more hourly reset scripts
599 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
602 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
603 updateConfiguration('last_hour', getHour());
607 runFilterChain('load_includes', 'hourly');
610 // Load more reset scripts
611 function FILTER_RUN_RESET_INCLUDES () {
612 // Is the reset set or old sql_patches?
613 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
615 reportBug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
618 // Get more daily reset scripts
619 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
621 // Update configuration if this reset is not being debugged
622 if (!isDebugResetEnabled()) {
623 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
626 // Is the config entry set?
627 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
629 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
630 // Include weekly reset scripts
631 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
633 // Update configuration if this reset is not being debugged
634 if (!isWeeklyResetDebugEnabled()) {
635 updateConfiguration('last_week', getWeek());
639 // Create current month mark
640 $currMonth = getMonth();
643 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
644 // Include monthly reset scripts
645 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
647 // Update configuration if this reset is not being debugged
648 if (!isMonthlyResetDebugEnabled()) {
649 updateConfiguration('last_month', $currMonth);
655 runFilterChain('load_includes', 'reset');
658 // Filter for removing the given extension
659 function FILTER_REMOVE_EXTENSION () {
660 // Delete this extension (remember to remove it from your server *before* you click on welcome!
661 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
662 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
664 // Remove the extension from cache array as well
665 removeExtensionFromArray();
668 rebuildCache('extension', 'extension');
671 // Filter for flushing the output
672 function FILTER_FLUSH_OUTPUT () {
677 // Prepares an SQL statement part for HTML mail and/or holiday dependency
678 function FILTER_HTML_INCLUDE_USERS ($mode) {
679 // Exclude no users by default
683 if ($mode == 'html') {
684 $MORE = " AND `html`='Y'";
687 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
688 // Add something for the holiday extension
689 $MORE .= " AND `holiday_active`='N'";
696 // Filter for determining what/action/module
697 function FILTER_DETERMINE_WHAT_ACTION () {
698 // In installation phase we don't have what/action
699 if (isInstallationPhase()) {
709 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
711 if (!isModuleSet()) {
712 // Is the request element set?
713 if (isGetRequestElementSet('module')) {
714 // Set module from request
715 setModule(getRequestElement('module'));
716 } elseif (isHtmlOutputMode()) {
717 // Set default module 'index'
721 setModule('unknown');
725 // Fix 'what' if not yet set
727 setWhat(getWhatFromModule(getModule()));
730 // Fix 'action' if not yet set
731 if (!isActionSet()) {
735 setAction(getActionFromModuleWhat(getModule(), getWhat()));
737 // Set action/what to empty
743 // Set action/what to empty
748 // Set default 'what' value
749 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
750 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
751 if (getModule() == 'admin') {
752 // Set 'action' value to 'login' in admin menu
753 setAction(getActionFromModuleWhat(getModule(), getWhat()));
754 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
755 // Set 'what' value to 'welcome' in guest and member menu
756 setWhatFromConfig('index_home');
758 // Anything else like begging link
764 // Sends out pooled mails
765 function FILTER_TRIGGER_SENDING_POOL () {
766 // Are we in normal output mode?
767 if (!isHtmlOutputMode()) {
768 // Only in normal output mode to prevent race-conditons!
772 $GLOBALS['pool_cnt'] = '0';
774 // Init & set the include pool
775 initIncludePool('pool');
776 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
779 runFilterChain('load_includes', 'pool');
781 // Remove the counter
782 unset($GLOBALS['pool_cnt']);
785 // Filter for checking and updating SVN revision
786 function FILTER_CHECK_REPOSITORY_REVISION () {
787 // Only execute this filter if installed and all config entries are there
788 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
790 // Check for patch level differences between database and current hard-coded
791 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
792 // Update database and CONFIG array
793 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
794 setConfigEntry('patch_level', getCurrentRepositoryRevision());
795 setConfigEntry('patch_ctime', time());
799 // Filter for running daily reset
800 function FILTER_RUN_DAILY_RESET () {
801 // Only execute this filter if installed
802 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
806 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
807 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
808 // Tell every module we are in reset-mode!
813 // Filter for running hourly reset
814 function FILTER_RUN_HOURLY_RESET () {
815 // Only execute this filter if installed
816 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
820 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
821 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
822 // Tell every module we are in reset-mode!
827 // Filter for loading more runtime includes (not for installation)
828 function FILTER_LOAD_RUNTIME_INCLUDES () {
829 // Load more includes
830 foreach (array('databases', 'session', 'versions') as $inc) {
832 loadIncludeOnce('inc/' . $inc . '.php');
836 // Filter for checking admin ACL
837 function FILTER_CHECK_ADMIN_ACL () {
838 // Extension not installed so it's always allowed to access everywhere!
841 // Ok, Cookie-Update done
842 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
843 // Check if action GET variable was set
844 $action = getAction();
846 // Get action value by what-value
847 $action = getActionFromModuleWhat('admin', getWhat());
850 // Check for access control line of current menu entry
851 $ret = isAdminsAllowedByAcl($action, getWhat());
855 $GLOBALS['acl_allow'] = $ret;
858 // Init random number/cache buster
859 function FILTER_INIT_RANDOM_NUMBER () {
860 // Is the extension ext-sql_patches installed and at least 0.3.6?
861 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
862 // Generate random number
863 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 99999), getMemberId(), ''));
865 // Generate *WEAK* code
866 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
869 // Copy it to CACHE_BUSTER
870 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
873 // Update module counter
874 function FILTER_COUNT_MODULE () {
875 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ' - ENTERED!');
876 // Do count all other modules but not accesses on CSS file css.php!
877 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
878 array(getModule()), __FUNCTION__, __LINE__);
879 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
882 // Handles fatal errors
883 function FILTER_HANDLE_FATAL_ERRORS () {
884 // Do we have errors to handle and right output mode?
885 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
886 // Abort executing here
891 setContentType('text/html');
894 loadIncludeOnce('inc/load_config.php');
896 // Default content is none
899 // Installation phase or regular mode?
900 if ((isInstallationPhase())) {
901 // While we are installing ouput other header than while it is installed... :-)
903 foreach (getFatalArray() as $key => $value) {
904 // Prepare content for the template
911 $OUT .= loadTemplate('install_fatal_row', true, $content);
914 // Load main template
915 $content = loadTemplate('install_fatal_table', true, $OUT);
916 } elseif (isInstalled()) {
917 // Display all runtime fatal errors
919 foreach (getFatalArray() as $key => $value) {
920 // Prepare content for the template
927 $OUT .= loadTemplate('runtime_fatal_row', true, $content);
930 // Load main template
931 $content = loadTemplate('runtime_fatal_table', true, $OUT);
934 // Message to regular users (non-admin)
935 $CORR = '{--FATAL_REPORT_ERRORS--}';
937 // Maybe the admin wants to take a look?
939 $CORR = '{--FATAL_CORRECT_ERRORS--}';
942 // Remember all in array
949 loadIncludeOnce('inc/header.php');
951 // Load main template
952 loadTemplate('fatal_errors', false, $content);
954 // Delete all to prevent double-display
958 loadIncludeOnce('inc/footer.php');
964 // Filter for displaying copyright line
965 function FILTER_DISPLAY_COPYRIGHT () {
966 // Shall we display the copyright notice?
967 if ((isFullPage()) && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['__header_sent'] == 2) && (ifCopyrightFooterEnabled())) {
969 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
970 // Copyright with backlink, thanks! :-)
971 $GLOBALS['__page_footer'] .= loadTemplate('copyright_backlink', true);
973 // No backlink in Copyright note
974 $GLOBALS['__page_footer'] .= loadTemplate('copyright', true);
979 // Filter for displaying parsing time
980 function FILTER_DISPLAY_PARSING_TIME () {
981 // Shall we display the parsing time and number of queries?
982 // 1234 5 54 4 5 5 4 4 5543 3 4432 2 332 2 21
983 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (isFullPage())) && (!isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['__header_sent'] == 2)) {
984 // Then display it here
985 displayParsingTime();
989 // Filter for flushing template cache
990 function FILTER_FLUSH_TEMPLATE_CACHE () {
991 // Do not flush when debugging the template cache
992 if (isDebuggingTemplateCache()) {
993 // Do not flush templates in debug-mode
997 // Do we have cached eval() data?
998 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
1000 foreach ($GLOBALS['template_eval'] as $template => $eval) {
1001 // Flush the cache (if not yet found)
1002 flushTemplateCache($template, $eval);
1007 // Filter for loading user data
1008 function FILTER_FETCH_USER_DATA ($userid = NULL) {
1009 // Is the userid not set? Then use member id
1010 if (!isValidUserId($userid)) {
1011 $userid = getMemberId();
1015 if (!fetchUserData($userid)) {
1016 // Userid is not valid
1017 reportBug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
1021 setMemberId($userid);
1024 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
1025 function FILTER_RESET_USER_LOGIN_FAILURE () {
1026 // Is the user data valid?
1028 // Do only run for logged in members
1029 reportBug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
1032 // Remmeber login failures if available
1033 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1034 // Reset login failures
1035 SQL_QUERY_ESC("UPDATE
1036 `{?_MYSQL_PREFIX?}_user_data`
1043 array(getMemberId()), __FUNCTION__, __LINE__);
1045 // Store it in session
1046 setSession('mailer_member_failures' , getUserData('login_failures'));
1047 setSession('mailer_member_last_failure', getUserData('last_failure'));
1051 // Try to login the admin by setting some session/cookie variables
1052 function FILTER_DO_LOGIN_ADMIN ($filterData) {
1053 // Now set all session variables and store the result for later processing
1054 $GLOBALS['admin_login_success'] = ((
1055 setAdminMd5(encodeHashForCookie($filterData['pass_hash']))
1057 setAdminId($filterData['id'])
1059 setAdminLast(time())
1062 // Return the data for further processing
1066 // Filter for loading page header, this should be ran first!
1067 function FILTER_LOAD_PAGE_HEADER () {
1068 // Output page header code
1069 $GLOBALS['__page_header'] = loadTemplate('page_header', true);
1071 // Include meta data in 'guest' module
1072 if ((isModuleSet()) && (getModule() == 'index')) {
1073 // Load meta data template
1074 $GLOBALS['__page_header'] .= loadTemplate('metadata', true);
1076 // Add meta description to header
1077 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1078 // Add meta description not in admin and login module and when the script is installed
1079 generateMetaDescriptionCode();
1084 // Filter for adding style sheet, closing page header
1085 function FILTER_FINISH_PAGE_HEADER () {
1086 // Include stylesheet
1087 loadIncludeOnce('inc/stylesheet.php');
1090 $GLOBALS['__page_header'] .= '</head>';
1093 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1094 function FILTER_CLEANUP_DNS_CACHE () {
1095 // Is the latest version installed?
1096 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1098 loadIncludeOnce('inc/classes/resolver.class.php');
1100 // Instance the resolver
1101 $resolver = new HostnameResolver();
1104 $resolver->purgeEntries();
1106 // Cute, isn't it? ;-)
1110 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1111 function FILTER_SET_CURRENT_DATE () {
1113 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1115 // Epoche time for yesterday, today ... all at 00:00 am
1116 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1117 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1120 // Filter for marking extension as installed
1121 function FILTER_EXTENSION_MARK_INSTALLED ($filterData) {
1122 // Mark it as installed
1123 $GLOBALS['ext_is_installed'][$filterData['ext_name']] = true;
1126 // Filter for generating mails links for 'pool' mails
1127 function FILTER_GENERATE_POOL_MAIL_LINKS ($filterData) {
1129 if ($filterData['type'] == 'mid') {
1131 $filterData['__output'] .= loadTemplate('admin_links_' . strtolower($filterData['mail_status']) . '_pool_mail', true, $filterData);
1138 // Filter to activate exchange
1139 function FILTER_ACTIVATE_EXCHANGE () {
1140 // Is the extension 'user' there?
1141 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1142 // Silently abort here
1146 // Check total amount of users
1147 if (getTotalConfirmedUser() >= getActivateXchange()) {
1149 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N',`hidden`='N',`mem_only`='Y' WHERE `module`='order' LIMIT 1");
1150 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y',`locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1153 runFilterChain('run_sqls');
1155 // Update configuration
1156 updateConfiguration('activate_xchange' ,0);
1159 rebuildCache('modules', 'modules');
1163 // Filter to handle configuration
1164 function FILTER_HANDLE_HOME_IN_INDEX_SETTING ($filterData) {
1165 // Is ext-sql_patches up-to-date?
1166 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled())) {
1167 // Is 'search' as same as 'index_home'?
1168 if ($filterData['search'] == getIndexHome()) {
1169 // Then set 'content' to link to index.php
1170 $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>';
1178 // Filter to add history entry
1179 function FILTER_ADD_HISTORY_ENTRY ($filterData) {
1181 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_history` (`history_subject`,`history_userid`,`history_value`) VALUES ('%s',%s,'%s')",
1183 __FUNCTION__, __LINE__);
1185 // Remember insert id for other filters
1186 $filterData['history_id'] = SQL_INSERTID();
1192 // Filter for initializing ext-sql_patches
1193 function FILTER_GENERATE_FILE_SECRET_HASH ($filterData) {
1194 // Transfer POINTS word
1195 if (isExtensionInstalledAndNewer('sql_patches', '0.0.3')) {
1196 // Okay, recent enough, so transfer the word for POINTS
1197 setConfigEntry('POINTS', getPointsWord());
1201 setConfigEntry('secret_key', '');
1203 // Read key from secret file
1204 if ((getFileHash() == '') || (getMasterSalt() == '') || (getPassScramble() == '')) {
1205 // Maybe need setup of secret key!
1206 loadIncludeOnce('inc/gen_sql_patches.php');
1210 if ((getFileHash() != '') && (getMasterSalt() != '') && (getPassScramble() != '')) {
1211 // File hash fas generated so we can also file the secret file... hopefully.
1212 $hashFile = sprintf("%s%s.%s.cache", getPath(), getCachePath(), getFileHash());
1214 // Is the secret key file readable?
1215 if (isFileReadable($hashFile)) {
1217 setConfigEntry('secret_key', readFromFile($hashFile));
1219 // Remove it from database
1220 updateConfiguration('file_hash', '');
1222 // Cannot read secret file!
1223 reportBug(__FILE__, __LINE__, 'Cannot read secret file! Please try to reload.');