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