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