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