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