Naming inconsistencies for userid fixed
[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 : Generic filters                                  *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Allgemeine Filter                                *
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 - 2009 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         die();
42 } // END - if
43
44 // Filter for flushing all new filters to the database
45 function FILTER_FLUSH_FILTERS () {
46         // Clear all previous SQL queries
47         initSqls();
48
49         // Are we installing?
50         if ((isInstallationPhase())) {
51                 // Then silently skip this filter
52                 return true;
53         } // END - if
54
55         // Is a database link here and not in installation mode?
56         if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
57                 // Abort here
58                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'));
59                 return false;
60         } // END - if
61
62         // Is the extension sql_patches updated?
63         if ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) {
64                 // Abort silently here
65                 return false;
66         } // END - if
67
68         // Nothing is added/remove by default
69         $inserted = 0;
70         $removed = 0;
71
72         // Prepare SQL queries
73         $insertSQL = "INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES";
74         $removeSQL = "DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE";
75
76         // Write all filters to database
77         foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
78                 // Walk through all filters
79                 foreach ($filterArray as $filterFunction => $active) {
80                         // Is this filter loaded?
81                         //* DEBUG: */ print 'FOUND:'.$filterName.'/'.$filterFunction.'='.$active.'<br />';
82                         if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
83                                 // Add this filter (all filters are active by default)
84                                 //* DEBUG: */ print 'ADD:'.$filterName.'/'.$filterFunction.'<br />';
85                                 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
86                                 $inserted++;
87                         } elseif ($active == 'R') {
88                                 // Remove this filter
89                                 //* DEBUG: */ print 'REMOVE:'.$filterName.'/'.$filterFunction.'<br />';
90                                 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
91                                 $removed++;
92                         }
93                 } // END - foreach
94         } // END - foreach
95
96         // Something has been added?
97         if ($inserted > 0) {
98                 // Finish SQL command and add it
99                 addSql(substr($insertSQL, 0, -1));
100         } // END - if
101
102         // Something has been removed?
103         if ($removed > 0) {
104                 // Finish SQL command and add it
105                 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
106         } // END - if
107
108         // Shall we update usage counters (ONLY FOR DEBUGGING!)
109         if (getConfig('update_filter_usage') == 'Y') {
110                 // Update all counters
111                 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
112                         // Walk through all filters
113                         foreach ($filterArray as $filterFunction => $cnt) {
114                                 // Construct and add the query
115                                 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
116                                         bigintval($cnt),
117                                         $filterName,
118                                         $filterFunction
119                                 ));
120                         } // END - foreach
121                 } // END - foreach
122         } // END - if
123
124         // Run the run_sqls filter in non-dry mode
125         runFilterChain('run_sqls');
126
127         // Should we rebuild cache?
128         if (($inserted > 0) || ($removed > 0)) {
129                 // Destroy cache
130                 rebuildCacheFile('filter', 'filter');
131         } // END - if
132 }
133
134 // Filter for calling the handler for login failures
135 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
136         // Init content
137         $content = $data;
138
139         // Handle failed logins here if not in guest
140         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={getAction()},what={getWhat()},level={$data['access_level']}<br />");
141         if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getConfig('index_home')))) && ($data['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.0')))) {
142                 // Handle failure
143                 $content['content'] .= handleLoginFailtures($data['access_level']);
144         } // END - if
145
146         // Return the content
147         return $content;
148 }
149
150 // Filter for redirecting to logout if sql_patches has been installed
151 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
152         // Remove this filter
153         unregisterFilter('shutdown', __FUNCTION__);
154
155         // Is the element set?
156         if (isset($GLOBALS['ext_load_mode'])) {
157                 // Redirect here
158                 redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . $GLOBALS['ext_load_mode'] . '=sql_patches');
159         } // END - if
160
161         // This should not happen!
162         logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
163 }
164
165 // Filter for auto-activation of a extension
166 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
167         // Is this extension always activated?
168         if (getExtensionAlwaysActive() == 'Y') {
169                 // Then activate the extension
170                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$data['ext_name']}<br />");
171                 doActivateExtension($data['ext_name']);
172         } // END - if
173
174         // Return the data
175         return $data;
176 }
177
178 // Filter for solving task given task
179 function FILTER_SOLVE_TASK ($data) {
180         // Don't solve anything if no admin!
181         if (!isAdmin()) return $data;
182
183         // Is this a direct task id or array element task_id is found?
184         if (is_int($data)) {
185                 // Then solve it...
186                 adminSolveTask($data);
187         } elseif ((is_array($data)) && (isset($data['task_id']))) {
188                 // Solve it...
189                 adminSolveTask($data['task_id']);
190         } else {
191                 // Not detectable!
192                 debug_report_bug(sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
193         }
194
195         // Return the data
196         return $data;
197 }
198
199 // Filter to load include files
200 function FILTER_LOAD_INCLUDES ($pool) {
201         // Is it null?
202         if (is_null($pool)) {
203                 // This should not happen!
204                 debug_report_bug('pool is null.');
205         } // END - if
206
207         // Is the pool an array and 'pool' set?
208         if ((is_array($pool)) && (isset($pool['pool']))) {
209                 // Then use it as pool
210                 $realPool = $pool['pool'];
211         } else {
212                 // Default is $data as inclusion list
213                 $realPool = $pool;
214         }
215
216         // Get inc pool
217         $data = getIncludePool($realPool);
218
219         // Is it an array?
220         if ((!isset($data)) || (!is_array($data))) {
221                 // Then abort here
222                 debug_report_bug(sprintf("INC_POOL is no array! Type: %s", gettype($data)));
223         } elseif (isset($data['inc_pool'])) {
224                 // Use this as new inclusion pool!
225                 setIncludePool($realPool, $data['inc_pool']);
226         }
227
228         // Check for added include files
229         if (countIncludePool($realPool) > 0) {
230                 // Loads every include file
231                 loadIncludePool($realPool);
232
233                 // Reset array
234                 initIncludePool($realPool);
235         } // END - if
236
237         // Continue with processing
238         return $pool;
239 }
240
241 // Filter for running SQL commands
242 function FILTER_RUN_SQLS ($data) {
243         // Debug message
244         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Entered!");
245
246         // Is the array there?
247         if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
248                 // Run SQL commands
249                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Found ".countSqls()." queries to run.");
250                 foreach (getSqls() as $sqls) {
251                         // New cache format...
252                         foreach ($sqls as $sql) {
253                                 // Trim spaces away
254                                 $sql = trim($sql);
255
256                                 // Is there still a query left?
257                                 if (!empty($sql)) {
258                                         // Do we have an "ALTER TABLE" command?
259                                         if (substr(strtolower($sql), 0, 11) == 'alter table') {
260                                                 // Analyse the alteration command
261                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Alterting table: {$sql}");
262                                                 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__);
263                                         } else {
264                                                 // Run regular SQL command
265                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Running regular query: {$sql}");
266                                                 SQL_QUERY($sql, __FUNCTION__, __LINE__, false);
267                                         }
268                                 } // END - if
269                         } // END - foreach
270                 } // END - foreach
271         } // END - if
272
273         // Debug message
274         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Left!");
275 }
276
277 // Filter for updating/validating login data
278 function FILTER_UPDATE_LOGIN_DATA () {
279         // Add missing array
280         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
281
282         // Recheck if logged in
283         if (!isMember()) return false;
284
285         // Secure user id
286         setMemberId(getSession('userid'));
287
288         // Found a userid?
289         if (fetchUserData(getMemberId())) {
290                 // Load last module and online time
291                 $content = getUserDataArray();
292
293                 // Maybe first login time?
294                 if (empty($content['last_module'])) $content['last_module'] = 'login';
295
296                 // This will be displayed on welcome page! :-)
297                 if (empty($GLOBALS['last_online']['module'])) {
298                         $GLOBALS['last_online']['module'] = $content['last_module'];
299                         $GLOBALS['last_online']['online'] = $content['last_online'];
300                 } // END - if
301
302                 // 'what' not set?
303                 if (!isWhatSet()) {
304                         // Fix it to default
305                         setWhat('welcome');
306                         if (getConfig('index_home') != '') setWhatFromConfig('index_home');
307                 } // END - if
308
309                 // Update last module / online time
310                 SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_user_data` SET `last_module`='%s', `last_online`=UNIX_TIMESTAMP(), `REMOTE_ADDR`='%s' WHERE `userid`=%s LIMIT 1",
311                         array(
312                                 getWhat(),
313                                 detectRemoteAddr(),
314                                 getMemberId()
315                         ), __FUNCTION__, __LINE__);
316         }  else {
317                 // Destroy session, we cannot update!
318                 destroyMemberSession();
319         }
320 }
321
322 // Filter for initializing randomizer
323 function FILTER_INIT_RANDOMIZER () {
324         // Only execute this filter if installed
325         if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) return;
326
327         // Take a prime number which is long (if you know a longer one please try it out!)
328         setConfigEntry('_PRIME', 591623);
329
330         // Calculate "entropy" with the prime number (for code generation)
331         setConfigEntry('_ADD', (getConfig('_PRIME') * getConfig('_PRIME') / (pi() * getConfig('code_length') + 1)));
332
333         // Simply init the randomizer with seed and _ADD value
334         mt_srand(generateSeed() + getConfig('_ADD'));
335 }
336
337 // Filter for removing updates
338 function FILTER_REMOVE_UPDATES ($data) {
339         // Init removal list
340         initExtensionRemovalList();
341
342         // Add the current extension to it
343         addCurrentExtensionToRemovalList();
344
345         // Simply remove it
346         unsetExtensionSqls();
347
348         // Do we need to remove update depency?
349         if (countExtensionUpdateDependencies() > 0) {
350                 // Then find all updates we shall no longer execute
351                 foreach (getExtensionUpdateDependencies() as $id=>$ext_name) {
352                         // Shall we remove this update?
353                         if (in_array($ext_name, getExtensionRemovalList())) {
354                                 // Then remove this extension!
355                                 removeExtensionUpdateDependency($ext_name);
356                         } // END - if
357                 } // END - foreach
358         } // END - if
359
360         // Return data
361         return $data;
362 }
363
364 // Determines username for current user state
365 function FILTER_DETERMINE_USERNAME () {
366         // Check if logged in
367         if (isMember()) {
368                 // Is still logged in so we welcome him with his name
369                 if (fetchUserData(getMemberId())) {
370                         // Load surname and family's name and build the username
371                         $content = getUserDataArray();
372
373                         // Prepare username
374                         setUsername($content['surname'] . ' ' . $content['family']);
375
376                         // Additionally admin?
377                         if (isAdmin()) {
378                                 // Add it
379                                 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
380                         } // END - if
381                 } else {
382                         // Hmmm, logged in and no valid userid?
383                         setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
384
385                         // Destroy session
386                         destroyMemberSession();
387                 }
388         } elseif (isAdmin()) {
389                 // Admin is there
390                 setUsername('{--USERNAME_ADMIN--}');
391         } else {
392                 // He's a guest, hello there... ;-)
393                 setUsername('{--USERNAME_GUEST--}');
394         }
395 }
396
397 // Filter for compiling config entries
398 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
399         // Save the uncompiled code
400         $uncompiled = $code;
401
402         // Do we have cache?
403         if (!isset($GLOBALS['compiled_config'][$code])) {
404                 // Compile {?some_var?} to getConfig('some_var')
405                 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
406
407                 // Some entries found?
408                 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
409                         // Replace all matches
410                         foreach ($matches[0] as $key => $match) {
411                                 // Do we have cache?
412                                 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
413                                         // Is the config valid?
414                                         if (isConfigEntrySet($matches[1][$key])) {
415                                                 // Set it for caching
416                                                 $GLOBALS['compile_config'][$matches[1][$key]] = "\".getConfig('" . $matches[1][$key] . "').\"";
417                                         } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
418                                                 // Use default value
419                                                 $GLOBALS['compile_config'][$matches[1][$key]] = "\".getConfig('" . 'DEFAULT_' . strtoupper($matches[1][$key]) . "').\"";
420                                         } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
421                                                 // No config, try the language system
422                                                 $GLOBALS['compile_config'][$matches[1][$key]] = "\".getMessage('". 'DEFAULT_' . strtoupper($matches[1][$key]) . "').\"";
423                                         } else {
424                                                 // Unhandled!
425                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
426                                         }
427                                 } // END - if
428
429                                 // Use this for replacing
430                                 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
431                                 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die('<pre>'.htmlentities($code).'</pre>');
432                         } // END - foreach
433                 } // END - if
434
435                 // Add it to cache
436                 $GLOBALS['compiled_config'][$uncompiled] = $code;
437         } // END - if
438
439         // Should we compile it?
440         if ($compiled === true) {
441                 // Run the code
442                 eval("\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . "\";");
443         } // END - if
444
445         // Return compiled code
446         return $GLOBALS['compiled_config'][$uncompiled];
447 }
448
449 // Filter for compiling extension data
450 function FILTER_COMPILE_EXTENSION ($code) {
451         // Compile {%cmd=some_value%} to get extension data
452         // Support cmd is:
453         //   - version -> getExtensionVersion() call
454         preg_match_all('/\{%((([a-zA-Z0-9-_]+)=([a-zA-Z0-9-_]+))*)\%\}/', $code, $matches);
455
456         // Some entries found?
457         if ((count($matches) > 0) && (count($matches[3]) > 0)) {
458                 // Replace all matches
459                 foreach ($matches[3] as $key => $cmd) {
460                         // By default we have no extension installed, so 'false' is assumed
461                         $replacer = 'false';
462
463                         // Is the extension installed?
464                         if (isExtensionActive($matches[4][$key])) {
465                                 // Construct call-back function name
466                                 $functionName = 'getExtension' . ucfirst(strtolower($cmd));
467
468                                 // Call the function
469                                 $replacer = call_user_func_array($functionName, $matches[4][$key]);
470                         } // END - if
471
472                         // Replace it and insert parameter for GET request
473                         $code = str_replace($matches[0][$key], sprintf("&amp;%s=%s&amp;rev=%s", $cmd, $replacer, getConfig('CURR_SVN_REVISION')), $code);
474                 } // END - foreach
475         } // END - if
476
477         // Return compiled code
478         return $code;
479 }
480
481 // Runs some generic filter update steps
482 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
483         // Create task
484         createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
485
486         // Update extension's version
487         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
488                 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
489
490         // Remove arrays
491         unsetSqls();
492         unset($GLOBALS['update_ver'][$ext_name]);
493 }
494
495 // Load more reset scripts
496 function FILTER_RUN_RESET_INCLUDES () {
497         // Is the reset set or old sql_patches?
498         if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (getOutputMode() == 0)) {
499                 // Then abort here
500                 logDebugMessage(__FUNCTION__, __LINE__, 'Cannot run reset! Please report this bug. Thanks');
501         } // END - if
502
503         // Get more daily reset scripts
504         setIncludePool('reset', getArrayFromDirectory('inc/reset/', 'reset_'));
505
506         // Update database
507         if ((!isConfigEntrySet('DEBUG_RESET')) || (getConfig('DEBUG_RESET') != 'Y')) updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
508
509         // Is the config entry set?
510         if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
511                 // Create current week mark
512                 $currWeek = date('W', time());
513
514                 // Has it changed?
515                 if ((getConfig('last_week') != $currWeek) || (getConfig('DEBUG_WEEKLY') == 'Y')) {
516                         // Include weekly reset scripts
517                         mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
518
519                         // Update config
520                         if ((isConfigEntrySet('DEBUG_WEEKLY')) && (getConfig('DEBUG_WEEKLY') != 'Y')) updateConfiguration('last_week', $currWeek);
521                 } // END - if
522
523                 // Create current month mark
524                 $currMonth = date('m', time());
525
526                 // Has it changed?
527                 if ((getConfig('last_month') != $currMonth) || (getConfig('DEBUG_MONTHLY') == 'Y')) {
528                         // Include monthly reset scripts
529                         mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
530
531                         // Update config
532                         if ((isConfigEntrySet('DEBUG_MONTHLY')) && (getConfig('DEBUG_MONTHLY') != 'Y')) updateConfiguration('last_month', $currMonth);
533                 } // END - if
534         } // END - if
535
536         // Run the filter
537         runFilterChain('load_includes', 'reset');
538 }
539
540 // Filter for removing the given extension
541 function FILTER_REMOVE_EXTENSION () {
542         // Delete this extension (remember to remove it from your server *before* you click on welcome!
543         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
544                 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
545
546         // Remove the extension from global cache array as well
547         removeExtensionFromArray();
548
549         // Remove the cache
550         rebuildCacheFile('extension', 'extension');
551 }
552
553 // Filter for flushing the output
554 function FILTER_FLUSH_OUTPUT () {
555         // Simple, he?
556         outputHtml('');
557 }
558
559 // Prepares an SQL statement part for HTML mail and/or holiday depency
560 function FILTER_HTML_INCLUDE_USERS ($mode) {
561         // Exclude no users by default
562         $MORE = '';
563
564         // HTML mail?
565         if ($mode == 'html') $MORE = " AND `html`='Y'";
566         if ((isExtensionActive('holiday')) && (getExtensionVersion('holiday') >= '0.1.3')) {
567                 // Add something for the holiday extension
568                 $MORE .= " AND `holiday_active`='N'";
569         } // END - if
570
571         // Return result
572         return $MORE;
573 }
574
575 // Filter for determining what/action/module
576 function FILTER_DETERMINE_WHAT_ACTION () {
577         // In installation phase we don't have what/action
578         if (isInstallationPhase()) {
579                 // Set both to empty
580                 setAction('');
581                 setWhat('');
582
583                 // Abort here
584                 return;
585         } // END - if
586
587         // Get all values
588         if ((getOutputMode() != 1) && (getOutputMode() != -1)) {
589                 // Fix module
590                 if (!isModuleSet()) {
591                         // Is the request element set?
592                         if (isGetRequestElementSet('module')) {
593                                 // Set module from request
594                                 setModule(getRequestElement('module'));
595                         } else {
596                                 // Set default module 'index'
597                                 setModule('index');
598                         }
599                 } // END - if
600
601                 // Fix 'what' if not yet set
602                 if (!isWhatSet())   setWhat(getWhatFromModule(getModule()));
603
604                 // Fix 'action' if not yet set
605                 if (!isActionSet()) setAction(getModeAction(getModule(), getWhat()));
606         } else {
607                 // Set action/what to empty
608                 setAction('');
609                 setWhat('');
610         }
611
612         // Set default 'what' value
613         //* DEBUG: */ outputHtml('-'.getModule().'/'.getWhat()."-<br />");
614         if ((!isWhatSet()) && (!isActionSet()) && (getOutputMode() != 1) && (getOutputMode() != -1)) {
615                 if (getModule() == 'admin') {
616                         // Set 'action' value to 'login' in admin menu
617                         setAction(getModeAction(getModule(), getWhat()));
618                 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
619                         // Set 'what' value to 'welcome' in guest and member menu
620                         setWhatFromConfig('index_home');
621                 } else {
622                         // Anything else like begging link
623                         setWhat('');
624                 }
625         } // END - if
626 }
627
628 // Sends out pooled mails
629 function FILTER_TRIGGER_SENDING_POOL () {
630         // Are we in normal output mode?
631         if (getOutputMode() != 0) {
632                 // Only in normal output mode to prevent race-conditons!
633         } // END - if
634
635         // Init counter
636         $GLOBALS['pool_cnt'] = 0;
637
638         // Init & set the include pool
639         initIncludePool('pool');
640         setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
641
642         // Run the filter
643         runFilterChain('load_includes', 'pool');
644
645         // Remove the counter
646         unset($GLOBALS['pool_cnt']);
647 }
648
649 // Filter for checking and updating SVN revision
650 function FILTER_CHECK_SVN_REVISION () {
651         // Only execute this filter if installed and all config entries are there
652         if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
653
654         // Check for patch level differences between databases and current hard-coded
655         if ((getConfig('CURR_SVN_REVISION') > getConfig('patch_level')) || (getConfig('patch_level') == 'CURR_SVN_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
656                 // Update database and CONFIG array
657                 updateConfiguration(array('patch_level', 'patch_ctime'), array(getConfig('CURR_SVN_REVISION'), 'UNIX_TIMESTAMP()'));
658                 setConfigEntry('patch_level', getConfig('CURR_SVN_REVISION'));
659                 setConfigEntry('patch_ctime', time());
660         } // END - if
661 }
662
663 // Filter for running daily reset
664 function FILTER_RUN_DAILY_RESET () {
665         // Only execute this filter if installed
666         if ((!isInstalled()) || (!isAdminRegistered())) return;
667
668         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
669         // 012    3              4             43        3         4432    2         3             3       21    1                    221    1                 221    1                  2          21    1             22     10
670         if (((date('d', getConfig('last_update')) != date('d', time())) || ((isConfigEntrySet('DEBUG_RESET')) && (getConfig('DEBUG_RESET') == 'Y'))) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (getOutputMode() != 1)) {
671                 // Tell every module we are in reset-mode!
672                 doReset();
673         } // END - if
674 }
675
676 // Filter for loading more runtime includes (not for installation)
677 function FILTER_LOAD_RUNTIME_INCLUDES () {
678         // Load more includes
679         foreach (array('inc/databases.php','inc/session.php','inc/versions.php') as $inc) {
680                 // Load the include
681                 loadIncludeOnce($inc);
682         } // END - foreach
683
684         // Load admin include file if he is admin
685         if (isAdmin()) {
686                 // Administrative functions
687                 loadIncludeOnce('inc/modules/admin/admin-inc.php');
688         } // END - if
689         //* DEBUG: */ addPointsThroughReferalSystem('test', 36, 1000);
690         //* DEBUG: */ die();
691 }
692
693 // Filter for checking admin ACL
694 function FILTER_CHECK_ADMIN_ACL () {
695         // Extension not installed so it's always allowed to access everywhere!
696         $ret = true;
697
698         // Ok, Cookie-Update done
699         if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
700                 // Check if action GET variable was set
701                 $action = getAction();
702                 if (isWhatSet()) {
703                         // Get action value by what-value
704                         $action = getModeAction('admin', getWhat());
705                 } // END - if
706
707                 // Check for access control line of current menu entry
708                 $ret = adminsCheckAdminAcl($action, getWhat());
709         } // END - if
710
711         // Set it here
712         $GLOBALS['acl_allow'] = $ret;
713 }
714
715 // Init random number/cache buster
716 function FILTER_INIT_RANDOM_NUMBER () {
717         // Is the extension sql_patches installed and at least 0.3.6?
718         if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
719                 // Generate random number
720                 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
721         } else {
722                 // Generate weak (!!!) code
723                 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
724         }
725
726         // Copy it to CACHE_BUSTER
727         setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
728 }
729
730 // Update module counter
731 function FILTER_COUNT_MODULE () {
732         // Do count all other modules but not accesses on CSS file css.php!
733         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
734                 array(getModule()), __FUNCTION__, __LINE__);
735 }
736
737 // Handles fatal errors
738 function FILTER_HANDLE_FATAL_ERRORS () {
739         // Do we have errors to handle and right output mode?
740         if ((getTotalFatalErrors() == 0) || (getOutputMode() != 0)) {
741                 // Abort executing here
742                 return false;
743         } // END - if
744
745         // Set content type
746         setContentType('text/html');
747
748         // Load config here
749         loadIncludeOnce('inc/load_config.php');
750
751         // Set unset variable
752         if (empty($check)) $check = '';
753
754         // Default is none
755         $content = '';
756
757         // Installation phase or regular mode?
758         if ((isInstallationPhase())) {
759                 // While we are installing ouput other header than while it is installed... :-)
760                 $OUT = '';
761                 foreach (getFatalArray() as $key => $value) {
762                         // Prepare content for the template
763                         $content = array(
764                                 'key'   => ($key + 1),
765                                 'value' => $value
766                         );
767
768                         // Load row template
769                         $OUT .= loadTemplate('install_fatal_row', true, $content);
770                 }
771
772                 // Load main template
773                 $content = loadTemplate('install_fatal_table', true, $OUT);
774         } elseif (isInstalled()) {
775                 // Display all runtime fatal errors
776                 $OUT = '';
777                 foreach (getFatalArray() as $key => $value) {
778                         // Prepare content for the template
779                         $content = array(
780                                 'key'   => ($key + 1),
781                                 'value' => $value
782                         );
783
784                         // Load row template
785                         $OUT .= loadTemplate('runtime_fatal_row', true, $content);
786                 }
787
788                 // Load main template
789                 $content = loadTemplate('runtime_fatal_table', true, $OUT);
790         }
791
792         // Message to regular users (non-admin)
793         $CORR = getMessage('FATAL_REPORT_ERRORS');
794
795         // PHP warnings fixed
796         if ($check == 'done') {
797                 if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
798         } // END - if
799
800         // Remember all in array
801         $content = array(
802                 'rows' => $content,
803                 'corr' => $CORR
804         );
805
806         // Load footer
807         loadIncludeOnce('inc/header.php');
808
809         // Load main template
810         loadTemplate('fatal_errors', false, $content);
811
812         // Delete all to prevent double-display
813         initFatalMessages();
814
815         // Load footer
816         loadIncludeOnce('inc/footer.php');
817
818         // Abort here
819         shutdown();
820 }
821
822 // Filter for displaying copyright line
823 function FILTER_DISPLAY_COPYRIGHT () {
824         // Shall we display the copyright notice?
825         if ((!isGetRequestElementSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
826                 // Backlink enabled?
827                 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
828                         // Copyright with backlink, thanks! :-)
829                         loadTemplate('copyright_backlink');
830                 } else {
831                         // No backlink in Copyright note
832                         loadTemplate('copyright');
833                 }
834         } // END - if
835 }
836
837 // Filter for displaying parsing time
838 function FILTER_DISPLAY_PARSING_TIME () {
839         // Shall we display the parsing time and number of queries?
840         // 1234                            5                      54    4         5              5       4    4                       5       543    3                   4432    2             33     2    2                              21
841         if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestElementSet('frame'))) || (isInstallationPhase())) && (getOutputMode() == 0) && ($GLOBALS['header_sent'] == 2)) {
842                 // Then display it here
843                 displayParsingTime();
844         } // END - if
845 }
846
847 // Filter for flushing template cache
848 function FILTER_FLUSH_TEMPLATE_CACHE () {
849         // Do we have cached eval() data?
850         if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
851                 // Now flush all
852                 foreach ($GLOBALS['template_eval'] as $template=>$eval) {
853                         // Flush the cache (if not yet found)
854                         flushTemplateCache($template, $eval);
855                 } // END - if
856         } // END - if
857 }
858
859 // [EOF]
860 ?>