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