0.0.0 shall be our first version
[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'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
168
169         // Is this extension always activated?
170         if (isThisExtensionAlwaysActive()) {
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'])) {
262                                         $data['enable_codes'] = true;
263                                 } // END - if
264
265                                 // Is there still a query left?
266                                 if (!empty($sql)) {
267                                         // Do we have an "ALTER TABLE" command?
268                                         if (substr(strtolower($sql), 0, 11) == 'alter table') {
269                                                 // Analyse the alteration command
270                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
271                                                 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
272                                         } else {
273                                                 // Run regular SQL command
274                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($data['enable_codes']));
275                                                 SQL_QUERY($sql, __FUNCTION__, __LINE__, $data['enable_codes']);
276                                         }
277                                 } // END - if
278                         } // END - foreach
279                 } // END - foreach
280         } // END - if
281
282         // Debug message
283         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
284 }
285
286 // Filter for updating/validating login data
287 function FILTER_UPDATE_LOGIN_DATA () {
288         // Add missing array
289         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
290                 $GLOBALS['last_online'] = array();
291         } // END - if
292
293         // Recheck if logged in
294         if (!isMember()) {
295                 return false;
296         } // END - if
297
298         // Secure user id
299         setMemberId(getSession('userid'));
300
301         // Found a userid?
302         if (fetchUserData(getMemberId())) {
303                 // Load last module and online time
304                 $content = getUserDataArray();
305
306                 // Maybe first login time?
307                 if (empty($content['last_module'])) {
308                         $content['last_module'] = 'login';
309                 } // END - if
310
311                 // This will be displayed on welcome page! :-)
312                 if (empty($GLOBALS['last_online']['module'])) {
313                         $GLOBALS['last_online']['module'] = $content['last_module'];
314                         $GLOBALS['last_online']['online'] = $content['last_online'];
315                 } // END - if
316
317                 // 'what' not set?
318                 if (!isWhatSet()) {
319                         // Fix it to default
320                         setWhat('welcome');
321                         if (getIndexHome() != '') {
322                                 setWhatFromConfig('index_home');
323                         } // END - if
324                 } // END - if
325
326                 // Update last module / online time
327                 updateLastActivity(getMemberId());
328         }  else {
329                 // Destroy session, we cannot update!
330                 destroyMemberSession();
331         }
332 }
333
334 // Filter for initializing randomizer
335 function FILTER_INIT_RANDOMIZER () {
336         // Only execute this filter if installed
337         if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
338                 return;
339         } // END - if
340
341         // Take a prime number which is long (if you know a longer one please try it out!)
342         setConfigEntry('_PRIME', 591623);
343
344         // Calculate "entropy" with the prime number (for code generation)
345         setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
346
347         // Simply init the randomizer with seed and _ADD value
348         mt_srand(generateSeed() + getConfig('_ADD'));
349 }
350
351 // Filter for removing updates
352 function FILTER_REMOVE_UPDATES ($data) {
353         // Init removal list
354         initExtensionRemovalList();
355
356         // Add the current extension to it
357         addCurrentExtensionToRemovalList();
358
359         // Simply remove it
360         unsetExtensionSqls();
361
362         // Do we need to remove update depency?
363         if (countExtensionUpdateDependencies() > 0) {
364                 // Then find all updates we shall no longer execute
365                 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
366                         // Shall we remove this update?
367                         if (in_array($ext_name, getExtensionRemovalList())) {
368                                 // Then remove this extension!
369                                 removeExtensionDependency($ext_name);
370                         } // END - if
371                 } // END - foreach
372         } // END - if
373
374         // Return data
375         return $data;
376 }
377
378 // Determines username for current user state
379 function FILTER_DETERMINE_USERNAME () {
380         // Check if logged in
381         if (isMember()) {
382                 // Is still logged in so we welcome him with his name
383                 if (fetchUserData(getMemberId())) {
384                         // Load surname and family's name and build the username
385                         $content = getUserDataArray();
386
387                         // Prepare username
388                         setUsername($content['surname'] . ' ' . $content['family']);
389
390                         // Additionally admin?
391                         if (isAdmin()) {
392                                 // Add it
393                                 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
394                         } // END - if
395                 } else {
396                         // Hmmm, logged in and no valid userid?
397                         setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
398
399                         // Destroy session
400                         destroyMemberSession();
401                 }
402         } elseif (isAdmin()) {
403                 // Admin is there
404                 setUsername('{--USERNAME_ADMIN--}');
405         } else {
406                 // He's a guest, hello there... ;-)
407                 setUsername('{--USERNAME_GUEST--}');
408         }
409 }
410
411 // Filter for compiling config entries
412 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
413         // Save the uncompiled code
414         $uncompiled = $code;
415
416         // Do we have cache?
417         if (!isset($GLOBALS['compiled_config'][$code])) {
418                 // Compile {?some_var?} to getConfig('some_var')
419                 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
420
421                 // Some entries found?
422                 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
423                         // Replace all matches
424                         foreach ($matches[0] as $key => $match) {
425                                 // Do we have cache?
426                                 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
427                                         // Is the config valid?
428                                         if (isConfigEntrySet($matches[1][$key])) {
429                                                 // Set it for caching
430                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
431                                         } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
432                                                 // Use default value
433                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
434                                         } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
435                                                 // No config, try the language system
436                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
437                                         } else {
438                                                 // Unhandled!
439                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
440                                         }
441                                 } // END - if
442
443                                 // Use this for replacing
444                                 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
445                                 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
446                         } // END - foreach
447                 } // END - if
448
449                 // Add it to cache
450                 $GLOBALS['compiled_config'][$uncompiled] = $code;
451         } // END - if
452
453         // Should we compile it?
454         if ($compiled === true) {
455                 // Run the code
456                 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
457                 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
458                 eval($eval);
459         } // END - if
460
461         // Return compiled code
462         return $GLOBALS['compiled_config'][$uncompiled];
463 }
464
465 // Filter for compiling expression code
466 function FILTER_COMPILE_EXPRESSION_CODE ($code) {
467         // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
468         // See switch() command below for supported commands
469         preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
470         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, true).'</pre>');
471
472         // Default is from outputHtml()
473         $outputMode = getScriptOutputMode();
474
475         // Some entries found?
476         if ((count($matches) > 0) && (count($matches[3]) > 0)) {
477                 // Replace all matches
478                 foreach ($matches[2] as $key => $cmd) {
479                         // Init replacer/call-back variable
480                         $replacer       = '';
481                         $callback       = '';
482                         $extraFunction  = '';
483                         $extraFunction2 = '';
484                         $value          = null;
485
486                         // Extract command and call-back
487                         $cmdArray = explode(',', $cmd);
488                         $cmd = $cmdArray[0];
489
490                         // Detect call-back function
491                         if (isset($cmdArray[1])) {
492                                 // Call-back function detected
493                                 $callback = $cmdArray[1];
494                         } // END - if
495
496                         // Detect extra function
497                         if (isset($cmdArray[2])) {
498                                 // Also detected
499                                 $extraFunction = $cmdArray[2];
500                         } // END - if
501
502                         // Detect extra function 2
503                         if (isset($cmdArray[3])) {
504                                 // Also detected
505                                 $extraFunction2 = $cmdArray[3];
506                         } // END - if
507
508                         // And value
509                         if (isset($matches[4][$key])) {
510                                 // Use this as value
511                                 $value = $matches[4][$key];
512                         } // END - if
513
514                         // Construct call-back function name for the command
515                         $commandFunction = 'doExpression' . capitalizeUnderscoreString($cmd);
516
517                         // Is this function there?
518                         if (function_exists($commandFunction)) {
519                                 // Prepare $matches, $key, $outputMode, etc.
520                                 $data = array(
521                                         'matches'     => $matches,
522                                         'key'         => $key,
523                                         'mode'        => getScriptOutputMode(),
524                                         'code'        => $code,
525                                         'callback'    => $callback,
526                                         'extra_func'  => $extraFunction,
527                                         'extra_func2' => $extraFunction2,
528                                         'value'       => $value
529                                 );
530
531                                 // Call it
532                                 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: function=' . $commandFunction);
533                                 $code = call_user_func($commandFunction, $data);
534                         } else {
535                                 // Unsupported command detected
536                                 logDebugMessage(__FUNCTION__, __LINE__, 'Command cmd=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
537                         }
538                 } // END - foreach
539         } // END - if
540
541         // Do we have non-HTML mode?
542         if (!isHtmlOutputMode()) {
543                 $code = decodeEntities($code);
544         } // END - if
545
546         // Return compiled code
547         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($code).'</pre>');
548         return $code;
549 }
550
551 // Runs some generic filter update steps
552 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
553         // Create task (we ignore the task id here)
554         createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
555
556         // Update extension's version
557         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
558                 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
559
560         // Remove arrays
561         unsetSqls();
562         unset($GLOBALS['update_ver'][$ext_name]);
563 }
564
565 // Load more hourly reset scripts
566 function FILTER_RUN_HOURLY_INCLUDES () {
567         // Is the reset set or old sql_patches?
568         if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) && (isHtmlOutputMode())) {
569                 // Then abort here
570                 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isHourlyResetEnabled()).',ext_newer[sql_patches:0.7.5]='.intval(isExtensionInstalledAndNewer('sql_patches', '0.7.5')).' Please report this bug. Thanks');
571         } // END - if
572
573         // Get more hourly reset scripts
574         setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
575
576         // Update database
577         if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
578                 updateConfiguration('last_hour', getHour());
579         } // END - if
580
581         // Run the filter
582         runFilterChain('load_includes', 'hourly');
583 }
584
585 // Load more reset scripts
586 function FILTER_RUN_RESET_INCLUDES () {
587         // Is the reset set or old sql_patches?
588         if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (isHtmlOutputMode())) {
589                 // Then abort here
590                 debug_report_bug(__FUNCTION__, __LINE__, 'Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
591         } // END - if
592
593         // Get more daily reset scripts
594         setIncludePool('reset', getArrayFromDirectory('inc/daily/', 'daily_'));
595
596         // Update database
597         if ((!isConfigEntrySet('DEBUG_RESET')) || (!isDebugResetEnabled())) {
598                 updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
599         } // END - if
600
601         // Is the config entry set?
602         if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
603                 // Create current week mark
604                 $currWeek = getWeek();
605
606                 // Has it changed?
607                 if ((getConfig('last_week') != $currWeek) || (isWeeklyResetDebugEnabled())) {
608                         // Include weekly reset scripts
609                         mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
610
611                         // Update config if not in debug mode
612                         if (!isWeeklyResetDebugEnabled()) updateConfiguration('last_week', $currWeek);
613                 } // END - if
614
615                 // Create current month mark
616                 $currMonth = getMonth();
617
618                 // Has it changed?
619                 if ((getLastMonth() != $currMonth) || (isMonthlyResetDebugEnabled())) {
620                         // Include monthly reset scripts
621                         mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
622
623                         // Update config
624                         if (!isMonthlyResetDebugEnabled()) {
625                                 updateConfiguration('last_month', $currMonth);
626                         } // END - if
627                 } // END - if
628         } // END - if
629
630         // Run the filter
631         runFilterChain('load_includes', 'reset');
632 }
633
634 // Filter for removing the given extension
635 function FILTER_REMOVE_EXTENSION () {
636         // Delete this extension (remember to remove it from your server *before* you click on welcome!
637         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
638                 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
639
640         // Remove the extension from cache array as well
641         removeExtensionFromArray();
642
643         // Remove the cache
644         rebuildCache('extension', 'extension');
645 }
646
647 // Filter for flushing the output
648 function FILTER_FLUSH_OUTPUT () {
649         // Simple, he?
650         outputHtml('');
651 }
652
653 // Prepares an SQL statement part for HTML mail and/or holiday depency
654 function FILTER_HTML_INCLUDE_USERS ($mode) {
655         // Exclude no users by default
656         $MORE = '';
657
658         // HTML mail?
659         if ($mode == 'html') $MORE = " AND `html`='Y'";
660         if (isExtensionInstalledAndNewer('holiday', '0.1.3')) {
661                 // Add something for the holiday extension
662                 $MORE .= " AND `holiday_active`='N'";
663         } // END - if
664
665         // Return result
666         return $MORE;
667 }
668
669 // Filter for determining what/action/module
670 function FILTER_DETERMINE_WHAT_ACTION () {
671         // In installation phase we don't have what/action
672         if (isInstallationPhase()) {
673                 // Set both to empty
674                 setAction('');
675                 setWhat('');
676
677                 // Abort here
678                 return;
679         } // END - if
680
681         // Get all values
682         if ((!isCssOutputMode()) && (!isRawOutputMode())) {
683                 // Fix module
684                 if (!isModuleSet()) {
685                         // Is the request element set?
686                         if (isGetRequestParameterSet('module')) {
687                                 // Set module from request
688                                 setModule(getRequestParameter('module'));
689                         } elseif (isHtmlOutputMode()) {
690                                 // Set default module 'index'
691                                 setModule('index');
692                         } else {
693                                 // Unknown module
694                                 setModule('unknown');
695                         }
696                 } // END - if
697
698                 // Fix 'what' if not yet set
699                 if (!isWhatSet()) {
700                         setWhat(getWhatFromModule(getModule()));
701                 } // END - if
702
703                 // Fix 'action' if not yet set
704                 if (!isActionSet()) {
705                         setAction(getActionFromModuleWhat(getModule(), getWhat()));
706                 } // END - if
707         } else {
708                 // Set action/what to empty
709                 setAction('');
710                 setWhat('');
711         }
712
713         // Set default 'what' value
714         //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
715         if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
716                 if (getModule() == 'admin') {
717                         // Set 'action' value to 'login' in admin menu
718                         setAction(getActionFromModuleWhat(getModule(), getWhat()));
719                 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
720                         // Set 'what' value to 'welcome' in guest and member menu
721                         setWhatFromConfig('index_home');
722                 } else {
723                         // Anything else like begging link
724                         setWhat('');
725                 }
726         } // END - if
727 }
728
729 // Sends out pooled mails
730 function FILTER_TRIGGER_SENDING_POOL () {
731         // Are we in normal output mode?
732         if (!isHtmlOutputMode()) {
733                 // Only in normal output mode to prevent race-conditons!
734         } // END - if
735
736         // Init counter
737         $GLOBALS['pool_cnt'] = '0';
738
739         // Init & set the include pool
740         initIncludePool('pool');
741         setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
742
743         // Run the filter
744         runFilterChain('load_includes', 'pool');
745
746         // Remove the counter
747         unset($GLOBALS['pool_cnt']);
748 }
749
750 // Filter for checking and updating SVN revision
751 function FILTER_CHECK_REPOSITORY_REVISION () {
752         // Only execute this filter if installed and all config entries are there
753         if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
754
755         // Check for patch level differences between database and current hard-coded
756         if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
757                 // Update database and CONFIG array
758                 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
759                 setConfigEntry('patch_level', getCurrentRepositoryRevision());
760                 setConfigEntry('patch_ctime', time());
761         } // END - if
762 }
763
764 // Filter for running daily reset
765 function FILTER_RUN_DAILY_RESET () {
766         // Only execute this filter if installed
767         if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) {
768                 return;
769         } // END - if
770
771         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
772         if (((getDay(getConfig('last_update')) != getDay()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
773                 // Tell every module we are in reset-mode!
774                 doReset();
775         } // END - if
776 }
777
778 // Filter for running hourly reset
779 function FILTER_RUN_HOURLY_RESET () {
780         // Only execute this filter if installed
781         if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.7.5'))) {
782                 return;
783         } // END - if
784
785         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
786         if (((getConfig('last_hour') != getHour()) || (isDebugResetEnabled())) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestParameterSet('register')) && (!isCssOutputMode())) {
787                 // Tell every module we are in reset-mode!
788                 doHourly();
789         } // END - if
790 }
791
792 // Filter for loading more runtime includes (not for installation)
793 function FILTER_LOAD_RUNTIME_INCLUDES () {
794         // Load more includes
795         foreach (array('databases', 'session', 'versions') as $inc) {
796                 // Load the include
797                 loadIncludeOnce('inc/' . $inc . '.php');
798         } // END - foreach
799 }
800
801 // Filter for checking admin ACL
802 function FILTER_CHECK_ADMIN_ACL () {
803         // Extension not installed so it's always allowed to access everywhere!
804         $ret = true;
805
806         // Ok, Cookie-Update done
807         if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
808                 // Check if action GET variable was set
809                 $action = getAction();
810                 if (isWhatSet()) {
811                         // Get action value by what-value
812                         $action = getActionFromModuleWhat('admin', getWhat());
813                 } // END - if
814
815                 // Check for access control line of current menu entry
816                 $ret = isAdminsAllowedByAcl($action, getWhat());
817         } // END - if
818
819         // Set it here
820         $GLOBALS['acl_allow'] = $ret;
821 }
822
823 // Init random number/cache buster
824 function FILTER_INIT_RANDOM_NUMBER () {
825         // Is the extension sql_patches installed and at least 0.3.6?
826         if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
827                 // Generate random number
828                 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
829         } else {
830                 // Generate *WEAK* code
831                 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
832         }
833
834         // Copy it to CACHE_BUSTER
835         setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
836 }
837
838 // Update module counter
839 function FILTER_COUNT_MODULE () {
840         // Do count all other modules but not accesses on CSS file css.php!
841         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
842                 array(getModule()), __FUNCTION__, __LINE__);
843 }
844
845 // Handles fatal errors
846 function FILTER_HANDLE_FATAL_ERRORS () {
847         // Do we have errors to handle and right output mode?
848         if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
849                 // Abort executing here
850                 return false;
851         } // END - if
852
853         // Set content type
854         setContentType('text/html');
855
856         // Load config here
857         loadIncludeOnce('inc/load_config.php');
858
859         // Set unset variable
860         if (empty($check)) $check = '';
861
862         // Default is none
863         $content = '';
864
865         // Installation phase or regular mode?
866         if ((isInstallationPhase())) {
867                 // While we are installing ouput other header than while it is installed... :-)
868                 $OUT = '';
869                 foreach (getFatalArray() as $key => $value) {
870                         // Prepare content for the template
871                         $content = array(
872                                 'key'   => ($key + 1),
873                                 'value' => $value
874                         );
875
876                         // Load row template
877                         $OUT .= loadTemplate('install_fatal_row', true, $content);
878                 }
879
880                 // Load main template
881                 $content = loadTemplate('install_fatal_table', true, $OUT);
882         } elseif (isInstalled()) {
883                 // Display all runtime fatal errors
884                 $OUT = '';
885                 foreach (getFatalArray() as $key => $value) {
886                         // Prepare content for the template
887                         $content = array(
888                                 'key'   => ($key + 1),
889                                 'value' => $value
890                         );
891
892                         // Load row template
893                         $OUT .= loadTemplate('runtime_fatal_row', true, $content);
894                 }
895
896                 // Load main template
897                 $content = loadTemplate('runtime_fatal_table', true, $OUT);
898         }
899
900         // Message to regular users (non-admin)
901         $CORR = '{--FATAL_REPORT_ERRORS--}';
902
903         // PHP warnings fixed
904         if ($check == 'done') {
905                 if (isAdmin()) $CORR = '{--FATAL_CORRECT_ERRORS--}';
906         } // END - if
907
908         // Remember all in array
909         $content = array(
910                 'rows' => $content,
911                 'corr' => $CORR
912         );
913
914         // Load footer
915         loadIncludeOnce('inc/header.php');
916
917         // Load main template
918         loadTemplate('fatal_errors', false, $content);
919
920         // Delete all to prevent double-display
921         initFatalMessages();
922
923         // Load footer
924         loadIncludeOnce('inc/footer.php');
925
926         // Abort here
927         shutdown();
928 }
929
930 // Filter for displaying copyright line
931 function FILTER_DISPLAY_COPYRIGHT () {
932         // Shall we display the copyright notice?
933         if ((!isGetRequestParameterSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
934                 // Backlink enabled?
935                 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
936                         // Copyright with backlink, thanks! :-)
937                         $GLOBALS['page_footer'] .= loadTemplate('copyright_backlink', true);
938                 } else {
939                         // No backlink in Copyright note
940                         $GLOBALS['page_footer'] .= loadTemplate('copyright', true);
941                 }
942         } // END - if
943 }
944
945 // Filter for displaying parsing time
946 function FILTER_DISPLAY_PARSING_TIME () {
947         // Shall we display the parsing time and number of queries?
948         // 1234                            5                      54    4         5              5       4    4                       5       543    3                   4432    2             33     2    2                              21
949         if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestParameterSet('frame'))) || (isInstallationPhase())) && (isHtmlOutputMode()) && ($GLOBALS['header_sent'] == 2)) {
950                 // Then display it here
951                 displayParsingTime();
952         } // END - if
953 }
954
955 // Filter for flushing template cache
956 function FILTER_FLUSH_TEMPLATE_CACHE () {
957         // Do not flush when debugging the template cache
958         if (isDebuggingTemplateCache()) return;
959
960         // Do we have cached eval() data?
961         if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
962                 // Now flush all
963                 foreach ($GLOBALS['template_eval'] as $template => $eval) {
964                         // Flush the cache (if not yet found)
965                         flushTemplateCache($template, $eval);
966                 } // END - if
967         } // END - if
968 }
969
970 // Filter for loading user data
971 function FILTER_FETCH_USER_DATA ($userid = 0) {
972         // Is the userid not set? Then use member id
973         if (($userid == '0') || (is_null($userid))) $userid = getMemberId();
974
975         // Get user data
976         if (!fetchUserData($userid)) {
977                 // Userid is not valid
978                 debug_report_bug(__FUNCTION__, __LINE__, 'User id '.$userid . ' is invalid.');
979         } // END - if
980
981         // Set member id
982         setMemberId($userid);
983 }
984
985 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
986 function FILTER_RESET_USER_LOGIN_FAILURE () {
987         // Is the user data valid?
988         if (!isMember()) {
989                 // Do only run for logged in members
990                 debug_report_bug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
991         } // END - if
992
993         // Remmeber login failures if available
994         if (isExtensionInstalledAndNewer('user', '0.3.7')) {
995                 // Reset login failures
996                 SQL_QUERY_ESC("UPDATE
997         `{?_MYSQL_PREFIX?}_user_data`
998 SET
999         `login_failures`=0,
1000         `last_failure`=NULL
1001 WHERE
1002         `userid`=%s
1003 LIMIT 1",
1004                         array(getMemberId()), __FUNCTION__, __LINE__);
1005
1006                 // Store it in session
1007                 setSession('mailer_member_failures' , getUserData('login_failures'));
1008                 setSession('mailer_member_last_failure', getUserData('last_failure'));
1009         } // END - if
1010 }
1011
1012 // Try to login the admin by setting some session/cookie variables
1013 function FILTER_DO_LOGIN_ADMIN ($data) {
1014         // Now set all session variables and store the result for later processing
1015         $GLOBALS['admin_login_success'] = ((
1016                 setAdminMd5(encodeHashForCookie($data['pass_hash']))
1017         ) && (
1018                 setAdminId($data['id'])
1019         ) && (
1020                 setAdminLast(time())
1021         ));
1022
1023         // Return the data for further processing
1024         return $data;
1025 }
1026
1027 // Filter for loading page header, this should be ran first!
1028 function FILTER_LOAD_PAGE_HEADER () {
1029         // Output page header code
1030         $GLOBALS['page_header'] = loadTemplate('page_header', true);
1031
1032         // Include meta data in 'guest' module
1033         if (getModule() == 'index') {
1034                 // Load meta data template
1035                 $GLOBALS['page_header'] .= loadTemplate('metadata', true);
1036
1037                 // Add meta description to header
1038                 if ((isInstalled()) && (isAdminRegistered()) && (SQL_IS_LINK_UP())) {
1039                         // Add meta description not in admin and login module and when the script is installed
1040                         generateMetaDescriptionCode();
1041                 } // END - if
1042         } // END - if
1043 }
1044
1045 // Filter for adding style sheet, closing page header
1046 function FILTER_FINISH_PAGE_HEADER () {
1047         // Include stylesheet
1048         loadIncludeOnce('inc/stylesheet.php');
1049
1050         // Closing HEAD tag
1051         $GLOBALS['page_header'] .= '</head>';
1052 }
1053
1054 // Cleans up the DNS cache if sql_patches is at least 0.7.0
1055 function FILTER_CLEANUP_DNS_CACHE () {
1056         // Is the latest version installed?
1057         if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1058                 // Load class file
1059                 loadIncludeOnce('inc/classes/resolver.class.php');
1060
1061                 // Instance the resolver
1062                 $resolver = new HostnameResolver();
1063
1064                 // Purge entries
1065                 $resolver->purgeEntries();
1066
1067                 // Cute, isn't it? ;-)
1068         } // END - if
1069 }
1070
1071 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1072 function FILTER_SET_CURRENT_DATE () {
1073         // Set current date
1074         setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1075
1076         // Epoche time for yesterday, today ... all at 00:00 am
1077         setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1078         setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1079 }
1080
1081 // [EOF]
1082 ?>