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 * -------------------------------------------------------------------- *
14 * -------------------------------------------------------------------- *
15 * Copyright (c) 2003 - 2008 by Roland Haeder *
16 * For more information visit: http://www.mxchange.org *
18 * This program is free software; you can redistribute it and/or modify *
19 * it under the terms of the GNU General Public License as published by *
20 * the Free Software Foundation; either version 2 of the License, or *
21 * (at your option) any later version. *
23 * This program is distributed in the hope that it will be useful, *
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
26 * GNU General Public License for more details. *
28 * You should have received a copy of the GNU General Public License *
29 * along with this program; if not, write to the Free Software *
30 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, *
32 ************************************************************************/
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36 $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
40 // Init "generic filter system"
41 function INIT_FILTER_SYSTEM () {
42 global $filters, $loadedFilters, $counter;
44 // Is the filter already initialized?
45 if ((isset($filters)) && (is_array($filters))) {
47 addFatalMessage(getMessage('FILTER_FAILED_ALREADY_INIT'));
51 // Init the filter system (just some ideas)
53 // Filters for pre-init phase
55 // Filters for post-init phase
56 'postinit' => array(),
57 // Filters for shutdown phase
61 // Init loaded filters and counter
62 $loadedFilters = array();
65 // Load all saved filers if sql_patches is updated
66 if (GET_EXT_VERSION("sql_patches") >= "0.5.9") {
69 if (GET_EXT_VERSION("sql_patches") >= "0.6.0") $ADD = ", `filter_counter`";
71 // Load all active filers
72 $result = SQL_QUERY("SELECT `filter_name`, `filter_function`, `filter_active`".$ADD."
73 FROM `{!_MYSQL_PREFIX!}_filters`
74 ORDER BY `filter_id` ASC", __FILE__, __LINE__);
77 if (SQL_NUMROWS($result) > 0) {
79 while ($filterArray = SQL_FETCHARRAY($result)) {
80 // Get filter name and function
81 $filterName = $filterArray['filter_name'];
82 $filterFunction = $filterArray['filter_function'];
84 // Set counter to default
85 $counter[$filterName][$filterFunction] = 0;
87 // Mark this filter as loaded (from database)
88 $loadedFilters[$filterName][$filterFunction] = true;
91 $filters[$filterName][$filterFunction] = $filterArray['filter_active'];
93 // Is the array element for counter there?
94 if (isset($filterArray['filter_counter'])) {
95 // Then use this value!
96 $counter[$filterName][$filterFunction] = $filterArray['filter_counter'];
102 SQL_FREERESULT($result);
106 REGISTER_FILTER('init', 'UPDATE_LOGIN_DATA');
107 REGISTER_FILTER('init', 'INIT_RANDOMIZER');
109 // Login failures handler
110 REGISTER_FILTER('post_youhere_line', 'CALL_HANDLER_LOGIN_FAILTURES');
112 // Filters for pre-extension-registration
113 REGISTER_FILTER('pre_extension_installed', 'RUN_SQLS');
115 // Filters for post-extension-registration
116 REGISTER_FILTER('post_extension_installed', 'AUTO_ACTIVATE_EXTENSION');
117 REGISTER_FILTER('post_extension_installed', 'SOLVE_TASK');
118 REGISTER_FILTER('post_extension_installed', 'LOAD_INCLUDES');
121 REGISTER_FILTER('solve_task', 'SOLVE_TASK');
123 // Loading includes in general
124 REGISTER_FILTER('load_includes', 'LOAD_INCLUDES');
127 REGISTER_FILTER('run_sqls', 'RUN_SQLS');
130 REGISTER_FILTER('check_admin_acl', 'CHECK_ADMIN_ACL');
132 // Register shutdown filters
133 REGISTER_FILTER('shutdown', 'FLUSH_FILTERS');
136 // "Registers" a new filter function
137 function REGISTER_FILTER ($filterName, $filterFunction, $silentAbort = true, $force = false, $dry_run = false) {
138 global $filters, $counter;
140 // Extend the filter function name
141 $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
143 // Is that filter already there?
144 if ((isset($filters[$filterName][$filterFunction])) && (!$force)) {
147 addFatalMessage(getMessage('FILTER_FAILED_ALREADY_ADDED'), array($filterFunction, $filterName));
154 // Is the function there?
155 if (!function_exists($filterFunction)) {
157 addFatalMessage(getMessage('FILTER_FAILED_NOT_FOUND'), array($filterFunction, $filterName));
163 // Simply add it to the array
164 $filters[$filterName][$filterFunction] = "Y";
165 $counter[$filterName][$filterFunction] = 0;
169 // "Unregisters" a filter from the given chain
170 function UNREGISTER_FILTER ($filterName, $filterFunction, $force = false, $dry_run = false) {
171 global $filters, $counter, $loadedFilters;
173 // Extend the filter function name only if not loaded from database
174 if (!isset($loadedFilters[$filterName][$filterFunction])) {
175 $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
178 // Is that filter there?
179 if ((!isset($filters[$filterName][$filterFunction])) && (!$force)) {
180 // Not found, so abort here
181 addFatalMessage(getMessage('FILTER_FAILED_NOT_REMOVED'), array($filterFunction, $filterName));
185 // Shall we remove? (default, not while just showing an extension removal)
187 // Mark for filter removal
188 $filters[$filterName][$filterFunction] = "R";
189 unset($counter[$filterName][$filterFunction]);
193 // "Runs" the given filters, data is optional and can be any type of data
194 function RUN_FILTER ($filterName, $data = null, $silentAbort = true) {
195 global $filters, $counter;
197 // Is that filter chain there?
198 if (!isset($filters[$filterName])) {
199 // Then abort here (quick'N'dirty hack)
200 if ((!$silentAbort) && (defined('FILTER_FAILED_NO_FILTER_FOUND'))) {
202 addFatalMessage(getMessage('FILTER_FAILED_NO_FILTER_FOUND'), $filterName);
209 // Default return value
210 $returnValue = $data;
212 // Then run all filters
213 foreach ($filters[$filterName] as $filterFunction=>$active) {
215 //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): name={$filterName},func={$filterFunction},active={$active}<br />\n";
217 // Is the filter active?
218 if ($active == "Y") {
219 // Is this filter there?
220 if (!function_exists($filterFunction)) {
222 UNREGISTER_FILTER($filterName, $filterFunction);
228 // Call the filter chain
229 $returnValue = call_user_func_array($filterFunction, array($returnValue));
231 // Update usage counter
232 $counter[$filterName][$filterFunction]++;
236 // Return the filtered content
240 // -----------------------------------------------------------------------------
241 // Generic filter functions we always need
242 // -----------------------------------------------------------------------------
244 // Filter for flushing all new filters to the database
245 function FILTER_FLUSH_FILTERS () {
246 global $filters, $counter, $link, $loadedFilters, $SQLs;
248 // Clear all previous SQL queries
251 // Is a database link here and not in installation mode?
252 if ((!is_resource($link)) && (!isBooleanConstantAndTrue('mxchange_installing'))) {
254 addFatalMessage(getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'), array($filterFunction, $filterName));
258 // Is the extension sql_patches updated?
259 if (EXT_VERSION_IS_OLDER("sql_patches", "0.5.9")) {
260 // Abort silently here
264 // Nothing is added/remove by default
265 $inserted = 0; $removed = 0;
267 // Prepare SQL queries
268 $insertSQL = "INSERT INTO `{!_MYSQL_PREFIX!}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES";
269 $removeSQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_filters` WHERE";
271 // Write all filters to database
272 foreach ($filters as $filterName => $filterArray) {
273 // Walk through all filters
274 foreach ($filterArray as $filterFunction => $active) {
275 // Is this filter loaded?
276 if (!isset($loadedFilters[$filterName][$filterFunction])) {
277 // Add this filter (all filters are active by default)
278 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
280 } elseif ($active == "R") {
281 // Remove this filter
282 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
288 // Something has been added?
290 // Finish SQL command
291 $insertSQL = substr($insertSQL, 0, -1);
294 $SQLs[] = $insertSQL;
297 // Something has been removed?
299 // Finish SQL command
300 $removeSQL = substr($removeSQL, 0, -2) . "LIMIT ".$removed;
303 $SQLs[] = $removeSQL;
306 // Shall we update usage counters (ONLY FOR DEBUGGING!)
307 if (getConfig('update_filter_usage') == "Y") {
308 // Update all counters
309 foreach ($counter as $filterName => $filterArray) {
310 // Walk through all filters
311 foreach ($filterArray as $filterFunction => $cnt) {
312 // Construct and add the query
313 $SQLs[] = sprintf("UPDATE `{!_MYSQL_PREFIX!}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
322 // Run the run_sqls filter in non-dry mode
323 RUN_FILTER('run_sqls', array('dry_run' => false, 'sqls' => $SQLs));
326 // Filter for calling the handler for login failures
327 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
331 // Handle failed logins here if not in guest
332 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={$GLOBALS['action']},what={$GLOBALS['what']},lvl={$data['access_level']}<br />\n";
333 if ((($data['type'] == "what") || ($data['type'] == "action") && ((!isset($GLOBALS['what'])) || ($GLOBALS['what'] == "overview") || ($GLOBALS['what'] == getConfig('index_home')))) && ($data['access_level'] != "guest") && ((GET_EXT_VERSION("sql_patches") >= "0.4.7") || (GET_EXT_VERSION("admins") >= "0.7.0"))) {
335 $content['content'] .= HANDLE_LOGIN_FAILTURES($data['access_level']);
338 // Return the content
342 // Filter for redirecting to logout if sql_patches has been installed
343 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
344 // Remove this filter
345 UNREGISTER_FILTER('shutdown', __FUNCTION__);
347 // Is the element set?
348 if (isset($GLOBALS['ext_load_mode'])) {
350 LOAD_URL("modules.php?module=admin&logout=1&".$GLOBALS['ext_load_mode']."=sql_patches");
353 // This should not happen!
354 DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot auto-logout because no extension load-mode has been set.");
357 // Filter for auto-activation of a extension
358 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
359 global $EXT_ALWAYS_ACTIVE;
361 // Is this extension always activated?
362 if ($EXT_ALWAYS_ACTIVE == "Y") {
363 // Then activate the extension
364 //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$data['ext_name']}<br />\n";
365 ACTIVATE_EXTENSION($data['ext_name']);
372 // Filter for solving task given task
373 function FILTER_SOLVE_TASK ($data) {
374 // Don't solve anything if no admin!
375 if (!IS_ADMIN()) return $data;
377 // Is this a direct task id or array element task_id is found?
380 ADMIN_SOLVE_TASK($data);
381 } elseif ((is_array($data)) && (isset($data['task_id']))) {
383 ADMIN_SOLVE_TASK($data['task_id']);
390 // Filter to load include files
391 function FILTER_LOAD_INCLUDES ($data) {
394 // Default is $data as inclusion list
398 if ((!isset($data)) || (!is_array($data))) {
400 DEBUG_LOG(__FILE__, __LINE__, "INC_POOL is no array!");
402 } elseif (isset($data['inc_pool'])) {
403 // Use this as new inclusion pool!
404 $INC_POOL = $data['inc_pool'];
407 // Check for added include files
408 if (count($INC_POOL) > 0) {
409 // Loads every include file
410 foreach ($INC_POOL as $FQFN) {
411 LOAD_INC_ONCE($FQFN);
415 if (isset($data['inc_pool'])) $data['inc_pool'] = array();
418 // Continue with processing
422 // Filter for running SQL commands
423 function FILTER_RUN_SQLS ($data) {
424 // Is the array there?
425 if ((isset($data['sqls'])) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
427 foreach ($data['sqls'] as $sql) {
430 // Do we have an "ALTER TABLE" command?
431 if (substr(strtolower($sql), 0, 11) == "alter table") {
432 // Analyse the alteration command
433 SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
435 // Run regular SQL command
436 $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
443 // Filter for updating/validating login data
444 function FILTER_UPDATE_LOGIN_DATA () {
446 if (!is_array($LAST)) $LAST = array();
448 // Recheck if logged in
449 if (!IS_MEMBER()) return false;
452 $GLOBALS['userid'] = bigintval(get_session('userid'));
454 // Load last module and last online time
455 $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
456 array($GLOBALS['userid']), __FILE__, __LINE__);
459 if (SQL_NUMROWS($result) == 1) {
460 // Load last module and online time
461 list($mod, $onl) = SQL_FETCHROW($result);
463 // Maybe first login time?
464 if (empty($mod)) $mod = "login";
466 // This will be displayed on welcome page! :-)
467 if (empty($LAST['module'])) {
468 $LAST['module'] = $mod; $LAST['online'] = $onl;
472 if (empty($GLOBALS['what'])) {
474 $GLOBALS['what'] = "welcome";
475 if (getConfig('index_home') != "") $GLOBALS['what'] = getConfig('index_home');
478 // Update last module / online time
479 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET last_module='%s', last_online=UNIX_TIMESTAMP(), REMOTE_ADDR='%s' WHERE userid=%s LIMIT 1",
480 array($GLOBALS['what'], GET_REMOTE_ADDR(), $GLOBALS['userid']), __FILE__, __LINE__);
482 // Destroy session, we cannot update!
483 destroy_user_session();
487 SQL_FREERESULT($result);
490 // Filter for checking admin ACL
491 function FILTER_CHECK_ADMIN_ACL () {
492 // Extension not installed so it's always allowed to access everywhere!
495 // Ok, Cookie-Update done
496 if (GET_EXT_VERSION("admins") >= "0.3") {
497 // Check if action GET variable was set
498 $action = SQL_ESCAPE($GLOBALS['action']);
499 if (!empty($GLOBALS['what'])) {
500 // Get action value by what-value
501 $action = GET_ACTION("admin", $GLOBALS['what']);
504 // Check for access control line of current menu entry
505 $ret = ADMINS_CHECK_ACL($action, $GLOBALS['what']);
512 // Filter for initializing randomizer
513 function FILTER_INIT_RANDOMIZER () {
514 // Simply init the randomizer with seed and _ADD value
515 mt_srand(generateSeed() + constant('_ADD'));