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