1ffea5b4208a6d0d597807fa718e0cb0be955720
[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  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
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.                                  *
22  *                                                                      *
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.                         *
27  *                                                                      *
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,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
37         require($INC);
38 }
39
40 // Init "generic filter system"
41 function INIT_FILTER_SYSTEM () {
42         global $filters, $loadedFilters, $counter;
43
44         // Is the filter already initialized?
45         if ((isset($filters)) && (is_array($filters))) {
46                 // Then abort here
47                 addFatalMessage(getMessage('FILTER_FAILED_ALREADY_INIT'));
48                 return false;
49         } // END - if
50
51         // Init the filter system (just some ideas)
52         $filters = array(
53                 // Filters for pre-init phase
54                 'preinit'   => array(),
55                 // Filters for post-init phase
56                 'postinit'  => array(),
57                 // Filters for shutdown phase
58                 'shutdown'  => array()
59         );
60
61         // Init loaded filters and counter
62         $loadedFilters =  array();
63         $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", __FILE__, __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                                 $counter[$filterName][$filterFunction] = 0;
86
87                                 // Mark this filter as loaded (from database)
88                                 $loadedFilters[$filterName][$filterFunction] = true;
89
90                                 // Set this filter
91                                 $filters[$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                                         $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         REGISTER_FILTER('init', 'UPDATE_LOGIN_DATA');
107         REGISTER_FILTER('init', 'INIT_RANDOMIZER');
108
109         // Login failures handler
110         REGISTER_FILTER('post_youhere_line', 'CALL_HANDLER_LOGIN_FAILTURES');
111
112         // Filters for pre-extension-registration
113         REGISTER_FILTER('pre_extension_installed', 'RUN_SQLS');
114
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');
119
120         // Solving tasks
121         REGISTER_FILTER('solve_task', 'SOLVE_TASK');
122
123         // Loading includes in general
124         REGISTER_FILTER('load_includes', 'LOAD_INCLUDES');
125
126         // Run SQLs
127         REGISTER_FILTER('run_sqls', 'RUN_SQLS');
128
129         // Admin ACL check
130         REGISTER_FILTER('check_admin_acl', 'CHECK_ADMIN_ACL');
131
132         // Register shutdown filters
133         REGISTER_FILTER('shutdown', 'FLUSH_FILTERS');
134 }
135
136 // "Registers" a new filter function
137 function REGISTER_FILTER ($filterName, $filterFunction, $silentAbort = true, $force = false, $dry_run = false) {
138         global $filters, $counter;
139
140         // Extend the filter function name
141         $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
142
143         // Is that filter already there?
144         if ((isset($filters[$filterName][$filterFunction])) && (!$force)) {
145                 // Then abort here
146                 if (!$silentAbort) {
147                         addFatalMessage(getMessage('FILTER_FAILED_ALREADY_ADDED'), array($filterFunction, $filterName));
148                 } // END - if
149
150                 // Abort here
151                 return false;
152         } // END - if
153
154         // Is the function there?
155         if (!function_exists($filterFunction)) {
156                 // Then abort here
157                 addFatalMessage(getMessage('FILTER_FAILED_NOT_FOUND'), array($filterFunction, $filterName));
158                 return false;
159         } // END - if
160
161         // Shall we add it?
162         if (!$dry_run) {
163                 // Simply add it to the array
164                 $filters[$filterName][$filterFunction] = "Y";
165                 $counter[$filterName][$filterFunction] = 0;
166         } // END - if
167 }
168
169 // "Unregisters" a filter from the given chain
170 function UNREGISTER_FILTER ($filterName, $filterFunction, $force = false, $dry_run = false) {
171         global $filters, $counter, $loadedFilters;
172
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));
176         } // END - if
177
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));
182                 return false;
183         } // END - if
184
185         // Shall we remove? (default, not while just showing an extension removal)
186         if (!$dry_run) {
187                 // Mark for filter removal
188                 $filters[$filterName][$filterFunction] = "R";
189                 unset($counter[$filterName][$filterFunction]);
190         } // END  - if
191 }
192
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;
196
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'))) {
201                         // Add fatal message
202                         addFatalMessage(getMessage('FILTER_FAILED_NO_FILTER_FOUND'), $filterName);
203                 } // END - if
204
205                 // Abort here
206                 return false;
207         } // END - if
208
209         // Default return value
210         $returnValue = $data;
211
212         // Then run all filters
213         foreach ($filters[$filterName] as $filterFunction=>$active) {
214                 // Debug message
215                 //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): name={$filterName},func={$filterFunction},active={$active}<br />\n";
216
217                 // Is the filter active?
218                 if ($active == "Y") {
219                         // Is this filter there?
220                         if (!function_exists($filterFunction)) {
221                                 // Unregister it
222                                 UNREGISTER_FILTER($filterName, $filterFunction);
223
224                                 // Skip this entry
225                                 continue;
226                         } // END - if
227
228                         // Call the filter chain
229                         $returnValue = call_user_func_array($filterFunction, array($returnValue));
230
231                         // Update usage counter
232                         $counter[$filterName][$filterFunction]++;
233                 } // END - if
234         } // END - foreach
235
236         // Return the filtered content
237         return $returnValue;
238 }
239
240 // -----------------------------------------------------------------------------
241 // Generic filter functions we always need
242 // -----------------------------------------------------------------------------
243
244 // Filter for flushing all new filters to the database
245 function FILTER_FLUSH_FILTERS () {
246         global $filters, $counter, $link, $loadedFilters, $SQLs;
247
248         // Clear all previous SQL queries
249         $SQLs = array();
250
251         // Is a database link here and not in installation mode?
252         if ((!is_resource($link)) && (!isBooleanConstantAndTrue('mxchange_installing'))) {
253                 // Abort here
254                 addFatalMessage(getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'), array($filterFunction, $filterName));
255                 return false;
256         } // END - if
257
258         // Is the extension sql_patches updated?
259         if (EXT_VERSION_IS_OLDER("sql_patches", "0.5.9")) {
260                 // Abort silently here
261                 return false;
262         } // END - if
263
264         // Nothing is added/remove by default
265         $inserted = 0; $removed = 0;
266
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";
270
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);
279                                 $inserted++;
280                         } elseif ($active == "R") {
281                                 // Remove this filter
282                                 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
283                                 $removed++;
284                         }
285                 } // END - foreach
286         } // END - foreach
287
288         // Something has been added?
289         if ($inserted > 0) {
290                 // Finish SQL command
291                 $insertSQL = substr($insertSQL, 0, -1);
292
293                 // And run it
294                 $SQLs[] = $insertSQL;
295         } // END - if
296
297         // Something has been removed?
298         if ($removed > 0) {
299                 // Finish SQL command
300                 $removeSQL = substr($removeSQL, 0, -2) . "LIMIT ".$removed;
301
302                 // And run it
303                 $SQLs[] = $removeSQL;
304         } // END - if
305
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",
314                                         bigintval($cnt),
315                                         $filterName,
316                                         $filterFunction
317                                 );
318                         } // END - foreach
319                 } // END - foreach
320         } // END - if
321
322         // Run the run_sqls filter in non-dry mode
323         RUN_FILTER('run_sqls', array('dry_run' => false, 'sqls' => $SQLs));
324 }
325
326 // Filter for calling the handler for login failures
327 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
328         // Init content
329         $content = $data;
330
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"))) {
334                 // Handle failure
335                 $content['content'] .= HANDLE_LOGIN_FAILTURES($data['access_level']);
336         } // END - if
337
338         // Return the content
339         return $content;
340 }
341
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__);
346
347         // Is the element set?
348         if (isset($GLOBALS['ext_load_mode'])) {
349                 // Redirect here
350                 LOAD_URL("modules.php?module=admin&amp;logout=1&amp;".$GLOBALS['ext_load_mode']."=sql_patches");
351         } // END - if
352
353         // This should not happen!
354         DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot auto-logout because no extension load-mode has been set.");
355 }
356
357 // Filter for auto-activation of a extension
358 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
359         global $EXT_ALWAYS_ACTIVE;
360
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']);
366         } // END - if
367
368         // Return the data
369         return $data;
370 }
371
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;
376
377         // Is this a direct task id or array element task_id is found?
378         if (is_int($data)) {
379                 // Then solve it...
380                 ADMIN_SOLVE_TASK($data);
381         } elseif ((is_array($data)) && (isset($data['task_id']))) {
382                 // Solve it...
383                 ADMIN_SOLVE_TASK($data['task_id']);
384         }
385
386         // Return the data
387         return $data;
388 }
389
390 // Filter to load include files
391 function FILTER_LOAD_INCLUDES ($data) {
392         // Default is $data as inclusion list
393         $INC_POOL = $data;
394
395         // Is it an array?
396         if ((!isset($data)) || (!is_array($data))) {
397                 // Then abort here
398                 DEBUG_LOG(__FILE__, __LINE__, "INC_POOL is no array!");
399                 return $data;
400         } elseif (isset($data['inc_pool'])) {
401                 // Use this as new inclusion pool!
402                 $INC_POOL = $data['inc_pool'];
403         }
404
405         // Check for added include files
406         if (count($INC_POOL) > 0) {
407                 // Loads every include file
408                 foreach ($INC_POOL as $FQFN) {
409                         LOAD_INC_ONCE($FQFN);
410                 } // END - foreach
411
412                 // Reset array
413                 if (isset($data['inc_pool'])) $data['inc_pool'] = array();
414         } // END - if
415
416         // Continue with processing
417         return $data;
418 }
419
420 // Filter for running SQL commands
421 function FILTER_RUN_SQLS ($data) {
422         // Is the array there?
423         if ((isset($data['sqls'])) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
424                 // Run SQL commands
425                 foreach ($data['sqls'] as $sql) {
426                         $sql = trim($sql);
427                         if (!empty($sql)) {
428                                 // Do we have an "ALTER TABLE" command?
429                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
430                                         // Analyse the alteration command
431                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
432                                 } else {
433                                         // Run regular SQL command
434                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
435                                 }
436                         } // END - if
437                 } // END - foreach
438         } // END - if
439 }
440
441 // Filter for updating/validating login data
442 function FILTER_UPDATE_LOGIN_DATA () {
443         global $LAST;
444         if (!is_array($LAST)) $LAST = array();
445
446         // Recheck if logged in
447         if (!IS_MEMBER()) return false;
448
449         // Secure user ID
450         $GLOBALS['userid'] = bigintval(get_session('userid'));
451
452         // Load last module and last online time
453         $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
454                 array($GLOBALS['userid']), __FILE__, __LINE__);
455
456         // Entry found?
457         if (SQL_NUMROWS($result) == 1) {
458                 // Load last module and online time
459                 list($mod, $onl) = SQL_FETCHROW($result);
460
461                 // Maybe first login time?
462                 if (empty($mod)) $mod = "login";
463
464                 // This will be displayed on welcome page! :-)
465                 if (empty($LAST['module'])) {
466                         $LAST['module'] = $mod; $LAST['online'] = $onl;
467                 } // END - if
468
469                 // "what" not set?
470                 if (empty($GLOBALS['what'])) {
471                         // Fix it to default
472                         $GLOBALS['what'] = "welcome";
473                         if (getConfig('index_home') != "") $GLOBALS['what'] = getConfig('index_home');
474                 } // END - if
475
476                 // Update last module / online time
477                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET last_module='%s', last_online=UNIX_TIMESTAMP(), REMOTE_ADDR='%s' WHERE userid=%s LIMIT 1",
478                         array($GLOBALS['what'], GET_REMOTE_ADDR(), $GLOBALS['userid']), __FILE__, __LINE__);
479         }  else {
480                 // Destroy session, we cannot update!
481                 destroy_user_session();
482         }
483
484         // Free the result
485         SQL_FREERESULT($result);
486 }
487
488 // Filter for checking admin ACL
489 function FILTER_CHECK_ADMIN_ACL () {
490         // Extension not installed so it's always allowed to access everywhere!
491         $ret = true;
492
493         // Ok, Cookie-Update done
494         if (GET_EXT_VERSION("admins") >= "0.3") {
495                 // Check if action GET variable was set
496                 $action = SQL_ESCAPE($GLOBALS['action']);
497                 if (!empty($GLOBALS['what'])) {
498                         // Get action value by what-value
499                         $action = GET_ACTION("admin", $GLOBALS['what']);
500                 } // END - if
501
502                 // Check for access control line of current menu entry
503                 $ret = ADMINS_CHECK_ACL($action, $GLOBALS['what']);
504         } // END - if
505
506         // Return result
507         return $ret;
508 }
509
510 // Filter for initializing randomizer
511 function FILTER_INIT_RANDOMIZER () {
512         // Simply init the randomizer with seed and _ADD value
513         mt_srand(generateSeed() + constant('_ADD'));
514 }
515
516 //
517 ?>