2 /************************************************************************
3 * MXChange v0.2.1 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 * Needs to be in all Files and every File needs "svn propset *
18 * svn:keywords Date Revision" (autoprobset!) at least!!!!!! *
19 * -------------------------------------------------------------------- *
20 * Copyright (c) 2003 - 2009 by Roland Haeder *
21 * For more information visit: http://www.mxchange.org *
23 * This program is free software; you can redistribute it and/or modify *
24 * it under the terms of the GNU General Public License as published by *
25 * the Free Software Foundation; either version 2 of the License, or *
26 * (at your option) any later version. *
28 * This program is distributed in the hope that it will be useful, *
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
31 * GNU General Public License for more details. *
33 * You should have received a copy of the GNU General Public License *
34 * along with this program; if not, write to the Free Software *
35 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
37 ************************************************************************/
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
44 // Filter for flushing all new filters to the database
45 function FILTER_FLUSH_FILTERS () {
46 // Clear all previous SQL queries
50 if ((isInstallationPhase())) {
51 // Then silently skip this filter
55 // Is a database link here and not in installation mode?
56 if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
58 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'));
62 // Is the extension sql_patches updated?
63 if ((!isExtensionInstalled('sql_patches')) || (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: */ print 'FOUND:'.$filterName.'/'.$filterFunction.'='.$active.'<br />';
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: */ print 'ADD:'.$filterName.'/'.$filterFunction.'<br />';
85 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
87 } elseif ($active == 'R') {
89 //* DEBUG: */ print 'REMOVE:'.$filterName.'/'.$filterFunction.'<br />';
90 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
96 // Something has been added?
99 $insertSQL = substr($insertSQL, 0, -1);
105 // Something has been removed?
107 // Finish SQL command
108 $removeSQL = substr($removeSQL, 0, -2) . 'LIMIT '.$removed;
114 // Shall we update usage counters (ONLY FOR DEBUGGING!)
115 if (getConfig('update_filter_usage') == 'Y') {
116 // Update all counters
117 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
118 // Walk through all filters
119 foreach ($filterArray as $filterFunction => $cnt) {
120 // Construct and add the query
121 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
130 // Run the run_sqls filter in non-dry mode
131 runFilterChain('run_sqls');
133 // Should we rebuild cache?
134 if (($inserted > 0) || ($removed > 0)) {
136 rebuildCacheFile('filter', 'filter');
140 // Filter for calling the handler for login failures
141 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
145 // Handle failed logins here if not in guest
146 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={getAction()},what={getWhat()},level={$data['access_level']}<br />");
147 if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getConfig('index_home')))) && ($data['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.0')))) {
149 $content['content'] .= handleLoginFailtures($data['access_level']);
152 // Return the content
156 // Filter for redirecting to logout if sql_patches has been installed
157 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
158 // Remove this filter
159 unregisterFilter('shutdown', __FUNCTION__);
161 // Is the element set?
162 if (isset($GLOBALS['ext_load_mode'])) {
164 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
167 // This should not happen!
168 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
171 // Filter for auto-activation of a extension
172 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
173 // Is this extension always activated?
174 if (getExtensionAlwaysActive() == 'Y') {
175 // Then activate the extension
176 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$data['ext_name']}<br />");
177 doActivateExtension($data['ext_name']);
184 // Filter for solving task given task
185 function FILTER_SOLVE_TASK ($data) {
186 // Don't solve anything if no admin!
187 if (!isAdmin()) return $data;
189 // Is this a direct task id or array element task_id is found?
192 adminSolveTask($data);
193 } elseif ((is_array($data)) && (isset($data['task_id']))) {
195 adminSolveTask($data['task_id']);
198 debug_report_bug(sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
205 // Filter to load include files
206 function FILTER_LOAD_INCLUDES ($pool) {
208 if (is_null($pool)) {
209 // This should not happen!
210 debug_report_bug('pool is null.');
213 // Is the pool an array and 'pool' set?
214 if ((is_array($pool)) && (isset($pool['pool']))) {
215 // Then use it as pool
216 $realPool = $pool['pool'];
218 // Default is $data as inclusion list
223 $data = getIncludePool($realPool);
226 if ((!isset($data)) || (!is_array($data))) {
228 debug_report_bug(sprintf("INC_POOL is no array! Type: %s", gettype($data)));
229 } elseif (isset($data['inc_pool'])) {
230 // Use this as new inclusion pool!
231 setIncludePool($realPool, $data['inc_pool']);
234 // Check for added include files
235 if (countIncludePool($realPool) > 0) {
236 // Loads every include file
237 loadIncludePool($realPool);
240 initIncludePool($realPool);
243 // Continue with processing
247 // Filter for running SQL commands
248 function FILTER_RUN_SQLS ($data) {
250 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Entered!");
252 // Is the array there?
253 if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
255 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Found ".countSqls()." queries to run.");
256 foreach (getSqls() as $sqls) {
257 // New cache format...
258 foreach ($sqls as $sql) {
262 // Is there still a query left?
264 // Do we have an "ALTER TABLE" command?
265 if (substr(strtolower($sql), 0, 11) == 'alter table') {
266 // Analyse the alteration command
267 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Alterting table: {$sql}");
268 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__);
270 // Run regular SQL command
271 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Running regular query: {$sql}");
272 SQL_QUERY($sql, __FUNCTION__, __LINE__, false);
280 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Left!");
283 // Filter for updating/validating login data
284 function FILTER_UPDATE_LOGIN_DATA () {
286 if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
288 // Recheck if logged in
289 if (!isMember()) return false;
292 setUserId(getSession('userid'));
294 // Load last module and last online time
295 $result = SQL_QUERY_ESC("SELECT `last_module`, `last_online` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
296 array(getUserId()), __FUNCTION__, __LINE__);
299 if (SQL_NUMROWS($result) == 1) {
300 // Load last module and online time
301 $content = SQL_FETCHARRAY($result);
303 // Maybe first login time?
304 if (empty($content['last_module'])) $content['last_module'] = 'login';
306 // This will be displayed on welcome page! :-)
307 if (empty($GLOBALS['last_online']['module'])) {
308 $GLOBALS['last_online']['module'] = $content['last_module']; $GLOBALS['last_online']['online'] = $content['last_online'];
315 if (getConfig('index_home') != '') setWhatFromConfig('index_home');
318 // Update last module / online time
319 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
324 ), __FUNCTION__, __LINE__);
326 // Destroy session, we cannot update!
327 destroyUserSession();
331 SQL_FREERESULT($result);
334 // Filter for checking admin ACL
335 function FILTER_CHECK_ADMIN_ACL () {
336 // Extension not installed so it's always allowed to access everywhere!
339 // Ok, Cookie-Update done
340 if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
341 // Check if action GET variable was set
342 $action = getAction();
344 // Get action value by what-value
345 $action = getModeAction('admin', getWhat());
348 // Check for access control line of current menu entry
349 $ret = adminsCheckAdminAcl($action, getWhat());
356 // Filter for initializing randomizer
357 function FILTER_INIT_RANDOMIZER () {
358 // Simply init the randomizer with seed and _ADD value
359 mt_srand(generateSeed() + getConfig('_ADD'));
362 // Filter for removing updates
363 function FILTER_REMOVE_UPDATES ($data) {
365 initExtensionRemovalList();
367 // Add the current extension to it
368 addCurrentExtensionToRemovalList();
371 unsetExtensionSqls();
373 // Do we need to remove update depency?
374 if (countExtensionUpdateDependencies() > 0) {
375 // Then find all updates we shall no longer execute
376 foreach (getExtensionUpdateDependencies() as $id=>$ext_name) {
377 // Shall we remove this update?
378 if (in_array($ext_name, getExtensionRemovalList())) {
379 // Then remove this extension!
380 removeExtensionUpdateDependency($ext_name);
389 // Determines username for current user state
390 function FILTER_DETERMINE_USERNAME () {
391 // Check if logged in
393 // Is still logged in so we welcome him with his name
394 $result = SQL_QUERY_ESC("SELECT `surname`, `family` FROM `{?_MYSQL_PREFIX?}_user_data` WHERE `userid`=%s LIMIT 1",
395 array(getUserId()), __FILE__, __LINE__);
396 if (SQL_NUMROWS($result) == 1) {
397 // Load surname and family's name and build the username
398 $content = SQL_FETCHARRAY($result);
401 setUsername($content['surname'] . ' ' . $content['family']);
403 // Additionally admin?
406 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
409 // Hmmm, logged in and no valid userid?
410 setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
413 destroyUserSession();
420 SQL_FREERESULT($result);
421 } elseif (isAdmin()) {
423 setUsername('{--USERNAME_ADMIN--}');
425 // He's a guest, hello there... ;-)
426 setUsername('{--USERNAME_GUEST--}');
430 // Filter for compiling config entries
431 function FILTER_COMPILE_CONFIG ($code) {
432 // Compile {?some_var?} to getConfig('some_var')
433 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
435 // Some entries found?
436 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
437 // Replace all matches
438 foreach ($matches[0] as $key => $match) {
440 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
441 // Is the config valid?
442 if (isConfigEntrySet($matches[1][$key])) {
443 // Set it for caching
444 $GLOBALS['compile_config'][$matches[1][$key]] = getConfig($matches[1][$key]);
446 // No config, try the language system
447 $GLOBALS['compile_config'][$matches[1][$key]] = getMessage('DEFAULT_' . strtoupper($matches[1][$key]));
451 // Use this for replacing
452 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
453 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die('<pre>'.htmlentities($code).'</pre>');
457 // Return compiled code
461 // Filter for compiling extension data
462 function FILTER_COMPILE_EXTENSION ($code) {
463 // Compile {%cmd=some_value%} to get extension data
465 // - version -> getExtensionVersion() call
466 preg_match_all('/\{%((([a-zA-Z0-9-_]+)=([a-zA-Z0-9-_]+))*)\%\}/', $code, $matches);
468 // Some entries found?
469 if ((count($matches) > 0) && (count($matches[3]) > 0)) {
470 // Replace all matches
471 foreach ($matches[3] as $key => $cmd) {
472 // Construct call-back function name
473 $functionName = 'getExtension' . ucfirst(strtolower($cmd));
476 $replacer = call_user_func_array($functionName, $matches[4][$key]);
478 // Replace it and insert parameter for GET request
479 $code = str_replace($matches[0][$key], sprintf("&%s=%s&rev=%s", $cmd, $replacer, getConfig('CURR_SVN_REVISION')), $code);
483 // Return compiled code
487 // Runs some generic filter update steps
488 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
490 createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
492 // Update extension's version
493 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
494 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
498 unset($GLOBALS['update_ver'][$ext_name]);
501 // Load more reset scripts
502 function FILTER_RUN_RESET_INCLUDES () {
503 // Is the reset set or old sql_patches?
504 if ((!isResetModeEnabled()) || (!isExtensionInstalledAndOlder('sql_patches', '0.4.5'))) {
506 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot run reset! Please report this bug. Thanks');
509 // Get more daily reset scripts
510 setIncludePool('reset', getArrayFromDirectory('inc/reset/', 'reset_'));
513 if (getConfig('DEBUG_RESET') != 'Y') updateConfiguration('last_update', time());
515 // Is the config entry set?
516 if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
517 // Create current week mark
518 $currWeek = date('W', time());
521 if ((getConfig('last_week') != $currWeek) || (getConfig('DEBUG_WEEKLY') == 'Y')) {
522 // Include weekly reset scripts
523 mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
526 if (getConfig('DEBUG_WEEKLY') != 'Y') updateConfiguration('last_week', $currWeek);
529 // Create current month mark
530 $currMonth = date('m', time());
533 if ((getConfig('last_month') != $currMonth) || (getConfig('DEBUG_MONTHLY') == 'Y')) {
534 // Include monthly reset scripts
535 mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
538 if (getConfig('DEBUG_MONTHLY') != 'Y') updateConfiguration('last_month', $currMonth);
543 runFilterChain('load_includes', 'reset');
546 // Filter for removing the given extension
547 function FILTER_REMOVE_EXTENSION () {
548 // Delete this extension (remember to remove it from your server *before* you click on welcome!
549 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
550 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
552 // Remove the extension from global cache array as well
553 removeExtensionFromArray();
556 rebuildCacheFile('extension', 'extension');
559 // Filter for flushing the output
560 function FILTER_FLUSH_OUTPUT () {
565 // Prepares an SQL statement part for HTML mail and/or holiday depency
566 function FILTER_HTML_INCLUDE_USERS ($mode) {
567 // Exclude no users by default
571 if ($mode == 'html') $MORE = " AND `html`='Y'";
572 if ((isExtensionActive('holiday')) && (getExtensionVersion('holiday') >= '0.1.3')) {
573 // Add something for the holiday extension
574 $MORE .= " AND `holiday_active`='N'";
581 // Filter for determining what/action/module
582 function FILTER_DETERMINE_WHAT_ACTION () {
583 // In installation phase we don't have what/action
584 if (isInstallationPhase()) {
594 if ((getOutputMode() != 1) && (getOutputMode() != -1)) {
596 if (!isModuleSet()) setModule('index');
598 // Fix 'what' if not yet set
599 if (!isWhatSet()) setWhat(getWhatFromModule(getModule()));
601 // Fix 'action' if not yet set
602 if (!isActionSet()) setAction(getModeAction(getModule(), getWhat()));
604 // Set action/what to empty
609 // Set default 'what' value
610 //* DEBUG: */ outputHtml('-'.getModule().'/'.getWhat()."-<br />");
611 if ((!isWhatSet()) && (!isActionSet()) && (getOutputMode() != 1) && (getOutputMode() != -1)) {
612 if (getModule() == 'admin') {
613 // Set 'action' value to 'login' in admin menu
614 setAction(getModeAction(getModule(), getWhat()));
615 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
616 // Set 'what' value to 'welcome' in guest and member menu
617 setWhatFromConfig('index_home');
619 // Anything else like begging link
625 // Sends out pooled mails
626 function FILTER_TRIGGER_SENDING_POOL () {
627 // Are we in normal output mode?
628 if (getOutputMode() != '0') {
629 // Only in normal output mode to prevent race-conditons!
633 $GLOBALS['pool_cnt'] = 0;
635 // Init & set the include pool
636 initIncludePool('pool');
637 setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
640 runFilterChain('load_includes', 'pool');
642 // Remove the counter
643 unset($GLOBALS['pool_cnt']);
646 // Filter for checking and updating SVN revision
647 function FILTER_CHECK_SVN_REVISION () {
648 // Check for patch level differences between databases and current hard-coded
649 if ((getConfig('CURR_SVN_REVISION') > getConfig('patch_level')) || (getConfig('patch_level') == 'CURR_SVN_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
650 // Update database and CONFIG array
651 updateConfiguration(array('patch_level', 'patch_ctime'), array(getConfig('CURR_SVN_REVISION'), 'UNIX_TIMESTAMP()'));
652 setConfigEntry('patch_level', getConfig('CURR_SVN_REVISION'));
653 setConfigEntry('patch_ctime', time());
657 // Filter for running daily reset
658 function FILTER_RUN_DAILY_RESET () {
659 // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
660 // 012 3 4 43 3 4432 2 3 3 21 1 221 1 221 1 2 21 1 22 10
661 if (((date('d', getConfig('last_update')) != date('d', time())) || (getConfig('DEBUG_RESET') == 'Y')) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (getOutputMode() != 1)) {
662 // Tell every module we are in reset-mode!
667 // Filter for loading more runtime includes (not for installation)
668 function FILTER_LOAD_RUNTIME_INCLUDES () {
669 // Load more includes
670 foreach (array('inc/session.php','inc/versions.php') as $inc) {
672 loadIncludeOnce($inc);
675 // Load admin include file if he is admin
677 // Administrative functions
678 loadIncludeOnce('inc/modules/admin/admin-inc.php');
680 //* DEBUG: */ addPointsThroughReferalSystem('test', 36, 1000);