1019759bdee08d74e290dda0760ec7cbc0122c71
[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  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // Filter for flushing all new filters to the database
45 function FILTER_FLUSH_FILTERS () {
46         // Clear all previous SQL queries
47         initSqls();
48
49         // Are we installing?
50         if ((isInstallationPhase())) {
51                 // Then silently skip this filter
52                 return true;
53         } // END - if
54
55         // Is a database link here and not in installation mode?
56         if ((!SQL_IS_LINK_UP()) && (!isInstalling())) {
57                 // Abort here
58                 addFatalMessage(__FUNCTION__, __LINE__, getMessage('FILTER_FLUSH_FAILED_NO_DATABASE'));
59                 return false;
60         } // END - if
61
62         // Is the extension sql_patches updated?
63         if ((!isExtensionInstalled('sql_patches')) || (isExtensionInstalledAndOlder('sql_patches', '0.5.9'))) {
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: */ print 'FOUND:'.$filterName.'/'.$filterFunction.'='.$active.'<br />';
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: */ print 'ADD:'.$filterName.'/'.$filterFunction.'<br />';
85                                 $insertSQL .= sprintf("('%s','%s','Y'),", $filterName, $filterFunction);
86                                 $inserted++;
87                         } elseif ($active == 'R') {
88                                 // Remove this filter
89                                 //* DEBUG: */ print 'REMOVE:'.$filterName.'/'.$filterFunction.'<br />';
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 (getConfig('update_filter_usage') == 'Y') {
110                 // Update all counters
111                 foreach ($GLOBALS['cache_array']['filter']['counter'] as $filterName => $filterArray) {
112                         // Walk through all filters
113                         foreach ($filterArray as $filterFunction => $cnt) {
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($cnt),
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                 rebuildCacheFile('filter', 'filter');
131         } // END - if
132 }
133
134 // Filter for calling the handler for login failures
135 function FILTER_CALL_HANDLER_LOGIN_FAILTURES ($data) {
136         // Init content
137         $content = $data;
138
139         // Handle failed logins here if not in guest
140         //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):type={$data['type']},action={getAction()},what={getWhat()},level={$data['access_level']}<br />");
141         if ((($data['type'] == 'what') || ($data['type'] == 'action') && ((!isWhatSet()) || (getWhat() == 'overview') || (getWhat() == getConfig('index_home')))) && ($data['access_level'] != 'guest') && ((isExtensionInstalledAndNewer('sql_patches', '0.4.7')) || (isExtensionInstalledAndNewer('admins', '0.7.0')))) {
142                 // Handle failure
143                 $content['content'] .= handleLoginFailtures($data['access_level']);
144         } // END - if
145
146         // Return the content
147         return $content;
148 }
149
150 // Filter for redirecting to logout if sql_patches has been installed
151 function FILTER_REDIRECT_TO_LOGOUT_SQL_PATCHES () {
152         // Remove this filter
153         unregisterFilter('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 ($data) {
167         // Is this extension always activated?
168         if (getExtensionAlwaysActive() == 'Y') {
169                 // Then activate the extension
170                 //* DEBUG: */ outputHtml(__FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$data['ext_name']}<br />");
171                 doActivateExtension($data['ext_name']);
172         } // END - if
173
174         // Return the data
175         return $data;
176 }
177
178 // Filter for solving task given task
179 function FILTER_SOLVE_TASK ($data) {
180         // Don't solve anything if no admin!
181         if (!isAdmin()) return $data;
182
183         // Is this a direct task id or array element task_id is found?
184         if (is_int($data)) {
185                 // Then solve it...
186                 adminSolveTask($data);
187         } elseif ((is_array($data)) && (isset($data['task_id']))) {
188                 // Solve it...
189                 adminSolveTask($data['task_id']);
190         } else {
191                 // Not detectable!
192                 debug_report_bug(sprintf("Cannot resolve task. data[%s]=<pre>%s</pre>", gettype($data), print_r($data, true)));
193         }
194
195         // Return the data
196         return $data;
197 }
198
199 // Filter to load include files
200 function FILTER_LOAD_INCLUDES ($pool) {
201         // Is it null?
202         if (is_null($pool)) {
203                 // This should not happen!
204                 debug_report_bug('pool is null.');
205         } // END - if
206
207         // Is the pool an array and 'pool' set?
208         if ((is_array($pool)) && (isset($pool['pool']))) {
209                 // Then use it as pool
210                 $realPool = $pool['pool'];
211         } else {
212                 // Default is $data as inclusion list
213                 $realPool = $pool;
214         }
215
216         // Get inc pool
217         $data = getIncludePool($realPool);
218
219         // Is it an array?
220         if ((!isset($data)) || (!is_array($data))) {
221                 // Then abort here
222                 debug_report_bug(sprintf("INC_POOL is no array! Type: %s", gettype($data)));
223         } elseif (isset($data['inc_pool'])) {
224                 // Use this as new inclusion pool!
225                 setIncludePool($realPool, $data['inc_pool']);
226         }
227
228         // Check for added include files
229         if (countIncludePool($realPool) > 0) {
230                 // Loads every include file
231                 loadIncludePool($realPool);
232
233                 // Reset array
234                 initIncludePool($realPool);
235         } // END - if
236
237         // Continue with processing
238         return $pool;
239 }
240
241 // Filter for running SQL commands
242 function FILTER_RUN_SQLS ($data) {
243         // Debug message
244         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Entered!");
245
246         // Is the array there?
247         if ((isSqlsValid()) && ((!isset($data['dry_run'])) || ($data['dry_run'] == false))) {
248                 // Run SQL commands
249                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Found ".countSqls()." queries to run.");
250                 foreach (getSqls() as $sqls) {
251                         // New cache format...
252                         foreach ($sqls as $sql) {
253                                 // Trim spaces away
254                                 $sql = trim($sql);
255
256                                 // Is there still a query left?
257                                 if (!empty($sql)) {
258                                         // Do we have an "ALTER TABLE" command?
259                                         if (substr(strtolower($sql), 0, 11) == 'alter table') {
260                                                 // Analyse the alteration command
261                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Alterting table: {$sql}");
262                                                 SQL_ALTER_TABLE($sql, __FUNCTION__, __LINE__);
263                                         } else {
264                                                 // Run regular SQL command
265                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Running regular query: {$sql}");
266                                                 SQL_QUERY($sql, __FUNCTION__, __LINE__, false);
267                                         }
268                                 } // END - if
269                         } // END - foreach
270                 } // END - foreach
271         } // END - if
272
273         // Debug message
274         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "- Left!");
275 }
276
277 // Filter for updating/validating login data
278 function FILTER_UPDATE_LOGIN_DATA () {
279         // Add missing array
280         if ((!isset($GLOBALS['last_online'])) || (!is_array($GLOBALS['last_online']))) $GLOBALS['last_online'] = array();
281
282         // Recheck if logged in
283         if (!isMember()) return false;
284
285         // Secure user id
286         setMemberId(getSession('userid'));
287
288         // Found a userid?
289         if (fetchUserData(getMemberId())) {
290                 // Load last module and online time
291                 $content = getUserDataArray();
292
293                 // Maybe first login time?
294                 if (empty($content['last_module'])) $content['last_module'] = 'login';
295
296                 // This will be displayed on welcome page! :-)
297                 if (empty($GLOBALS['last_online']['module'])) {
298                         $GLOBALS['last_online']['module'] = $content['last_module'];
299                         $GLOBALS['last_online']['online'] = $content['last_online'];
300                 } // END - if
301
302                 // 'what' not set?
303                 if (!isWhatSet()) {
304                         // Fix it to default
305                         setWhat('welcome');
306                         if (getConfig('index_home') != '') setWhatFromConfig('index_home');
307                 } // END - if
308
309                 // Update last module / online time
310                 updateLastActivity(getMemberId());
311         }  else {
312                 // Destroy session, we cannot update!
313                 destroyMemberSession();
314         }
315 }
316
317 // Filter for initializing randomizer
318 function FILTER_INIT_RANDOMIZER () {
319         // Only execute this filter if installed
320         if ((!isInstalled()) || (!isExtensionInstalledAndNewer('other', '0.2.5'))) return;
321
322         // Take a prime number which is long (if you know a longer one please try it out!)
323         setConfigEntry('_PRIME', 591623);
324
325         // Calculate "entropy" with the prime number (for code generation)
326         setConfigEntry('_ADD', (getConfig('_PRIME') * getConfig('_PRIME') / (pi() * getConfig('code_length') + 1)));
327
328         // Simply init the randomizer with seed and _ADD value
329         mt_srand(generateSeed() + getConfig('_ADD'));
330 }
331
332 // Filter for removing updates
333 function FILTER_REMOVE_UPDATES ($data) {
334         // Init removal list
335         initExtensionRemovalList();
336
337         // Add the current extension to it
338         addCurrentExtensionToRemovalList();
339
340         // Simply remove it
341         unsetExtensionSqls();
342
343         // Do we need to remove update depency?
344         if (countExtensionUpdateDependencies() > 0) {
345                 // Then find all updates we shall no longer execute
346                 foreach (getExtensionUpdateDependencies() as $id => $ext_name) {
347                         // Shall we remove this update?
348                         if (in_array($ext_name, getExtensionRemovalList())) {
349                                 // Then remove this extension!
350                                 removeExtensionUpdateDependency($ext_name);
351                         } // END - if
352                 } // END - foreach
353         } // END - if
354
355         // Return data
356         return $data;
357 }
358
359 // Determines username for current user state
360 function FILTER_DETERMINE_USERNAME () {
361         // Check if logged in
362         if (isMember()) {
363                 // Is still logged in so we welcome him with his name
364                 if (fetchUserData(getMemberId())) {
365                         // Load surname and family's name and build the username
366                         $content = getUserDataArray();
367
368                         // Prepare username
369                         setUsername($content['surname'] . ' ' . $content['family']);
370
371                         // Additionally admin?
372                         if (isAdmin()) {
373                                 // Add it
374                                 setUsername(getUsername() . ' ({--USERNAME_ADMIN_SHORT--})');
375                         } // END - if
376                 } else {
377                         // Hmmm, logged in and no valid userid?
378                         setUsername('<em>{--USERNAME_UNKNOWN--}</em>');
379
380                         // Destroy session
381                         destroyMemberSession();
382                 }
383         } elseif (isAdmin()) {
384                 // Admin is there
385                 setUsername('{--USERNAME_ADMIN--}');
386         } else {
387                 // He's a guest, hello there... ;-)
388                 setUsername('{--USERNAME_GUEST--}');
389         }
390 }
391
392 // Filter for compiling config entries
393 function FILTER_COMPILE_CONFIG ($code, $compiled = false) {
394         // Save the uncompiled code
395         $uncompiled = $code;
396
397         // Do we have cache?
398         if (!isset($GLOBALS['compiled_config'][$code])) {
399                 // Compile {?some_var?} to getConfig('some_var')
400                 preg_match_all('/\{\?(([a-zA-Z0-9-_]+)*)\?\}/', $code, $matches);
401
402                 // Some entries found?
403                 if ((count($matches) > 0) && (count($matches[0]) > 0)) {
404                         // Replace all matches
405                         foreach ($matches[0] as $key => $match) {
406                                 // Do we have cache?
407                                 if (!isset($GLOBALS['compile_config'][$matches[1][$key]])) {
408                                         // Is the config valid?
409                                         if (isConfigEntrySet($matches[1][$key])) {
410                                                 // Set it for caching
411                                                 $GLOBALS['compile_config'][$matches[1][$key]] = "\" . getConfig('" . $matches[1][$key] . "') . \"";
412                                         } elseif (isConfigEntrySet('default_' . strtoupper($matches[1][$key]))) {
413                                                 // Use default value
414                                                 $GLOBALS['compile_config'][$matches[1][$key]] = "\" . getConfig('" . 'DEFAULT_' . strtoupper($matches[1][$key]) . "') . \"";
415                                         } elseif (isMessageIdValid('DEFAULT_' . strtoupper($matches[1][$key]))) {
416                                                 // No config, try the language system
417                                                 $GLOBALS['compile_config'][$matches[1][$key]] = "\" . getMessage('". 'DEFAULT_' . strtoupper($matches[1][$key]) . "') . \"";
418                                         } else {
419                                                 // Unhandled!
420                                                 $GLOBALS['compile_config'][$matches[1][$key]] = '!' . $matches[1][$key] . '!';
421                                         }
422                                 } // END - if
423
424                                 // Use this for replacing
425                                 $code = str_replace($match, $GLOBALS['compile_config'][$matches[1][$key]], $code);
426                                 //* DEBUG: */ if (($match == '{?URL?}') && (strlen($code) > 10000)) die('<pre>'.secureString($code).'</pre>');
427                         } // END - foreach
428                 } // END - if
429
430                 // Add it to cache
431                 $GLOBALS['compiled_config'][$uncompiled] = $code;
432         } // END - if
433
434         // Should we compile it?
435         if ($compiled === true) {
436                 // Run the code
437                 $eval = "\$GLOBALS['compiled_config'][\$uncompiled] = \"" . $GLOBALS['compiled_config'][$uncompiled] . "\";";
438                 //* DEBUG: */ print('<pre>' . str_replace('$', '&#36;', htmlentities($eval)) . '</pre>');
439                 eval($eval);
440         } // END - if
441
442         // Return compiled code
443         return $GLOBALS['compiled_config'][$uncompiled];
444 }
445
446 // Filter for compiling extension data
447 function FILTER_COMPILE_EXTENSION ($code) {
448         // Compile {%cmd=some_value%} to get extension data
449         // Support cmd is:
450         //   - version -> getExtensionVersion() call
451         preg_match_all('/\{%(([a-zA-Z0-9-_,]+)(=([^\}]+)){0,1})*%\}/', $code, $matches);
452         //* DEBUG: */ print('<pre>'.print_r($matches, true).'</pre>');
453
454         // Default is from OUTPUT_HTML
455         $outputMode = getOutputMode();
456
457         // Some entries found?
458         if ((count($matches) > 0) && (count($matches[3]) > 0)) {
459                 // Replace all matches
460                 foreach ($matches[2] as $key => $cmd) {
461                         // Init replacer/call-back variable
462                         $replacer = '';
463                         $callback = '';
464                         $extraFunction = '';
465
466                         // Extract command and call-back
467                         $cmdArray = explode(',', $cmd);
468                         $cmd = $cmdArray[0];
469                         if (isset($cmdArray[1])) $callback = $cmdArray[1];
470                         if (isset($cmdArray[2])) $extraFunction = $cmdArray[2];
471
472                         // Is the extension installed or code provided?
473                         // @TODO This whole switch-block is very static
474                         switch ($cmd) {
475                                 case 'code': // Code asked for
476                                         $code = str_replace($matches[0][$key], "\" . getCode('" . $matches[4][$key] . "') . \"", $code);
477                                         break;
478
479                                 case 'url':
480                                         // Do we have JS-mode?
481                                         if (substr($cmd, -2, 2) == 'js') $outputMode = 1;
482
483                                         // Handle an URL here
484                                         $replacer = "\" . encodeUrl(\"" . $matches[4][$key] . "\", " . $outputMode . ") . \"";
485
486                                         // Replace it
487                                         $code = str_replace($matches[0][$key], $replacer, $code);
488                                         break;
489
490                                 case 'server':
491                                         // This will make 'foo_bar' to detectFooBar()
492                                         $functionName = "'detect' . implode('', array_map('ucfirst', explode('_', '" . $callback . "')))";
493
494                                         // Replace it
495                                         $code = str_replace($matches[0][$key], "\" . call_user_func(" . $functionName . ") . \"", $code);
496                                         break;
497
498                                 case 'user':
499                                         // Use current userid by default
500                                         $functionName = 'getMemberId()';
501
502                                         // User-related data, so is there a userid?
503                                         if (!empty($matches[4][$key])) {
504                                                 // Do we have a userid or $userid?
505                                                 if ($matches[4][$key] == '$userid') {
506                                                         // Use dynamic call
507                                                         $functionName = "getFetchedUserData('userid', \$userid, '" . $callback . "')";
508                                                 } elseif ($matches[4][$key] > 0) {
509                                                         // User data found
510                                                         $functionName = "getFetchedUserData('userid', " . $matches[4][$key] . ", " . $callback . "')";
511                                                 } // END - if
512                                         } elseif ((!empty($callback)) && (isUserDataValid())) {
513                                                 // "Call-back" alias column for current logged in user's data
514                                                 $functionName = "getUserData('" . $callback . "')";
515                                         }
516
517                                         // Do we have another function to run (e.g. translations)
518                                         if (!empty($extraFunction)) {
519                                                 // Surround the original function call with it
520                                                 $functionName = $extraFunction . '(' . $functionName . ')';
521                                         } // END - if
522
523                                         // Now replace the code
524                                         $code = str_replace($matches[0][$key], "\" . " . $functionName . " . \"", $code);
525                                         break;
526
527                                 case 'ext':
528                                         // Not installed is default
529                                         $replacer = 'false';
530
531                                         // Is the extension installed?
532                                         if (isExtensionInstalled($matches[4][$key])) {
533                                                 // Construct call-back function name
534                                                 $functionName = 'getExtension' . ucfirst(strtolower($callback));
535
536                                                 // Construct call of the function
537                                                 $replacer = "\" . call_user_func_array('" . $functionName . "', array('" . $matches[4][$key] . "', true)) . \"";
538                                         } // END - if
539
540                                         // Replace it and insert parameter for GET request
541                                         $code = str_replace($matches[0][$key], sprintf("&amp;ext=%s&amp;ver=%s&amp;rev=\" . getConfig('CURR_SVN_REVISION') . \"", $matches[4][$key], $replacer), $code);
542                                         break;
543
544                                 case 'config': // @TODO FILTER_COMPILE_CONFIG does not handle call-back functions so we handle it here again
545                                         // Read configuration
546                                         $configValue = getConfig($matches[4][$key]);
547
548                                         // Do we have a call-back?
549                                         if (!empty($callback)) {
550                                                 // Parse it through this function
551                                                 $configValue = call_user_func_array($callback, array($configValue));
552                                         } // END - if
553
554                                         // Replace the config entry
555                                         $code = str_replace($matches[0][$key], $configValue, $code);
556                                         break;
557
558                                 default:
559                                         // Unsupported command detected
560                                         debug_report_bug('Command=' . $cmd . ', callback=' . $callback . ', extra=' . $extraFunction . ' is unsupported.');
561                                         break;
562                         } // END - switch
563                 } // END - foreach
564         } // END - if
565
566         // Do we have non-HTML mode?
567         if ((getOutputMode() != '0') || ($outputMode != '0')) $code = decodeEntities($code);
568
569         // Return compiled code
570         //* DEBUG: */ die('<pre>'.htmlentities($code).'</pre>');
571         return $code;
572 }
573
574 // Runs some generic filter update steps
575 function FILTER_UPDATE_EXTENSION_DATA ($ext_name) {
576         // Create task
577         createExtensionUpdateTask(getCurrentAdminId(), $ext_name, $GLOBALS['update_ver'][$ext_name], SQL_ESCAPE(getExtensionNotes(getExtensionNotes())));
578
579         // Update extension's version
580         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_version`='%s' WHERE `ext_name`='%s' LIMIT 1",
581                 array($GLOBALS['update_ver'][$ext_name], $ext_name), __FUNCTION__, __LINE__);
582
583         // Remove arrays
584         unsetSqls();
585         unset($GLOBALS['update_ver'][$ext_name]);
586 }
587
588 // Load more reset scripts
589 function FILTER_RUN_RESET_INCLUDES () {
590         // Is the reset set or old sql_patches?
591         if (((!isResetModeEnabled()) || (!isExtensionInstalled('sql_patches'))) && (getOutputMode() == '0')) {
592                 // Then abort here
593                 debug_report_bug('Cannot run reset! enabled='.intval(isResetModeEnabled()).',ext='.intval(isExtensionInstalled('sql_patches')).' Please report this bug. Thanks');
594         } // END - if
595
596         // Get more daily reset scripts
597         setIncludePool('reset', getArrayFromDirectory('inc/reset/', 'reset_'));
598
599         // Update database
600         if ((!isConfigEntrySet('DEBUG_RESET')) || (getConfig('DEBUG_RESET') != 'Y')) updateConfiguration('last_update', 'UNIX_TIMESTAMP()');
601
602         // Is the config entry set?
603         if (isExtensionInstalledAndNewer('sql_patches', '0.4.2')) {
604                 // Create current week mark
605                 $currWeek = date('W', time());
606
607                 // Has it changed?
608                 if ((getConfig('last_week') != $currWeek) || (getConfig('DEBUG_WEEKLY') == 'Y')) {
609                         // Include weekly reset scripts
610                         mergeIncludePool('reset', getArrayFromDirectory('inc/weekly/', 'weekly_'));
611
612                         // Update config
613                         if ((isConfigEntrySet('DEBUG_WEEKLY')) && (getConfig('DEBUG_WEEKLY') != 'Y')) updateConfiguration('last_week', $currWeek);
614                 } // END - if
615
616                 // Create current month mark
617                 $currMonth = date('m', time());
618
619                 // Has it changed?
620                 if ((getConfig('last_month') != $currMonth) || (getConfig('DEBUG_MONTHLY') == 'Y')) {
621                         // Include monthly reset scripts
622                         mergeIncludePool('reset', getArrayFromDirectory('inc/monthly/', 'monthly_'));
623
624                         // Update config
625                         if ((isConfigEntrySet('DEBUG_MONTHLY')) && (getConfig('DEBUG_MONTHLY') != 'Y')) updateConfiguration('last_month', $currMonth);
626                 } // END - if
627         } // END - if
628
629         // Run the filter
630         runFilterChain('load_includes', 'reset');
631 }
632
633 // Filter for removing the given extension
634 function FILTER_REMOVE_EXTENSION () {
635         // Delete this extension (remember to remove it from your server *before* you click on welcome!
636         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
637                 array(getCurrentExtensionName()), __FUNCTION__, __LINE__);
638
639         // Remove the extension from global cache array as well
640         removeExtensionFromArray();
641
642         // Remove the cache
643         rebuildCacheFile('extension', 'extension');
644 }
645
646 // Filter for flushing the output
647 function FILTER_FLUSH_OUTPUT () {
648         // Simple, he?
649         outputHtml('');
650 }
651
652 // Prepares an SQL statement part for HTML mail and/or holiday depency
653 function FILTER_HTML_INCLUDE_USERS ($mode) {
654         // Exclude no users by default
655         $MORE = '';
656
657         // HTML mail?
658         if ($mode == 'html') $MORE = " AND `html`='Y'";
659         if ((isExtensionActive('holiday')) && (getExtensionVersion('holiday') >= '0.1.3')) {
660                 // Add something for the holiday extension
661                 $MORE .= " AND `holiday_active`='N'";
662         } // END - if
663
664         // Return result
665         return $MORE;
666 }
667
668 // Filter for determining what/action/module
669 function FILTER_DETERMINE_WHAT_ACTION () {
670         // In installation phase we don't have what/action
671         if (isInstallationPhase()) {
672                 // Set both to empty
673                 setAction('');
674                 setWhat('');
675
676                 // Abort here
677                 return;
678         } // END - if
679
680         // Get all values
681         if ((getOutputMode() != 1) && (getOutputMode() != -1)) {
682                 // Fix module
683                 if (!isModuleSet()) {
684                         // Is the request element set?
685                         if (isGetRequestElementSet('module')) {
686                                 // Set module from request
687                                 setModule(getRequestElement('module'));
688                         } elseif (getOutputMode() == '0') {
689                                 // Set default module 'index'
690                                 setModule('index');
691                         } else {
692                                 // Unknown module
693                                 setModule('unknown');
694                         }
695                 } // END - if
696
697                 // Fix 'what' if not yet set
698                 if (!isWhatSet())   setWhat(getWhatFromModule(getModule()));
699
700                 // Fix 'action' if not yet set
701                 if (!isActionSet()) setAction(getModeAction(getModule(), getWhat()));
702         } else {
703                 // Set action/what to empty
704                 setAction('');
705                 setWhat('');
706         }
707
708         // Set default 'what' value
709         //* DEBUG: */ outputHtml('-'.getModule().'/'.getWhat()."-<br />");
710         if ((!isWhatSet()) && (!isActionSet()) && (getOutputMode() != 1) && (getOutputMode() != -1)) {
711                 if (getModule() == 'admin') {
712                         // Set 'action' value to 'login' in admin menu
713                         setAction(getModeAction(getModule(), getWhat()));
714                 } elseif ((getModule() == 'index') || (getModule() == 'login')) {
715                         // Set 'what' value to 'welcome' in guest and member menu
716                         setWhatFromConfig('index_home');
717                 } else {
718                         // Anything else like begging link
719                         setWhat('');
720                 }
721         } // END - if
722 }
723
724 // Sends out pooled mails
725 function FILTER_TRIGGER_SENDING_POOL () {
726         // Are we in normal output mode?
727         if (getOutputMode() != 0) {
728                 // Only in normal output mode to prevent race-conditons!
729         } // END - if
730
731         // Init counter
732         $GLOBALS['pool_cnt'] = '0';
733
734         // Init & set the include pool
735         initIncludePool('pool');
736         setIncludePool('pool', getArrayFromDirectory('inc/pool/', 'pool-'));
737
738         // Run the filter
739         runFilterChain('load_includes', 'pool');
740
741         // Remove the counter
742         unset($GLOBALS['pool_cnt']);
743 }
744
745 // Filter for checking and updating SVN revision
746 function FILTER_CHECK_SVN_REVISION () {
747         // Only execute this filter if installed and all config entries are there
748         if ((!isInstalled()) || (!isConfigEntrySet('patch_level'))) return;
749
750         // Check for patch level differences between databases and current hard-coded
751         if ((getConfig('CURR_SVN_REVISION') > getConfig('patch_level')) || (getConfig('patch_level') == 'CURR_SVN_REVISION') || (getConfig('patch_ctime') == 'UNIX_TIMES')) {
752                 // Update database and CONFIG array
753                 updateConfiguration(array('patch_level', 'patch_ctime'), array(getConfig('CURR_SVN_REVISION'), 'UNIX_TIMESTAMP()'));
754                 setConfigEntry('patch_level', getConfig('CURR_SVN_REVISION'));
755                 setConfigEntry('patch_ctime', time());
756         } // END - if
757 }
758
759 // Filter for running daily reset
760 function FILTER_RUN_DAILY_RESET () {
761         // Only execute this filter if installed
762         if ((isInstallationPhase()) || (!isInstalled()) || (!isAdminRegistered()) || (!isExtensionInstalled('sql_patches'))) return;
763
764         // Shall we run the reset scripts? If a day has changed, maybe also a week/month has changed... Simple! :D
765         if (((date('d', getConfig('last_update')) != date('d', time())) || ((isConfigEntrySet('DEBUG_RESET')) && (getConfig('DEBUG_RESET') == 'Y'))) && (!isInstallationPhase()) && (isAdminRegistered()) && (!isGetRequestElementSet('register')) && (getOutputMode() != 1)) {
766                 // Tell every module we are in reset-mode!
767                 doReset();
768         } // END - if
769 }
770
771 // Filter for loading more runtime includes (not for installation)
772 function FILTER_LOAD_RUNTIME_INCLUDES () {
773         // Load more includes
774         foreach (array('inc/databases.php','inc/session.php','inc/versions.php') as $inc) {
775                 // Load the include
776                 loadIncludeOnce($inc);
777         } // END - foreach
778
779         // Load admin include file if he is admin
780         if (isAdmin()) {
781                 // Administrative functions
782                 loadIncludeOnce('inc/modules/admin/admin-inc.php');
783         } // END - if
784         //* DEBUG: */ addPointsThroughReferalSystem('test', 36, 1000);
785         //* DEBUG: */ die();
786 }
787
788 // Filter for checking admin ACL
789 function FILTER_CHECK_ADMIN_ACL () {
790         // Extension not installed so it's always allowed to access everywhere!
791         $ret = true;
792
793         // Ok, Cookie-Update done
794         if ((isExtensionInstalledAndNewer('admins', '0.3.0')) && (isExtensionActive('admins'))) {
795                 // Check if action GET variable was set
796                 $action = getAction();
797                 if (isWhatSet()) {
798                         // Get action value by what-value
799                         $action = getModeAction('admin', getWhat());
800                 } // END - if
801
802                 // Check for access control line of current menu entry
803                 $ret = adminsCheckAdminAcl($action, getWhat());
804         } // END - if
805
806         // Set it here
807         $GLOBALS['acl_allow'] = $ret;
808 }
809
810 // Init random number/cache buster
811 function FILTER_INIT_RANDOM_NUMBER () {
812         // Is the extension sql_patches installed and at least 0.3.6?
813         if ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && (isExtensionInstalledAndNewer('other', '0.2.5'))) {
814                 // Generate random number
815                 setConfigEntry('RAND_NUMBER', generateRandomCode(10, mt_rand(10000, 32766), getMemberId(), ''));
816         } else {
817                 // Generate weak (!!!) code
818                 setConfigEntry('RAND_NUMBER', mt_rand(1000000, 9999999));
819         }
820
821         // Copy it to CACHE_BUSTER
822         setConfigEntry('CACHE_BUSTER', getConfig('RAND_NUMBER'));
823 }
824
825 // Update module counter
826 function FILTER_COUNT_MODULE () {
827         // Do count all other modules but not accesses on CSS file css.php!
828         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_mod_reg` SET `clicks`=`clicks`+1 WHERE `module`='%s' LIMIT 1",
829                 array(getModule()), __FUNCTION__, __LINE__);
830 }
831
832 // Handles fatal errors
833 function FILTER_HANDLE_FATAL_ERRORS () {
834         // Do we have errors to handle and right output mode?
835         if ((getTotalFatalErrors() == '0') || (getOutputMode() != 0)) {
836                 // Abort executing here
837                 return false;
838         } // END - if
839
840         // Set content type
841         setContentType('text/html');
842
843         // Load config here
844         loadIncludeOnce('inc/load_config.php');
845
846         // Set unset variable
847         if (empty($check)) $check = '';
848
849         // Default is none
850         $content = '';
851
852         // Installation phase or regular mode?
853         if ((isInstallationPhase())) {
854                 // While we are installing ouput other header than while it is installed... :-)
855                 $OUT = '';
856                 foreach (getFatalArray() as $key => $value) {
857                         // Prepare content for the template
858                         $content = array(
859                                 'key'   => ($key + 1),
860                                 'value' => $value
861                         );
862
863                         // Load row template
864                         $OUT .= loadTemplate('install_fatal_row', true, $content);
865                 }
866
867                 // Load main template
868                 $content = loadTemplate('install_fatal_table', true, $OUT);
869         } elseif (isInstalled()) {
870                 // Display all runtime fatal errors
871                 $OUT = '';
872                 foreach (getFatalArray() as $key => $value) {
873                         // Prepare content for the template
874                         $content = array(
875                                 'key'   => ($key + 1),
876                                 'value' => $value
877                         );
878
879                         // Load row template
880                         $OUT .= loadTemplate('runtime_fatal_row', true, $content);
881                 }
882
883                 // Load main template
884                 $content = loadTemplate('runtime_fatal_table', true, $OUT);
885         }
886
887         // Message to regular users (non-admin)
888         $CORR = getMessage('FATAL_REPORT_ERRORS');
889
890         // PHP warnings fixed
891         if ($check == 'done') {
892                 if (isAdmin()) $CORR = getMessage('FATAL_CORRECT_ERRORS');
893         } // END - if
894
895         // Remember all in array
896         $content = array(
897                 'rows' => $content,
898                 'corr' => $CORR
899         );
900
901         // Load footer
902         loadIncludeOnce('inc/header.php');
903
904         // Load main template
905         loadTemplate('fatal_errors', false, $content);
906
907         // Delete all to prevent double-display
908         initFatalMessages();
909
910         // Load footer
911         loadIncludeOnce('inc/footer.php');
912
913         // Abort here
914         shutdown();
915 }
916
917 // Filter for displaying copyright line
918 function FILTER_DISPLAY_COPYRIGHT () {
919         // Shall we display the copyright notice?
920         if ((!isGetRequestElementSet('frame')) && (basename($_SERVER['PHP_SELF']) != 'mailid_top.php') && ((getConfig('WRITE_FOOTER') == 'Y') || (isInstalling())) && ($GLOBALS['header_sent'] == 2)) {
921                 // Backlink enabled?
922                 if (((isConfigEntrySet('ENABLE_BACKLINK')) && (getConfig('ENABLE_BACKLINK') == 'Y')) || (isInstalling())) {
923                         // Copyright with backlink, thanks! :-)
924                         loadTemplate('copyright_backlink');
925                 } else {
926                         // No backlink in Copyright note
927                         loadTemplate('copyright');
928                 }
929         } // END - if
930 }
931
932 // Filter for displaying parsing time
933 function FILTER_DISPLAY_PARSING_TIME () {
934         // Shall we display the parsing time and number of queries?
935         // 1234                            5                      54    4         5              5       4    4                       5       543    3                   4432    2             33     2    2                              21
936         if ((((isExtensionInstalledAndNewer('sql_patches', '0.4.1')) && (getConfig('show_timings') == 'Y') && (!isGetRequestElementSet('frame'))) || (isInstallationPhase())) && (getOutputMode() == '0') && ($GLOBALS['header_sent'] == 2)) {
937                 // Then display it here
938                 displayParsingTime();
939         } // END - if
940 }
941
942 // Filter for flushing template cache
943 function FILTER_FLUSH_TEMPLATE_CACHE () {
944         // Do not flush when debugging the template cache
945         if (isDebuggingTemplateCache()) return;
946
947         // Do we have cached eval() data?
948         if ((isset($GLOBALS['template_eval'])) && (count($GLOBALS['template_eval']) > 0)) {
949                 // Now flush all
950                 foreach ($GLOBALS['template_eval'] as $template => $eval) {
951                         // Flush the cache (if not yet found)
952                         flushTemplateCache($template, $eval);
953                 } // END - if
954         } // END - if
955 }
956
957 // Filter for loading user data
958 function FILTER_FETCH_USER_DATA ($userid = 0) {
959         // Is the userid not set? Then use member id
960         if (($userid == '0') || (is_null($userid))) $userid = getMemberId();
961
962         // Get user data
963         if (!fetchUserData($userid)) {
964                 // Userid is not valid
965                 debug_report_bug('User id '.$userid . ' is invalid.');
966         } // END - if
967
968         // Set member id
969         setMemberId($userid);
970 }
971
972 // Filter for reseting users' last login failure, only available with latest ext-sql_patches
973 function FILTER_RESET_USER_LOGIN_FAILURE () {
974         // Is the user data valid?
975         if (!isMember()) {
976                 // Do only run for logged in members
977                 debug_report_bug('Please only run this filter for logged in users.');
978         } // END - if
979
980         // Remmeber login failures if available
981         if (isExtensionInstalledAndNewer('sql_patches', '0.6.1')) {
982                 // Reset login failures
983                 SQL_QUERY_ESC("UPDATE
984         `{?_MYSQL_PREFIX?}_user_data`
985 SET
986         `login_failures`=0,
987         `last_failure`='0000-00-00 00:00:00'
988 WHERE
989         `userid`=%s
990 LIMIT 1",
991                         array(getMemberId()), __FILE__, __LINE__);
992
993                 // Store it in session
994                 setSession('mxchange_member_failures' , getUserData('login_failures'));
995                 setSession('mxchange_member_last_fail', getUserData('last_failure'));
996         } // END - if
997 }
998
999 // [EOF]
1000 ?>