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
48 // Is a database link here and not in installation mode?
49 if ((!SQL_IS_LINK_UP()) && (!isInstallationPhase())) {
51 reportBug(__FUNCTION__, __LINE__, 'No database link is up. Cannot flush filters.');
52 } elseif ((isInstallationPhase()) && (!SQL_IS_LINK_UP())) {
53 // If the link is not up in installation phase, skip flushing filters
57 // Is the extension ext-sql_patches updated and not in installation phase?
58 if ((!isInstallationPhase()) && ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9')))) {
59 // Log only in debug mode
60 if (isDebugModeEnabled()) {
61 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot flush filters, ext-sql_patches might be missing. isExtensionInstalled()=' . intval(isExtensionInstalled('sql_patches')) . ',isExtensionInstalledAndOlder()=' . intval(isExtensionInstalledAndOlder('sql_patches', '0.5.9')));
64 // Abort silently here
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() == 'welcome') || (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 ext-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 reportBug(__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 reportBug(__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 reportBug(__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) {
251 //* DEBUG: */ die('getSqls()=<pre>'.print_r(getSqls(), TRUE).'</pre>ext_update_depends=<pre>'.print_r($GLOBALS['ext_update_depends'], TRUE).'</pre>');
252 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Entered!');
254 // Is the array there?
255 if ((isSqlsValid()) && ((!isset($filterData['dry_run'])) || ($filterData['dry_run'] == FALSE))) {
257 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Found ' . countSqls() . ' queries to run.');
258 foreach (getSqls() as $mode => $sqls) {
260 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'mode=' . $mode . ',count()=' . count($sqls));
262 // New cache format...
263 foreach ($sqls as $sql) {
267 // Is 'enable_codes' not set? Then set it to true
268 if (!isset($filterData['enable_codes'])) {
269 $filterData['enable_codes'] = TRUE;
272 // Is there still a query left?
274 // Is there an "ALTER TABLE" command?
275 if (substr(strtolower($sql), 0, 11) == 'alter table') {
276 // Analyse the alteration command
277 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
278 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
280 // Run regular SQL command
281 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
282 SQL_QUERY($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
285 // Has a line changed?
286 if (!SQL_HASZEROAFFECTED()) {
287 // Add it to total account
288 $count += SQL_AFFECTEDROWS();
296 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
298 // Clear any SQL queries
305 // Filter for updating/validating login data
306 function FILTER_UPDATE_LOGIN_DATA () {
308 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
309 $GLOBALS['last_online'] = array();
312 // Recheck if logged in
313 if ((!isMember()) || ((isAdmin()) && (!isDebugModeEnabled()))) {
318 setMemberId(getSession('userid'));
321 if (fetchUserData(getMemberId())) {
322 // Load last module and online time
323 $content = getUserDataArray();
325 // Maybe first login time?
326 if (empty($content[getUserLastWhatName()])) {
327 $content[getUserLastWhatName()] = 'login';
330 // This will be displayed on welcome page! :-)
331 if (empty($GLOBALS['last_online']['module'])) {
332 $GLOBALS['last_online']['module'] = $content[getUserLastWhatName()];
333 $GLOBALS['last_online']['online'] = $content['last_online'];
340 if (getIndexHome() != '') {
341 setWhatFromConfig('index_home');
345 // Update last module / online time
346 updateLastActivity(getMemberId());
348 // Destroy session, we cannot update!
349 destroyMemberSession();
353 // Filter for initializing randomizer
354 function FILTER_INIT_RANDOMIZER () {
355 // Take a prime number which is long (if you know a longer one please try it out!)
356 setConfigEntry('_PRIME', 591623);
358 // Only execute this filter if installed
359 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
361 setConfigEntry('_ADD', 0);
365 // Calculate "entropy" with the prime number (for code generation)
366 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
368 // Simply init the randomizer with seed and _ADD value
369 mt_srand(generateSeed() + getConfig('_ADD'));
372 // Filter for removing updates
373 function FILTER_REMOVE_UPDATES ($filterData) {
375 initExtensionRemovalList();
377 // Add the current extension to it
378 addCurrentExtensionToRemovalList();
381 unsetExtensionSqls();
383 // Are there update dependencies to remove?
384 if (countExtensionUpdateDependencies() > 0) {
385 // Then find all updates we shall no longer execute
386 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
387 // Shall we remove this update?
388 if (in_array($ext_name, getExtensionRemovalList())) {
389 // Then remove this extension!
390 removeExtensionDependency($ext_name);
399 // Determines username for current user state
400 function FILTER_DETERMINE_USERNAME () {
401 // Check if logged in
403 // Is still logged in so we welcome him with his name
404 if (fetchUserData(getMemberId())) {
405 // Load surname and family's name and build the username
406 $content = getUserDataArray();
409 setUsername($content['surname'] . ' ' . $content['family']);
411 // Additionally admin?
414 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
417 // Hmmm, logged in and no valid userid?
418 setUsername('<span class="bad">{--USERNAME_UNKNOWN--}</span>');
421 destroyMemberSession();
423 } elseif (isAdmin()) {
425 setUsername('{--USERNAME_ADMIN--}');
427 // He's a guest, hello there... ;-)
428 setUsername('{--USERNAME_GUEST--}');
432 // Filter for compiling config entries
433 function FILTER_COMPILE_CONFIG ($code, $compiled = FALSE) {
434 // Save the uncompiled code
438 if (!isset($GLOBALS['compiled_config'][$code])) {
439 // Compile {?some_var?} to getConfig('some_var')
440 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
442 // Some entries found?
443 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
444 // Replace all matches
445 foreach ($matches[0] as $key => $match) {
447 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
448 // Is the config valid?
449 if (isConfigEntrySet($matches[1][$key])) {
450 // Set it for caching
451 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
452 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
454 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
455 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
456 // No config, try the language system
457 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
460 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
464 // Use this for replacing
465 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
466 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
471 $GLOBALS['compiled_config'][$uncompiled] = $code;
474 // Should we compile it?
475 if ($compiled === TRUE) {
477 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
478 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
482 // Return compiled code
483 return $GLOBALS['compiled_config'][$uncompiled];
486 // Filter for compiling expression code
487 function FILTER_COMPILE_EXPRESSION_CODE ($filterData) {
488 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
489 // See switch() command below for supported commands
490 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $filterData, $matches);
491 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, TRUE).'</pre>');
493 // Default is from outputHtml()
494 $outputMode = getScriptOutputMode();
496 // Some entries found?
497 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
498 // Replace all matches
499 foreach ($matches[2] as $key => $eti) {
500 // Init replacer/call-back variable
504 $extraFunction2 = '';
507 // Extract command and call-back
508 $etiArray = explode(',', $eti);
511 // Detect call-back function
512 if (isset($etiArray[1])) {
513 // Call-back function detected
514 $callback = $etiArray[1];
517 // Detect extra function
518 if (isset($etiArray[2])) {
520 $extraFunction = $etiArray[2];
523 // Detect extra function 2
524 if (isset($etiArray[3])) {
526 $extraFunction2 = $etiArray[3];
530 if (isset($matches[4][$key])) {
532 $value = $matches[4][$key];
535 // Construct call-back function name for the command
536 $etiFunction = 'doExpression' . capitalizeUnderscoreString($eti);
538 // Is this function there?
539 if (function_exists($etiFunction)) {
540 // Prepare $matches, $key, $outputMode, etc.
542 'matches' => $matches,
544 'output_mode' => getScriptOutputMode(),
545 'code' => $filterData,
546 'callback' => $callback,
547 'extra_func' => $extraFunction,
548 'extra_func2' => $extraFunction2,
553 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: etiFunction=' . $etiFunction);
554 $filterData = call_user_func($etiFunction, $data);
556 // Unsupported command detected
557 logDebugMessage(__FUNCTION__, __LINE__, 'eti=' . $eti . ', callback=' . $callback . ', extra=' . $extraFunction . ' - unsupported');
562 // Is there non-HTML mode?
563 if (!isHtmlOutputMode()) {
564 $filterData = decodeEntities($filterData);
567 // Return compiled code
568 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($filterData).'</pre>');
572 // Runs some generic filter update steps
573 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
574 // Create task (we ignore the task id here)
575 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
577 // Update extension's version
578 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
579 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
583 unset($GLOBALS['update_ver'][$ext_name]);
586 // Load more hourly reset scripts
587 function FILTER_RUN_HOURLY_INCLUDES () {
588 // Is the reset set or old sql_patches?
589 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
591 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');
594 // Get more hourly reset scripts
595 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
598 if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
599 updateConfiguration('last_hour', getHour());
603 runFilterChain('load_includes', 'hourly');
606 // Load more reset scripts
607 function FILTER_RUN_RESET_INCLUDES () {
608 // Is the reset set or old sql_patches?
609 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
611 reportBug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
614 // Get more daily reset scripts
615 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
617 // Update configuration if this reset is not being debugged
618 if (!isDebugResetEnabled()) {
619 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
622 // Is the config entry set?
623 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
625 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
626 // Include weekly reset scripts
627 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
629 // Update configuration if this reset is not being debugged
630 if (!isWeeklyResetDebugEnabled()) {
631 updateConfiguration('last_week', getWeek());
635 // Create current month mark
636 $currMonth = getMonth();
639 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
640 // Include monthly reset scripts
641 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
643 // Update configuration if this reset is not being debugged
644 if (!isMonthlyResetDebugEnabled()) {
645 updateConfiguration('last_month', $currMonth);
651 runFilterChain('load_includes', 'reset');
654 // Filter for removing the given extension
655 function FILTER_REMOVE_EXTENSION () {
656 // Delete this extension (remember to remove it from your server *before* you click on welcome!
657 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
658 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
660 // Remove the extension from cache array as well
661 removeExtensionFromArray();
664 rebuildCache('extension', 'extension');
667 // Filter for flushing the output
668 function FILTER_FLUSH_OUTPUT () {
673 // Prepares an SQL statement part for HTML mail and/or holiday dependency
674 function FILTER_HTML_INCLUDE_USERS ($mode) {
675 // Exclude no users by default
679 if ($mode == 'html') {
680 $MORE = " AND `html`='Y'";
683 if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
684 // Add something for the holiday extension
685 $MORE .= " AND `holiday_active`='N'";
692 // Filter for determining what/action/module
693 function FILTER_DETERMINE_WHAT_ACTION () {
694 // In installation phase we don't have what/action
695 if (isInstallationPhase()) {
705 if ((!isCssOutputMode()) && (!isRawOutputMode())) {
707 if (!isModuleSet()) {
708 // Is the request element set?
709 if (isGetRequestElementSet('module')) {
710 // Set module from request
711 setModule(getRequestElement('module'));
712 } elseif (isHtmlOutputMode()) {
713 // Set default module 'index'
717 setModule('unknown');
721 // Fix 'what' if not yet set
723 setWhat(getWhatFromModule(getModule()));
726 // Fix 'action' if not yet set
727 if (!isActionSet()) {
731 setAction(getActionFromModuleWhat(getModule(), getWhat()));
733 // Set action/what to empty
739 // Set action/what to empty
744 // Set default 'what' value
745 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
746 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
747 if (getModule() == 'admin') {
748 // Set 'action' value to 'login' in admin menu
749 setAction(getActionFromModuleWhat(getModule(), getWhat()));
750 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
751 // Set 'what' value to 'welcome' in guest and member menu
752 setWhatFromConfig('index_home');
754 // Anything else like begging link
760 // Sends out pooled mails
761 function FILTER_TRIGGER_SENDING_POOL () {
762 // Are we in normal output mode?
763 if (!isHtmlOutputMode()) {
764 // Only in normal output mode to prevent race-conditons!
768 $GLOBALS['pool_cnt'] = '0';
770 // Init & set the include pool
771 initIncludePool('pool');
772 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
775 runFilterChain('load_includes', 'pool');
777 // Remove the counter
778 unset($GLOBALS['pool_cnt']);
781 // Filter for checking and updating SVN revision
782 function FILTER_CHECK_REPOSITORY_REVISION () {
783 // Only execute this filter if installed and all config entries are there
784 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
786 // Check for patch level differences between database and current hard-coded
787 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
788 // Update database and CONFIG array
789 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
790 setConfigEntry('patch_level', getCurrentRepositoryRevision());
791 setConfigEntry('patch_ctime', time());
795 // Filter for running daily reset
796 function FILTER_RUN_DAILY_RESET () {
797 // Only execute this filter if installed
798 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
802 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
803 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
804 // Tell every module we are in reset-mode!
809 // Filter for running hourly reset
810 function FILTER_RUN_HOURLY_RESET () {
811 // Only execute this filter if installed
812 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
816 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
817 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
818 // Tell every module we are in reset-mode!
823 // Filter for loading more runtime includes (not for installation)
824 function FILTER_LOAD_RUNTIME_INCLUDES () {
825 // Load more includes
826 foreach (array('databases', 'session', 'versions') as $inc) {
828 loadIncludeOnce('inc/' . $inc . '.php');
832 // Filter for checking admin ACL
833 function FILTER_CHECK_ADMIN_ACL () {
834 // Extension not installed so it's always allowed to access everywhere!
837 // Ok, Cookie-Update done
838 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
839 // Check if action GET variable was set
840 $action = getAction();
842 // Get action value by what-value
843 $action = getActionFromModuleWhat('admin', getWhat());
846 // Check for access control line of current menu entry
847 $ret = isAdminsAllowedByAcl($action, getWhat());
851 $GLOBALS['acl_allow'] = $ret;
854 // Init random number/cache buster
855 function FILTER_INIT_RANDOM_NUMBER () {
856 // Is the extension ext-sql_patches installed and at least 0.3.6?
857 if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
858 // Generate random number
859 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 99999), getMemberId(), ''));
861 // Generate *WEAK* code
862 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
865 // Copy it to CACHE_BUSTER
866 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
869 // Update module counter
870 function FILTER_COUNT_MODULE () {
871 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ' - ENTERED!');
872 // Do count all other modules but not accesses on CSS file css.php!
873 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
874 array(getModule()), __FUNCTION__, __LINE__);
875 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
878 // Handles fatal errors
879 function FILTER_HANDLE_FATAL_ERRORS () {
880 // Is there errors to handle and right output mode?
881 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
882 // Abort executing here
887 setContentType('text/html');
890 loadIncludeOnce('inc/load_config.php');
892 // Default content is none
895 // Installation phase or regular mode?
896 if ((isInstallationPhase())) {
897 // While we are installing ouput other header than while it is installed... :-)
899 foreach (getFatalArray() as $key => $value) {
900 // Prepare content for the template
907 $OUT .= loadTemplate('install_fatal_row', TRUE, $content);
910 // Load main template
911 $content = loadTemplate('install_fatal_table', TRUE, $OUT);
912 } elseif (isInstalled()) {
913 // Display all runtime fatal errors
915 foreach (getFatalArray() as $key => $value) {
916 // Prepare content for the template
923 $OUT .= loadTemplate('runtime_fatal_row', TRUE, $content);
926 // Load main template
927 $content = loadTemplate('runtime_fatal_table', TRUE, $OUT);
930 // Message to regular users (non-admin)
931 $CORR = '{--FATAL_REPORT_ERRORS--}';
933 // Maybe the admin wants to take a look?
935 $CORR = '{--FATAL_CORRECT_ERRORS--}';
938 // Remember all in array
945 loadIncludeOnce('inc/header.php');
947 // Load main template
948 loadTemplate('fatal_errors', FALSE, $content);
950 // Delete all to prevent double-display
954 loadIncludeOnce('inc/footer.php');
960 // Filter for displaying copyright line
961 function FILTER_DISPLAY_COPYRIGHT () {
962 // Shall we display the copyright notice?
963 if ((isFullPage()) && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['__header_sent'] == 2) && (ifCopyrightFooterEnabled())) {
965 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
966 // Copyright with backlink, thanks! :-)
967 $GLOBALS['__page_footer'] .= loadTemplate('copyright_backlink', TRUE);
969 // No backlink in Copyright note
970 $GLOBALS['__page_footer'] .= loadTemplate('copyright', TRUE);
975 // Filter for displaying parsing time
976 function FILTER_DISPLAY_PARSING_TIME () {
977 // Shall we display the parsing time and number of queries?
978 // 1234 5 54 4 5 5 4 4 5543 3 4432 2 332 2 21
979 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (isFullPage())) && (!isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['__header_sent'] == 2)) {
980 // Then display it here
981 displayParsingTime();
985 // Filter for flushing template cache
986 function FILTER_FLUSH_TEMPLATE_CACHE () {
987 // Do not flush when debugging the template cache
988 if (isDebuggingTemplateCache()) {
989 // Do not flush templates in debug-mode
993 // Is there cached eval() data?
994 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
996 foreach ($GLOBALS['template_eval'] as $prefix => $templateArray) {
997 foreach ($templateArray as $template => $eval) {
998 // Flush the cache (if not yet found)
999 flushTemplateCache($prefix, $template, $eval);
1005 // Filter for loading user data
1006 function FILTER_FETCH_USER_DATA ($userid = NULL) {
1007 // Is the userid not set? Then use member id
1008 if (!isValidUserId($userid)) {
1009 $userid = getMemberId();
1013 if (!fetchUserData($userid)) {
1014 // Userid is not valid
1015 reportBug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
1019 setMemberId($userid);
1022 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
1023 function FILTER_RESET_USER_LOGIN_FAILURE () {
1024 // Is the user data valid?
1026 // Do only run for logged in members
1027 reportBug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
1030 // Remmeber login failures if available
1031 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1032 // Reset login failures
1033 SQL_QUERY_ESC("UPDATE
1034 `{?_MYSQL_PREFIX?}_user_data`
1041 array(getMemberId()), __FUNCTION__, __LINE__);
1043 // Store it in session
1044 setSession('mailer_member_failures' , getUserData('login_failures'));
1045 setSession('mailer_member_last_failure', getUserData('last_failure'));
1049 // Try to login the admin by setting some session/cookie variables
1050 function FILTER_DO_LOGIN_ADMIN ($filterData) {
1051 // Now set all session variables and store the result for later processing
1052 $GLOBALS['admin_login_success'] = ((
1053 setAdminMd5(encodeHashForCookie($filterData['pass_hash']))
1055 setAdminId($filterData['id'])
1057 setAdminLast(time())
1060 // Return the data for further processing
1064 // Filter for loading page header, this should be ran first!
1065 function FILTER_LOAD_PAGE_HEADER () {
1066 // Output page header code
1067 $GLOBALS['__page_header'] = loadTemplate('page_header', TRUE);
1069 // Include meta data in 'guest' module
1070 if ((isModuleSet()) && (getModule() == 'index')) {
1071 // Load meta data template
1072 $GLOBALS['__page_header'] .= loadTemplate('metadata', TRUE);
1074 // Add meta description to header
1075 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1076 // Add meta description not in admin and login module and when the script is installed
1077 generateMetaDescriptionCode();
1082 // Filter for adding style sheet, closing page header
1083 function FILTER_FINISH_PAGE_HEADER () {
1084 // Include stylesheet
1085 loadIncludeOnce('inc/stylesheet.php');
1088 $GLOBALS['__page_header'] .= '</head>';
1091 // Cleans up the DNS cache if ext-sql_patches is at least 0.7.0
1092 function FILTER_CLEANUP_DNS_CACHE () {
1093 // Is the latest version installed?
1094 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1096 loadIncludeOnce('inc/classes/resolver.class.php');
1098 // Instance the resolver
1099 $resolver = new HostnameResolver();
1102 $resolver->purgeEntries();
1104 // Cute, isn't it? ;-)
1108 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1109 function FILTER_SET_CURRENT_DATE () {
1111 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1113 // Epoche time for yesterday, today ... all at 00:00 am
1114 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1115 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1118 // Filter for marking extension as installed
1119 function FILTER_EXTENSION_MARK_INSTALLED ($filterData) {
1120 // Mark it as installed
1121 $GLOBALS['ext_is_installed'][$filterData['ext_name']] = TRUE;
1124 // Filter for generating mails links for 'pool' mails
1125 function FILTER_GENERATE_POOL_MAIL_LINKS ($filterData) {
1127 if ($filterData['type'] == 'mid') {
1129 $filterData['__output'] .= loadTemplate('admin_links_' . strtolower($filterData['mail_status']) . '_pool_mail', TRUE, $filterData);
1136 // Filter to activate exchange
1137 function FILTER_ACTIVATE_EXCHANGE () {
1138 // Is the extension 'user' there?
1139 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1140 // Silently abort here
1144 // Check total amount of users
1145 if (getTotalConfirmedUser() >= getActivateXchange()) {
1147 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N',`hidden`='N',`mem_only`='Y' WHERE `module`='order' LIMIT 1");
1148 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y',`locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1151 runFilterChain('run_sqls');
1153 // Update configuration
1154 updateConfiguration('activate_xchange' ,0);
1157 rebuildCache('modules', 'modules');
1161 // Filter to handle configuration
1162 function FILTER_HANDLE_HOME_IN_INDEX_SETTING ($filterData) {
1163 // Is ext-sql_patches up-to-date?
1164 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled())) {
1165 // Is 'search' as same as 'index_home'?
1166 if ($filterData['search'] == getIndexHome()) {
1167 // Then set 'content' to link to index.php
1168 $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>';
1176 // Filter to add history entry
1177 function FILTER_ADD_HISTORY_ENTRY ($filterData) {
1179 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_history` (`history_subject`, `history_userid`, `history_value`) VALUES ('%s',%s,'%s')",
1181 __FUNCTION__, __LINE__);
1183 // Remember insert id for other filters
1184 $filterData['history_id'] = SQL_INSERTID();
1190 // Filter for initializing ext-sql_patches
1191 function FILTER_GENERATE_FILE_SECRET_HASH ($filterData) {
1192 // Transfer POINTS word
1193 if (isExtensionInstalledAndNewer('sql_patches', '0.0.3')) {
1194 // Okay, recent enough, so transfer the word for POINTS
1195 setConfigEntry('POINTS', getPointsWord());
1199 setConfigEntry('secret_key', '');
1201 // Read key from secret file
1202 if ((getFileHash() == '') || (getMasterSalt() == '') || (getPassScramble() == '')) {
1203 // Maybe need setup of secret key!
1204 loadIncludeOnce('inc/gen_sql_patches.php');
1208 if ((getFileHash() != '') && (getMasterSalt() != '') && (getPassScramble() != '')) {
1209 // File hash fas generated so we can also file the secret file... hopefully.
1210 $hashFile = sprintf("%s%s.%s.cache", getPath(), getCachePath(), getFileHash());
1212 // Is the secret key file readable?
1213 if (isFileReadable($hashFile)) {
1215 setConfigEntry('secret_key', readFromFile($hashFile));
1217 // Remove it from database
1218 updateConfiguration('file_hash', '');
1220 // Cannot read secret file!
1221 reportBug(__FILE__, __LINE__, 'Cannot read secret file! Please try to reload.');
1229 // Filter to initialize session
1230 function FILTER_INIT_SESSION ($filterData) {
1231 // Determine and set referral id
1232 determineReferralId();
1238 // Filter for sending "build mail" to admin
1239 function FILTER_SEND_BUILD_MAIL ($filterData) {
1240 // Was one line updated?
1241 if ($filterData['affected'] > 0) {
1242 // Then call the proper function
1243 call_user_func_array('sendGenericBuildMails', $filterData);