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