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