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