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
54 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot flush filters: No link is up.');
58 // Is the extension ext-sql_patches updated?
59 if (((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) && (!isInstallationPhase())) {
60 // Log only in debug mode
61 if (isDebugModeEnabled()) {
62 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')));
65 // Abort silently here
69 // Nothing is added/remove by default
73 // Prepare SQL queries
74 $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`, `filter_function`, `filter_active`) VALUES';
75 $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
77 // Write all filters to database
78 foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
79 // Walk through all filters
80 foreach ($filterArray as $filterFunction => $active) {
81 // Is this filter loaded?
82 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
83 if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
84 // Is this filter already in database?
85 if (countSumTotalData($filterFunction, 'filters', 'filter_name', 'filter_function', TRUE, sprintf(" AND `filter_name`='%s'", SQL_ESCAPE($filterName))) == 0) {
86 // Add this filter (all filters are active by default)
87 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD:'.$filterName.'/'.$filterFunction);
88 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
90 } elseif (isDebugModeEnabled()) {
91 // Log already registered filters
92 logDebugMessage(__FUNCTION__, __LINE__, 'Already registered: filterName=' . $filterName . ',filterFunction=' . $filterFunction . ',active=' . $active);
94 } elseif ($active == 'R') {
96 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'REMOVE:'.$filterName.'/'.$filterFunction);
97 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
104 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inserted=' . $inserted . ',removed=' . $removed . ' - AFTER COLLECTION');
106 // Something has been added?
108 // Finish SQL command and add it
109 addSql(substr($insertSQL, 0, -1));
112 // Something has been removed?
114 // Finish SQL command and add it
115 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
118 // Shall we update usage counters (ONLY FOR DEBUGGING!)
119 if (isFilterUsageUpdateEnabled()) {
120 // Update all counters
121 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
122 // Walk through all filters
123 foreach ($filterArray as $filterFunction => $count) {
124 // Construct and add the query
125 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
134 // Run the run_sqls filter in non-dry mode
135 runFilterChain('run_sqls');
137 // Should we rebuild cache?
138 if (($inserted > 0) || ($removed > 0)) {
140 rebuildCache('filter', 'filter');
144 // Filter for calling the handler for login failures
145 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($filterData) {
147 $content = $filterData;
149 // Handle failed logins here if not in guest
150 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $filterData['type'] . ',action=' . getAction() . ',what=' . getWhat() . ',level=' . $filterData['access_level']);
151 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')))) {
153 $content['content'] .= handleLoginFailures($filterData['access_level']);
156 // Return the content
160 // Filter for auto-activation of a extension
161 function FILTER_AUTO_ACTIVATE_EXTENSION ($filterData) {
163 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $filterData['ext_name'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
165 // Is this extension always activated?
166 if (isThisExtensionAlwaysActive()) {
167 // Then activate the extension
168 doActivateExtension($filterData['ext_name']);
175 // Filter for solving task given task
176 function FILTER_SOLVE_TASK ($filterData) {
177 // Don't solve anything if no admin!
182 // Is this a direct task id or array element task_id is found?
183 if (is_int($filterData)) {
185 adminSolveTask($filterData);
186 } elseif ((is_array($filterData)) && (isset($filterData['task_id']))) {
188 adminSolveTask($filterData['task_id']);
191 reportBug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($filterData), print_r($filterData, TRUE)));
198 // Filter to load include files
199 function FILTER_LOAD_INCLUDES ($filterData) {
201 if (is_null($filterData)) {
202 // This should not happen!
203 reportBug(__FUNCTION__, __LINE__, 'pool is null.');
206 // Is the pool an array and 'pool' set?
207 if ((is_array($filterData)) && (isset($filterData['pool']))) {
208 // Then use it as pool
209 $realPool = $filterData['pool'];
211 // Default is $data as inclusion list
212 $realPool = $filterData;
216 $data = getIncludePool($realPool);
219 if ((!isset($data)) || (!is_array($data))) {
221 reportBug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
222 } elseif (isset($data['inc_pool'])) {
223 // Use this as new inclusion pool!
224 setIncludePool($realPool, $data['inc_pool']);
227 // Check for added include files
228 if (countIncludePool($realPool) > 0) {
229 // Loads every include file
230 loadIncludePool($realPool);
233 initIncludePool($realPool);
236 // Continue with processing
240 // Filter for running SQL commands
241 function FILTER_RUN_SQLS ($filterData) {
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($filterData['dry_run'])) || ($filterData['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($filterData['enable_codes'])) {
264 $filterData['enable_codes'] = TRUE;
267 // Is there still a query left?
269 // Is there an "ALTER TABLE" command? Exclude installation phase here as it would cause this query to fail
270 if ((substr(strtolower($sql), 0, 11) == 'alter table') && (!isset($filterData['ext_installing']))) {
271 // Analyse the alteration command
272 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
273 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
275 // Run regular SQL command
276 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
277 SQL_QUERY($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
280 // Has a line changed?
281 if (!SQL_HASZEROAFFECTED()) {
282 // Add it to total account
283 $count += SQL_AFFECTEDROWS();
291 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
297 // Filter for updating/validating login data
298 function FILTER_UPDATE_LOGIN_DATA () {
300 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
301 $GLOBALS['last_online'] = array();
304 // Recheck if logged in
305 if ((!isMember()) || ((isAdmin()) && (!isDebugModeEnabled()))) {
310 setMemberId(getSession('userid'));
313 if (fetchUserData(getMemberId())) {
314 // Load last module and online time
315 $content = getUserDataArray();
317 // Maybe first login time?
318 if (empty($content[getUserLastWhatName()])) {
319 $content[getUserLastWhatName()] = 'login';
322 // This will be displayed on welcome page! :-)
323 if (empty($GLOBALS['last_online']['module'])) {
324 $GLOBALS['last_online']['module'] = $content[getUserLastWhatName()];
325 $GLOBALS['last_online']['online'] = $content['last_online'];
332 if (getIndexHome() != '') {
333 setWhatFromConfig('index_home');
337 // Update last module / online time
338 updateLastActivity(getMemberId());
340 // Destroy session, we cannot update!
341 destroyMemberSession();
345 // Filter for initializing randomizer
346 function FILTER_INIT_RANDOMIZER () {
347 // Take a prime number which is long (if you know a longer one please try it out!)
348 setConfigEntry('_PRIME', 591623);
350 // Initialize array with all allowed chars
351 $GLOBALS['_abc'] = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,6,7,8,9,-,+,_,/,.');
353 // Only execute this filter if installed
354 if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
356 setConfigEntry('_ADD', 0);
360 // Calculate "entropy" with the prime number (for code generation)
361 setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
363 // Simply init the randomizer with seed and _ADD value
364 mt_srand(generateSeed() + getConfig('_ADD'));
367 // Filter for removing updates
368 function FILTER_REMOVE_UPDATES ($filterData) {
370 initExtensionRemovalList();
372 // Add the current extension to it
373 addCurrentExtensionToRemovalList();
376 unsetExtensionSqls();
378 // Are there update dependencies to remove?
379 if (countExtensionUpdateDependencies() > 0) {
380 // Then find all updates we shall no longer execute
381 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
382 // Shall we remove this update?
383 if (in_array($ext_name, getExtensionRemovalList())) {
384 // Then remove this extension!
385 removeExtensionDependency($ext_name);
394 // Determines username for current user state
395 function FILTER_DETERMINE_USERNAME () {
396 // Check if logged in
398 // Is still logged in so we welcome him with his name
399 if (fetchUserData(getMemberId())) {
400 // Load surname and family's name and build the username
401 $content = getUserDataArray();
404 setUsername($content['surname'] . ' ' . $content['family']);
406 // Additionally admin?
409 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
412 // Hmmm, logged in and no valid userid?
413 setUsername('<span class="bad">{--USERNAME_UNKNOWN--}</span>');
416 destroyMemberSession();
418 } elseif (isAdmin()) {
420 setUsername('{--USERNAME_ADMIN--}');
422 // He's a guest, hello there... ;-)
423 setUsername('{--USERNAME_GUEST--}');
427 // Filter for compiling config entries
428 function FILTER_COMPILE_CONFIG ($code, $compiled = FALSE) {
429 // Save the uncompiled code
433 if (!isset($GLOBALS['compiled_config'][$code])) {
434 // Compile {?some_var?} to getConfig('some_var')
435 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
437 // Some entries found?
438 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
439 // Replace all matches
440 foreach ($matches[0] as $key => $match) {
442 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
443 // Is the config valid?
444 if (isConfigEntrySet($matches[1][$key])) {
445 // Set it for caching
446 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
447 } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
449 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
450 } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
451 // No config, try the language system
452 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
455 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
459 // Use this for replacing
460 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
461 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
466 $GLOBALS['compiled_config'][$uncompiled] = $code;
469 // Should we compile it?
470 if ($compiled === TRUE) {
472 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
473 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
477 // Return compiled code
478 return $GLOBALS['compiled_config'][$uncompiled];
481 // Filter for compiling expression code
482 function FILTER_COMPILE_EXPRESSION_CODE ($filterData) {
483 // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
484 // See switch() command below for supported commands
485 preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $filterData, $matches);
486 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, TRUE).'</pre>');
488 // Default is from outputHtml()
489 $outputMode = getScriptOutputMode();
491 // Some entries found?
492 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
493 // Replace all matches
494 foreach ($matches[2] as $key => $eti) {
495 // Init replacer/call-back variable
499 $extraFunction2 = '';
502 // Extract command and call-back
503 $etiArray = explode(',', $eti);
506 // Detect call-back function
507 if (isset($etiArray[1])) {
508 // Call-back function detected
509 $callback = $etiArray[1];
512 // Detect extra function
513 if (isset($etiArray[2])) {
515 $extraFunction = $etiArray[2];
518 // Detect extra function 2
519 if (isset($etiArray[3])) {
521 $extraFunction2 = $etiArray[3];
525 if (isset($matches[4][$key])) {
527 $value = $matches[4][$key];
530 // Construct call-back function name for the command
531 $etiFunction = 'doExpression' . capitalizeUnderscoreString($eti);
533 // Is this function there?
534 if (function_exists($etiFunction)) {
535 // Prepare $matches, $key, $outputMode, etc.
537 'matches' => $matches,
539 'output_mode' => getScriptOutputMode(),
540 'code' => $filterData,
541 'callback' => $callback,
542 'extra_func' => $extraFunction,
543 'extra_func2' => $extraFunction2,
548 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: etiFunction=' . $etiFunction);
549 $filterData = call_user_func($etiFunction, $data);
551 // Unsupported command detected
552 logDebugMessage(__FUNCTION__, __LINE__, 'eti=' . $eti . ',etiFunction=' . $etiFunction . ',callback=' . $callback . ',extraFunction=' . $extraFunction . ',extraFunction2=' . $extraFunction2 . ' - UNSUPPORTED');
557 // Is there non-HTML/AJAX mode?
558 if ((!isHtmlOutputMode()) && (!isAjaxOutputMode())) {
559 $filterData = decodeEntities($filterData);
562 // Return compiled code
563 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($filterData).'</pre>');
567 // Runs some generic filter update steps
568 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
569 // Create task (we ignore the task id here)
570 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
572 // Update extension's version
573 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
574 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
578 unset($GLOBALS['update_ver'][$ext_name]);
581 // Load more hourly reset scripts
582 function FILTER_RUN_HOURLY_INCLUDES () {
583 // Is the reset set or old sql_patches?
584 if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
586 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');
589 // Get more hourly reset scripts
590 setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
593 if ((!isConfigEntrySet('DEBUG_HOURLY')) || (!isDebugHourlyEnabled())) {
594 updateConfiguration('last_hour', getHour());
598 runFilterChain('load_includes', 'hourly');
601 // Load more reset scripts
602 function FILTER_RUN_RESET_INCLUDES () {
603 // Is the reset set or old sql_patches?
604 if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
606 reportBug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
609 // Get more daily reset scripts
610 setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
612 // Update configuration if this reset is not being debugged
613 if (!isDebugResetEnabled()) {
614 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
617 // Is the config entry set?
618 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
620 if (((isConfigEntrySet('last_week')) && (getConfig('last_week') != getWeek())) || (isWeeklyResetDebugEnabled())) {
621 // Include weekly reset scripts
622 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
624 // Update configuration if this reset is not being debugged
625 if (!isWeeklyResetDebugEnabled()) {
626 updateConfiguration('last_week', getWeek());
630 // Create current month mark
631 $currMonth = getMonth();
634 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
635 // Include monthly reset scripts
636 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
638 // Update configuration if this reset is not being debugged
639 if (!isMonthlyResetDebugEnabled()) {
640 updateConfiguration('last_month', $currMonth);
646 runFilterChain('load_includes', 'reset');
649 // Filter for removing the given extension
650 function FILTER_REMOVE_EXTENSION () {
651 // Delete this extension (remember to remove it from your server *before* you click on welcome!
652 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
653 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
655 // Remove the extension from cache array as well
656 removeExtensionFromArray();
659 rebuildCache('extension', 'extension');
662 // Filter for flushing the output
663 function FILTER_FLUSH_OUTPUT () {
664 // Is this filter called?
665 if (isset($GLOBALS[__FUNCTION__])) {
667 reportBug(__FUNCTION__, __LINE__, 'Double call of ' . __FUNCTION__ . ' causes problems with sent headers.');
670 // Mark this filter as called
671 $GLOBALS[__FUNCTION__] = TRUE;
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 module registered?
713 if (!isModuleRegistered(getRequestElement('module'))) {
714 // Is not a valid module
715 redirectToUrl('modules.php?module=index');
718 // Is the request element set?
719 if (isGetRequestElementSet('module')) {
720 // Set module from request
721 setModule(getRequestElement('module'));
722 } elseif (isHtmlOutputMode()) {
723 // Set default module 'index'
727 setModule('unknown');
731 // Fix 'what' if not yet set
733 setWhat(getWhatFromModule(getModule()));
736 // Fix 'action' if not yet set
737 if (!isActionSet()) {
741 setAction(getActionFromModuleWhat(getModule(), getWhat()));
743 // Set action/what to empty
749 // Set action/what to empty
754 // Set default 'what' value
755 //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
756 if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
757 if (getModule() == 'admin') {
758 // Set 'action' value to 'login' in admin menu
759 setAction(getActionFromModuleWhat(getModule(), getWhat()));
760 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
761 // Set 'what' value to 'welcome' in guest and member menu
762 setWhatFromConfig('index_home');
764 // Anything else like begging link
770 // Sends out pooled mails
771 function FILTER_TRIGGER_SENDING_POOL () {
772 // Are we in normal output mode?
773 if (!isHtmlOutputMode()) {
774 // Only in normal output mode to prevent race-conditons!
779 $GLOBALS['pool_cnt'] = '0';
781 // Init & set the include pool
782 initIncludePool('pool');
783 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
786 runFilterChain('load_includes', 'pool');
788 // Remove the counter
789 unset($GLOBALS['pool_cnt']);
792 // Filter for checking and updating SVN revision
793 function FILTER_CHECK_REPOSITORY_REVISION () {
794 // Only execute this filter if installed and all config entries are there
795 if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
797 // Check for patch level differences between database and current hard-coded
798 if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
799 // Update database and CONFIG array
800 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
801 setConfigEntry('patch_level', getCurrentRepositoryRevision());
802 setConfigEntry('patch_ctime', time());
806 // Filter for running daily reset
807 function FILTER_RUN_DAILY_RESET () {
808 // Only execute this filter if installed
809 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
813 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
814 if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
815 // Tell every module we are in reset-mode!
820 // Filter for running hourly reset
821 function FILTER_RUN_HOURLY_RESET () {
822 // Only execute this filter if installed
823 if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
827 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
828 if ((((isConfigEntrySet('last_hour')) && (getConfig('last_hour') != getHour())) || (isDebugHourlyEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (!isCssOutputMode())) {
829 // Tell every module we are in reset-mode!
834 // Filter for loading more runtime includes (not for installation)
835 function FILTER_LOAD_RUNTIME_INCLUDES () {
836 // Load more includes
837 foreach (array('databases', 'session', 'versions') as $inc) {
839 loadIncludeOnce('inc/' . $inc . '.php');
843 // Filter for checking admin ACL
844 function FILTER_CHECK_ADMIN_ACL () {
845 // Extension not installed so it's always allowed to access everywhere!
848 // Ok, Cookie-Update done
849 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
850 // Check if action GET variable was set
851 $action = getAction();
853 // Get action value by what-value
854 $action = getActionFromModuleWhat('admin', getWhat());
857 // Check for access control line of current menu entry
858 $ret = isAdminsAllowedByAcl($action, getWhat());
862 $GLOBALS['acl_allow'] = $ret;
865 // Init random number/cache buster
866 function FILTER_INIT_RANDOM_NUMBER () {
867 // Is the extension ext-sql_patches installed and at least 0.3.6?
868 if (isSessionVariableSet('random_number')) {
870 setConfigEntry('RAND_NUMBER', getSession('random_number'));
871 } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
872 // Generate random number
873 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 99999), getMemberId(), ''));
875 // Generate *WEAK* code
876 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
879 // Set it in session for faster script execusion
880 setSession('random_number', getConfig('RAND_NUMBER'));
882 // Copy it to CACHE_BUSTER
883 setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
886 // Update module counter
887 function FILTER_COUNT_MODULE () {
888 // Is installation phase?
889 if (isInstallationPhase()) {
890 // Then don't count any modules
894 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ' - ENTERED!');
895 // Do count all other modules but not accesses on CSS file css.php!
896 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
897 array(getModule()), __FUNCTION__, __LINE__);
898 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ',SQL_AFFECTEDROWS()=' . SQL_AFFECTEDROWS() . ' - EXIT!');
901 // Handles fatal errors
902 function FILTER_HANDLE_FATAL_ERRORS () {
903 // Is there errors to handle and right output mode?
904 if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
905 // Abort executing here
910 setContentType('text/html');
913 loadIncludeOnce('inc/load_config.php');
915 // Default content is none
918 // Installation phase or regular mode?
919 if ((isInstallationPhase())) {
920 // While we are installing ouput other header than while it is installed... :-)
922 foreach (getFatalArray() as $key => $value) {
923 // Prepare content for the template
930 $OUT .= loadTemplate('install_fatal_row', TRUE, $content);
933 // Load main template
934 $content = loadTemplate('install_fatal_table', TRUE, $OUT);
935 } elseif (isInstalled()) {
936 // Display all runtime fatal errors
938 foreach (getFatalArray() as $key => $value) {
939 // Prepare content for the template
946 $OUT .= loadTemplate('runtime_fatal_row', TRUE, $content);
949 // Load main template
950 $content = loadTemplate('runtime_fatal_table', TRUE, $OUT);
953 // Message to regular users (non-admin)
954 $CORR = '{--FATAL_REPORT_ERRORS--}';
956 // Maybe the admin wants to take a look?
958 $CORR = '{--FATAL_CORRECT_ERRORS--}';
961 // Remember all in array
968 loadIncludeOnce('inc/header.php');
970 // Load main template
971 loadTemplate('fatal_errors', FALSE, $content);
973 // Delete all to prevent double-display
977 loadIncludeOnce('inc/footer.php');
983 // Filter for displaying copyright line
984 function FILTER_DISPLAY_COPYRIGHT () {
985 // Shall we display the copyright notice?
986 if ((isFullPage()) && ((getWriteFooter() == 'Y') || (isInstalling())) && ($GLOBALS['__header_sent'] == 2) && (ifCopyrightFooterEnabled())) {
988 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
989 // Copyright with backlink, thanks! :-)
990 $GLOBALS['__page_footer'] .= loadTemplate('copyright_backlink', TRUE);
992 // No backlink in Copyright note
993 $GLOBALS['__page_footer'] .= loadTemplate('copyright', TRUE);
998 // Filter for displaying parsing time
999 function FILTER_DISPLAY_PARSING_TIME () {
1000 // Shall we display the parsing time and number of queries?
1001 // 1234 5 54 4 554 4 5543 3 4432 2 332 2 21
1002 if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (isShowTimingsEnabled()) && (isFullPage())) && (!isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['__header_sent'] == 2)) {
1003 // Then display it here
1004 displayParsingTime();
1008 // Filter for flushing template cache
1009 function FILTER_FLUSH_TEMPLATE_CACHE () {
1010 // Do not flush when debugging the template cache
1011 if (isDebugTemplateCacheEnabled()) {
1012 // Do not flush templates in debug-mode
1016 // Is there cached eval() data?
1017 if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
1019 foreach ($GLOBALS['template_eval'] as $prefix => $templateArray) {
1020 foreach ($templateArray as $template => $eval) {
1021 // Flush the cache (if not yet found)
1022 flushTemplateCache($prefix, $template, $eval);
1028 // Filter for loading user data
1029 function FILTER_FETCH_USER_DATA ($userid = NULL) {
1030 // Is the userid not set?
1031 if (!isValidId($userid)) {
1032 // Then use member id
1033 $userid = getMemberId();
1037 if (!fetchUserData($userid)) {
1038 // Userid is not valid
1039 reportBug(__FUNCTION__, __LINE__, 'User id ' . $userid . ' is invalid.');
1043 setMemberId($userid);
1045 // Continue with next filter
1049 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
1050 function FILTER_RESET_USER_LOGIN_FAILURE () {
1051 // Is the user data valid?
1053 // Do only run for logged in members
1054 reportBug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
1057 // Remmeber login failures if available
1058 if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1059 // Reset login failures
1060 SQL_QUERY_ESC("UPDATE
1061 `{?_MYSQL_PREFIX?}_user_data`
1068 array(getMemberId()), __FUNCTION__, __LINE__);
1070 // Store it in session
1071 setSession('mailer_member_failures' , getUserData('login_failures'));
1072 setSession('mailer_member_last_failure', getUserData('last_failure'));
1076 // Try to login the admin by setting some session/cookie variables
1077 function FILTER_DO_LOGIN_ADMIN ($filterData) {
1078 // Now set all session variables and store the result for later processing
1079 $GLOBALS['admin_login_success'] = ((
1080 setAdminMd5(encodeHashForCookie($filterData['pass_hash']))
1082 setAdminId($filterData['id'])
1084 setAdminLast(time())
1087 // Return the data for further processing
1091 // Filter for loading page header, this should be ran first!
1092 function FILTER_LOAD_PAGE_HEADER () {
1093 // Output page header code
1094 $GLOBALS['__page_header'] = loadTemplate('page_header', TRUE);
1096 // Include meta data in 'guest' module
1097 if (isModuleSet()) {
1098 // Load meta data template
1099 $GLOBALS['__page_header'] .= loadTemplate(getMenuModeFromModule() . '_metadata', TRUE);
1101 // Add meta description to header
1102 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP()) && (getModule() == 'index')) {
1103 // Add meta description not in admin and login module and when the script is installed
1104 generateMetaDescriptionCode();
1109 // Filter for adding style sheet, closing page header
1110 function FILTER_FINISH_PAGE_HEADER () {
1111 // Include stylesheet
1112 loadIncludeOnce('inc/stylesheet.php');
1115 $GLOBALS['__page_header'] .= '</head>';
1118 // Cleans up the DNS cache if ext-sql_patches is at least 0.7.0
1119 function FILTER_CLEANUP_DNS_CACHE () {
1120 // Is the latest version installed?
1121 if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1123 loadIncludeOnce('inc/classes/resolver.class.php');
1125 // Instance the resolver
1126 $resolver = new HostnameResolver();
1129 $resolver->purgeEntries();
1131 // Cute, isn't it? ;-)
1135 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1136 function FILTER_SET_CURRENT_DATE () {
1138 setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1140 // Epoche time for yesterday, today ... all at 00:00 am
1141 setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1142 setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1145 // Filter for marking extension as installed
1146 function FILTER_EXTENSION_MARK_INSTALLED ($filterData) {
1147 // Mark it as installed
1148 $GLOBALS['ext_is_installed'][$filterData['ext_name']] = TRUE;
1151 // Filter for generating mails links for 'pool' mails
1152 function FILTER_GENERATE_POOL_MAIL_LINKS ($filterData) {
1153 // Is type 'normal'?
1154 if ($filterData['type'] == 'normal') {
1156 $filterData['__output'] .= loadTemplate('admin_links_' . strtolower($filterData['mail_status']) . '_pool_mail', TRUE, $filterData);
1163 // Filter to activate exchange
1164 function FILTER_ACTIVATE_EXCHANGE () {
1165 // Is the extension 'user' there?
1166 if ((!isExtensionActive('user')) || (getActivateXchange() == '0')) {
1167 // Silently abort here
1171 // Check total amount of users
1172 if (getTotalConfirmedUser() >= getActivateXchange()) {
1174 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N',`hidden`='N',`mem_only`='Y' WHERE `module`='order' LIMIT 1");
1175 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y',`locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1178 runFilterChain('run_sqls');
1180 // Update configuration
1181 updateConfiguration('activate_xchange' ,0);
1184 rebuildCache('modules', 'modules');
1188 // Filter to handle configuration
1189 function FILTER_HANDLE_HOME_IN_INDEX_SETTING ($filterData) {
1190 // Is ext-sql_patches up-to-date?
1191 if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled())) {
1192 // Is 'search' as same as 'index_home'?
1193 if ($filterData['search'] == getIndexHome()) {
1194 // Then set 'content' to link to index.php
1195 $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>';
1203 // Filter to add history entry
1204 function FILTER_ADD_HISTORY_ENTRY ($filterData) {
1206 SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_history` (`history_subject`, `history_userid`, `history_value`) VALUES ('%s',%s,'%s')",
1208 __FUNCTION__, __LINE__);
1210 // Remember insert id for other filters
1211 $filterData['history_id'] = SQL_INSERTID();
1217 // Filter for initializing ext-sql_patches
1218 function FILTER_GENERATE_FILE_SECRET_HASH ($filterData) {
1219 // Transfer POINTS word
1220 if (isExtensionInstalledAndNewer('sql_patches', '0.0.3')) {
1221 // Okay, recent enough, so transfer the word for POINTS
1222 setConfigEntry('POINTS', getPointsWord());
1226 setConfigEntry('secret_key', '');
1228 // Read key from secret file
1229 if ((getFileHash() == '') || (getMasterSalt() == '') || (getPassScramble() == '')) {
1230 // Maybe need setup of secret key!
1231 loadIncludeOnce('inc/gen_sql_patches.php');
1235 if ((getFileHash() != '') && (getMasterSalt() != '') && (getPassScramble() != '')) {
1236 // File hash fas generated so we can also file the secret file... hopefully.
1237 $hashFile = sprintf("%s%s.%s.cache", getPath(), getCachePath(), getFileHash());
1239 // Is the secret key file readable?
1240 if (isFileReadable($hashFile)) {
1242 setConfigEntry('secret_key', readFromFile($hashFile));
1244 // Remove it from database
1245 updateConfiguration('file_hash', '');
1247 // Cannot read secret file!
1248 reportBug(__FILE__, __LINE__, 'Cannot read secret file! Please try to reload.');
1256 // Filter to initialize session
1257 function FILTER_INIT_SESSION ($filterData) {
1258 // Determine and set referral id
1259 determineReferralId();
1265 // Filter for sending "build mail" to admin
1266 function FILTER_SEND_BUILD_MAIL ($filterData) {
1267 // Was one line updated?
1268 if (($filterData['affected'] > 0) || (isDebugBuildMailsEnabled())) {
1269 // Then call the proper function
1270 call_user_func_array('sendGenericBuildMails', $filterData);
1277 // Handles click on referral banner
1278 function FILTER_HANDLE_REFERRER_BANNER_CLICK ($filterData) {
1279 // Check required parameters
1280 if ((isGetRequestElementSet('user')) && (isGetRequestElementSet('banner'))) {
1281 // Update clicks counter...
1282 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refbanner` SET `clicks`=`clicks`+1 WHERE `id`=%s LIMIT 1",
1283 array(bigintval(getRequestElement('banner'))), __FUNCTION__, __LINE__);
1285 // A line has been updated?
1286 if ((!SQL_HASZEROAFFECTED()) && (isGetRequestElementSet('user'))) {
1287 // Redirect to the user's referral link
1288 redirectToUrl('ref.php?refid=' . bigintval(getRequestElement('user')));
1292 // Return filter data
1296 // Filter for handling viewing of a referral banner
1297 function FILTER_HANDLE_REFERRER_BANNER_VIEW ($filterData) {
1298 // Are all required parameters set
1299 if ((isGetRequestElementSet('user')) && (isGetRequestElementSet('banner'))) {
1300 // For later things... ;-)
1301 $result = SQL_QUERY_ESC("SELECT `url` FROM `{?_MYSQL_PREFIX?}_refbanner` WHERE `id`=%s LIMIT 1",
1302 array(bigintval(getRequestElement('banner'))), __FUNCTION__, __LINE__);
1304 // Is there the banner?
1305 if (SQL_NUMROWS($result) == 1) {
1307 $data = SQL_FETCHARRAY($result);
1310 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_refbanner` SET `counter`=`counter`+1 WHERE `id`=%s LIMIT 1",
1311 array(bigintval(getRequestElement('banner'))), __FUNCTION__, __LINE__);
1313 // Set header and ...
1314 setContentType('image/' . substr($data['url'], -3, 3));
1317 redirectToUrl($data['url'], FALSE);
1320 // @TODO No banner found, output some default banner
1321 logDebugMessage(__FUNCTION__, __LINE__, 'Banner ' . bigintval(getRequestElement('banner')) . ' not found.');
1324 SQL_FREERESULT($result);
1327 // Do nothing for now
1328 redirectToUrl('modules.php?module=index');
1331 // Filter for redirecting on wrong server name (e.g. bad.your-server.tld will be redirected to your-server.tld)
1332 function FILTER_REDIRECT_WRONG_SERVER_NAME ($filterData) {
1336 // Is the configured URL same as SERVER_NAME?
1337 if (extractHostnameFromUrl($url) != detectServerName()) {
1339 logWrongServerNameRedirect();
1341 // Then redirect to configured URL
1342 redirectToRequestUri();
1345 // Return filter data
1349 // Filter for adding hidden session id
1350 function FILTER_ADD_INPUT_HIDDEN_SESSION_ID ($filterData) {
1351 // Is a spider detected?
1352 if ((!isSpider()) && (!isSessionValid()) && ($filterData['__form_method'] == 'get')) {
1353 // No, then add the hidden field
1354 $filterData['__replacer'] .= '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
1357 // Return filter data
1361 // Filter for purging old SERVER_NAME entries
1362 function FILTER_SERVER_NAME_EXTRA_AUTOPURGE ($filterData) {
1363 // Is purging configured?
1364 if ((isApServerNameEnabled()) && (getApServerNameSince() > 0)) {
1365 // Then start purging
1366 SQL_QUERY('DELETE LOW_PRIORITY FROM
1367 `{?_MYSQL_PREFIX?}_server_name_log`
1369 (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`server_name_added`)) >= {?ap_server_name_since?}',
1370 __FILE__, __LINE__);
1372 // Are some entries deleted?
1373 if (SQL_AFFECTEDROWS() > 0) {
1374 // Okay, then send an email to the admin
1375 sendAdminNotification('{--ADMIN_PURGE_USER_SERVER_NAME_LOG_SUBJECT--}', 'admin_purge_user_server_name_log', SQL_AFFECTEDROWS());
1379 // Return filter data
1383 // Filter for detecting menu mode
1384 function FILTER_DETERMINE_MENU_MODE_GENERIC ($filterData) {
1386 switch (getModule()) {
1387 case 'confirm': // Login script is 'member'
1388 $filterData = 'member';
1392 // Return filter data
1396 // Filter to exclude default referral id
1397 function FILTER_EXCLUDE_DEFAULT_REFID ($filterData = array()) {
1399 if (isValidId(getDefRefid())) {
1401 array_push($filterData, '{?def_refid?}');