More usage of EL
[mailer.git] / inc / filters.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                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  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Filter for flushing all new filters to the database
46 function FILTER_FLUSH_FILTERS () {
47         // Clear all previous SQL queries
48         initSqls();
49
50         // Are we installing?
51         if ((isInstallationPhase())) {
52                 // Then silently skip this filter
53                 return true;
54         } // END - if
55
56         // Is a database link here and not in installation mode?
57         if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
58                 // Abort here
59                 addFatalMessage(__FUNCTION__, __LINE__, '{--FILTER_FLUSH_FAILED_NO_DATABASE--}');
60                 return false;
61         } // END - if
62
63         // Is the extension sql_patches updated?
64         if ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) {
65                 // Abort silently here
66                 return false;
67         } // END - if
68
69         // Nothing is added/remove by default
70         $inserted = '0';
71         $removed = '0';
72
73         // Prepare SQL queries
74         $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`,`filter_function`,`filter_active`) VALUES';
75         $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
76
77         // Write all filters to database
78         foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
79                 // Walk through all filters
80                 foreach ($filterArray as $filterFunction => $active) {
81                         // Is this filter loaded?
82                         //* DEBUG: */ debugOutput('FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
83                         if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
84                                 // Add this filter (all filters are active by default)
85                                 //* DEBUG: */ debugOutput('ADD:'.$filterName.'/'.$filterFunction);
86                                 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
87                                 $inserted++;
88                         } elseif ($active == 'R') {
89                                 // Remove this filter
90                                 //* DEBUG: */ debugOutput('REMOVE:'.$filterName.'/'.$filterFunction);
91                                 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
92                                 $removed++;
93                         }
94                 } // END - foreach
95         } // END - foreach
96
97         // Something has been added?
98         if ($inserted > 0) {
99                 // Finish SQL command and add it
100                 addSql(substr($insertSQL, 0, -1));
101         } // END - if
102
103         // Something has been removed?
104         if ($removed > 0) {
105                 // Finish SQL command and add it
106                 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
107         } // END - if
108
109         // Shall we update usage counters (ONLY FOR DEBUGGING!)
110         if (isFilterUsageUpdateEnabled()) {
111                 // Update all counters
112                 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
113                         // Walk through all filters
114                         foreach ($filterArray as $filterFunction => $cnt) {
115                                 // Construct and add the query
116                                 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
117                                         bigintval($cnt),
118                                         $filterName,
119                                         $filterFunction
120                                 ));
121                         } // END - foreach
122                 } // END - foreach
123         } // END - if
124
125         // Run the run_sqls filter in non-dry mode
126         runFilterChain('run_sqls');
127
128         // Should we rebuild cache?
129         if (($inserted > 0) || ($removed > 0)) {
130                 // Destroy cache
131                 rebuildCache('filter', 'filter');
132         } // END - if
133 }
134
135 // Filter for calling the handler for login failures
136 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
137         // Init content
138         $content = $data;
139
140         // Handle failed logins here if not in guest
141         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "type=".$data['type'].",action=".getAction().",what=".getWhat().",level=".$data['access_level']."<br />");
142         if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getIndexHome()))) && ($data['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.0')))) {
143                 // Handle failure
144                 $content['content'] .= handleLoginFailures($data['access_level']);
145         } // END - if
146
147         // Return the content
148         return $content;
149 }
150
151 // Filter for redirecting to logout if sql_patches has been installed
152 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
153         // Remove this filter
154         unregisterFilter(__FUNCTION__, __LINE__, 'shutdown', __FUNCTION__);
155
156         // Is the element set?
157         if (isset($GLOBALS['ext_load_mode'])) {
158                 // Redirect here
159                 redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . $GLOBALS['ext_load_mode'] . '=sql_patches');
160         } // END - if
161
162         // This should not happen!
163         logDebugMessage(__FUNCTION__, __LINE__, 'Cannot auto-logout because no extension load-mode has been set.');
164 }
165
166 // Filter for auto-activation of a extension
167 function FILTER_AUTO_ACTIVATE_EXTENSION ($data) {
168         // Is this extension always activated?
169         if (isExtensionAlwaysActive()) {
170                 // Then activate the extension
171                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name={$data['ext_name']}<br />");
172                 doActivateExtension($data['ext_name']);
173         } // END - if
174
175         // Return the data
176         return $data;
177 }
178
179 // Filter for solving task given task
180 function FILTER_SOLVE_TASK ($data) {
181         // Don't solve anything if no admin!
182         if (!isAdmin()) return $data;
183
184         // Is this a direct task id or array element task_id is found?
185         if (is_int($data)) {
186                 // Then solve it...
187                 adminSolveTask($data);
188         } elseif ((is_array($data)) && (isset($data['task_id']))) {
189                 // Solve it...
190                 adminSolveTask($data['task_id']);
191         } else {
192                 // Not detectable!
193                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
194         }
195
196         // Return the data
197         return $data;
198 }
199
200 // Filter to load include files
201 function FILTER_LOAD_INCLUDES ($pool) {
202         // Is it null?
203         if (is_null($pool)) {
204                 // This should not happen!
205                 debug_report_bug(__FUNCTION__, __LINE__, 'pool is null.');
206         } // END - if
207
208         // Is the pool an array and 'pool' set?
209         if ((is_array($pool)) && (isset($pool['pool']))) {
210                 // Then use it as pool
211                 $realPool = $pool['pool'];
212         } else {
213                 // Default is $data as inclusion list
214                 $realPool = $pool;
215         }
216
217         // Get inc pool
218         $data = getIncludePool($realPool);
219
220         // Is it an array?
221         if ((!isset($data)) || (!is_array($data))) {
222                 // Then abort here
223                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("INC_POOL is no array! Type: %s", gettype($data)));
224         } elseif (isset($data['inc_pool'])) {
225                 // Use this as new inclusion pool!
226                 setIncludePool($realPool, $data['inc_pool']);
227         }
228
229         // Check for added include files
230         if (countIncludePool($realPool) > 0) {
231                 // Loads every include file
232                 loadIncludePool($realPool);
233
234                 // Reset array
235                 initIncludePool($realPool);
236         } // END - if
237
238         // Continue with processing
239         return $pool;
240 }
241
242 // Filter for running SQL commands
243 function FILTER_RUN_SQLS ($data) {
244         // Debug message
245         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Entered!");
246
247         // Is the array there?
248         if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
249                 // Run SQL commands
250                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Found ".countSqls()." queries to run.");
251                 foreach (getSqls() as $sqls) {
252                         // New cache format...
253                         foreach ($sqls as $sql) {
254                                 // Trim spaces away
255                                 $sql = trim($sql);
256
257                                 // Is 'enable_codes' not set? Then set it to true
258                                 if (!isset($data['enable_codes'])) $data['enable_codes'] = true;
259
260                                 // Is there still a query left?
261                                 if (!empty($sql)) {
262                                         // Do we have an "ALTER TABLE" command?
263                                         if (substr(strtolower($sql), 0, 11) == 'alter table') {
264                                                 // Analyse the alteration command
265                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
266                                                 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
267                                         } else {
268                                                 // Run regular SQL command
269                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($data['enable_codes']);
270                                                 SQL_QUERY($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
271                                         }
272                                 } // END - if
273                         } // END - foreach
274                 } // END - foreach
275         } // END - if
276
277         // Debug message
278         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Left!");
279 }
280
281 // Filter for updating/validating login data
282 function FILTER_UPDATE_LOGIN_DATA () {
283         // Add missing array
284         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
285
286         // Recheck if logged in
287         if (!isMember()) return false;
288
289         // Secure user id
290         setMemberId(getSession('userid'));
291
292         // Found a userid?
293         if (fetchUserData(getMemberId())) {
294                 // Load last module and online time
295                 $content = getUserDataArray();
296
297                 // Maybe first login time?
298                 if (empty($content['last_module'])) $content['last_module'] = 'login';
299
300                 // This will be displayed on welcome page! :-)
301                 if (empty($GLOBALS['last_online']['module'])) {
302                         $GLOBALS['last_online']['module'] = $content['last_module'];
303                         $GLOBALS['last_online']['online'] = $content['last_online'];
304                 } // END - if
305
306                 // 'what' not set?
307                 if (!isWhatSet()) {
308                         // Fix it to default
309                         setWhat('welcome');
310                         if (getIndexHome() != '') setWhatFromConfig('index_home');
311                 } // END - if
312
313                 // Update last module / online time
314                 updateLastActivity(getMemberId());
315         }  else {
316                 // Destroy session, we cannot update!
317                 destroyMemberSession();
318         }
319 }
320
321 // Filter for initializing randomizer
322 function FILTER_INIT_RANDOMIZER () {
323         // Only execute this filter if installed
324         if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) return;
325
326         // Take a prime number which is long (if you know a longer one please try it out!)
327         setConfigEntry('_PRIME', 591623);
328
329         // Calculate "entropy" with the prime number (for code generation)
330         setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getConfig('code_length') + 1)));
331
332         // Simply init the randomizer with seed and _ADD value
333         mt_srand(generateSeed() + getConfig('_ADD'));
334 }
335
336 // Filter for removing updates
337 function FILTER_REMOVE_UPDATES ($data) {
338         // Init removal list
339         initExtensionRemovalList();
340
341         // Add the current extension to it
342         addCurrentExtensionToRemovalList();
343
344         // Simply remove it
345         unsetExtensionSqls();
346
347         // Do we need to remove update depency?
348         if (countExtensionUpdateDependencies() > 0) {
349                 // Then find all updates we shall no longer execute
350                 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
351                         // Shall we remove this update?
352                         if (in_array($ext_name, getExtensionRemovalList())) {
353                                 // Then remove this extension!
354                                 removeExtensionUpdateDependency($ext_name);
355                         } // END - if
356                 } // END - foreach
357         } // END - if
358
359         // Return data
360         return $data;
361 }
362
363 // Determines username for current user state
364 function FILTER_DETERMINE_USERNAME () {
365         // Check if logged in
366         if (isMember()) {
367                 // Is still logged in so we welcome him with his name
368                 if (fetchUserData(getMemberId())) {
369                         // Load surname and family's name and build the username
370                         $content = getUserDataArray();
371
372                         // Prepare username
373                         setUsername($content['surname'] . ' ' . $content['family']);
374
375                         // Additionally admin?
376                         if (isAdmin()) {
377                                 // Add it
378                                 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
379                         } // END - if
380                 } else {
381                         // Hmmm, logged in and no valid userid?
382                         setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
383
384                         // Destroy session
385                         destroyMemberSession();
386                 }
387         } elseif (isAdmin()) {
388                 // Admin is there
389                 setUsername('{--USERNAME_ADMIN--}');
390         } else {
391                 // He's a guest, hello there... ;-)
392                 setUsername('{--USERNAME_GUEST--}');
393         }
394 }
395
396 // Filter for compiling config entries
397 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
398         // Save the uncompiled code
399         $uncompiled = $code;
400
401         // Do we have cache?
402         if (!isset($GLOBALS['compiled_config'][$code])) {
403                 // Compile {?some_var?} to getConfig('some_var')
404                 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
405
406                 // Some entries found?
407                 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
408                         // Replace all matches
409                         foreach ($matches[0] as $key => $match) {
410                                 // Do we have cache?
411                                 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
412                                         // Is the config valid?
413                                         if (isConfigEntrySet($matches[1][$key])) {
414                                                 // Set it for caching
415                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
416                                         } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
417                                                 // Use default value
418                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
419                                         } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
420                                                 // No config, try the language system
421                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
422                                         } else {
423                                                 // Unhandled!
424                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
425                                         }
426                                 } // END - if
427
428                                 // Use this for replacing
429                                 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
430                                 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
431                         } // END - foreach
432                 } // END - if
433
434                 // Add it to cache
435                 $GLOBALS['compiled_config'][$uncompiled] = $code;
436         } // END - if
437
438         // Should we compile it?
439         if ($compiled === true) {
440                 // Run the code
441                 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
442                 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
443                 eval($eval);
444         } // END - if
445
446         // Return compiled code
447         return $GLOBALS['compiled_config'][$uncompiled];
448 }
449
450 // Filter for compiling expression code
451 function FILTER_COMPILE_EXPRESSION_CODE ($code) {
452         // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
453         // See switch() command below for supported commands
454         preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
455         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
456
457         // Default is from outputHtml()
458         $outputMode = getScriptOutputMode();
459
460         // Some entries found?
461         if ((count($matches) > 0) && (count($matches[3]) > 0)) {
462                 // Replace all matches
463                 foreach ($matches[2] as $key => $cmd) {
464                         // Init replacer/call-back variable
465                         $replacer       = '';
466                         $callback       = '';
467                         $extraFunction  = '';
468                         $extraFunction2 = '';
469                         $value          = '';
470
471                         // Extract command and call-back
472                         $cmdArray = explode(',', $cmd);
473                         $cmd = $cmdArray[0];
474
475                         // Detect call-back function
476                         if (isset($cmdArray[1])) {
477                                 // Call-back function detected
478                                 $callback = $cmdArray[1];
479                         } // END - if
480
481                         // Detect extra function
482                         if (isset($cmdArray[2])) {
483                                 // Also detected
484                                 $extraFunction = $cmdArray[2];
485                         } // END - if
486
487                         // Detect extra function 2
488                         if (isset($cmdArray[3])) {
489                                 // Also detected
490                                 $extraFunction2 = $cmdArray[3];
491                         } // END - if
492
493                         // And value
494                         if (isset($matches[4][$key])) {
495                                 // Use this as value
496                                 $value = $matches[4][$key];
497                         } // END - if
498
499                         // Construct call-back function name for the command
500                         $commandFunction = 'doExpression' . ucfirst(strtolower($cmd));
501
502                         // Is this function there?
503                         if (function_exists($commandFunction)) {
504                                 // Prepare $matches, $key, $outputMode, etc.
505                                 $data = array(
506                                         'matches'     => $matches,
507                                         'key'         => $key,
508                                         'mode'        => $outputMode,
509                                         'code'        => $code,
510                                         'callback'    => $callback,
511                                         'extra_func'  => $extraFunction,
512                                         'extra_func2' => $extraFunction2,
513                                         'value'       => $value
514                                 );
515
516                                 // Call it
517                                 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
518                                 $code = call_user_func($commandFunction, $data);
519                         } else {
520                                 // Unsupported command detected
521                                 debug_report_bug(__FUNCTION__, __LINE__, 'Command=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
522                         }
523                 } // END - foreach
524         } // END - if
525
526         // Do we have non-HTML mode?
527         if ((getScriptOutputMode() != '0') || ($outputMode != '0')) $code = decodeEntities($code);
528
529         // Return compiled code
530         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($code).'</pre>');
531         return $code;
532 }
533
534 // Runs some generic filter update steps
535 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
536         // Create task (we ignore the task id here)
537         createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
538
539         // Update extension's version
540         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
541                 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
542
543         // Remove arrays
544         unsetSqls();
545         unset($GLOBALS['update_ver'][$ext_name]);
546 }
547
548 // Load more reset scripts
549 function FILTER_RUN_RESET_INCLUDES () {
550         // Is the reset set or old sql_patches?
551         if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (getScriptOutputMode() == '0')) {
552                 // Then abort here
553                 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
554         } // END - if
555
556         // Get more daily reset scripts
557         setIncludePool('reset', getArrayFromDirectory('inc/reset/', 'reset_'));
558
559         // Update database
560         if ((!isConfigEntrySet('DEBUG_RESET')) || (getConfig('DEBUG_RESET') != 'Y')) updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
561
562         // Is the config entry set?
563         if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
564                 // Create current week mark
565                 $currWeek = getWeek();
566
567                 // Has it changed?
568                 if ((getConfig('last_week') != $currWeek) || (isWeeklyResetDebugEnabled())) {
569                         // Include weekly reset scripts
570                         mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
571
572                         // Update config if not in debug mode
573                         if (!isWeeklyResetDebugEnabled()) updateConfiguration('last_week', $currWeek);
574                 } // END - if
575
576                 // Create current month mark
577                 $currMonth = getMonth();
578
579                 // Has it changed?
580                 if ((getConfig('last_month') != $currMonth) || (isMonthlyResetDebugEnabled())) {
581                         // Include monthly reset scripts
582                         mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
583
584                         // Update config
585                         if (!isMonthlyResetDebugEnabled()) updateConfiguration('last_month', $currMonth);
586                 } // END - if
587         } // END - if
588
589         // Run the filter
590         runFilterChain('load_includes', 'reset');
591 }
592
593 // Filter for removing the given extension
594 function FILTER_REMOVE_EXTENSION () {
595         // Delete this extension (remember to remove it from your server *before* you click on welcome!
596         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
597                 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
598
599         // Remove the extension from cache array as well
600         removeExtensionFromArray();
601
602         // Remove the cache
603         rebuildCache('extension', 'extension');
604 }
605
606 // Filter for flushing the output
607 function FILTER_FLUSH_OUTPUT () {
608         // Simple, he?
609         outputHtml('');
610 }
611
612 // Prepares an SQL statement part for HTML mail and/or holiday depency
613 function FILTER_HTML_INCLUDE_USERS ($mode) {
614         // Exclude no users by default
615         $MORE = '';
616
617         // HTML mail?
618         if ($mode == 'html') $MORE = " AND `html`='Y'";
619         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
620                 // Add something for the holiday extension
621                 $MORE .= " AND `holiday_active`='N'";
622         } // END - if
623
624         // Return result
625         return $MORE;
626 }
627
628 // Filter for determining what/action/module
629 function FILTER_DETERMINE_WHAT_ACTION () {
630         // In installation phase we don't have what/action
631         if (isInstallationPhase()) {
632                 // Set both to empty
633                 setAction('');
634                 setWhat('');
635
636                 // Abort here
637                 return;
638         } // END - if
639
640         // Get all values
641         if ((getScriptOutputMode() != 1) && (getScriptOutputMode() != -1)) {
642                 // Fix module
643                 if (!isModuleSet()) {
644                         // Is the request element set?
645                         if (isGetRequestParameterSet('module')) {
646                                 // Set module from request
647                                 setModule(getRequestParameter('module'));
648                         } elseif (getScriptOutputMode() == '0') {
649                                 // Set default module 'index'
650                                 setModule('index');
651                         } else {
652                                 // Unknown module
653                                 setModule('unknown');
654                         }
655                 } // END - if
656
657                 // Fix 'what' if not yet set
658                 if (!isWhatSet())   setWhat(getWhatFromModule(getModule()));
659
660                 // Fix 'action' if not yet set
661                 if (!isActionSet()) setAction(getActionFromModuleWhat(getModule(), getWhat()));
662         } else {
663                 // Set action/what to empty
664                 setAction('');
665                 setWhat('');
666         }
667
668         // Set default 'what' value
669         //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
670         if ((!isWhatSet()) && (!isActionSet()) && (getScriptOutputMode() != 1) && (getScriptOutputMode() != -1)) {
671                 if (getModule() == 'admin') {
672                         // Set 'action' value to 'login' in admin menu
673                         setAction(getActionFromModuleWhat(getModule(), getWhat()));
674                 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
675                         // Set 'what' value to 'welcome' in guest and member menu
676                         setWhatFromConfig('index_home');
677                 } else {
678                         // Anything else like begging link
679                         setWhat('');
680                 }
681         } // END - if
682 }
683
684 // Sends out pooled mails
685 function FILTER_TRIGGER_SENDING_POOL () {
686         // Are we in normal output mode?
687         if (getScriptOutputMode() != 0) {
688                 // Only in normal output mode to prevent race-conditons!
689         } // END - if
690
691         // Init counter
692         $GLOBALS['pool_cnt'] = '0';
693
694         // Init & set the include pool
695         initIncludePool('pool');
696         setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
697
698         // Run the filter
699         runFilterChain('load_includes', 'pool');
700
701         // Remove the counter
702         unset($GLOBALS['pool_cnt']);
703 }
704
705 // Filter for checking and updating SVN revision
706 function FILTER_CHECK_SVN_REVISION () {
707         // Only execute this filter if installed and all config entries are there
708         if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
709
710         // Check for patch level differences between databases and current hard-coded
711         if ((getCurrSvnRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURR_SVN_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
712                 // Update database and CONFIG array
713                 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrSvnRevision(), 'UNIX_TIMESTAMP()'));
714                 setConfigEntry('patch_level', getCurrSvnRevision());
715                 setConfigEntry('patch_ctime', time());
716         } // END - if
717 }
718
719 // Filter for running daily reset
720 function FILTER_RUN_DAILY_RESET () {
721         // Only execute this filter if installed
722         if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) return;
723
724         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
725         if (((getDay(getConfig('last_update')) != getDay()) || ((isConfigEntrySet('DEBUG_RESET')) && (getConfig('DEBUG_RESET') == 'Y'))) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (getScriptOutputMode() != 1)) {
726                 // Tell every module we are in reset-mode!
727                 doReset();
728         } // END - if
729 }
730
731 // Filter for loading more runtime includes (not for installation)
732 function FILTER_LOAD_RUNTIME_INCLUDES () {
733         // Load more includes
734         foreach (array('inc/databases.php','inc/session.php','inc/versions.php') as $inc) {
735                 // Load the include
736                 loadIncludeOnce($inc);
737         } // END - foreach
738 }
739
740 // Filter for checking admin ACL
741 function FILTER_CHECK_ADMIN_ACL () {
742         // Extension not installed so it's always allowed to access everywhere!
743         $ret = true;
744
745         // Ok, Cookie-Update done
746         if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
747                 // Check if action GET variable was set
748                 $action = getAction();
749                 if (isWhatSet()) {
750                         // Get action value by what-value
751                         $action = getActionFromModuleWhat('admin', getWhat());
752                 } // END - if
753
754                 // Check for access control line of current menu entry
755                 $ret = adminsCheckAdminAcl($action, getWhat());
756         } // END - if
757
758         // Set it here
759         $GLOBALS['acl_allow'] = $ret;
760 }
761
762 // Init random number/cache buster
763 function FILTER_INIT_RANDOM_NUMBER () {
764         // Is the extension sql_patches installed and at least 0.3.6?
765         if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
766                 // Generate random number
767                 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
768         } else {
769                 // Generate weak (!!!) code
770                 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
771         }
772
773         // Copy it to CACHE_BUSTER
774         setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
775 }
776
777 // Update module counter
778 function FILTER_COUNT_MODULE () {
779         // Do count all other modules but not accesses on CSS file css.php!
780         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
781                 array(getModule()), __FUNCTION__, __LINE__);
782 }
783
784 // Handles fatal errors
785 function FILTER_HANDLE_FATAL_ERRORS () {
786         // Do we have errors to handle and right output mode?
787         if ((!ifFatalErrorsDetected()) || (getScriptOutputMode() != '0')) {
788                 // Abort executing here
789                 return false;
790         } // END - if
791
792         // Set content type
793         setContentType('text/html');
794
795         // Load config here
796         loadIncludeOnce('inc/load_config.php');
797
798         // Set unset variable
799         if (empty($check)) $check = '';
800
801         // Default is none
802         $content = '';
803
804         // Installation phase or regular mode?
805         if ((isInstallationPhase())) {
806                 // While we are installing ouput other header than while it is installed... :-)
807                 $OUT = '';
808                 foreach (getFatalArray() as $key => $value) {
809                         // Prepare content for the template
810                         $content = array(
811                                 'key'   => ($key + 1),
812                                 'value' => $value
813                         );
814
815                         // Load row template
816                         $OUT .= loadTemplate('install_fatal_row', true, $content);
817                 }
818
819                 // Load main template
820                 $content = loadTemplate('install_fatal_table', true, $OUT);
821         } elseif (isInstalled()) {
822                 // Display all runtime fatal errors
823                 $OUT = '';
824                 foreach (getFatalArray() as $key => $value) {
825                         // Prepare content for the template
826                         $content = array(
827                                 'key'   => ($key + 1),
828                                 'value' => $value
829                         );
830
831                         // Load row template
832                         $OUT .= loadTemplate('runtime_fatal_row', true, $content);
833                 }
834
835                 // Load main template
836                 $content = loadTemplate('runtime_fatal_table', true, $OUT);
837         }
838
839         // Message to regular users (non-admin)
840         $CORR = '{--FATAL_REPORT_ERRORS--}';
841
842         // PHP warnings fixed
843         if ($check == 'done') {
844                 if (isAdmin()) $CORR = '{--FATAL_CORRECT_ERRORS--}';
845         } // END - if
846
847         // Remember all in array
848         $content = array(
849                 'rows' => $content,
850                 'corr' => $CORR
851         );
852
853         // Load footer
854         loadIncludeOnce('inc/header.php');
855
856         // Load main template
857         loadTemplate('fatal_errors', false, $content);
858
859         // Delete all to prevent double-display
860         initFatalMessages();
861
862         // Load footer
863         loadIncludeOnce('inc/footer.php');
864
865         // Abort here
866         shutdown();
867 }
868
869 // Filter for displaying copyright line
870 function FILTER_DISPLAY_COPYRIGHT () {
871         // Shall we display the copyright notice?
872         if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
873                 // Backlink enabled?
874                 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
875                         // Copyright with backlink, thanks! :-)
876                         $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
877                 } else {
878                         // No backlink in Copyright note
879                         $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
880                 }
881         } // END - if
882 }
883
884 // Filter for displaying parsing time
885 function FILTER_DISPLAY_PARSING_TIME () {
886         // Shall we display the parsing time and number of queries?
887         // 1234                            5                      54    4         5              5       4    4                       5       543    3                   4432    2             33     2    2                              21
888         if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (getScriptOutputMode() == '0') && ($GLOBALS['header_sent'] == 2)) {
889                 // Then display it here
890                 displayParsingTime();
891         } // END - if
892 }
893
894 // Filter for flushing template cache
895 function FILTER_FLUSH_TEMPLATE_CACHE () {
896         // Do not flush when debugging the template cache
897         if (isDebuggingTemplateCache()) return;
898
899         // Do we have cached eval() data?
900         if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
901                 // Now flush all
902                 foreach ($GLOBALS['template_eval'] as $template => $eval) {
903                         // Flush the cache (if not yet found)
904                         flushTemplateCache($template, $eval);
905                 } // END - if
906         } // END - if
907 }
908
909 // Filter for loading user data
910 function FILTER_FETCH_USER_DATA ($userid = 0) {
911         // Is the userid not set? Then use member id
912         if (($userid == '0') || (is_null($userid))) $userid = getMemberId();
913
914         // Get user data
915         if (!fetchUserData($userid)) {
916                 // Userid is not valid
917                 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
918         } // END - if
919
920         // Set member id
921         setMemberId($userid);
922 }
923
924 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
925 function FILTER_RESET_USER_LOGIN_FAILURE () {
926         // Is the user data valid?
927         if (!isMember()) {
928                 // Do only run for logged in members
929                 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
930         } // END - if
931
932         // Remmeber login failures if available
933         if (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
934                 // Reset login failures
935                 SQL_QUERY_ESC("UPDATE
936         `{?_MYSQL_PREFIX?}_user_data`
937 SET
938         `login_failures`=0,
939         `last_failure`='0000-00-00 00:00:00'
940 WHERE
941         `userid`=%s
942 LIMIT 1",
943                         array(getMemberId()), __FUNCTION__, __LINE__);
944
945                 // Store it in session
946                 setSession('mailer_member_failures' , getUserData('login_failures'));
947                 setSession('mailer_member_last_failure', getUserData('last_failure'));
948         } // END - if
949 }
950
951 // Try to login the admin by setting some session/cookie variables
952 function FILTER_DO_LOGIN_ADMIN ($data) {
953         // Now set all session variables and store the result for later processing
954         $GLOBALS['admin_login_success'] = ((
955                 setSession('admin_md5', encodeHashForCookie($data['pass_hash']))
956         ) && (
957                 setSession('admin_id', $data['id'])
958         ) && (
959                 setSession('admin_last', time())
960         ));
961
962         // Return the data for further processing
963         return $data;
964 }
965
966 // Filter for loading page header, this should be ran first!
967 function FILTER_LOAD_PAGE_HEADER () {
968         // Determine the page title
969         $content['header_title'] = determinePageTitle();
970
971         // Output page header code
972         $GLOBALS['page_header'] = loadTemplate('page_header', true, $content);
973
974         // Include meta data in 'guest' module
975         if (getModule() == 'index') {
976                 // Load meta data template
977                 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
978
979                 // Add meta description to header
980                 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
981                         // Add meta description not in admin and login module and when the script is installed
982                         generateMetaDescriptionCode();
983                 } // END - if
984         } // END - if
985 }
986
987 // Filter for adding style sheet, closing page header
988 function FILTER_FINISH_PAGE_HEADER () {
989         // Include stylesheet
990         loadIncludeOnce('inc/stylesheet.php');
991
992         // Closing HEAD tag
993         $GLOBALS['page_header'] .= '</head>';
994 }
995
996 // Cleans up the DNS cache if sql_patches is at least 0.7.0
997 function FILTER_CLEANUP_DNS_CACHE () {
998         // Is the latest version installed?
999         if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1000                 // Load class file
1001                 loadIncludeOnce('inc/classes/resolver.class.php');
1002
1003                 // Instance the resolver
1004                 $resolver = new HostnameResolver();
1005
1006                 // Purge entries
1007                 $resolver->purgeEntries();
1008
1009                 // Cute, isn't it? ;-)
1010         } // END - if
1011 }
1012
1013 // [EOF]
1014 ?>