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