A lot rewrites from double-quote to single-quote, some fixes for extension handling...
[mailer.git] / inc / filters.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 12/16/2008 *
4  * ===============                              Last change: 12/16/2008 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : filters.php                                      *
8  * -------------------------------------------------------------------- *
9  * Short description : Functions for filter system                      *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Funktionen fuer Filter-System                    *
12  * -------------------------------------------------------------------- *
13  * $Revision::                                                        $ *
14  * $Date::                                                            $ *
15  * $Tag:: 0.2.1-FINAL                                                 $ *
16  * $Author::                                                          $ *
17  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4)."/security.php";
42         require($INC);
43 }
44
45 // Init "generic filter system"
46 function 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         REGISTER_FILTER('post_extension_installed', 'REMOVE_UPDATES');
123
124         // Solving tasks
125         REGISTER_FILTER('solve_task', 'SOLVE_TASK');
126
127         // Loading includes in general
128         REGISTER_FILTER('load_includes', 'LOAD_INCLUDES');
129
130         // Run SQLs
131         REGISTER_FILTER('run_sqls', 'RUN_SQLS');
132
133         // Admin ACL check
134         REGISTER_FILTER('check_admin_acl', 'CHECK_ADMIN_ACL');
135
136         // Register shutdown filters
137         REGISTER_FILTER('shutdown', 'FLUSH_FILTERS');
138 }
139
140 // "Registers" a new filter function
141 function REGISTER_FILTER ($filterName, $filterFunction, $silentAbort = true, $force = false, $dry_run = false) {
142         // Extend the filter function name
143         $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
144
145         // Is that filter already there?
146         if ((isset($GLOBALS['filters']['chains'][$filterName][$filterFunction])) && (!$force)) {
147                 // Then abort here
148                 if (!$silentAbort) {
149                         addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_ALREADY_ADDED'), array($filterFunction, $filterName));
150                 } // END - if
151
152                 // Abort here
153                 return false;
154         } // END - if
155
156         // Is the function there?
157         if (!function_exists($filterFunction)) {
158                 // Then abort here
159                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NOT_FOUND'), array($filterFunction, $filterName));
160                 return false;
161         } // END - if
162
163         // Shall we add it?
164         if (!$dry_run) {
165                 // Simply add it to the array
166                 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = "Y";
167                 $GLOBALS['filters']['counter'][$filterName][$filterFunction] = 0;
168         } // END - if
169 }
170
171 // "Unregisters" a filter from the given chain
172 function UNREGISTER_FILTER ($filterName, $filterFunction, $force = false, $dry_run = false) {
173         // Extend the filter function name only if not loaded from database
174         if (!isset($GLOBALS['filters']['loaded'][$filterName][$filterFunction])) {
175                 $filterFunction = sprintf("FILTER_%s", strtoupper($filterFunction));
176         } // END - if
177
178         // Is that filter there?
179         if ((!isset($GLOBALS['filters']['chains'][$filterName][$filterFunction])) && (!$force)) {
180                 // Not found, so abort here
181                 addFatalMessage(__FUNCTION__, __LINE__, 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                 $GLOBALS['filters']['chains'][$filterName][$filterFunction] = "R";
189                 unset($GLOBALS['filters']['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 runFilterChain ($filterName, $data = null, $silentAbort = true) {
195         // Is that filter chain there?
196         if (!isset($GLOBALS['filters']['chains'][$filterName])) {
197                 // Then abort here (quick'N'dirty hack)
198                 if ((!$silentAbort) && (defined('FILTER_FAILED_NO_FILTER_FOUND'))) {
199                         // Add fatal message
200                         addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FAILED_NO_FILTER_FOUND'), $filterName);
201                 } // END - if
202
203                 // Abort here
204                 return false;
205         } // END - if
206
207         // Default return value
208         $returnValue = $data;
209
210         // Then run all filters
211         foreach ($GLOBALS['filters']['chains'][$filterName] as $filterFunction=>$active) {
212                 // Debug message
213                 //* DEBUG: */ echo __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): name={$filterName},func={$filterFunction},active={$active}<br />\n";
214
215                 // Is the filter active?
216                 if ($active == 'Y') {
217                         // Is this filter there?
218                         if (!function_exists($filterFunction)) {
219                                 // Unregister it
220                                 UNREGISTER_FILTER($filterName, $filterFunction);
221
222                                 // Skip this entry
223                                 continue;
224                         } // END - if
225
226                         // Call the filter chain
227                         $returnValue = call_user_func_array($filterFunction, array($returnValue));
228
229                         // Update usage counter
230                         $GLOBALS['filters']['counter'][$filterName][$filterFunction]++;
231                 } // END - if
232         } // END - foreach
233
234         // Return the filtered content
235         return $returnValue;
236 }
237
238 // -----------------------------------------------------------------------------
239 // Generic filter functions we always need
240 // -----------------------------------------------------------------------------
241
242 // Filter for flushing all new filters to the database
243 function FILTER_FLUSH_FILTERS () {
244         // Clear all previous SQL queries
245         INIT_SQLS();
246
247         // Are we installing?
248         if ((isInstalling()) || (!isInstalled())) {
249                 // Then silently skip this filter
250                 return true;
251         } // END - if
252
253         // Is a database link here and not in installation mode?
254         if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
255                 // Abort here
256                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'));
257                 return false;
258         } // END - if
259
260         // Is the extension sql_patches updated?
261         if (EXT_VERSION_IS_OLDER('sql_patches', '0.5.9')) {
262                 // Abort silently here
263                 return false;
264         } // END - if
265
266         // Nothing is added/remove by default
267         $inserted = 0; $removed = 0;
268
269         // Prepare SQL queries
270         $insertSQL = "INSERT INTO `{!_MYSQL_PREFIX!}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES";
271         $removeSQL = "DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_filters` WHERE";
272
273         // Write all filters to database
274         foreach ($GLOBALS['filters']['chains'] as $filterName => $filterArray) {
275                 // Walk through all filters
276                 foreach ($filterArray as $filterFunction => $active) {
277                         // Is this filter loaded?
278                         if (!isset($GLOBALS['filters']['loaded'][$filterName][$filterFunction])) {
279                                 // Add this filter (all filters are active by default)
280                                 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
281                                 $inserted++;
282                         } elseif ($active == "R") {
283                                 // Remove this filter
284                                 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
285                                 $removed++;
286                         }
287                 } // END - foreach
288         } // END - foreach
289
290         // Something has been added?
291         if ($inserted > 0) {
292                 // Finish SQL command
293                 $insertSQL = substr($insertSQL, 0, -1);
294
295                 // And run it
296                 ADD_SQL($insertSQL);
297         } // END - if
298
299         // Something has been removed?
300         if ($removed > 0) {
301                 // Finish SQL command
302                 $removeSQL = substr($removeSQL, 0, -2) . "LIMIT ".$removed;
303
304                 // And run it
305                 ADD_SQL($removeSQL);
306         } // END - if
307
308         // Shall we update usage counters (ONLY FOR DEBUGGING!)
309         if (getConfig('update_filter_usage') == 'Y') {
310                 // Update all counters
311                 foreach ($GLOBALS['filters']['counter'] as $filterName => $filterArray) {
312                         // Walk through all filters
313                         foreach ($filterArray as $filterFunction => $cnt) {
314                                 // Construct and add the query
315                                 ADD_SQL(sprintf("UPDATE `{!_MYSQL_PREFIX!}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
316                                         bigintval($cnt),
317                                         $filterName,
318                                         $filterFunction
319                                 ));
320                         } // END - foreach
321                 } // END - foreach
322         } // END - if
323
324         // Run the run_sqls filter in non-dry mode
325         runFilterChain('run_sqls');
326 }
327
328 // Filter for calling the handler for login failures
329 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
330         // Init content
331         $content = $data;
332
333         // Handle failed logins here if not in guest
334         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={$GLOBALS['action']},what={$GLOBALS['what']},lvl={$data['access_level']}<br />\n";
335         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'))) {
336                 // Handle failure
337                 $content['content'] .= HANDLE_LOGIN_FAILTURES($data['access_level']);
338         } // END - if
339
340         // Return the content
341         return $content;
342 }
343
344 // Filter for redirecting to logout if sql_patches has been installed
345 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
346         // Remove this filter
347         UNREGISTER_FILTER('shutdown', __FUNCTION__);
348
349         // Is the element set?
350         if (isset($GLOBALS['ext_load_mode'])) {
351                 // Redirect here
352                 LOAD_URL("modules.php?module=admin&amp;logout=1&amp;".$GLOBALS['ext_load_mode']."=sql_patches");
353         } // END - if
354
355         // This should not happen!
356         DEBUG_LOG(__FUNCTION__, __LINE__, "Cannot auto-logout because no extension load-mode has been set.");
357 }
358
359 // Filter for auto-activation of a extension
360 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
361         // Is this extension always activated?
362         if (EXT_GET_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 () {
392         // Default is $data as inclusion list
393         $data = GET_INC_POOL();
394
395         // Is it an array?
396         if ((!isset($data)) || (!is_array($data))) {
397                 // Then abort here
398                 debug_report_bug(sprintf("INC_POOL is no array! Type: %s", gettype($data)));
399         } elseif (isset($data['inc_pool'])) {
400                 // Use this as new inclusion pool!
401                 SET_INC_POOL($data['inc_pool']);
402         }
403
404         // Check for added include files
405         if (COUNT_INC_POOL() > 0) {
406                 // Loads every include file
407                 foreach (GET_INC_POOL() as $FQFN) {
408                         LOAD_INC_ONCE($FQFN);
409                 } // END - foreach
410
411                 // Reset array
412                 INIT_INC_POOL();
413         } // END - if
414
415         // Continue with processing
416         return $data;
417 }
418
419 // Filter for running SQL commands
420 function FILTER_RUN_SQLS ($data) {
421         // Debug message
422         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " - Entered!");
423
424         // Is the array there?
425         if ((IS_SQLS_VALID()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
426                 // Run SQL commands
427                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " - Found ".COUNT_SQLS()." queries to run.");
428                 foreach (GET_SQLS() as $sql) {
429                         // Trim spaces away
430                         $sql = trim($sql);
431
432                         // Is there still a query left?
433                         if (!empty($sql)) {
434                                 // Do we have an "ALTER TABLE" command?
435                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
436                                         // Analyse the alteration command
437                                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Alterting table: {$sql}");
438                                         SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__);
439                                 } else {
440                                         // Run regular SQL command
441                                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Running regular query: {$sql}");
442                                         SQL_QUERY($sql, __FUNCTION__, __LINE__, false);
443                                 }
444                         } // END - if
445                 } // END - foreach
446         } // END - if
447
448         // Debug message
449         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " - Left!");
450 }
451
452 // Filter for updating/validating login data
453 function FILTER_UPDATE_LOGIN_DATA () {
454         // Add missing array
455         if ((!isset($GLOBALS['last'])) || (!is_array($GLOBALS['last']))) $GLOBALS['last'] = array();
456
457         // Recheck if logged in
458         if (!IS_MEMBER()) return false;
459
460         // Secure user ID
461         setUserId(get_session('userid'));
462
463         // Load last module and last online time
464         $result = SQL_QUERY_ESC("SELECT last_module, last_online FROM `{!_MYSQL_PREFIX!}_user_data` WHERE userid=%s LIMIT 1",
465                 array(getUserId()), __FUNCTION__, __LINE__);
466
467         // Entry found?
468         if (SQL_NUMROWS($result) == 1) {
469                 // Load last module and online time
470                 list($mod, $onl) = SQL_FETCHROW($result);
471
472                 // Maybe first login time?
473                 if (empty($mod)) $mod = "login";
474
475                 // This will be displayed on welcome page! :-)
476                 if (empty($GLOBALS['last']['module'])) {
477                         $GLOBALS['last']['module'] = $mod; $GLOBALS['last']['online'] = $onl;
478                 } // END - if
479
480                 // "what" not set?
481                 if (empty($GLOBALS['what'])) {
482                         // Fix it to default
483                         $GLOBALS['what'] = "welcome";
484                         if (getConfig('index_home') != "") $GLOBALS['what'] = getConfig('index_home');
485                 } // END - if
486
487                 // Update last module / online time
488                 SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_user_data` SET `last_module`='%s', last_online=UNIX_TIMESTAMP(), REMOTE_ADDR='%s' WHERE userid=%s LIMIT 1",
489                         array($GLOBALS['what'], GET_REMOTE_ADDR(), getUserId()), __FUNCTION__, __LINE__);
490         }  else {
491                 // Destroy session, we cannot update!
492                 destroy_user_session();
493         }
494
495         // Free the result
496         SQL_FREERESULT($result);
497 }
498
499 // Filter for checking admin ACL
500 function FILTER_CHECK_ADMIN_ACL () {
501         // Extension not installed so it's always allowed to access everywhere!
502         $ret = true;
503
504         // Ok, Cookie-Update done
505         if (GET_EXT_VERSION('admins') >= '0.3.0') {
506                 // Check if action GET variable was set
507                 $action = SQL_ESCAPE($GLOBALS['action']);
508                 if (!empty($GLOBALS['what'])) {
509                         // Get action value by what-value
510                         $action = GET_ACTION('admin', $GLOBALS['what']);
511                 } // END - if
512
513                 // Check for access control line of current menu entry
514                 $ret = ADMINS_CHECK_ACL($action, $GLOBALS['what']);
515         } // END - if
516
517         // Return result
518         return $ret;
519 }
520
521 // Filter for initializing randomizer
522 function FILTER_INIT_RANDOMIZER () {
523         // Simply init the randomizer with seed and _ADD value
524         mt_srand(generateSeed() + constant('_ADD'));
525 }
526
527 // Filter for removing updates
528 function FILTER_REMOVE_UPDATES () {
529         // Init removal list
530         EXT_INIT_REMOVAL_LIST();
531
532         // Add the current extension to it
533         EXT_ADD_CURRENT_TO_REMOVAL_LIST();
534
535         // Simply remove it
536         UNSET_EXT_SQLS();
537
538         // Do we need to remove update depency?
539         if (EXT_COUNT_UPDATE_DEPENDS() > 0) {
540                 // Then find all updates we shall no longer execute
541                 foreach (EXT_GET_UPDATE_DEPENDS() as $id=>$ext_name) {
542                         // Shall we remove this update?
543                         if (in_array($ext_name, EXT_GET_REMOVAL_LIST())) {
544                                 // Then remove this extension!
545                                 EXT_REMOVE_UPDATE_DEPENDS($ext_name);
546                         } // END - if
547                 } // END - foreach
548         } // END - if
549 }
550
551 //
552 ?>