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