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