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