Rewrote many parts:
[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 - 2013 by Mailer Developer Team                   *
20  * For more information visit: http://mxchange.org                      *
21  *                                                                      *
22  * This program is free software; you can redistribute it and/or modify *
23  * it under the terms of the GNU General Public License as published by *
24  * the Free Software Foundation; either version 2 of the License, or    *
25  * (at your option) any later version.                                  *
26  *                                                                      *
27  * This program is distributed in the hope that it will be useful,      *
28  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
29  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
30  * GNU General Public License for more details.                         *
31  *                                                                      *
32  * You should have received a copy of the GNU General Public License    *
33  * along with this program; if not, write to the Free Software          *
34  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
35  * MA  02110-1301  USA                                                  *
36  ************************************************************************/
37
38 // Some security stuff...
39 if (!defined('__SECURITY')) {
40         die();
41 } // END - if
42
43 // Filter for flushing all new filters to the database
44 function FILTER_FLUSH_FILTERS () {
45         // Clear all previous SQL queries
46         initSqls();
47
48         // Is a database link here and not in installation mode?
49         if ((!isSqlLinkUp()) && (!isInstaller())) {
50                 // Abort here
51                 reportBug(__FUNCTION__, __LINE__, 'No database link is up. Cannot flush filters.');
52         } elseif ((isInstaller()) && (!isSqlLinkUp())) {
53                 // If the link is not up in installation phase, skip flushing filters
54                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Cannot flush filters: No link is up.');
55                 return;
56         }
57
58         // Is the extension ext-sql_patches updated?
59         if (((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) && (!isInstaller())) {
60                 // Log only in debug mode
61                 if (isDebugModeEnabled()) {
62                         logDebugMessage(__FUNCTION__, __LINE__, 'Cannot flush filters, ext-sql_patches might be missing. isExtensionInstalled()=' . intval(isExtensionInstalled('sql_patches')) . ',isExtensionInstalledAndOlder()=' . intval(isExtensionInstalledAndOlder('sql_patches', '0.5.9')));
63                 } // END - if
64
65                 // Abort silently here
66                 return FALSE;
67         } // END - if
68
69         // Nothing is added/remove by default
70         $inserted = '0';
71         $removed = '0';
72
73         // Prepare SQL queries
74         $insertSQL = 'INSERT INTO `{?_MYSQL_PREFIX?}_filters` (`filter_name`, `filter_function`, `filter_active`) VALUES';
75         $removeSQL = 'DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_filters` WHERE';
76
77         // Write all filters to database
78         foreach ($GLOBALS['cache_array']['filter']['chains'] as $filterName => $filterArray) {
79                 // Walk through all filters
80                 foreach ($filterArray as $filterFunction => $active) {
81                         // Is this filter loaded?
82                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'FOUND:'.$filterName.'/'.$filterFunction.'='.$active);
83                         if (((!isset($GLOBALS['cache_array']['filter']['loaded'][$filterName][$filterFunction])) && ($active != 'R')) || ($active == 'A')) {
84                                 // Is this filter already in database?
85                                 if (countSumTotalData($filterFunction, 'filters', 'filter_name', 'filter_function', TRUE, sprintf(" AND `filter_name`='%s'", sqlEscapeString($filterName))) == 0) {
86                                         // Add this filter (all filters are active by default)
87                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ADD:'.$filterName.'/'.$filterFunction);
88                                         $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
89                                         $inserted++;
90                                 } elseif (isDebugModeEnabled()) {
91                                         // Log already registered filters
92                                         logDebugMessage(__FUNCTION__, __LINE__, 'Already registered: filterName=' . $filterName . ',filterFunction=' . $filterFunction . ',active=' . $active);
93                                 }
94                         } elseif ($active == 'R') {
95                                 // Remove this filter
96                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'REMOVE:'.$filterName.'/'.$filterFunction);
97                                 $removeSQL .= sprintf(" (`filter_name`='%s' AND `filter_function`='%s') OR", $filterName, $filterFunction);
98                                 $removed++;
99                         }
100                 } // END - foreach
101         } // END - foreach
102
103         // Debug message
104         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'inserted=' . $inserted . ',removed=' . $removed . ' - AFTER COLLECTION');
105
106         // Something has been added?
107         if ($inserted > 0) {
108                 // Finish SQL command and add it
109                 addSql(substr($insertSQL, 0, -1));
110         } // END - if
111
112         // Something has been removed?
113         if ($removed > 0) {
114                 // Finish SQL command and add it
115                 addSql(substr($removeSQL, 0, -2) . 'LIMIT ' . $removed);
116         } // END - if
117
118         // Shall we update usage counters (ONLY FOR DEBUGGING!)
119         if (isFilterUsageUpdateEnabled()) {
120                 // Update all counters
121                 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
122                         // Walk through all filters
123                         foreach ($filterArray as $filterFunction => $count) {
124                                 // Construct and add the query
125                                 addSql(sprintf("UPDATE `{?_MYSQL_PREFIX?}_filters` SET `filter_counter`=%s WHERE `filter_name`='%s' AND `filter_function`='%s' LIMIT 1",
126                                         bigintval($count),
127                                         $filterName,
128                                         $filterFunction
129                                 ));
130                         } // END - foreach
131                 } // END - foreach
132         } // END - if
133
134         // Run the run_sqls filter in non-dry mode
135         runFilterChain('run_sqls');
136
137         // Should we rebuild cache?
138         if (($inserted > 0) || ($removed > 0)) {
139                 // Destroy cache
140                 rebuildCache('filter', 'filter');
141         } // END - if
142 }
143
144 // Filter for calling the handler for login failures
145 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($filterData) {
146         // Init content
147         $content = $filterData;
148
149         // Handle failed logins here if not in guest
150         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'type=' . $filterData['type'] . ',action=' . getAction() . ',what=' . getWhat() . ',level=' . $filterData['access_level']);
151         if ((($filterData['type'] == 'what') || ($filterData['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'welcome') || (getWhat() == getIndexHome()))) && ($filterData['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.6')))) {
152                 // Handle failure
153                 $content['content'] .= handleLoginFailures($filterData['access_level']);
154         } // END - if
155
156         // Return the content
157         return $content;
158 }
159
160 // Filter for auto-activation of a extension
161 function FILTER_AUTO_ACTIVATE_EXTENSION ($filterData) {
162         // Debug message
163         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $filterData['ext_name'] . ',isThisExtensionAlwaysActive()=' . intval(isThisExtensionAlwaysActive()));
164
165         // Is this extension always activated?
166         if (isThisExtensionAlwaysActive()) {
167                 // Then activate the extension
168                 doActivateExtension($filterData['ext_name']);
169         } // END - if
170
171         // Return the data
172         return $filterData;
173 }
174
175 // Filter for solving task given task
176 function FILTER_SOLVE_TASK ($filterData) {
177         // Don't solve anything if no admin!
178         if (!isAdmin()) {
179                 return $filterData;
180         } // END - if
181
182         // Is this a direct task id or array element task_id is found?
183         if (is_int($filterData)) {
184                 // Then solve it...
185                 adminSolveTask($filterData);
186         } elseif ((is_array($filterData)) && (isset($filterData['task_id']))) {
187                 // Solve it...
188                 adminSolveTask($filterData['task_id']);
189         } else {
190                 // Not detectable!
191                 reportBug(__FUNCTION__, __LINE__, sprintf('Cannot resolve task. data[%s]=<pre>%s</pre>', gettype($filterData), print_r($filterData, TRUE)));
192         }
193
194         // Return the data
195         return $filterData;
196 }
197
198 // Filter to load include files
199 function FILTER_LOAD_INCLUDES ($filterData) {
200         // Is it null?
201         if (is_null($filterData)) {
202                 // This should not happen!
203                 reportBug(__FUNCTION__, __LINE__, 'pool is null.');
204         } // END - if
205
206         // Is the pool an array and 'pool' set?
207         if ((is_array($filterData)) && (isset($filterData['pool']))) {
208                 // Then use it as pool
209                 $realPool = $filterData['pool'];
210         } else {
211                 // Default is $data as inclusion list
212                 $realPool = $filterData;
213         }
214
215         // Get inc pool
216         $data = getIncludePool($realPool);
217
218         // Is it an array?
219         if ((!isset($data)) || (!is_array($data))) {
220                 // Then abort here
221                 reportBug(__FUNCTION__, __LINE__, sprintf('INC_POOL is no array! Type: %s', gettype($data)));
222         } elseif (isset($data['inc_pool'])) {
223                 // Use this as new inclusion pool!
224                 setIncludePool($realPool, $data['inc_pool']);
225         }
226
227         // Check for added include files
228         if (countIncludePool($realPool) > 0) {
229                 // Loads every include file
230                 loadIncludePool($realPool);
231
232                 // Reset array
233                 initIncludePool($realPool);
234         } // END - if
235
236         // Continue with processing
237         return $filterData;
238 }
239
240 // Filter for running SQL commands
241 function FILTER_RUN_SQLS ($filterData) {
242         // Init counter
243         $count = 0;
244
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 ((ifSqlsRegistered()) && ((!isset($filterData['dry_run'])) || ($filterData['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($filterData['enable_codes'])) {
264                                         $filterData['enable_codes'] = TRUE;
265                                 } // END - if
266
267                                 // Is there still a query left?
268                                 if (!empty($sql)) {
269                                         // Is there an "ALTER TABLE" command? Exclude installation phase here as it would cause this query to fail
270                                         if ((substr(strtolower($sql), 0, 11) == 'alter table') && (!isset($filterData['ext_installing']))) {
271                                                 // Analyse the alteration command
272                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Alterting table: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
273                                                 sqlQueryAlterTable($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
274                                         } else {
275                                                 // Run regular SQL command
276                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Running regular query: ' . $sql . ',enable_codes=' . intval($filterData['enable_codes']));
277                                                 sqlQuery($sql, __FUNCTION__, __LINE__, $filterData['enable_codes']);
278                                         }
279
280                                         // Has a line changed?
281                                         if (!ifSqlHasZeroAffectedRows()) {
282                                                 // Add it to total account
283                                                 $count += sqlAffectedRows();
284                                         } // END - if
285                                 } // END - if
286                         } // END - foreach
287                 } // END - foreach
288         } // END - if
289
290         // Debug message
291         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, '- Left!');
292
293         // Return counter
294         return $count;
295 }
296
297 // Filter for updating/validating login data
298 function FILTER_UPDATE_LOGIN_DATA () {
299         // Add missing array
300         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) {
301                 $GLOBALS['last_online'] = array();
302         } // END - if
303
304         // Recheck if logged in
305         if ((!isMember()) || ((isAdmin()) && (!isDebugModeEnabled()))) {
306                 return FALSE;
307         } // END - if
308
309         // Secure user id
310         setMemberId(getSession('userid'));
311
312         // Found a userid?
313         if (fetchUserData(getMemberId())) {
314                 // Load last module and online time
315                 $content = getUserDataArray();
316
317                 // Maybe first login time?
318                 if (empty($content[getUserLastWhatName()])) {
319                         $content[getUserLastWhatName()] = 'login';
320                 } // END - if
321
322                 // This will be displayed on welcome page! :-)
323                 if (empty($GLOBALS['last_online']['module'])) {
324                         $GLOBALS['last_online']['module'] = $content[getUserLastWhatName()];
325                         $GLOBALS['last_online']['online'] = $content['last_online'];
326                 } // END - if
327
328                 // 'what' not set?
329                 if (!isWhatSet()) {
330                         // Fix it to default
331                         setWhat('welcome');
332                         if (getIndexHome() != '') {
333                                 setWhatFromConfig('index_home');
334                         } // END - if
335                 } // END - if
336
337                 // Update last module / online time
338                 updateLastActivity(getMemberId());
339         }  else {
340                 // Destroy session, we cannot update!
341                 destroyMemberSession();
342         }
343 }
344
345 // Filter for initializing randomizer
346 function FILTER_INIT_RANDOMIZER () {
347         // Take a prime number which is long (if you know a longer one please try it out!)
348         setConfigEntry('_PRIME', 591623);
349
350         // Initialize array with all allowed chars
351         $GLOBALS['_abc'] = explode(',', 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,6,7,8,9,-,+,_,/,.');
352
353         // Only execute this filter if installed
354         if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) {
355                 // Set missing entry
356                 setConfigEntry('_ADD', 0);
357                 return;
358         } // END - if
359
360         // Calculate "entropy" with the prime number (for code generation)
361         setConfigEntry('_ADD', (getPrime() * getPrime() / (pi() * getCodeLength() + 1)));
362
363         // Simply init the randomizer with seed and _ADD value
364         mt_srand(generateSeed() + getConfig('_ADD'));
365 }
366
367 // Filter for removing updates
368 function FILTER_REMOVE_UPDATES ($filterData) {
369         // Init removal list
370         initExtensionRemovalList();
371
372         // Add the current extension to it
373         addCurrentExtensionToRemovalList();
374
375         // Simply remove it
376         unsetExtensionSqls();
377
378         // Are there update dependencies to remove?
379         if (countExtensionUpdateDependencies() > 0) {
380                 // Then find all updates we shall no longer execute
381                 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
382                         // Shall we remove this update?
383                         if (in_array($ext_name, getExtensionRemovalList())) {
384                                 // Then remove this extension!
385                                 removeExtensionDependency($ext_name);
386                         } // END - if
387                 } // END - foreach
388         } // END - if
389
390         // Return data
391         return $filterData;
392 }
393
394 // Determines username for current user state
395 function FILTER_DETERMINE_USERNAME () {
396         // Check if logged in
397         if (isMember()) {
398                 // Is still logged in so we welcome him with his name
399                 if (fetchUserData(getMemberId())) {
400                         // Load surname and family's name and build the username
401                         $content = getUserDataArray();
402
403                         // Prepare username
404                         setUsername($content['surname'] . ' ' . $content['family']);
405
406                         // Additionally admin?
407                         if (isAdmin()) {
408                                 // Add it
409                                 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
410                         } // END - if
411                 } else {
412                         // Hmmm, logged in and no valid userid?
413                         setUsername('<span class="bad">{--USERNAME_UNKNOWN--}</span>');
414
415                         // Destroy session
416                         destroyMemberSession();
417                 }
418         } elseif (isAdmin()) {
419                 // Admin is there
420                 setUsername('{--USERNAME_ADMIN--}');
421         } else {
422                 // He's a guest, hello there... ;-)
423                 setUsername('{--USERNAME_GUEST--}');
424         }
425 }
426
427 // Filter for compiling config entries
428 function FILTER_COMPILE_CONFIG ($code, $compiled = FALSE) {
429         // Save the uncompiled code
430         $uncompiled = $code;
431
432         // Is there cache?
433         if (!isset($GLOBALS['compiled_config'][$code])) {
434                 // Compile {?some_var?} to getConfig('some_var')
435                 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
436
437                 // Some entries found?
438                 if ((isFilledArray($matches)) && (isFilledArray($matches[0]))) {
439                         // Replace all matches
440                         foreach ($matches[0] as $key => $match) {
441                                 // Is there cache?
442                                 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
443                                         // Is the config valid?
444                                         if (isConfigEntrySet($matches[1][$key])) {
445                                                 // Set it for caching
446                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . $matches[1][$key] . '%}';
447                                         } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
448                                                 // Use default value
449                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%config=' . 'DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
450                                         } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
451                                                 // No config, try the language system
452                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '{%message,DEFAULT_' . strtoupper($matches[1][$key]) . '%}';
453                                         } else {
454                                                 // Unhandled!
455                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
456                                         }
457                                 } // END - if
458
459                                 // Use this for replacing
460                                 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
461                                 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die(__FUNCTION__.'['.__LINE__.']:<pre>'.secureString($code).'</pre>');
462                         } // END - foreach
463                 } // END - if
464
465                 // Add it to cache
466                 $GLOBALS['compiled_config'][$uncompiled] = $code;
467         } // END - if
468
469         // Should we compile it?
470         if ($compiled === TRUE) {
471                 // Run the code
472                 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . '";';
473                 //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>' . encodeEntities($eval) . '</pre>');
474                 eval($eval);
475         } // END - if
476
477         // Return compiled code
478         return $GLOBALS['compiled_config'][$uncompiled];
479 }
480
481 // Filter for compiling expression code
482 function FILTER_COMPILE_EXPRESSION_CODE ($filterData) {
483         // Compile {%cmd,callback,extraFunction=some_value%} to get expression code snippets
484         // See switch() command below for supported commands
485         preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $filterData, $matches);
486         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.print_r($matches, TRUE).'</pre>');
487
488         // Default is from outputHtml()
489         $outputMode = getScriptOutputMode();
490
491         // Some entries found?
492         if ((isFilledArray($matches)) && (isFilledArray($matches[3]))) {
493                 // Replace all matches
494                 foreach ($matches[2] as $key => $eti) {
495                         // Init replacer/call-back variable
496                         $replacer       = '';
497                         $callback       = '';
498                         $extraFunction  = '';
499                         $extraFunction2 = '';
500                         $value          = NULL;
501
502                         // Extract command and call-back
503                         $etiArray = explode(',', $eti);
504                         $eti = $etiArray[0];
505
506                         // Detect call-back function
507                         if (isset($etiArray[1])) {
508                                 // Call-back function detected
509                                 $callback = $etiArray[1];
510                         } // END - if
511
512                         // Detect extra function
513                         if (isset($etiArray[2])) {
514                                 // Also detected
515                                 $extraFunction = $etiArray[2];
516                         } // END - if
517
518                         // Detect extra function 2
519                         if (isset($etiArray[3])) {
520                                 // Also detected
521                                 $extraFunction2 = $etiArray[3];
522                         } // END - if
523
524                         // And value
525                         if (isset($matches[4][$key])) {
526                                 // Use this as value
527                                 $value = $matches[4][$key];
528                         } // END - if
529
530                         // Construct call-back function name for the command
531                         $etiFunction = 'doExpression' . capitalizeUnderscoreString($eti);
532
533                         // Is this function there?
534                         if (function_exists($etiFunction)) {
535                                 // Prepare $matches, $key, $outputMode, etc.
536                                 $data = array(
537                                         'matches'     => $matches,
538                                         'key'         => $key,
539                                         'output_mode' => getScriptOutputMode(),
540                                         'code'        => $filterData,
541                                         'callback'    => $callback,
542                                         'extra_func'  => $extraFunction,
543                                         'extra_func2' => $extraFunction2,
544                                         'value'       => $value
545                                 );
546
547                                 // Call it
548                                 //* DEBUG: */ debugOutput(__FUNCTION__ . '[' . __LINE__ . ']: etiFunction=' . $etiFunction);
549                                 $filterData = call_user_func($etiFunction, $data);
550                         } else {
551                                 // Unsupported command detected
552                                 logDebugMessage(__FUNCTION__, __LINE__, 'eti=' . $eti . ',etiFunction=' . $etiFunction . ',callback=' . $callback . ',extraFunction=' . $extraFunction . ',extraFunction2=' . $extraFunction2 . ' - UNSUPPORTED');
553                         }
554                 } // END - foreach
555         } // END - if
556
557         // Is there non-HTML/AJAX mode?
558         if ((!isHtmlOutputMode()) && (!isAjaxOutputMode())) {
559                 $filterData = decodeEntities($filterData);
560         } // END - if
561
562         // Return compiled code
563         //* DEBUG: */ debugOutput(__FUNCTION__.'['.__LINE__.']:<pre>'.($filterData).'</pre>');
564         return $filterData;
565 }
566
567 // Runs some generic filter update steps
568 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
569         // Create task (we ignore the task id here)
570         createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], sqlEscapeString(getExtensionNotes(getExtensionNotes())));
571
572         // Update extension's version
573         sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
574                 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
575
576         // Remove arrays
577         unsetSqls();
578         unset($GLOBALS['update_ver'][$ext_name]);
579 }
580
581 // Load more hourly reset scripts
582 function FILTER_RUN_HOURLY_INCLUDES () {
583         // Is the reset set or old sql_patches?
584         if (((!isHourlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) && (isHtmlOutputMode())) {
585                 // Then abort here
586                 reportBug(__FUNCTION__, __LINE__, 'Cannot run hourly reset! enabled='.intval(isHourlyResetEnabled()).',isExtensionInstalledAndNewer='.intval(isExtensionInstalledAndNewer('sql_patches', '0.9.8')).' Please report this bug. Thanks');
587         } // END - if
588
589         // Is ext-sql_patches at least 0.9.8?
590         if (isExtensionInstalledAndNewer('sql_patches', '0.9.8')) {
591                 // Has it changed?
592                 if ((getLastHourly() != getHour()) || (isDebugHourlyEnabled())) {
593                         // Get more hourly reset scripts
594                         setIncludePool('hourly', getArrayFromDirectory('inc/hourly/', 'hourly_'));
595
596                 // Run the filter
597                 runFilterChain('load_includes', 'hourly');
598                 } // END - if
599         } // END - if
600 }
601
602 // Load more daily scripts
603 function FILTER_RUN_DAILY_INCLUDES () {
604         // Is the reset set or old sql_patches?
605         if (((!isDailyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) && (isHtmlOutputMode())) {
606                 // Then abort here
607                 reportBug(__FUNCTION__, __LINE__, 'Cannot run daily reset! enabled='.intval(isDailyResetEnabled()).',isExtensionInstalledAndNewer='.intval(isExtensionInstalledAndNewer('sql_patches', '0.9.8')).' Please report this bug. Thanks');
608         } // END - if
609
610         // Is ext-sql_patches at least 0.9.8?
611         if (isExtensionInstalledAndNewer('sql_patches', '0.9.8')) {
612                 // Has it changed?
613                 if ((getLastDaily() != getDay()) || (isDebugDailyEnabled())) {
614                         // Get more daily reset scripts
615                         setIncludePool('daily', getArrayFromDirectory('inc/daily/', 'daily_'));
616
617                         // Run the filter
618                         runFilterChain('load_includes', 'daily');
619                 } // END - if
620         } // END - if
621 }
622
623 // Load more weeklt scripts
624 function FILTER_RUN_WEEKLY_INCLUDES () {
625         // Is the reset set or old sql_patches?
626         if (((!isWeeklyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) && (isHtmlOutputMode())) {
627                 // Then abort here
628                 reportBug(__FUNCTION__, __LINE__, 'Cannot run weekly reset! enabled='.intval(isWeeklyResetEnabled()).',isExtensionInstalledAndNewer()='.intval(isExtensionInstalledAndNewer('sql_patches', '0.9.8')).' Please report this bug. Thanks');
629         } // END - if
630
631         // Is ext-sql_patches at least 0.9.8?
632         if (isExtensionInstalledAndNewer('sql_patches', '0.9.8')) {
633                 // Has it changed?
634                 if ((getLastWeekly() != getWeek()) || (isDebugWeeklyEnabled())) {
635                         // Include weekly reset scripts
636                         setIncludePool('weekly', getArrayFromDirectory('inc/weekly/', 'weekly_'));
637
638                         // Run the filter
639                         runFilterChain('load_includes', 'weekly');
640                 } // END - if
641         } // END - if
642 }
643
644 // Load more monthly scripts
645 function FILTER_RUN_MONTHLY_INCLUDES () {
646         // Is the reset set or old sql_patches?
647         if (((!isMonthlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) && (isHtmlOutputMode())) {
648                 // Then abort here
649                 reportBug(__FUNCTION__, __LINE__, 'Cannot run monthly reset! enabled='.intval(isMonthlyResetEnabled()).',isExtensionInstalledAndNewer='.intval(isExtensionInstalledAndNewer('sql_patches', '0.9.8')).' Please report this bug. Thanks');
650         } // END - if
651
652         // Is ext-sql_patches at least 0.9.8?
653         if (isExtensionInstalledAndNewer('sql_patches', '0.9.8')) {
654                 // Has it changed?
655                 if ((getLastMonthly() != getMonth()) || (isDebugMonthlyEnabled())) {
656                         // Include monthly reset scripts
657                         setIncludePool('monthly', getArrayFromDirectory('inc/monthly/', 'monthly_'));
658
659                         // Run the filter
660                         runFilterChain('load_includes', 'monthly');
661                 } // END - if
662         } // END - if
663 }
664
665 // Load more yearly scripts
666 function FILTER_RUN_YEARLY_INCLUDES () {
667         // Is the reset set or old sql_patches?
668         if (((!isYearlyResetEnabled()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) && (isHtmlOutputMode())) {
669                 // Then abort here
670                 reportBug(__FUNCTION__, __LINE__, 'Cannot run yearly reset! enabled='.intval(isYearlyResetEnabled()).',isExtensionInstalledAndNewer='.intval(isExtensionInstalledAndNewer('sql_patches', '0.9.8')).' Please report this bug. Thanks');
671         } // END - if
672
673         // Is ext-sql_patches at least 0.9.8?
674         if (isExtensionInstalledAndNewer('sql_patches', '0.9.8')) {
675                 // Has it changed?
676                 if ((getLastYearly() != getYear()) || (isDebugYearlyEnabled())) {
677                         // Include yearly reset scripts
678                         setIncludePool('yearly', getArrayFromDirectory('inc/yearly/', 'yearly_'));
679
680                         // Run the filter
681                         runFilterChain('load_includes', 'yearly');
682                 } // END - if
683         } // END - if
684 }
685
686 // Filter for removing the given extension
687 function FILTER_REMOVE_EXTENSION () {
688         // Delete this extension (remember to remove it from your server *before* you click on welcome!
689         sqlQueryEscaped("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
690                 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
691
692         // Remove the extension from cache array as well
693         removeExtensionFromArray();
694
695         // Remove the cache
696         rebuildCache('extension', 'extension');
697 }
698
699 // Filter for flushing the output
700 function FILTER_FLUSH_OUTPUT () {
701         // Is this filter called?
702         if (isset($GLOBALS[__FUNCTION__])) {
703                 // Abort here
704                 reportBug(__FUNCTION__, __LINE__, 'Double call of ' . __FUNCTION__ . ' causes problems with sent headers.');
705         } // END - if
706
707         // Mark this filter as called
708         $GLOBALS[__FUNCTION__] = TRUE;
709
710         // Simple, he?
711         outputHtml();
712 }
713
714 // Filter for determining what/action/module
715 function FILTER_DETERMINE_WHAT_ACTION () {
716         // In installation phase we don't have what/action
717         if (isInstaller()) {
718                 // Set both to empty
719                 setAction('');
720                 setWhat('');
721
722                 // Abort here
723                 return;
724         } // END - if
725
726         // Get all values
727         if ((!isCssOutputMode()) && (!isRawOutputMode())) {
728                 // Fix module
729                 if (!isModuleSet()) {
730                         // Is the module registered?
731                         if (!isModuleRegistered(getRequestElement('module'))) {
732                                 // Is not a valid module
733                                 redirectToUrl('modules.php?module=index');
734                         } // END - if
735
736                         // Is the request element set?
737                         if (isGetRequestElementSet('module')) {
738                                 // Set module from request
739                                 setModule(getRequestElement('module'));
740                         } elseif (isHtmlOutputMode()) {
741                                 // Set default module 'index'
742                                 setModule('index');
743                         } else {
744                                 // Unknown module
745                                 setModule('unknown');
746                         }
747                 } // END - if
748
749                 // Fix 'what' if not yet set
750                 if (!isWhatSet()) {
751                         setWhat(getWhatFromModule(getModule()));
752                 } // END - if
753
754                 // Fix 'action' if not yet set
755                 if (!isActionSet()) {
756                         // Is 'what' set?
757                         if (isWhatSet()) {
758                                 // Set action
759                                 setAction(getActionFromModuleWhat(getModule(), getWhat()));
760                         } else {
761                                 // Set action/what to empty
762                                 setAction('');
763                                 setWhat('');
764                         }
765                 } // END - if
766         } else {
767                 // Set action/what to empty
768                 setAction('');
769                 setWhat('');
770         }
771
772         // Set default 'what' value
773         //* DEBUG: */ debugOutput('-' . getModule() . '/' . getWhat() . '-');
774         if ((!isWhatSet()) && (!isActionSet()) && (!isCssOutputMode()) && (!isRawOutputMode())) {
775                 if (getModule() == 'admin') {
776                         // Set 'action' value to 'login' in admin menu
777                         setAction(getActionFromModuleWhat(getModule(), getWhat()));
778                 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
779                         // Set 'what' value to 'welcome' in guest and member menu
780                         setWhatFromConfig('index_home');
781                 } else {
782                         // Anything else like begging link
783                         setWhat('');
784                 }
785         } // END - if
786 }
787
788 // Sends out pooled mails
789 function FILTER_TRIGGER_SENDING_POOL () {
790         // Are we in normal output mode?
791         if (!isHtmlOutputMode()) {
792                 // Only in normal output mode to prevent race-conditons!
793                 return;
794         } // END - if
795
796         // Init counter
797         $GLOBALS['pool_cnt'] = '0';
798
799         // Init & set the include pool
800         initIncludePool('pool');
801         setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
802
803         // Run the filter
804         runFilterChain('load_includes', 'pool');
805
806         // Remove the counter
807         unset($GLOBALS['pool_cnt']);
808 }
809
810 // Filter for checking and updating SVN revision
811 function FILTER_CHECK_REPOSITORY_REVISION () {
812         // Only execute this filter if installed and all config entries are there
813         if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) {
814                 return;
815         } // END - if
816
817         // Check for patch level differences between database and current hard-coded
818         if ((getCurrentRepositoryRevision() > getConfig('patch_level')) || (getConfig('patch_level') == 'CURRENT_REPOSITORY_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
819                 // Update database and CONFIG array
820                 updateConfiguration(array('patch_level', 'patch_ctime'), array(getCurrentRepositoryRevision(), 'UNIX_TIMESTAMP()'));
821                 setConfigEntry('patch_level', getCurrentRepositoryRevision());
822                 setConfigEntry('patch_ctime', time());
823         } // END - if
824 }
825
826 // Filter for running hourly reset
827 function FILTER_RUN_HOURLY_RESET () {
828         // Only execute this filter if installed
829         if ((isInstaller()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) {
830                 return;
831         } // END - if
832
833         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
834         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getLastHourly()=' . getLastHourly() . ',getHour()=' . getHour());
835         if (((getLastHourly() != getHour()) || (isDebugHourlyEnabled())) && (!isInstaller()) && (isAdminRegistered()) && (!isGetRequestElementSet('setup')) && (!isCssOutputMode())) {
836                 // Tell every module we are in reset-mode!
837                 doHourly();
838         } // END - if
839 }
840
841 // Filter for running daily reset
842 function FILTER_RUN_DAILY_RESET () {
843         // Only execute this filter if installed
844         if ((isInstaller()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) {
845                 return;
846         } // END - if
847
848         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
849         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getLastDaily()=' . getLastDaily() . ',getDay()=' . getDay());
850         if (((getLastDaily() != getDay()) || (isDebugDailyEnabled())) && (!isInstaller()) && (isAdminRegistered()) && (!isGetRequestElementSet('setup')) && (!isCssOutputMode())) {
851                 // Tell every module we are in reset-mode!
852                 doDaily();
853         } // END - if
854 }
855
856 // Filter for running weekly reset
857 function FILTER_RUN_WEEKLY_RESET () {
858         // Only execute this filter if installed
859         if ((isInstaller()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) {
860                 return;
861         } // END - if
862
863         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
864         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getLastWeekly()=' . getLastWeekly() . ',getWeek()=' . getWeek());
865         if (((getLastWeekly() != getWeek()) || (isDebugWeeklyEnabled())) && (!isInstaller()) && (isAdminRegistered()) && (!isGetRequestElementSet('setup')) && (!isCssOutputMode())) {
866                 // Tell every module we are in reset-mode!
867                 doWeekly();
868         } // END - if
869 }
870
871 // Filter for running monthly reset
872 function FILTER_RUN_MONTHLY_RESET () {
873         // Only execute this filter if installed
874         if ((isInstaller()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) {
875                 return;
876         } // END - if
877
878         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
879         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getLastMonthly()=' . getLastMonthly() . ',getMonth()=' . getMonth());
880         if (((getLastMonthly() != getMonth()) || (isDebugMonthlyEnabled())) && (!isInstaller()) && (isAdminRegistered()) && (!isGetRequestElementSet('setup')) && (!isCssOutputMode())) {
881                 // Tell every module we are in reset-mode!
882                 doMonthly();
883         } // END - if
884 }
885
886 // Filter for running yearly reset
887 function FILTER_RUN_YEARLY_RESET () {
888         // Only execute this filter if installed
889         if ((isInstaller()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.8'))) {
890                 return;
891         } // END - if
892
893         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
894         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getLastYearly()=' . getLastYearly() . ',getYear()=' . getYear());
895         if (((getLastYearly() != getYear()) || (isDebugYearlyEnabled())) && (!isInstaller()) && (isAdminRegistered()) && (!isGetRequestElementSet('setup')) && (!isCssOutputMode())) {
896                 // Tell every module we are in reset-mode!
897                 doYearly();
898         } // END - if
899 }
900
901 // Filter for loading more runtime includes (not for installation)
902 function FILTER_LOAD_RUNTIME_INCLUDES () {
903         // Load more includes
904         foreach (array('databases', 'session', 'versions') as $inc) {
905                 // Load the include
906                 loadIncludeOnce('inc/' . $inc . '.php');
907         } // END - foreach
908 }
909
910 // Filter for checking admin ACL
911 function FILTER_CHECK_ADMIN_ACL () {
912         // Extension not installed so it's always allowed to access everywhere!
913         $ret = TRUE;
914
915         // Ok, Cookie-Update done
916         if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
917                 // Check if action GET variable was set
918                 $action = getAction();
919                 if (isWhatSet()) {
920                         // Get action value by what-value
921                         $action = getActionFromModuleWhat('admin', getWhat());
922                 } // END - if
923
924                 // Check for access control line of current menu entry
925                 $ret = isAdminsAllowedByAcl($action, getWhat());
926         } // END - if
927
928         // Set it here
929         $GLOBALS['acl_allow'] = $ret;
930 }
931
932 // Init random number/cache buster
933 function FILTER_INIT_RANDOM_NUMBER () {
934         // Is the extension ext-sql_patches installed and at least 0.3.6?
935         if (isSessionVariableSet('random_number')) {
936                 // Then set it
937                 setConfigEntry('RAND_NUMBER', getSession('random_number'));
938         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
939                 // Generate random number
940                 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 99999), getMemberId(), ''));
941         } else {
942                 // Generate *WEAK* code
943                 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
944         }
945
946         // Set it in session for faster script execusion
947         setSession('random_number', getConfig('RAND_NUMBER'));
948
949         // Copy it to CACHE_BUSTER
950         setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
951 }
952
953 // Update module counter
954 function FILTER_COUNT_MODULE () {
955         // Is installation phase or no admin registered?
956         if ((isInstaller()) || (!isInstalled()) || (!isAdminRegistered())) {
957                 // Then don't count any modules
958                 return;
959         } // END - if
960
961         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ' - ENTERED!');
962         // Count module click
963         sqlQueryEscaped("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
964                 array(getModule()), __FUNCTION__, __LINE__);
965         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getModule()=' . getModule() . ',sqlAffectedRows()=' . sqlAffectedRows() . ' - EXIT!');
966 }
967
968 // Handles fatal errors
969 function FILTER_HANDLE_FATAL_ERRORS () {
970         // Is there errors to handle and right output mode?
971         if ((!ifFatalErrorsDetected()) || (!isHtmlOutputMode())) {
972                 // Abort executing here
973                 return FALSE;
974         } // END - if
975
976         // Set content type
977         setContentType('text/html');
978
979         // Load config here
980         loadIncludeOnce('inc/load_config.php');
981
982         // Default content is none
983         $content = '';
984
985         // Installation phase or regular mode?
986         if ((isInstaller())) {
987                 // While we are installing ouput other header than while it is installed... :-)
988                 $OUT = '';
989                 foreach (getFatalArray() as $key => $value) {
990                         // Prepare content for the template
991                         $content = array(
992                                 'key'   => ($key + 1),
993                                 'value' => $value
994                         );
995
996                         // Load row template
997                         $OUT .= loadTemplate('install_fatal_row', TRUE, $content);
998                 }
999
1000                 // Load main template
1001                 $content = loadTemplate('install_fatal_table', TRUE, $OUT);
1002         } elseif (isInstalled()) {
1003                 // Display all runtime fatal errors
1004                 $OUT = '';
1005                 foreach (getFatalArray() as $key => $value) {
1006                         // Prepare content for the template
1007                         $content = array(
1008                                 'key'   => ($key + 1),
1009                                 'value' => $value
1010                         );
1011
1012                         // Load row template
1013                         $OUT .= loadTemplate('runtime_fatal_row', TRUE, $content);
1014                 }
1015
1016                 // Load main template
1017                 $content = loadTemplate('runtime_fatal_table', TRUE, $OUT);
1018         }
1019
1020         // Message to regular users (non-admin)
1021         $CORR = '{--FATAL_REPORT_ERRORS--}';
1022
1023         // Maybe the admin wants to take a look?
1024         if (isAdmin()) {
1025                 $CORR = '{--FATAL_CORRECT_ERRORS--}';
1026         } // END - if
1027
1028         // Remember all in array
1029         $content = array(
1030                 'rows' => $content,
1031                 'corr' => $CORR
1032         );
1033
1034         // Load footer
1035         loadIncludeOnce('inc/header.php');
1036
1037         // Load main template
1038         loadTemplate('fatal_errors', FALSE, $content);
1039
1040         // Delete all to prevent double-display
1041         initFatalMessages();
1042
1043         // Load footer
1044         loadIncludeOnce('inc/footer.php');
1045
1046         // Abort here
1047         doShutdown();
1048 }
1049
1050 // Filter for displaying copyright line
1051 function FILTER_DISPLAY_COPYRIGHT () {
1052         // Shall we display the copyright notice?
1053         if ((isFullPage()) && ((getWriteFooter() == 'Y') || (isInstalling())) && ($GLOBALS['__header_sent'] == 2) && (ifCopyrightFooterEnabled())) {
1054                 // Backlink enabled?
1055                 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
1056                         // Copyright with backlink, thanks! :-)
1057                         $GLOBALS['__page_footer'] .= loadTemplate('copyright_backlink', TRUE);
1058                 } else {
1059                         // No backlink in Copyright note
1060                         $GLOBALS['__page_footer'] .= loadTemplate('copyright', TRUE);
1061                 }
1062         } // END - if
1063 }
1064
1065 // Filter for displaying parsing time
1066 function FILTER_DISPLAY_PARSING_TIME () {
1067         // Shall we display the parsing time and number of queries?
1068         // 1234                            5                      54    4                    554    4          5543    3                    4432    2                332    2                              21
1069         if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (isShowTimingsEnabled()) && (isFullPage())) && (!isInstaller())) && (isHtmlOutputMode()) && ($GLOBALS['__header_sent'] == 2)) {
1070                 // Then display it here
1071                 displayParsingTime();
1072         } // END - if
1073 }
1074
1075 // Filter for flushing template cache
1076 function FILTER_FLUSH_TEMPLATE_CACHE () {
1077         // Do not flush when debugging the template cache
1078         if (isDebugTemplateCacheEnabled()) {
1079                 // Do not flush templates in debug-mode
1080                 return;
1081         } // END - if
1082
1083         // Is there cached eval() data?
1084         if ((isset($GLOBALS['template_eval'])) && (isFilledArray($GLOBALS['template_eval']))) {
1085                 // Flush all
1086                 foreach ($GLOBALS['template_eval'] as $prefix => $templateArray) {
1087                         foreach ($templateArray as $template => $eval) {
1088                                 // Flush the cache (if not yet found)
1089                                 flushTemplateCache($prefix, $template, $eval);
1090                         } // END - foreach
1091                 } // END - foreach
1092         } // END - if
1093 }
1094
1095 // Filter for loading user data
1096 function FILTER_FETCH_USER_DATA ($userid = NULL) {
1097         // Is the userid not set?
1098         if (!isValidId($userid)) {
1099                 // Then use member id
1100                 $userid = getMemberId();
1101         } // END - if
1102
1103         // Get user data
1104         if (!fetchUserData($userid)) {
1105                 // Userid is not valid
1106                 reportBug(__FUNCTION__, __LINE__, 'User id ' . $userid . ' is invalid.');
1107         } // END - if
1108
1109         // Set member id
1110         setMemberId($userid);
1111
1112         // Continue with next filter
1113         return $userid;
1114 }
1115
1116 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
1117 function FILTER_RESET_USER_LOGIN_FAILURE () {
1118         // Is the user data valid?
1119         if (!isMember()) {
1120                 // Do only run for logged in members
1121                 reportBug(__FUNCTION__, __LINE__, 'Please only run this filter for logged in users.');
1122         } // END - if
1123
1124         // Remmeber login failures if available
1125         if (isExtensionInstalledAndNewer('user', '0.3.7')) {
1126                 // Reset login failures
1127                 sqlQueryEscaped("UPDATE
1128         `{?_MYSQL_PREFIX?}_user_data`
1129 SET
1130         `login_failures`=0,
1131         `last_failure`=NULL
1132 WHERE
1133         `userid`=%s
1134 LIMIT 1",
1135                         array(getMemberId()), __FUNCTION__, __LINE__);
1136
1137                 // Store it in session
1138                 setSession('mailer_member_failures' , getUserData('login_failures'));
1139                 setSession('mailer_member_last_failure', getUserData('last_failure'));
1140         } // END - if
1141 }
1142
1143 // Try to login the admin by setting some session/cookie variables
1144 function FILTER_DO_LOGIN_ADMIN ($filterData) {
1145         // Now set all session variables and store the result for later processing
1146         $GLOBALS['admin_login_success'] = ((
1147                 setAdminMd5(encodeHashForCookie($filterData['pass_hash']))
1148         ) && (
1149                 setAdminId($filterData['id'])
1150         ) && (
1151                 setAdminLast(time())
1152         ));
1153
1154         // Return the data for further processing
1155         return $filterData;
1156 }
1157
1158 // Filter for loading page header, this should be ran first!
1159 function FILTER_LOAD_PAGE_HEADER () {
1160         // Output page header code
1161         $GLOBALS['__page_header'] = loadTemplate('page_header', TRUE);
1162
1163         // Include meta data in 'guest' module
1164         if (isModuleSet()) {
1165                 // Load meta data template
1166                 $GLOBALS['__page_header'] .= loadTemplate(getMenuModeFromModule() . '_metadata', TRUE);
1167
1168                 // Add meta description to header
1169                 if ((isInstalled()) && (isAdminRegistered()) && (isSqlLinkUp()) && (getModule() == 'index')) {
1170                         // Add meta description not in admin and login module and when the script is installed
1171                         generateMetaDescriptionCode();
1172                 } // END - if
1173         } // END - if
1174 }
1175
1176 // Filter for adding style sheet, closing page header
1177 function FILTER_FINISH_PAGE_HEADER () {
1178         // Include stylesheet
1179         loadIncludeOnce('inc/stylesheet.php');
1180
1181         // Closing HEAD tag
1182         $GLOBALS['__page_header'] .= '</head>';
1183 }
1184
1185 // Cleans up the DNS cache if ext-sql_patches is at least 0.7.0
1186 function FILTER_CLEANUP_DNS_CACHE () {
1187         // Is the latest version installed?
1188         if (isExtensionInstalledAndNewer('sql_patches', '0.7.0')) {
1189                 // Load class file
1190                 loadIncludeOnce('inc/classes/resolver.class.php');
1191
1192                 // Instance the resolver
1193                 $resolver = new HostnameResolver();
1194
1195                 // Purge entries
1196                 $resolver->purgeEntries();
1197
1198                 // Cute, isn't it? ;-)
1199         } // END - if
1200 }
1201
1202 // Filter for setting CURRENT_DATE, this is required after initialization of extensions
1203 function FILTER_SET_CURRENT_DATE () {
1204         // Set current date
1205         setConfigEntry('CURRENT_DATE', generateDateTime(time(), '3'));
1206
1207         // Epoche time for yesterday, today ... all at 00:00 am
1208         setConfigEntry('START_YDAY', makeTime(0, 0, 0, time() - getOneDay()));
1209         setConfigEntry('START_TDAY', makeTime(0, 0, 0, time()));
1210 }
1211
1212 // Filter for marking extension as installed
1213 function FILTER_EXTENSION_MARK_INSTALLED ($filterData) {
1214         // Mark it as installed
1215         $GLOBALS['ext_is_installed'][$filterData['ext_name']] = TRUE;
1216 }
1217
1218 // Filter for generating mails links for 'pool' mails
1219 function FILTER_GENERATE_POOL_MAIL_LINKS ($filterData) {
1220         // Is type 'normal'?
1221         if ($filterData['type'] == 'normal') {
1222                 // Load template
1223                 $filterData['__output'] .= loadTemplate('admin_links_' . strtolower($filterData['mail_status']) . '_pool_mail', TRUE, $filterData);
1224         } // END - if
1225
1226         // Return data
1227         return $filterData;
1228 }
1229
1230 // Filter to activate exchange
1231 function FILTER_ACTIVATE_EXCHANGE () {
1232         // Are the extension ext-user/other there?
1233         if ((!isExtensionActive('user')) || (!isExtensionInstalled('other')) || (isAjaxOutputMode()) || (getActivateXchange() == '0')) {
1234                 // Silently abort here
1235                 return FALSE;
1236         } // END - if
1237
1238         // Check total amount of users
1239         if (getTotalConfirmedUser() >= getActivateXchange()) {
1240                 // Activate System
1241                 addSql("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `locked`='N',`hidden`='N',`mem_only`='Y' WHERE `module`='order' LIMIT 1");
1242                 addSql("UPDATE `{?_MYSQL_PREFIX?}_member_menu` SET `visible`='Y',`locked`='N' WHERE `what`='order' OR `what`='unconfirmed' LIMIT 2");
1243
1244                 // Run SQLs
1245                 runFilterChain('run_sqls');
1246
1247                 // Update configuration
1248                 updateConfiguration('activate_xchange' ,0);
1249
1250                 // Rebuild cache
1251                 rebuildCache('modules', 'modules');
1252         } // END - if
1253 }
1254
1255 // Filter to handle configuration
1256 function FILTER_HANDLE_HOME_IN_INDEX_SETTING ($filterData) {
1257         // Is ext-sql_patches up-to-date?
1258         if ((isExtensionInstalledAndNewer('sql_patches', '0.8.3')) && (isDisplayHomeInIndexEnabled())) {
1259                 // Is 'search' as same as 'index_home'?
1260                 if ($filterData['search'] == getIndexHome()) {
1261                         // Then set 'content' to link to index.php
1262                         $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>';
1263                 } // END - if
1264         } // END - if
1265
1266         // Return data
1267         return $filterData;
1268 }
1269
1270 // Filter to add history entry
1271 function FILTER_ADD_HISTORY_ENTRY ($filterData) {
1272         // Add the entry
1273         sqlQueryEscaped("INSERT INTO `{?_MYSQL_PREFIX?}_history` (`history_subject`, `history_userid`, `history_value`) VALUES ('%s',%s,'%s')",
1274                 $filterData,
1275                 __FUNCTION__, __LINE__);
1276
1277         // Remember insert id for other filters
1278         $filterData['history_id'] = getSqlInsertId();
1279
1280         // Return data
1281         return $filterData;
1282 }
1283
1284 // Filter for initializing ext-sql_patches
1285 function FILTER_GENERATE_FILE_SECRET_HASH ($filterData) {
1286         // Is ext-sql_patches installed and transfer POINTS word?
1287         if ((!isExtensionInstalled('sql_patches')) || (!isExtensionInstalledAndNewer('sql_patches', '0.9.0'))) {
1288                 // Extension ext-sql_patches is missing, so better abort here
1289                 return;
1290         } // END - if
1291
1292         // Okay, recent enough, so transfer the word for POINTS
1293         setConfigEntry('POINTS', getPointsWord());
1294
1295         // Init key
1296         setConfigEntry('secret_key', '');
1297
1298         // File hash was generated so we can also file the secret file... hopefully.
1299         $hashFile = sprintf('%s%s.%s.cache', getPath(), getCachePath(), getFileHash());
1300
1301         // Read key from secret file
1302         if ((getFileHash() == '') || (getMasterSalt() == '') || (getPassScramble() == '') || (!isFileReadable($hashFile))) {
1303                 // Maybe need setup of secret key!
1304                 loadIncludeOnce('inc/gen_sql_patches.php');
1305
1306                 // Generate file name again
1307                 $hashFile = sprintf('%s%s.%s.cache', getPath(), getCachePath(), getFileHash());
1308         } // END - if
1309
1310         // Test again
1311         if ((getFileHash() != '') && (getMasterSalt() != '') && (getPassScramble() != '')) {
1312                 // Is the secret key file readable?
1313                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'hashFile=' . $hashFile);
1314                 if (isFileReadable($hashFile)) {
1315                         // Read file
1316                         setConfigEntry('secret_key', readFromFile($hashFile));
1317                 } else {
1318                         // Remove it from database
1319                         updateConfiguration('file_hash', '', '', '0', TRUE);
1320
1321                         // Cannot read secret file!
1322                         reportBug(__FILE__, __LINE__, 'Cannot read secret file! Please try to reload.');
1323                 }
1324         } // END - if
1325
1326         // Return data
1327         return $filterData;
1328 }
1329
1330 // Filter to initialize session
1331 function FILTER_INIT_SESSION ($filterData) {
1332         // Determine and set referral id
1333         determineReferralId();
1334
1335         // Return data
1336         return $filterData;
1337 }
1338
1339 // Filter for sending "build mail" to admin
1340 function FILTER_SEND_BUILD_MAIL ($filterData) {
1341         // Was one line updated?
1342         if (($filterData['affected'] > 0) || (isDebugBuildMailsEnabled())) {
1343                 // Then call the proper function
1344                 call_user_func_array('sendGenericBuildMails', $filterData);
1345         } // END - if
1346
1347         // Return data
1348         return $filterData;
1349 }
1350
1351 // Handles click on referral banner
1352 function FILTER_HANDLE_REFERRER_BANNER_CLICK ($filterData) {
1353         // Check required parameters
1354         if ((isGetRequestElementSet('user')) && (isGetRequestElementSet('banner'))) {
1355                 // Update clicks counter...
1356                 sqlQueryEscaped('UPDATE `{?_MYSQL_PREFIX?}_refbanner` SET `clicks`=`clicks`+1 WHERE `id`=%s LIMIT 1',
1357                         array(bigintval(getRequestElement('banner'))), __FUNCTION__, __LINE__);
1358
1359                 // A line has been updated?
1360                 if ((!ifSqlHasZeroAffectedRows()) && (isGetRequestElementSet('user'))) {
1361                         // Redirect to the user's referral link
1362                         redirectToUrl('ref.php?refid=' . bigintval(getRequestElement('user')));
1363                 } // END - if
1364         } // END - if
1365
1366         // Return filter data
1367         return $filterData;
1368 }
1369
1370 // Filter for handling viewing of a referral banner
1371 function FILTER_HANDLE_REFERRER_BANNER_VIEW ($filterData) {
1372         // Are all required parameters set
1373         if ((isGetRequestElementSet('user')) && (isGetRequestElementSet('banner'))) {
1374                 // For later things... ;-)
1375                 $result = sqlQueryEscaped('SELECT `url` FROM `{?_MYSQL_PREFIX?}_refbanner` WHERE `id`=%s LIMIT 1',
1376                         array(bigintval(getRequestElement('banner'))), __FUNCTION__, __LINE__);
1377
1378                 // Is there the banner?
1379                 if (sqlNumRows($result) == 1) {
1380                         // Load the URL
1381                         $data = sqlFetchArray($result);
1382
1383                         // Update counter
1384                         sqlQueryEscaped('UPDATE `{?_MYSQL_PREFIX?}_refbanner` SET `counter`=`counter`+1 WHERE `id`=%s LIMIT 1',
1385                                 array(bigintval(getRequestElement('banner'))), __FUNCTION__, __LINE__);
1386
1387                         // Set header and ...
1388                         setContentType('image/' . substr($data['url'], -3, 3));
1389
1390                         // Redirect
1391                         redirectToUrl($data['url'], FALSE);
1392                 } // END - if
1393
1394                 // @TODO No banner found, output some default banner
1395                 logDebugMessage(__FUNCTION__, __LINE__, 'Banner ' . bigintval(getRequestElement('banner')) . ' not found.');
1396
1397                 // Free memory
1398                 sqlFreeResult($result);
1399         } // END - if
1400
1401         // Do nothing for now
1402         redirectToUrl('modules.php?module=index');
1403 }
1404
1405 // Filter for redirecting on wrong server name (e.g. bad.your-server.tld will be redirected to your-server.tld)
1406 function FILTER_REDIRECT_WRONG_SERVER_NAME ($filterData) {
1407         // Get URL
1408         $url = getUrl();
1409
1410         // Is the configured URL same as SERVER_NAME?
1411         if (extractHostnameFromUrl($url) != detectServerName()) {
1412                 // Log all attempts
1413                 logWrongServerNameRedirect();
1414
1415                 // Then redirect to configured URL
1416                 redirectToRequestUri();
1417         } // END - if
1418
1419         // Return filter data
1420         return $filterData;
1421 }
1422
1423 // Filter for adding hidden session id
1424 function FILTER_ADD_INPUT_HIDDEN_SESSION_ID ($filterData) {
1425         // Is a spider detected?
1426         if ((!isSpider()) && (!isValidSession()) && ($filterData['__form_method'] == 'get')) {
1427                 // No, then add the hidden field
1428                 $filterData['__replacer'] .= '<input type="hidden" name="' . session_name() . '" value="' . session_id() . '" />';
1429         } // END - if
1430
1431         // Return filter data
1432         return $filterData;
1433 }
1434
1435 // Filter for purging old SERVER_NAME entries
1436 function FILTER_SERVER_NAME_EXTRA_AUTOPURGE ($filterData) {
1437         // Is purging configured?
1438         if ((isApServerNameEnabled()) && (getApServerNameSince() > 0)) {
1439                 // Then start purging
1440                 sqlQuery('DELETE LOW_PRIORITY FROM
1441         `{?_MYSQL_PREFIX?}_server_name_log`
1442 WHERE
1443         (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`server_name_added`)) >= {?ap_server_name_since?}',
1444                         __FILE__, __LINE__);
1445
1446                 // Are some entries deleted?
1447                 if (sqlAffectedRows() > 0) {
1448                         // Okay, then send an email to the admin
1449                         sendAdminNotification('{--ADMIN_PURGE_USER_SERVER_NAME_LOG_SUBJECT--}', 'admin_purge_user_server_name_log', sqlAffectedRows());
1450                 } // END - if
1451         } // END - if
1452
1453         // Return filter data
1454         return $filterData;
1455 }
1456
1457 // Filter for detecting menu mode
1458 function FILTER_DETERMINE_MENU_MODE_GENERIC ($filterData) {
1459         // "Detect" it
1460         switch (getModule()) {
1461                 case 'chk_login': // Is also faked
1462                 case 'confirm': // Login script is 'member'
1463                 case 'loader': // Is faked to 'member' to avoid indexing by search engines
1464                 case 'mailid': // Mail confirmation is 'member'
1465                         $filterData = 'member';
1466                         break;
1467         } // END - switch
1468
1469         // Return filter data
1470         return $filterData;
1471 }
1472
1473 // Filter to exclude default referral id
1474 function FILTER_EXCLUDE_DEFAULT_REFID ($filterData = array()) {
1475         // Is it valid?
1476         if (isValidId(getDefRefid())) {
1477                 // Exclude it
1478                 array_push($filterData, '{?def_refid?}');
1479         } // END - if
1480
1481         // Return it
1482         return $filterData;
1483 }
1484
1485 // [EOF]
1486 ?>