More language strings rewritten
[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         global $CSS;
393
394         // Default is $data as inclusion list
395         $INC_POOL = $data;
396
397         // Is it an array?
398         if ((!isset($data)) || (!is_array($data))) {
399                 // Then abort here
400                 DEBUG_LOG(__FILE__, __LINE__, "INC_POOL is no array!");
401                 return $data;
402         } elseif (isset($data['inc_pool'])) {
403                 // Use this as new inclusion pool!
404                 $INC_POOL = $data['inc_pool'];
405         }
406
407         // Check for added include files
408         if (count($INC_POOL) > 0) {
409                 // Loads every include file
410                 foreach ($INC_POOL as $FQFN) {
411                         LOAD_INC_ONCE($FQFN);
412                 } // END - foreach
413
414                 // Reset array
415                 if (isset($data['inc_pool'])) $data['inc_pool'] = array();
416         } // END - if
417
418         // Continue with processing
419         return $data;
420 }
421
422 // Filter for running SQL commands
423 function FILTER_RUN_SQLS ($data) {
424         // Is the array there?
425         if ((isset($data['sqls'])) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
426                 // Run SQL commands
427                 foreach ($data['sqls'] as $sql) {
428                         $sql = trim($sql);
429                         if (!empty($sql)) {
430                                 // Do we have an "ALTER TABLE" command?
431                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
432                                         // Analyse the alteration command
433                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
434                                 } else {
435                                         // Run regular SQL command
436                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
437                                 }
438                         } // END - if
439                 } // END - foreach
440         } // END - if
441 }
442
443 // Filter for updating/validating login data
444 function FILTER_UPDATE_LOGIN_DATA () {
445         global $LAST;
446         if (!is_array($LAST)) $LAST = array();
447
448         // Recheck if logged in
449         if (!IS_MEMBER()) return false;
450
451         // Secure user ID
452         $GLOBALS['userid'] = bigintval(get_session('userid'));
453
454         // Load last module and last online time
455         $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
456                 array($GLOBALS['userid']), __FILE__, __LINE__);
457
458         // Entry found?
459         if (SQL_NUMROWS($result) == 1) {
460                 // Load last module and online time
461                 list($mod, $onl) = SQL_FETCHROW($result);
462
463                 // Maybe first login time?
464                 if (empty($mod)) $mod = "login";
465
466                 // This will be displayed on welcome page! :-)
467                 if (empty($LAST['module'])) {
468                         $LAST['module'] = $mod; $LAST['online'] = $onl;
469                 } // END - if
470
471                 // "what" not set?
472                 if (empty($GLOBALS['what'])) {
473                         // Fix it to default
474                         $GLOBALS['what'] = "welcome";
475                         if (getConfig('index_home') != "") $GLOBALS['what'] = getConfig('index_home');
476                 } // END - if
477
478                 // Update last module / online time
479                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET last_module='%s', last_online=UNIX_TIMESTAMP(), REMOTE_ADDR='%s' WHERE userid=%s LIMIT 1",
480                         array($GLOBALS['what'], GET_REMOTE_ADDR(), $GLOBALS['userid']), __FILE__, __LINE__);
481         }  else {
482                 // Destroy session, we cannot update!
483                 destroy_user_session();
484         }
485
486         // Free the result
487         SQL_FREERESULT($result);
488 }
489
490 // Filter for checking admin ACL
491 function FILTER_CHECK_ADMIN_ACL () {
492         // Extension not installed so it's always allowed to access everywhere!
493         $ret = true;
494
495         // Ok, Cookie-Update done
496         if (GET_EXT_VERSION("admins") >= "0.3") {
497                 // Check if action GET variable was set
498                 $action = SQL_ESCAPE($GLOBALS['action']);
499                 if (!empty($GLOBALS['what'])) {
500                         // Get action value by what-value
501                         $action = GET_ACTION("admin", $GLOBALS['what']);
502                 } // END - if
503
504                 // Check for access control line of current menu entry
505                 $ret = ADMINS_CHECK_ACL($action, $GLOBALS['what']);
506         } // END - if
507
508         // Return result
509         return $ret;
510 }
511
512 // Filter for initializing randomizer
513 function FILTER_INIT_RANDOMIZER () {
514         // Simply init the randomizer with seed and _ADD value
515         mt_srand(generateSeed() + constant('_ADD'));
516 }
517
518 //
519 ?>