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