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