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