2 /************************************************************************
3 * MXChange v0.2.1 Start: 12/16/2008 *
4 * =============== Last change: 12/16/2008 *
6 * -------------------------------------------------------------------- *
8 * -------------------------------------------------------------------- *
9 * Short description : Functions for filter system *
10 * -------------------------------------------------------------------- *
11 * Kurzbeschreibung : Funktionen fuer Filter-System *
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 - 2008 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')) {
41 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
45 // Init "generic filter system"
46 function initFilterSystem () {
47 // Is the filter already initialized?
48 if ((isset($GLOBALS['filters']['chains'])) && (is_array($GLOBALS['filters']['chains']))) {
50 debug_report_bug(getMessage('FILTER_FAILED_ALREADY_INIT'));
53 // Init the filter system (just some ideas)
54 $GLOBALS['filters']['chains'] = array(
55 'preinit' => array(), // Filters for pre-init phase
56 'postinit' => array(), // Filters for post-init phase
57 'shutdown' => array() // Filters for shutdown phase
60 // Init loaded filters and counter
61 $GLOBALS['filters']['loaded'] = array();
62 $GLOBALS['filters']['counter'] = array();
64 // Load all saved filers if sql_patches is updated
65 if (isset($GLOBALS['cache_array']['filter']['filter_name'])) {
66 // Found in cache so rewrite the array
67 $filterArray = array();
68 foreach ($GLOBALS['cache_array']['filter']['filter_name'] as $idx => $filterName) {
69 // Get filter function
70 $filterFunction = $GLOBALS['cache_array']['filter']['filter_function'][$idx];
72 // Add the element with mapped index
73 $filterArray['counter'][$filterName][$filterFunction] = $GLOBALS['cache_array']['filter']['filter_counter'][$idx];
74 $filterArray['loaded'][$filterName][$filterFunction] = true;
75 $filterArray['chains'][$filterName][$filterFunction] = $GLOBALS['cache_array']['filter']['filter_active'][$idx];
79 //die('<pre>'.print_r($filterArray, true).'</pre>');
80 $GLOBALS['filters'] = $filterArray;
83 unset($GLOBALS['cache_array']['filter']);
84 } elseif (GET_EXT_VERSION('sql_patches') >= '0.5.9') {
87 if (GET_EXT_VERSION('sql_patches') >= '0.6.0') $add = ", `filter_counter`";
89 // Load all active filers
90 $result = SQL_QUERY("SELECT `filter_name`,`filter_function`,`filter_active`".$add."
91 FROM `{!_MYSQL_PREFIX!}_filters`
92 ORDER BY `filter_id` ASC", __FUNCTION__, __LINE__);
95 if (SQL_NUMROWS($result) > 0) {
97 while ($filterArray = SQL_FETCHARRAY($result)) {
98 // Get filter name and function
99 $filterName = $filterArray['filter_name'];
100 $filterFunction = $filterArray['filter_function'];
102 // Set counter to default
103 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 0;
105 // Mark this filter as loaded (from database)
106 $GLOBALS['filters']['loaded'][$filterName][$filterFunction] = true;
109 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = $filterArray['filter_active'];
111 // Is the array element for counter there?
112 if (isset($filterArray['filter_counter'])) {
113 // Then use this value!
114 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = $filterArray['filter_counter'];
120 SQL_FREERESULT($result);
124 registerFilter('init', 'UPDATE_LOGIN_DATA');
125 registerFilter('init', 'INIT_RANDOMIZER');
126 registerFilter('init', 'DETERMINE_USERNAME');
128 // Login failures handler
129 registerFilter('post_youhere_line', 'CALL_HANDLER_LOGIN_FAILTURES');
131 // Filters for pre-extension-registration
132 registerFilter('pre_extension_installed', 'RUN_SQLS');
134 // Filters for post-extension-registration
135 registerFilter('post_extension_installed', 'AUTO_ACTIVATE_EXTENSION');
136 registerFilter('post_extension_installed', 'SOLVE_TASK');
137 registerFilter('post_extension_installed', 'LOAD_INCLUDES');
138 registerFilter('post_extension_installed', 'REMOVE_UPDATES');
141 registerFilter('solve_task', 'SOLVE_TASK');
143 // Loading includes in general
144 registerFilter('load_includes', 'LOAD_INCLUDES');
147 registerFilter('run_sqls', 'RUN_SQLS');
150 registerFilter('check_admin_acl', 'CHECK_ADMIN_ACL');
152 // Register shutdown filters
153 registerFilter('shutdown', 'FLUSH_FILTERS');
156 // "Registers" a new filter function
157 function registerFilter ($filterName, $filterFunction, $silentAbort = true, $force = false, $dry_run = false) {
158 // Extend the filter function name
159 $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
161 // Is that filter already there?
162 if ((isset($GLOBALS['filters']['chains'][$filterName][$filterFunction])) && (!$force)) {
164 if ($silentAbort === false) {
165 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_ALREADY_ADDED'), array($filterFunction, $filterName));
172 // Is the function there?
173 if (!function_exists($filterFunction)) {
175 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NOT_FOUND'), array($filterFunction, $filterName));
181 // Simply add it to the array
182 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = 'Y';
183 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 0;
187 // "Unregisters" a filter from the given chain
188 function unregisterFilter ($filterName, $filterFunction, $force = false, $dry_run = false) {
189 // Extend the filter function name only if not loaded from database
190 if (!isset($GLOBALS['filters']['loaded'][$filterName][$filterFunction])) {
191 $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
194 // Is that filter there?
195 if ((!isset($GLOBALS['filters']['chains'][$filterName][$filterFunction])) && (!$force)) {
196 // Not found, so abort here
197 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NOT_REMOVED'), array($filterFunction, $filterName));
201 // Shall we remove? (default, not while just showing an extension removal)
202 if ($dry_run === false) {
203 // Mark for filter removal
204 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = 'R';
208 // "Runs" the given filters, data is optional and can be any type of data
209 function runFilterChain ($filterName, $data = null) {
210 // Is that filter chain there?
211 if (!isset($GLOBALS['filters']['chains'][$filterName])) {
212 // We should find all these non-existing filter chains
213 DEBUG_LOG(__FUNCTION__, __LINE__, 'Filter chain ' . $filterName . ' not found!');
219 // Default return value
220 $returnValue = $data;
222 // Then run all filters
223 foreach ($GLOBALS['filters']['chains'][$filterName] as $filterFunction => $active) {
225 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Running: name={$filterName},func={$filterFunction},active={$active}");
227 // Is the filter active?
228 if (($active == 'Y') || ((in_array($filterName, array('extension_remove', 'post_extension_run_sql'))) && ($active == 'R'))) {
229 // Is this filter there?
230 if (!function_exists($filterFunction)) {
232 unregisterFilter($filterName, $filterFunction);
238 // Call the filter chain
239 $returnValue = call_user_func_array($filterFunction, array($returnValue));
241 // Update usage counter
242 countFilterUsage($filterName, $filterFunction);
243 } elseif (isDebugModeEnabled()) {
245 DEBUG_LOG(__FUNCTION__, __LINE__, "Skipped: name={$filterName},func={$filterFunction},active={$active}");
249 // Return the filtered content
253 // Count the filter usage
254 function countFilterUsage ($filterName, $filterFunction) {
256 if (isset($GLOBALS['filters']['counter'][$filterName][$filterFunction])) {
257 // Yes, then increase
258 $GLOBALS['filters']['counter'][$filterName][$filterFunction]++;
261 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 1;
265 // -----------------------------------------------------------------------------
266 // Generic filter functions we always need
267 // -----------------------------------------------------------------------------
269 // Filter for flushing all new filters to the database
270 function FILTER_FLUSH_FILTERS () {
271 // Clear all previous SQL queries
274 // Are we installing?
275 if ((isInstalling()) || (!isInstalled())) {
276 // Then silently skip this filter
280 // Is a database link here and not in installation mode?
281 if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
283 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'));
287 // Is the extension sql_patches updated?
288 if (EXT_VERSION_IS_OLDER('sql_patches', '0.5.9')) {
289 // Abort silently here
293 // Nothing is added/remove by default
297 // Prepare SQL queries
298 $insertSQL = "INSERT INTO `{!_MYSQL_PREFIX!}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES";
299 $removeSQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_filters` WHERE";
301 // Write all filters to database
302 foreach ($GLOBALS['filters']['chains'] as $filterName => $filterArray) {
303 // Walk through all filters
304 foreach ($filterArray as $filterFunction => $active) {
305 // Is this filter loaded?
306 if (!isset($GLOBALS['filters']['loaded'][$filterName][$filterFunction])) {
307 // Add this filter (all filters are active by default)
308 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
310 } elseif ($active == 'R') {
311 // Remove this filter
312 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
318 // Something has been added?
320 // Finish SQL command
321 $insertSQL = substr($insertSQL, 0, -1);
327 // Something has been removed?
329 // Finish SQL command
330 $removeSQL = substr($removeSQL, 0, -2) . 'LIMIT '.$removed;
336 // Shall we update usage counters (ONLY FOR DEBUGGING!)
337 if (getConfig('update_filter_usage') == 'Y') {
338 // Update all counters
339 foreach ($GLOBALS['filters']['counter'] as $filterName => $filterArray) {
340 // Walk through all filters
341 foreach ($filterArray as $filterFunction => $cnt) {
342 // Construct and add the query
343 ADD_SQL(sprintf("UPDATE `{!_MYSQL_PREFIX!}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
352 // Run the run_sqls filter in non-dry mode
353 runFilterChain('run_sqls');
356 // Filter for calling the handler for login failures
357 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
361 // Handle failed logins here if not in guest
362 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={getAction()},what={getWhat()},lvl={$data['access_level']}<br />");
363 if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getConfig('index_home')))) && ($data['access_level'] != 'guest') && ((GET_EXT_VERSION('sql_patches') >= '0.4.7') || (GET_EXT_VERSION('admins') >= '0.7.0'))) {
365 $content['content'] .= HANDLE_LOGIN_FAILTURES($data['access_level']);
368 // Return the content
372 // Filter for redirecting to logout if sql_patches has been installed
373 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
374 // Remove this filter
375 unregisterFilter('shutdown', __FUNCTION__);
377 // Is the element set?
378 if (isset($GLOBALS['ext_load_mode'])) {
380 redirectToUrl('modules.php?module=admin&logout=1&' . $GLOBALS['ext_load_mode'] . '=sql_patches');
383 // This should not happen!
384 DEBUG_LOG(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
387 // Filter for auto-activation of a extension
388 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
389 // Is this extension always activated?
390 if (EXT_GET_ALWAYS_ACTIVE() == 'Y') {
391 // Then activate the extension
392 //* DEBUG: */ OUTPUT_HTML(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$data['ext_name']}<br />");
393 ACTIVATE_EXTENSION($data['ext_name']);
400 // Filter for solving task given task
401 function FILTER_SOLVE_TASK ($data) {
402 // Don't solve anything if no admin!
403 if (!IS_ADMIN()) return $data;
405 // Is this a direct task id or array element task_id is found?
408 ADMIN_SOLVE_TASK($data);
409 } elseif ((is_array($data)) && (isset($data['task_id']))) {
411 ADMIN_SOLVE_TASK($data['task_id']);
418 // Filter to load include files
419 function FILTER_LOAD_INCLUDES () {
420 // Default is $data as inclusion list
421 $data = GET_INC_POOL();
424 if ((!isset($data)) || (!is_array($data))) {
426 debug_report_bug(sprintf("INC_POOL is no array! Type: %s", gettype($data)));
427 } elseif (isset($data['inc_pool'])) {
428 // Use this as new inclusion pool!
429 SET_INC_POOL($data['inc_pool']);
432 // Check for added include files
433 if (COUNT_INC_POOL() > 0) {
434 // Loads every include file
435 foreach (GET_INC_POOL() as $FQFN) {
436 loadIncludeOnce($FQFN);
443 // Continue with processing
447 // Filter for running SQL commands
448 function FILTER_RUN_SQLS ($data) {
450 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "- Entered!");
452 // Is the array there?
453 if ((IS_SQLS_VALID()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
455 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "- Found ".COUNT_SQLS()." queries to run.");
456 foreach (GET_SQLS() as $sql) {
460 // Is there still a query left?
462 // Do we have an "ALTER TABLE" command?
463 if (substr(strtolower($sql), 0, 11) == "alter table") {
464 // Analyse the alteration command
465 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Alterting table: {$sql}");
466 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__);
468 // Run regular SQL command
469 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Running regular query: {$sql}");
470 SQL_QUERY($sql, __FUNCTION__, __LINE__, false);
477 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "- Left!");
480 // Filter for updating/validating login data
481 function FILTER_UPDATE_LOGIN_DATA () {
483 if ((!isset($GLOBALS['last'])) || (!is_array($GLOBALS['last']))) $GLOBALS['last'] = array();
485 // Recheck if logged in
486 if (!IS_MEMBER()) return false;
489 setUserId(getSession('userid'));
491 // Load last module and last online time
492 $result = SQL_QUERY_ESC("SELECT `last_module`, `last_online` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
493 array(getUserId()), __FUNCTION__, __LINE__);
496 if (SQL_NUMROWS($result) == 1) {
497 // Load last module and online time
498 $DATA = SQL_FETCHARRAY($result);
500 // Maybe first login time?
501 if (empty($DATA['last_module'])) $DATA['last_module'] = 'login';
503 // This will be displayed on welcome page! :-)
504 if (empty($GLOBALS['last']['module'])) {
505 $GLOBALS['last']['module'] = $DATA['last_module']; $GLOBALS['last']['online'] = $DATA['last_online'];
512 if (getConfig('index_home') != '') setWhatFromConfig('index_home');
515 // Update last module / online time
516 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
521 ), __FUNCTION__, __LINE__);
523 // Destroy session, we cannot update!
524 destroyUserSession();
528 SQL_FREERESULT($result);
531 // Filter for checking admin ACL
532 function FILTER_CHECK_ADMIN_ACL () {
533 // Extension not installed so it's always allowed to access everywhere!
536 // Ok, Cookie-Update done
537 if ((GET_EXT_VERSION('admins') >= '0.3.0') && (EXT_IS_ACTIVE('admins'))) {
538 // Check if action GET variable was set
539 $action = getAction();
541 // Get action value by what-value
542 $action = getModeAction('admin', getWhat());
545 // Check for access control line of current menu entry
546 $ret = adminsCheckAdminAcl($action, getWhat());
553 // Filter for initializing randomizer
554 function FILTER_INIT_RANDOMIZER () {
555 // Simply init the randomizer with seed and _ADD value
556 mt_srand(generateSeed() + getConfig('_ADD'));
559 // Filter for removing updates
560 function FILTER_REMOVE_UPDATES () {
562 EXT_INIT_REMOVAL_LIST();
564 // Add the current extension to it
565 EXT_ADD_CURRENT_TO_REMOVAL_LIST();
570 // Do we need to remove update depency?
571 if (EXT_COUNT_UPDATE_DEPENDS() > 0) {
572 // Then find all updates we shall no longer execute
573 foreach (EXT_GET_UPDATE_DEPENDS() as $id=>$ext_name) {
574 // Shall we remove this update?
575 if (in_array($ext_name, EXT_GET_REMOVAL_LIST())) {
576 // Then remove this extension!
577 EXT_REMOVE_UPDATE_DEPENDS($ext_name);
583 // Determines username for current user state
584 function FILTER_DETERMINE_USERNAME () {
587 // Check if logged in
589 // Is still logged in so we welcome him with his name
590 $result = SQL_QUERY_ESC("SELECT `surname`, `family` FROM `{!_MYSQL_PREFIX!}_user_data` WHERE `userid`=%s LIMIT 1",
591 array(getUserId()), __FILE__, __LINE__);
592 if (SQL_NUMROWS($result) == 1) {
593 // Load surname and family's name and build the username
594 list($s, $f) = SQL_FETCHROW($result);
595 $username = $s . ' ' . $f;
597 // Additionally admin?
600 $username .= ' ({--_ADMIN_SHORT--})';
603 // Hmmm, logged in and no valid userid?
604 $username = '<em>{--_UNKNOWN--}</em>';
607 destroyUserSession();
614 SQL_FREERESULT($result);
615 } elseif (IS_ADMIN()) {
617 $username = getMessage('_ADMIN');
619 // He's a guest, hello there... ;-)
620 $username = getMessage('_GUEST');