Same fix for isActionSet()
[mailer.git] / inc / filters.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 12/16/2008 *
4  * ===============                              Last change: 12/16/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : filters.php                                      *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for filter system                      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer Filter-System                    *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
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                  *
22  *                                                                      *
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.                                  *
27  *                                                                      *
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.                         *
32  *                                                                      *
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,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), '/inc') + 4) . '/security.php';
42         require($INC);
43 }
44
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']))) {
49                 // Then abort here
50                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_ALREADY_INIT'));
51                 return false;
52         } // END - if
53
54         // Init the filter system (just some ideas)
55         $GLOBALS['filters']['chains'] = array(
56                 'preinit'   => array(), // Filters for pre-init phase
57                 'postinit'  => array(), // Filters for post-init phase
58                 'shutdown'  => array()  // Filters for shutdown phase
59         );
60
61         // Init loaded filters and counter
62         $GLOBALS['filters']['loaded'] =  array();
63         $GLOBALS['filters']['counter'] = array();
64
65         // Load all saved filers if sql_patches is updated
66         if (GET_EXT_VERSION('sql_patches') >= '0.5.9') {
67                 // Init add
68                 $add = '';
69                 if (GET_EXT_VERSION('sql_patches') >= '0.6.0') $add = ", `filter_counter`";
70
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", __FUNCTION__, __LINE__);
75
76                 // Are there entries?
77                 if (SQL_NUMROWS($result) > 0) {
78                         // Load all filters
79                         while ($filterArray = SQL_FETCHARRAY($result)) {
80                                 // Get filter name and function
81                                 $filterName     = $filterArray['filter_name'];
82                                 $filterFunction = $filterArray['filter_function'];
83
84                                 // Set counter to default
85                                 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 0;
86
87                                 // Mark this filter as loaded (from database)
88                                 $GLOBALS['filters']['loaded'][$filterName][$filterFunction] = true;
89
90                                 // Set this filter
91                                 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = $filterArray['filter_active'];
92
93                                 // Is the array element for counter there?
94                                 if (isset($filterArray['filter_counter'])) {
95                                         // Then use this value!
96                                         $GLOBALS['filters']['counter'][$filterName][$filterFunction] = $filterArray['filter_counter'];
97                                 } // END - if
98                         } // END - while
99                 } // END - if
100
101                 // Free result
102                 SQL_FREERESULT($result);
103         } // END - if
104
105         // Init filters
106         registerFilter('init', 'UPDATE_LOGIN_DATA');
107         registerFilter('init', 'INIT_RANDOMIZER');
108
109         // Login failures handler
110         registerFilter('post_youhere_line', 'CALL_HANDLER_LOGIN_FAILTURES');
111
112         // Filters for pre-extension-registration
113         registerFilter('pre_extension_installed', 'RUN_SQLS');
114
115         // Filters for post-extension-registration
116         registerFilter('post_extension_installed', 'AUTO_ACTIVATE_EXTENSION');
117         registerFilter('post_extension_installed', 'SOLVE_TASK');
118         registerFilter('post_extension_installed', 'loadIncludeLUDES');
119         registerFilter('post_extension_installed', 'REMOVE_UPDATES');
120
121         // Solving tasks
122         registerFilter('solve_task', 'SOLVE_TASK');
123
124         // Loading includes in general
125         registerFilter('load_includes', 'loadIncludeLUDES');
126
127         // Run SQLs
128         registerFilter('run_sqls', 'RUN_SQLS');
129
130         // Admin ACL check
131         registerFilter('check_admin_acl', 'CHECK_ADMIN_ACL');
132
133         // Register shutdown filters
134         registerFilter('shutdown', 'FLUSH_FILTERS');
135 }
136
137 // "Registers" a new filter function
138 function registerFilter ($filterName, $filterFunction, $silentAbort = true, $force = false, $dry_run = false) {
139         // Extend the filter function name
140         $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
141
142         // Is that filter already there?
143         if ((isset($GLOBALS['filters']['chains'][$filterName][$filterFunction])) && (!$force)) {
144                 // Then abort here
145                 if (!$silentAbort) {
146                         addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_ALREADY_ADDED'), array($filterFunction, $filterName));
147                 } // END - if
148
149                 // Abort here
150                 return false;
151         } // END - if
152
153         // Is the function there?
154         if (!function_exists($filterFunction)) {
155                 // Then abort here
156                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NOT_FOUND'), array($filterFunction, $filterName));
157                 return false;
158         } // END - if
159
160         // Shall we add it?
161         if (!$dry_run) {
162                 // Simply add it to the array
163                 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = 'Y';
164                 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 0;
165         } // END - if
166 }
167
168 // "Unregisters" a filter from the given chain
169 function unregisterFilter ($filterName, $filterFunction, $force = false, $dry_run = false) {
170         // Extend the filter function name only if not loaded from database
171         if (!isset($GLOBALS['filters']['loaded'][$filterName][$filterFunction])) {
172                 $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
173         } // END - if
174
175         // Is that filter there?
176         if ((!isset($GLOBALS['filters']['chains'][$filterName][$filterFunction])) && (!$force)) {
177                 // Not found, so abort here
178                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NOT_REMOVED'), array($filterFunction, $filterName));
179                 return false;
180         } // END - if
181
182         // Shall we remove? (default, not while just showing an extension removal)
183         if ($dry_run === false) {
184                 // Mark for filter removal
185                 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = 'R';
186         } // END  - if
187 }
188
189 // "Runs" the given filters, data is optional and can be any type of data
190 function runFilterChain ($filterName, $data = null, $silentAbort = true) {
191         // Is that filter chain there?
192         if (!isset($GLOBALS['filters']['chains'][$filterName])) {
193                 // Then abort here (quick'N'dirty hack)
194                 if (($silentAbort === false) && (defined('FILTER_FAILED_NO_FILTER_FOUND'))) {
195                         // Add fatal message
196                         addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NO_FILTER_FOUND'), $filterName);
197                 } // END - if
198
199                 // Abort here
200                 return false;
201         } // END - if
202
203         // Default return value
204         $returnValue = $data;
205
206         // Then run all filters
207         foreach ($GLOBALS['filters']['chains'][$filterName] as $filterFunction=>$active) {
208                 // Debug message
209                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Running: name={$filterName},func={$filterFunction},active={$active}");
210
211                 // Is the filter active?
212                 if (($active == 'Y') || ((in_array($filterName, array('extension_remove', 'post_extension_run_sql'))) && ($active == 'R'))) {
213                         // Is this filter there?
214                         if (!function_exists($filterFunction)) {
215                                 // Unregister it
216                                 unregisterFilter($filterName, $filterFunction);
217
218                                 // Skip this entry
219                                 continue;
220                         } // END - if
221
222                         // Call the filter chain
223                         $returnValue = call_user_func_array($filterFunction, array($returnValue));
224
225                         // Update usage counter
226                         countFilterUsage($filterName, $filterFunction);
227                 } elseif (isDebugModeEnabled()) {
228                         // Debug message
229                         DEBUG_LOG(__FUNCTION__, __LINE__, "Skipped: name={$filterName},func={$filterFunction},active={$active}");
230                 }
231         } // END - foreach
232
233         // Return the filtered content
234         return $returnValue;
235 }
236
237 // Count the filter usage
238 function countFilterUsage ($filterName, $filterFunction) {
239         // Is it there?
240         if (isset($GLOBALS['filters']['counter'][$filterName][$filterFunction])) {
241                 // Yes, then increase
242                 $GLOBALS['filters']['counter'][$filterName][$filterFunction]++;
243         } else {
244                 // No, then create
245                 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 1;
246         }
247 }
248
249 // -----------------------------------------------------------------------------
250 // Generic filter functions we always need
251 // -----------------------------------------------------------------------------
252
253 // Filter for flushing all new filters to the database
254 function FILTER_FLUSH_FILTERS () {
255         // Clear all previous SQL queries
256         INIT_SQLS();
257
258         // Are we installing?
259         if ((isInstalling()) || (!isInstalled())) {
260                 // Then silently skip this filter
261                 return true;
262         } // END - if
263
264         // Is a database link here and not in installation mode?
265         if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
266                 // Abort here
267                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'));
268                 return false;
269         } // END - if
270
271         // Is the extension sql_patches updated?
272         if (EXT_VERSION_IS_OLDER('sql_patches', '0.5.9')) {
273                 // Abort silently here
274                 return false;
275         } // END - if
276
277         // Nothing is added/remove by default
278         $inserted = 0;
279         $removed = 0;
280
281         // Prepare SQL queries
282         $insertSQL = "INSERT INTO `{!_MYSQL_PREFIX!}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES";
283         $removeSQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_filters` WHERE";
284
285         // Write all filters to database
286         foreach ($GLOBALS['filters']['chains'] as $filterName => $filterArray) {
287                 // Walk through all filters
288                 foreach ($filterArray as $filterFunction => $active) {
289                         // Is this filter loaded?
290                         if (!isset($GLOBALS['filters']['loaded'][$filterName][$filterFunction])) {
291                                 // Add this filter (all filters are active by default)
292                                 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
293                                 $inserted++;
294                         } elseif ($active == "R") {
295                                 // Remove this filter
296                                 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
297                                 $removed++;
298                         }
299                 } // END - foreach
300         } // END - foreach
301
302         // Something has been added?
303         if ($inserted > 0) {
304                 // Finish SQL command
305                 $insertSQL = substr($insertSQL, 0, -1);
306
307                 // And run it
308                 ADD_SQL($insertSQL);
309         } // END - if
310
311         // Something has been removed?
312         if ($removed > 0) {
313                 // Finish SQL command
314                 $removeSQL = substr($removeSQL, 0, -2) . "LIMIT ".$removed;
315
316                 // And run it
317                 ADD_SQL($removeSQL);
318         } // END - if
319
320         // Shall we update usage counters (ONLY FOR DEBUGGING!)
321         if (getConfig('update_filter_usage') == 'Y') {
322                 // Update all counters
323                 foreach ($GLOBALS['filters']['counter'] as $filterName => $filterArray) {
324                         // Walk through all filters
325                         foreach ($filterArray as $filterFunction => $cnt) {
326                                 // Construct and add the query
327                                 ADD_SQL(sprintf("UPDATE `{!_MYSQL_PREFIX!}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
328                                 bigintval($cnt),
329                                 $filterName,
330                                 $filterFunction
331                                 ));
332                         } // END - foreach
333                 } // END - foreach
334         } // END - if
335
336         // Run the run_sqls filter in non-dry mode
337         runFilterChain('run_sqls');
338 }
339
340 // Filter for calling the handler for login failures
341 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
342         // Init content
343         $content = $data;
344
345         // Handle failed logins here if not in guest
346         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={getAction()},what={getWhat()},lvl={$data['access_level']}<br />\n";
347         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'))) {
348                 // Handle failure
349                 $content['content'] .= HANDLE_LOGIN_FAILTURES($data['access_level']);
350         } // END - if
351
352         // Return the content
353         return $content;
354 }
355
356 // Filter for redirecting to logout if sql_patches has been installed
357 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
358         // Remove this filter
359         unregisterFilter('shutdown', __FUNCTION__);
360
361         // Is the element set?
362         if (isset($GLOBALS['ext_load_mode'])) {
363                 // Redirect here
364                 redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . $GLOBALS['ext_load_mode'] . '=sql_patches');
365         } // END - if
366
367         // This should not happen!
368         DEBUG_LOG(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
369 }
370
371 // Filter for auto-activation of a extension
372 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
373         // Is this extension always activated?
374         if (EXT_GET_ALWAYS_ACTIVE() == 'Y') {
375                 // Then activate the extension
376                 //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$data['ext_name']}<br />\n";
377                 ACTIVATE_EXTENSION($data['ext_name']);
378         } // END - if
379
380         // Return the data
381         return $data;
382 }
383
384 // Filter for solving task given task
385 function FILTER_SOLVE_TASK ($data) {
386         // Don't solve anything if no admin!
387         if (!IS_ADMIN()) return $data;
388
389         // Is this a direct task id or array element task_id is found?
390         if (is_int($data)) {
391                 // Then solve it...
392                 ADMIN_SOLVE_TASK($data);
393         } elseif ((is_array($data)) && (isset($data['task_id']))) {
394                 // Solve it...
395                 ADMIN_SOLVE_TASK($data['task_id']);
396         }
397
398         // Return the data
399         return $data;
400 }
401
402 // Filter to load include files
403 function FILTER_loadIncludeLUDES () {
404         // Default is $data as inclusion list
405         $data = GET_INC_POOL();
406
407         // Is it an array?
408         if ((!isset($data)) || (!is_array($data))) {
409                 // Then abort here
410                 debug_report_bug(sprintf("INC_POOL is no array! Type: %s", gettype($data)));
411         } elseif (isset($data['inc_pool'])) {
412                 // Use this as new inclusion pool!
413                 SET_INC_POOL($data['inc_pool']);
414         }
415
416         // Check for added include files
417         if (COUNT_INC_POOL() > 0) {
418                 // Loads every include file
419                 foreach (GET_INC_POOL() as $FQFN) {
420                         loadIncludeOnce($FQFN);
421                 } // END - foreach
422
423                 // Reset array
424                 INIT_INC_POOL();
425         } // END - if
426
427         // Continue with processing
428         return $data;
429 }
430
431 // Filter for running SQL commands
432 function FILTER_RUN_SQLS ($data) {
433         // Debug message
434         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " - Entered!");
435
436         // Is the array there?
437         if ((IS_SQLS_VALID()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
438                 // Run SQL commands
439                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " - Found ".COUNT_SQLS()." queries to run.");
440                 foreach (GET_SQLS() as $sql) {
441                         // Trim spaces away
442                         $sql = trim($sql);
443
444                         // Is there still a query left?
445                         if (!empty($sql)) {
446                                 // Do we have an "ALTER TABLE" command?
447                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
448                                         // Analyse the alteration command
449                                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Alterting table: {$sql}");
450                                         SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__);
451                                 } else {
452                                         // Run regular SQL command
453                                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Running regular query: {$sql}");
454                                         SQL_QUERY($sql, __FUNCTION__, __LINE__, false);
455                                 }
456                         } // END - if
457                 } // END - foreach
458         } // END - if
459
460         // Debug message
461         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " - Left!");
462 }
463
464 // Filter for updating/validating login data
465 function FILTER_UPDATE_LOGIN_DATA () {
466         // Add missing array
467         if ((!isset($GLOBALS['last'])) || (!is_array($GLOBALS['last']))) $GLOBALS['last'] = array();
468
469         // Recheck if logged in
470         if (!IS_MEMBER()) return false;
471
472         // Secure user ID
473         setUserId(getSession('userid'));
474
475         // Load last module and last online time
476         $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
477                 array(getUserId()), __FUNCTION__, __LINE__);
478
479         // Entry found?
480         if (SQL_NUMROWS($result) == 1) {
481                 // Load last module and online time
482                 list($mod, $onl) = SQL_FETCHROW($result);
483
484                 // Maybe first login time?
485                 if (empty($mod)) $mod = 'login';
486
487                 // This will be displayed on welcome page! :-)
488                 if (empty($GLOBALS['last']['module'])) {
489                         $GLOBALS['last']['module'] = $mod; $GLOBALS['last']['online'] = $onl;
490                 } // END - if
491
492                 // 'what' not set?
493                 if (!isWhatSet()) {
494                         // Fix it to default
495                         setWhat('welcome');
496                         if (getConfig('index_home') != '') setWhatFromConfig('index_home');
497                 } // END - if
498
499                 // Update last module / online time
500                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `last_module`='%s', last_online=UNIX_TIMESTAMP(), REMOTE_ADDR='%s' WHERE userid=%s LIMIT 1",
501                         array(getWhat(), detectRemoteAddr(), getUserId()), __FUNCTION__, __LINE__);
502         }  else {
503                 // Destroy session, we cannot update!
504                 destroyUserSession();
505         }
506
507         // Free the result
508         SQL_FREERESULT($result);
509 }
510
511 // Filter for checking admin ACL
512 function FILTER_CHECK_ADMIN_ACL () {
513         // Extension not installed so it's always allowed to access everywhere!
514         $ret = true;
515
516         // Ok, Cookie-Update done
517         if ((GET_EXT_VERSION('admins') >= '0.3.0') && (EXT_IS_ACTIVE('admins'))) {
518                 // Check if action GET variable was set
519                 $action = getAction();
520                 if (isWhatSet()) {
521                         // Get action value by what-value
522                         $action = getModeAction('admin', getWhat());
523                 } // END - if
524
525                 // Check for access control line of current menu entry
526                 $ret = adminsCheckAdminAcl($action, getWhat());
527         } // END - if
528
529         // Return result
530         return $ret;
531 }
532
533 // Filter for initializing randomizer
534 function FILTER_INIT_RANDOMIZER () {
535         // Simply init the randomizer with seed and _ADD value
536         mt_srand(generateSeed() + getConfig('_ADD'));
537 }
538
539 // Filter for removing updates
540 function FILTER_REMOVE_UPDATES () {
541         // Init removal list
542         EXT_INIT_REMOVAL_LIST();
543
544         // Add the current extension to it
545         EXT_ADD_CURRENT_TO_REMOVAL_LIST();
546
547         // Simply remove it
548         UNSET_EXT_SQLS();
549
550         // Do we need to remove update depency?
551         if (EXT_COUNT_UPDATE_DEPENDS() > 0) {
552                 // Then find all updates we shall no longer execute
553                 foreach (EXT_GET_UPDATE_DEPENDS() as $id=>$ext_name) {
554                         // Shall we remove this update?
555                         if (in_array($ext_name, EXT_GET_REMOVAL_LIST())) {
556                                 // Then remove this extension!
557                                 EXT_REMOVE_UPDATE_DEPENDS($ext_name);
558                         } // END - if
559                 } // END - foreach
560         } // END - if
561 }
562
563 //
564 ?>