2aab347cb82b7ead98fe349cccb3ad24b298706b
[mailer.git] / inc / extensions-functions.php
1 <?php
2 /************************************************************************
3  * Mailer v0.2.1-FINAL                                Start: 10/25/2009 *
4  * ===================                          Last change: 10/25/2009 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : extensions-functions.php                         *
8  * -------------------------------------------------------------------- *
9  * Short description : Extension management                             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Erweiterungen-Management                         *
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  * Copyright (c) 2009, 2010 by Mailer Developer Team                    *
22  * For more information visit: http://www.mxchange.org                  *
23  *                                                                      *
24  * This program is free software; you can redistribute it and/or modify *
25  * it under the terms of the GNU General Public License as published by *
26  * the Free Software Foundation; either version 2 of the License, or    *
27  * (at your option) any later version.                                  *
28  *                                                                      *
29  * This program is distributed in the hope that it will be useful,      *
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
32  * GNU General Public License for more details.                         *
33  *                                                                      *
34  * You should have received a copy of the GNU General Public License    *
35  * along with this program; if not, write to the Free Software          *
36  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
37  * MA  02110-1301  USA                                                  *
38  ************************************************************************/
39
40 // Some security stuff...
41 if (!defined('__SECURITY')) {
42         die();
43 } // END - if
44
45 // Load the extension and maybe found language and function files.
46 function loadExtension ($ext_name, $ext_mode = 'init', $ext_ver = '', $dry_run = false) {
47         // If this happens twice, we need the bug report from you, except for updates/tests
48         if ((isset($GLOBALS['loaded_extension'][$ext_name][$ext_mode])) && (!in_array($ext_mode, array('update', 'test')))) {
49                 debug_report_bug(__FUNCTION__, __LINE__, '() is called twice: ext_name=' . $ext_name . ', ext_mode='. $ext_mode . ',ext_sqls=' . print_r(getExtensionSqls(), true) . ', ext_register_running=' . print_r($GLOBALS['ext_register_running'], true) . ', ext_running_updates=' . print_r($GLOBALS['ext_running_updates'], true));
50         } // END - if
51
52         // Make sure this situation can only happen once
53         $GLOBALS['loaded_extension'][$ext_name][$ext_mode] = true;
54
55         // Set extension mode
56         setExtensionMode($ext_mode);
57
58         // Set current extension name
59         setCurrentExtensionName($ext_name);
60
61         if (!empty($ext_ver)) {
62                 // Set current extension version
63                 setCurrentExtensionVersion($ext_ver);
64         } else {
65                 // Set it to 0.0
66                 setCurrentExtensionVersion('0.0');
67
68                 // In all but test-mode we need these messages to debug! Please report all (together, e.g.)
69                 if ($ext_mode != 'test') {
70                         // Log empty versions not in test-mode, but maybe it is fine...
71                         logDebugMessage(__FUNCTION__, __LINE__, 'Extension version is empty, setting to 0.0. ext_name=' . $ext_name . ', ext_mode=' . $ext_mode . ', dry_run=' . intval($dry_run));
72                 } // END - if
73         }
74
75         // Set dry-run
76         enableExtensionDryRun($dry_run);
77
78         // Init array
79         initIncludePool('extension');
80
81         // Init EXT_UPDATE_DEPENDS if not yet done
82         if (!isExtensionUpdateDependenciesInitialized()) {
83                 // Init here...
84                 initExtensionUpdateDependencies();
85         } // END - if
86
87         // Init current extension name list
88         initExtensionSqls();
89
90         // Is the extension already loaded?
91         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Loading extension ' . $ext_name . ', mode=' . getExtensionMode() . ', ver=' . getCurrentExtensionVersion());
92         if ((isset($GLOBALS['ext_loaded']['ext'][$ext_name])) && (getExtensionMode() == 'init')) {
93                 // Debug message
94                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension %s already loaded.", $ext_name));
95
96                 // Abort here
97                 return false;
98         } // END - if
99
100         // Is the extension file NOT there?
101         if (!isExtensionNameValid($ext_name)) {
102                 // Debug message
103                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension %s not found or not readable.", $ext_name));
104
105                 // Abort here
106                 return false;
107         } // END - if
108
109         // Load extension's own language file if not in test mode
110         if ((getExtensionMode() != 'test') && (ifExtensionHasLanguageFile($ext_name))) {
111                 // Load it
112                 loadLanguageFile($ext_name);
113         } // END - if
114
115         // Do we have cache?
116         if (isExtensionFunctionFileReadable($ext_name)) {
117                 // Not yet loaded?
118                 if ((($GLOBALS['cache_array']['extension']['ext_func'][$ext_name] == 'Y') || (!isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name]))) && (!isset($GLOBALS['ext_loaded']['funcs'][$ext_name]))) {
119                         // Construct FQFN for functions file
120                         $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
121
122                         // Mark it as loaded
123                         $GLOBALS['ext_loaded']['funcs'][$ext_name] = true;
124
125                         // Download functions file
126                         loadIncludeOnce($funcsInclude);
127                 } // END - if
128         } elseif ((!isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name])) && (isDebugModeEnabled()) && (getOutputMode() == '0') && ($ext_name != 'sql_patches') && (substr($ext_name, 0, 10) != 'admintheme') && (getExtensionMode() == 'test')) {
129                 // No functions file is not so good...
130                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("NOTICE: Extension %s has no own functions file or we cannot read from it. mode=%s",
131                         $ext_name,
132                         getExtensionMode()
133                 ));
134         }
135
136         // Extensions are not deprecated by default
137         setExtensionDeprecated('N');
138
139         // Extensions are not always active by default
140         setExtensionAlwaysActive('N');
141
142         // Extension update notes
143         // @TODO Do we still need this? setExtensionUpdateNotes('');
144
145         // Include the extension file
146         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Extension loaded.');
147         loadExtensionInclude();
148
149         // Is this extension deprecated?
150         if (isExtensionDeprecated()) {
151                 // Deactivate the extension
152                 doDeactivateExtension($ext_name);
153
154                 // Abort here
155                 return false;
156         } // END - if
157
158         // Mark it as loaded in normal mode
159         if (getExtensionMode() == '') {
160                 // Mark it now...
161                 $GLOBALS['ext_loaded']['ext'][$ext_name] = true;
162         } // END - if
163
164         // All fine!
165         return true;
166 }
167
168 // Registeres an extension and possible update depencies
169 function registerExtension ($ext_name, $taskId, $dry_run = false, $logout = true) {
170         // Set current extension name
171         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',task_id=' . $taskId . ',dry_run=' . intval($dry_run) . ',logout=' . intval($logout) . ' - ENTERED!');
172         setCurrentExtensionName($ext_name);
173
174         // Enable dry-run
175         enableExtensionDryRun($dry_run);
176
177         // By default all extensions are in productive phase
178         enableExtensionProductive();
179
180         // This shall never do a non-admin user or if the extension is active (already installed)
181         if ((!isAdmin()) || (isExtensionInstalled($ext_name))) {
182                 // Abort here with 'false'
183                 return false;
184         } // END - if
185
186         // When this extension is already in registration/update phase, all is fine
187         if ((isExtensionRegistrationRunning($ext_name)) || (isExtensionUpdateRunning($ext_name))) {
188                 // Then abort here with 'true' becaus it is fine
189                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - ALREADY!');
190                 return true;
191         } // END - if
192
193         // This registration is running
194         addExtensionRunningRegistration($ext_name);
195
196         // Init EXT_UPDATE_DEPENDS if not yet done
197         if (!isExtensionUpdateDependenciesInitialized()) {
198                 // Init here...
199                 initExtensionUpdateDependencies();
200         } // END - if
201
202         // Is the task id zero? Then we need to auto-fix it here
203         if ($taskId == '0') {
204                 // Try to find the task
205                 $taskId = determineExtensionTaskId(getCurrentExtensionName());
206
207                 // Still zero and not in dry-run?
208                 if (($taskId == '0') && (!isExtensionDryRun())) {
209                         // Now try to create a new task
210                         $taskId = createNewExtensionTask(getCurrentExtensionName());
211
212                         // Is it still zero?
213                         if ($taskId == '0') {
214                                 // Then request a bug report
215                                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("%s: task_id is still zero after determineExtensionTaskId(%s)",
216                                         __FUNCTION__,
217                                         getCurrentExtensionName()
218                                 ));
219                         } // END - if
220                 } // END - if
221         } // END - if
222
223         // Init queries and notes
224         initExtensionSqls();
225         initExtensionNotes();
226
227         // Init variables
228         $ret = false;
229         $test = false;
230         initIncludePool('extension');
231
232         // By default we have no failures
233         setExtensionReportsFailure(false);
234
235         // Does this extension exists?
236         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
237         if (loadExtension(getCurrentExtensionName(), 'register', '', isExtensionDryRun())) {
238                 // Set current extension name again
239                 setCurrentExtensionName($ext_name);
240
241                 // And run possible updates
242                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName());
243                 $history = getExtensionVersionHistory();
244                 foreach ($history as $ver) {
245                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver=' . $ver);
246                         // Load extension in update mode
247                         loadExtension(getCurrentExtensionName(), 'update', $ver, isExtensionDryRun());
248
249                         // Add update notes to our output
250                         addExtensionNotes($ver);
251                 } // END - foreach
252
253                 // Does this extension depends on an outstanding update of another update?
254                 for ($dmy = getExtensionUpdateIterator(); getExtensionUpdateIterator() < countExtensionUpdateDependencies();) {
255                         // Get next update
256                         $ext_update = getExtensionUpdateDependenciesIterator();
257
258                         // Increment here to avoid endless loop
259                         incrementExtensionUpdateIterator();
260
261                         // Check if extension is not installed and not already in registration procedure and if loading it wents finally fine...
262                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',isExtensionRegistrationRunning(' . $ext_update . ')=' . intval(isExtensionRegistrationRunning($ext_update)));
263                         if ((!isExtensionInstalled($ext_update)) && (!isExtensionRegistrationRunning($ext_update)) && (loadExtension($ext_update, 'test', '', isExtensionDryRun()))) {
264                                 // Set current extension name again
265                                 setCurrentExtensionName($ext_name);
266
267                                 // If versions mismatch update extension first
268                                 $ext_ver = '';
269                                 if (isExtensionInstalled($ext_update)) {
270                                         // Get version only if installed
271                                         $ext_ver = getExtensionVersion($ext_update);
272                                 } // END - if
273
274                                 // Extension version set? If empty the extension is not registered
275                                 if (empty($ext_ver)) {
276                                         // Extension not registered so far so first load task's id...
277                                         $task = determineExtensionTaskId($ext_update);
278
279                                         // Entry found?
280                                         if ($task > 0) {
281                                                 // Try to register the extension
282                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ':ext_update=' . $ext_update . ',taskId=' . $task);
283                                                 $test = registerExtension($ext_update, $task, isExtensionDryRun(), false);
284
285                                                 // Reset extension name
286                                                 setCurrentExtensionName($ext_name);
287                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
288                                                 //* DEBUG: */ debugOutput(getCurrentExtensionName().':<pre>' . print_r($test, true) . '</pre>');
289                                         } // END - if
290                                 } elseif ($ext_ver != getCurrentExtensionVersion()) {
291                                         // Ok, update this extension now
292                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ',currVer=' . getCurrentExtensionVersion());
293                                         $GLOBALS['ext_backup_name'][$ext_update][$ext_ver] = getCurrentExtensionName();
294                                         $GLOBALS['ext_backup_ver'][$ext_update][$ext_ver] = getCurrentExtensionVersion();
295                                         updateExtension($ext_update, $ext_ver, isExtensionDryRun());
296                                         setCurrentExtensionName($GLOBALS['ext_backup_name'][$ext_update][$ext_ver]);
297                                         setCurrentExtensionVersion($GLOBALS['ext_backup_ver'][$ext_update][$ext_ver]);
298                                         unset($GLOBALS['ext_backup_name'][$ext_update][$ext_ver]);
299                                         unset($GLOBALS['ext_backup_ver'][$ext_update][$ext_ver]);
300                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ',currVer=' . getCurrentExtensionVersion());
301
302                                         // All okay!
303                                         $test = true;
304                                 } else {
305                                         // Nothing to register / update before...
306                                         $test = true;
307                                 }
308                         } else {
309                                 // Required file for update does not exists!
310                                 $test = true;
311                                 // But this is fine for the first time...
312                         }
313
314                         // Restore the current extension name
315                         setCurrentExtensionName($ext_name);
316                 } // END - for
317
318                 // Is there no update?
319                 if (countExtensionUpdateDependencies(getCurrentExtensionName()) == 0) {
320                         // Then test is passed!
321                         $test = true;
322                 } // END - if
323
324                 // Switch back to register mode
325                 setExtensionMode('register');
326
327                 // Remains true if extension registration reports no failures
328                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
329                 //* DEBUG: */ debugOutput(getCurrentExtensionName().':<pre>' . print_r($test, true) . '</pre>');
330                 $test = (($test === true) && (getExtensionReportsFailure() === false));
331                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
332                 //* DEBUG: */ debugOutput(getCurrentExtensionName().':<pre>' . print_r($test, true) . '</pre>');
333
334                 // Does everthing before wents ok?
335                 if ($test === true) {
336                         // "Dry-run-mode" activated?
337                         if ((isExtensionDryRun() === false) && (!isExtensionOnRemovalList())) {
338                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName());
339                                 // Init SQLs and transfer ext->generic
340                                 initSqls();
341                                 setSqlsArray(getExtensionSqls());
342
343                                 // Run installation pre-installation filters
344                                 runFilterChain('pre_extension_installed', array('dry_run' => isExtensionDryRun()));
345
346                                 // Register extension
347                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'insert=' . getCurrentExtensionName() . '/' . getCurrentExtensionVersion() . ' - INSERT!');
348                                 if (isExtensionInstalledAndNewer('sql_patches', '0.0.6')) {
349                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ',always_active=' . getExtensionAlwaysActive() . ', ext_ver=' . getCurrentExtensionVersion() . 'ext_css=' . getExtensionHasCss());
350                                         // New way, with CSS
351                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_extensions` (`ext_name`, `ext_active`, `ext_version`,`ext_has_css`) VALUES ('%s','%s','%s','%s')",
352                                                 array(
353                                                         getCurrentExtensionName(),
354                                                         getExtensionAlwaysActive(),
355                                                         getCurrentExtensionVersion(),
356                                                         getExtensionHasCss()
357                                                 ), __FUNCTION__, __LINE__);
358                                 } else {
359                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ',always_active=' . getExtensionAlwaysActive() . ', ext_ver=' . getCurrentExtensionVersion());
360                                         // Old way, no CSS
361                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_extensions` (`ext_name`, `ext_active`, `ext_version`) VALUES ('%s','%s','%s')",
362                                                 array(
363                                                         getCurrentExtensionName(),
364                                                         getExtensionAlwaysActive(),
365                                                         getCurrentExtensionVersion()
366                                                 ), __FUNCTION__, __LINE__);
367                                 }
368
369                                 // Remove cache file(s) if extension is active
370                                 runFilterChain('post_extension_installed', array(
371                                         'pool'     => 'extension',
372                                         'ext_name' => getCurrentExtensionName(),
373                                         'task_id'  => $taskId
374                                 ));
375
376                                 // Re-init queries and notes
377                                 initExtensionSqls(true);
378                                 initExtensionNotes();
379
380                                 // Mark it as installed
381                                 $GLOBALS['ext_is_installed'][getCurrentExtensionName()] = true;
382
383                                 // In normal mode return a true on success
384                                 $ret = true;
385                         } elseif (isExtensionDryRun() === true) {
386                                 // In  "dry-run" mode do always return a true
387                                 $ret = true;
388
389                                 // Re-init queries and notes
390                                 initExtensionNotes();
391                         } else {
392                                 // Extension has been removed for updates, so all is fine!
393                                 $ret = true;
394                         }
395                 } else {
396                         // No, an error occurs while registering extension :-(
397                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName());
398                         $ret = false;
399                 }
400         } elseif (($taskId > 0) && (getCurrentExtensionName() != '')) {
401                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
402                 // Remove task from system when id and extension's name is valid
403                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `id`=%s AND `status`='NEW' LIMIT 1",
404                         array(bigintval($taskId)), __FUNCTION__, __LINE__);
405         }
406
407         // Is this the sql_patches?
408         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . '/' . getExtensionMode());
409         if ((getCurrentExtensionName() == 'sql_patches') && ((getExtensionMode() == 'register') || (getExtensionMode() == 'remove')) && (!isExtensionDryRun()) && ($test)) {
410                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ': LOAD!');
411                 if ($logout === true) {
412                         // Then redirect to logout
413                         redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . getExtensionMode() . '=sql_patches');
414                 } else {
415                         // Add temporary filter
416                         registerFilter('shutdown', 'REDIRECT_TO_LOGOUT_SQL_PATCHES', true, true);
417                         $GLOBALS['ext_load_mode'] = getExtensionMode();
418                 }
419         } // END - if
420
421         // Return status code
422         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ' - EXIT!');
423         //* DEBUG: */ debugOutput(getCurrentExtensionName().':<pre>'.print_r($ret, true).'</pre>');
424         return $ret;
425 }
426
427 // Run SQL queries for given extension id
428 // @TODO Change from ext_id to ext_name (not just even the variable! ;-) )
429 function doExtensionSqls ($ext_id, $load_mode) {
430         // This shall never do a non-admin user!
431         if (!isAdmin()) return false;
432
433         // Get extension's name
434         $ext_name = getExtensionName($ext_id);
435
436         // Set current SQL name
437         setCurrentExtensionName($ext_name);
438
439         // Init EXT_UPDATE_DEPENDS
440         if (!isExtensionUpdateDependenciesInitialized()) {
441                 // Init here...
442                 initExtensionUpdateDependencies();
443         } // END - if
444
445         // Init array
446         initExtensionSqls();
447
448         // By default no SQL has been executed
449         $sqlRan = false;
450
451         // Load extension in detected mode
452         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ":ext_name[{$ext_id}]=".getCurrentExtensionName()."");
453         loadExtension(getCurrentExtensionName(), $load_mode, '', false);
454
455         // Init these SQLs
456         initSqls();
457         setSqlsArray(getExtensionSqls());
458
459         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ":SQLs::count=".countSqls()."");
460         if (isSqlsValid()) {
461                 // Run SQL commands...
462                 runFilterChain('run_sqls');
463         } // END - if
464
465         // Run any filters depending on the action here
466         runFilterChain('extension_' . $load_mode);
467
468         // Remove cache file(s) if extension is active
469         if (((isExtensionActive('cache')) && ((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == 'activate') || ($load_mode == 'deactivate'))) {
470                 // Run filters
471                 runFilterChain('post_extension_run_sql', getCurrentExtensionName());
472         } // END - if
473
474         // Is this the sql_patches?
475         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": id=".$ext_id.",currName=".getCurrentExtensionName().",loadMode=".$load_mode);
476         if ((getCurrentExtensionName() == 'sql_patches') && (($load_mode == 'register') || ($load_mode == 'remove'))) {
477                 // Then redirect to logout
478                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": LOAD!");
479                 redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . $load_mode . '=sql_patches');
480         } // END - if
481 }
482
483 // Check wether the given extension is installed
484 function isExtensionInstalled ($ext_name) {
485         // We don't like empty extension names here
486         if (empty($ext_name)) {
487                 // Please fix them all
488                 debug_report_bug(__FUNCTION__.': ext_name is empty.');
489         } // END - if
490
491         // By default non is installed
492         $isInstalled = false;
493
494         // Check if there is a cache entry
495         if (isset($GLOBALS['ext_is_installed'][$ext_name])) {
496                 // Use cache built from below queries
497                 $isInstalled = $GLOBALS['ext_is_installed'][$ext_name];
498         } elseif (isset($GLOBALS['cache_array']['extension']['ext_id'][$ext_name])) {
499                 // Found!
500                 $isInstalled = true;
501
502                 // Count cache hits
503                 incrementStatsEntry('cache_hits');
504         } elseif ((isInstallationPhase())) {
505                 // Extensions are all inactive/not installed during installation
506         } else {
507                 // Look in database
508                 $ext_id = getExtensionId($ext_name);
509
510                 // Do we have a record?
511                 $isInstalled = ($ext_id > 0);
512
513                 // Is it installed, then cache the entry
514                 if ($isInstalled === true) {
515                         // Dummy call (get is okay here)
516                         getExtensionId($ext_name, true);
517                 } // END - if
518
519                 // Remember the status
520                 $GLOBALS['ext_is_installed'][$ext_name] = $isInstalled;
521         }
522
523         // Return status
524         return $isInstalled;
525 }
526
527 // Check if given extension is active
528 function isExtensionActive ($ext_name) {
529         // Extensions are all inactive during installation
530         if ((isInstallationPhase()) || (empty($ext_name))) return false;
531
532         // Not active is the default
533         $data['ext_active'] = 'N';
534
535         // Check cache
536         if (isset($GLOBALS['cache_array']['extension']['ext_active'][$ext_name])) {
537                 // Load from cache
538                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
539                 $data['ext_active'] = $GLOBALS['cache_array']['extension']['ext_active'][$ext_name];
540
541                 // Count cache hits
542                 incrementStatsEntry('cache_hits');
543         } elseif (isset($GLOBALS['ext_loaded'][$ext_name])) {
544                 // @TODO Extension is loaded, what next?
545                 debug_report_bug(__FUNCTION__, __LINE__, 'LOADED:' . $ext_name);
546         } elseif (($ext_name == 'cache') || (!isExtensionInstalled('cache'))) {
547                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
548                 // Load from database
549                 $result = SQL_QUERY_ESC("SELECT `ext_active` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
550                         array($ext_name), __FUNCTION__, __LINE__);
551
552                 // Entry found?
553                 if (SQL_NUMROWS($result) == 1) {
554                         // Load entry
555                         $data = SQL_FETCHARRAY($result);
556                 } // END - if
557
558                 // Free result
559                 SQL_FREERESULT($result);
560
561                 // Write cache array
562                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name."[DB]: ".$data['ext_active']."");
563                 $GLOBALS['cache_array']['extension']['ext_active'][$ext_name] = $data['ext_active'];
564         } else {
565                 // Extension not active!
566                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name.": Not active!");
567                 $GLOBALS['cache_array']['extension']['ext_active'][$ext_name] = 'N';
568         }
569
570         // Debug message
571         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name.",active=".$data['ext_active']."");
572
573         // Is this extension activated? (For admins we always have active extensions...)
574         return ($data['ext_active'] == 'Y');
575 }
576
577 // Get version from extensions
578 function getExtensionVersion ($ext_name, $force = false) {
579         // By default no extension is found
580         $data['ext_version'] = 'false';
581
582         // Empty extension name should be fixed!
583         if (empty($ext_name)) {
584                 // Please report this bug!
585                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_name is empty which is not allowed here.');
586         } // END - if
587
588         // Extensions are all inactive during installation
589         if (isInstallationPhase()) return '';
590         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": ext_name=".$ext_name."");
591
592         // Is the cache written?
593         if (isset($GLOBALS['cache_array']['extension']['ext_version'][$ext_name])) {
594                 // Load data from cache
595                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $ext_name . ': CACHE!');
596                 $data['ext_version'] = $GLOBALS['cache_array']['extension']['ext_version'][$ext_name];
597
598                 // Count cache hits
599                 incrementStatsEntry('cache_hits');
600         } elseif ((!isCacheInstanceValid()) || (isset($GLOBALS['cache_array']['extension'])) || (getOutputMode() != 0)) {
601                 // Load from database
602                 $result = SQL_QUERY_ESC("SELECT `ext_version` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
603                         array($ext_name), __FUNCTION__, __LINE__);
604                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $ext_name . ': DB - '.SQL_NUMROWS($result).'');
605
606                 // Is the extension there?
607                 if (SQL_NUMROWS($result) == 1) {
608                         // Load entry
609                         $data = SQL_FETCHARRAY($result);
610                 } elseif (isDebugModeEnabled()) {
611                         // Not found, please report all
612                         debug_report_bug(__FUNCTION__, __LINE__, sprintf(": Cannot find extension %s in database!", $ext_name));
613                 }
614
615                 // Free result
616                 SQL_FREERESULT($result);
617
618                 // Set cache
619                 $GLOBALS['cache_array']['extension']['ext_version'][$ext_name] = $data['ext_version'];
620         }
621
622         // Extension version should not be invalid
623         if (($data['ext_version'] == 'false') && ($force === false)) {
624                 // Please report this trouble
625                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Extension <span class=\"data\">%s</span> has empty version!", $ext_name));
626         } // END - if
627
628         // Return result
629         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": ret={$data['ext_version']}");
630         return $data['ext_version'];
631 }
632
633 // Updates a given extension with current extension version to latest version
634 function updateExtension ($ext_name, $ext_ver, $dry_run = false) {
635         // Only admins are allowed to update extensions
636         if ((!isAdmin()) || (empty($ext_name))) return false;
637
638         // Set current SQL name
639         setCurrentExtensionName($ext_name);
640
641         // Init arrays
642         initExtensionSqls();
643         initExtensionNotes();
644         initIncludePool('extension');
645
646         // Load extension in test mode
647         loadExtension($ext_name, 'test', $ext_ver, isExtensionDryRun());
648
649         // Save version history
650         $history = getExtensionVersionHistory();
651
652         // Remove old SQLs array to prevent possible bugs
653         initExtensionSqls();
654
655         // Check if version is updated
656         //* DEBUG: */ debugOutput(getCurrentExtensionName().'/'.$ext_name.':'.getThisExtensionVersion().'/'.$ext_ver.'/'.intval(is_array($history)));
657         if (((getThisExtensionVersion() != $ext_ver) || (isExtensionDryRun())) && (is_array($history))) {
658                 // Search for starting point
659                 $start = array_search($ext_ver, $history);
660
661                 // And load SQL queries in order of version history
662                 for ($idx = ($start + 1); $idx < count($history); $idx++) {
663                         // Set extension version
664                         $GLOBALS['update_ver'][getCurrentExtensionName()] = $history[$idx];
665
666                         // Load again...
667                         loadExtension(getCurrentExtensionName(), 'update', $GLOBALS['update_ver'][getCurrentExtensionName()], isExtensionDryRun());
668
669                         // Get all depencies
670                         $depencies = getExtensionUpdateDependencies();
671
672                         // Nothing to apply?
673                         if (count($depencies) > 0) {
674                                 // Apply all extension depencies
675                                 foreach ($depencies as $ext_depend) {
676                                         // Did we already update/register this?
677                                         if (!isset($GLOBALS['ext_updated'][$ext_depend])) {
678                                                 // Set it as current
679                                                 setCurrentExtensionName($ext_depend);
680
681                                                 // Mark it as already updated before we update it
682                                                 $GLOBALS['ext_updated'][$ext_depend] = true;
683
684                                                 // Is the extension there?
685                                                 if (isExtensionInstalled($ext_depend)) {
686                                                         // Update another extension first!
687                                                         $test = updateExtension($ext_depend, getExtensionVersion($ext_depend), isExtensionDryRun());
688                                                 } else {
689                                                         // Register new extension
690                                                         $test = registerExtension($ext_depend, 0, isExtensionDryRun(), false);
691                                                 }
692                                         } // END - if
693                                 } // END - foreach
694
695                                 // Set extension version here
696                                 setCurrentExtensionVersion($ext_ver);
697
698                                 // Set name back
699                                 setCurrentExtensionName($ext_name);
700                         } // END - if
701
702                         // Add notes
703                         addExtensionNotes($history[$idx]);
704                 } // END - for
705
706                 // In real-mode execute any existing includes
707                 if (isExtensionDryRun() === false) {
708                         $GLOBALS['ext_inc_pool'][getCurrentExtensionName()] = getIncludePool('extension');
709                         runFilterChain('load_includes', 'extension');
710                         setIncludePool('extension', $GLOBALS['ext_inc_pool'][getCurrentExtensionName()]);
711                         unset($GLOBALS['ext_inc_pool'][getCurrentExtensionName()]);
712                 } // END - if
713
714                 // Init these SQLs
715                 initSqls();
716                 setSqlsArray(getExtensionSqls());
717
718                 // Run SQLs
719                 runFilterChain('run_sqls', array('dry_run' => isExtensionDryRun()));
720
721                 if (isExtensionDryRun() === false) {
722                         // Run filters on success extension update
723                         runFilterChain('extension_update', getCurrentExtensionName());
724                 } // END - if
725         } // END - if
726 }
727
728 // Output verbose SQL table for extension
729 function addExtensionVerboseSqlTable ($title = '', $dashed = '', $switch = false, $width = '100%') {
730         // Empty title?
731         if (empty($title)) {
732                 // Then fix it to default
733                 $title = '{--ADMIN_SQLS_EXECUTED_ON_REMOVAL--}';
734         } // END - if
735
736         // Init variables
737         $OUT = '';
738
739         // Do we have queries?
740         if ((isExtensionInstalledAndNewer('sql_patches', '0.0.7')) && (getConfig('verbose_sql') == 'Y')) {
741                 // Init switch color
742                 $SW = 2;
743
744                 // Get all SQLs
745                 foreach (getExtensionSqls() as $sqls) {
746                         // New array format is recursive
747                         foreach ($sqls as $idx => $sql) {
748                                 // Trim out spaces
749                                 $sql = trim($sql);
750
751                                 // Output command if set
752                                 if (!empty($sql)) {
753                                         // Prepare output for template
754                                         $content = array(
755                                                 'sw'  => $SW,
756                                                 'i'   => ($idx+1),
757                                                 'sql' => $sql
758                                         );
759
760                                         // Load row template
761                                         $OUT .= loadTemplate('admin_ext_sql_row', true, $content);
762
763                                         // Switch color
764                                         $SW = 3 - $SW;
765                                 } // END - if
766                         } // END - foreach
767                 } // END - foreach
768
769                 // Prepare content for template
770                 $content = array(
771                         'width'  => $width,
772                         'dashed' => $dashed,
773                         'title'  => $title,
774                         'rows'   => $OUT
775                 );
776
777                 // Load main template
778                 $OUT = loadTemplate('admin_ext_sql_table', true, $content);
779         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.0.7')) && (getConfig('verbose_sql') == 'Y')) {
780                 // No addional SQL commands to run
781                 $OUT = loadTemplate('admin_settings_saved', true, '{--ADMIN_NO_ADDITIONAL_SQLS--}');
782         } // END - if
783
784         // Return output
785         return $OUT;
786 }
787
788 // Get extension name from id
789 function getExtensionName ($ext_id) {
790         // Init extension name
791         $data['ext_name'] = '';
792
793         // Is cache there?
794         if (isset($GLOBALS['cache_array']['extension']['ext_name'][$ext_id])) {
795                 // Load from cache
796                 $data['ext_name'] = $GLOBALS['cache_array']['extension']['ext_name'][$ext_id];
797
798                 // Count cache hits
799                 incrementStatsEntry('cache_hits');
800         } elseif (!isExtensionActive('cache')) {
801                 // Load from database
802                 $result = SQL_QUERY_ESC("SELECT `ext_name` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `id`=%s LIMIT 1",
803                         array(bigintval($ext_id)), __FUNCTION__, __LINE__);
804
805                 // Is the entry there?
806                 if (SQL_NUMROWS($result) == 1) {
807                         // Get the extension's name from database
808                         $data = SQL_FETCHARRAY($result);
809                 } // END - if
810
811                 // Free result
812                 SQL_FREERESULT($result);
813         }
814
815         // Did we find some extension?
816         if (empty($data['ext_name'])) {
817                 // We should fix these all!
818                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_name is empty. ext_id=' . $ext_id);
819         } // END - if
820
821         // Return the extension name
822         return $data['ext_name'];
823 }
824
825 // Get extension id from name
826 function getExtensionId ($ext_name) {
827         // Init id number
828         $data['ext_id'] = '0';
829
830         // Do we have cache?
831         if (isset($GLOBALS['cache_array']['extension']['ext_id'][$ext_name])) {
832                 // Load from cache
833                 $data['ext_id'] = $GLOBALS['cache_array']['extension']['ext_id'][$ext_name];
834
835                 // Count cache hits
836                 incrementStatsEntry('cache_hits');
837         } else {
838                 // Load from database
839                 $result = SQL_QUERY_ESC("SELECT `id` AS ext_id FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
840                         array($ext_name), __FUNCTION__, __LINE__);
841
842                 // Is the entry there?
843                 if (SQL_NUMROWS($result) == 1) {
844                         // Get the extension's id from database
845                         $data = SQL_FETCHARRAY($result);
846                 } // END - if
847
848                 // Free result
849                 SQL_FREERESULT($result);
850
851                 // Cache it
852                 $GLOBALS['cache_array']['extension']['ext_id'][$ext_name] = $data['ext_id'];
853         }
854
855         // Return value
856         return $data['ext_id'];
857 }
858
859 // Determines wether the given extension name is valid
860 function isExtensionNameValid ($ext_name) {
861         // Do we have cache?
862         if (!isset($GLOBALS['ext_name_valid'][$ext_name])) {
863                 // Generate include file name
864                 $INC = sprintf("inc/extensions/ext-%s.php", $ext_name);
865
866                 // Is there a file in inc/extensions/ ?
867                 $GLOBALS['ext_name_valid'][$ext_name] = isIncludeReadable($INC);
868         } // END - if
869
870         // Return result
871         return $GLOBALS['ext_name_valid'][$ext_name];
872 }
873
874 // Determines wether the given extension id is valid
875 function isExtensionIdValid ($ext_id) {
876         // Default is nothing valid
877         $isValid = false;
878
879         // Check in cache then in database
880         if (isset($GLOBALS['cache_array']['extension']['ext_name'][$ext_id])) {
881                 // Valid!
882                 $isValid = true;
883
884                 // Count cache hits
885                 incrementStatsEntry('cache_hits');
886         } else {
887                 // Query database
888                 $isValid = (countSumTotalData($ext_id, 'extensions', 'id', 'id', true) == 1);
889         }
890
891         // Return result
892         return $isValid;
893 }
894
895 // Activate given extension
896 function doActivateExtension ($ext_name) {
897         // Activate the extension
898         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_active`='Y' WHERE `ext_name`='%s' LIMIT 1",
899                 array($ext_name), __FUNCTION__, __LINE__);
900
901         // Extension has been activated?
902         if (SQL_AFFECTEDROWS() == 1) {
903                 // Then run all queries
904                 doExtensionSqls(getExtensionId($ext_name), 'activate');
905         } // END - if
906 }
907
908 // Deactivate given extension
909 function doDeactivateExtension($ext_name) {
910         // Activate the extension
911         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_active`='N' WHERE `ext_name`='%s' LIMIT 1",
912                 array($ext_name), __FUNCTION__, __LINE__);
913
914         // Extension has been activated?
915         if (SQL_AFFECTEDROWS() == 1) {
916                 // Then run all queries
917                 doExtensionSqls(getExtensionId($ext_name), 'deactivate');
918
919                 // Create new task (we ignore the task id here)
920                 createExtensionDeactivationTask($ext_name);
921
922                 // Notify the admin
923                 sendAdminNotification(
924                         getMessage('ADMIN_SUBJECT_EXTENSION_DEACTIVATED'),
925                         'admin_ext_deactivated',
926                         array('ext_name' => $ext_name)
927                 );
928         } // END - if
929 }
930
931 // Checks wether the extension is older than given
932 function isExtensionOlder ($ext_name, $ext_ver) {
933         // Get current extension version
934         $currVersion = getExtensionVersion($ext_name);
935
936         // Remove all dots from both versions
937         $currVersion = str_replace('.', '', $currVersion);
938         $ext_ver = str_replace('.', '', $ext_ver);
939
940         // Now compare both and return the result
941         return ($currVersion < $ext_ver);
942 }
943
944 // Creates a new task for updated extension
945 function createExtensionUpdateTask ($adminId, $ext_name, $ext_ver, $notes) {
946         // Create subject line
947         $subject = '[UPDATE-' . $ext_name . '-' . $ext_ver . ':] {--ADMIN_UPDATE_EXTENSION_SUBJ--}';
948
949         // Get task id
950         $taskId = determineTaskIdBySubject($subject);
951
952         // Is the extension there?
953         if (isExtensionInstalled($ext_name)) {
954                 // Check if task is not there
955                 if ($taskId == '0') {
956                         // Create extension update-task
957                         $taskId = createNewTask($subject, $notes, 'EXTENSION_UPDATE', 0, $adminId);
958                 } // END - if
959         } else {
960                 // Extension not there! :-(
961                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Extension <span class=\"data\">%s</span> not found but should be updated?", $ext_name));
962         }
963
964         // Return task id
965         return $taskId;
966 }
967
968 // Creates a new task for newly installed extension
969 function createNewExtensionTask ($ext_name) {
970         // Generate subject line
971         $subject = sprintf("[%s:]", $ext_name);
972
973         // Get task id
974         $taskId = determineTaskIdBySubject($subject);
975
976         // Not installed and do we have created a task for the admin?
977         if (($taskId == '0') && (!isExtensionInstalled($ext_name))) {
978                 // Set default message if ext-foo is missing
979                 $message = getMaskedMessage('ADMIN_EXTENSION_TEXT_FILE_MISSING', $ext_name);
980
981                 // Template file
982                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
983                         getConfig('PATH'),
984                         getLanguage(),
985                         $ext_name
986                 );
987
988                 // Load text for task if found
989                 if (isFileReadable($tpl)) {
990                         // Load extension's own text template (HTML!)
991                         $message = loadTemplate('ext_' . $ext_name, true);
992                 } else {
993                         // Write this in debug.log as well
994                         logDebugMessage(__FUNCTION__, __LINE__, $message);
995                 }
996
997                 // Task not created so it's a brand-new extension which we need to register and create a task for!
998                 $taskId = createNewTask($subject, $message, 'EXTENSION', 0, getCurrentAdminId(), false);
999         } // END - if
1000
1001         // Return task id
1002         return $taskId;
1003 }
1004
1005 // Creates a task for automatically deactivated (deprecated) extension
1006 function createExtensionDeactivationTask ($ext_name) {
1007         // Create subject line
1008         $subject = sprintf("[%s:] %s", $ext_name, '{--TASK_SUBJ_EXTENSION_DEACTIVATED--}');
1009
1010         // Get task id
1011         $taskId = determineTaskIdBySubject($subject);
1012
1013         // Not installed and do we have created a task for the admin?
1014         if (($taskId == '0') && (isExtensionInstalled($ext_name))) {
1015                 // Task not created so add it
1016                 $taskId = createNewTask($subject, SQL_ESCAPE(loadTemplate('task_EXTENSION_deactivated', true, $ext_name)), 'EXTENSION_DEACTIVATION');
1017         } // END - if
1018
1019         // Return task id
1020         return $taskId;
1021 }
1022
1023 // Checks if the module has a menu
1024 function ifModuleHasMenu ($mod, $forceDb = false) {
1025         // All is false by default
1026         $ret = false;
1027
1028         // Extension installed and newer than or has version 0.1.2?
1029         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
1030                 // Cache version is okay, so let's check the cache!
1031                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$mod])) {
1032                         // Check module cache and count hit
1033                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$mod] == 'Y');
1034                         incrementStatsEntry('cache_hits');
1035                 } elseif (isset($GLOBALS['cache_array']['extension']['ext_menu'][$mod])) {
1036                         // Check cache and count hit
1037                         $ret = ($GLOBALS['cache_array']['extension']['ext_menu'][$mod] == 'Y');
1038                         incrementStatsEntry('cache_hits');
1039                 } else {
1040                         // Admin/guest/member/sponsor modules have always a menu!
1041                         $ret = in_array($mod, array('admin', 'index', 'login', 'sponsor'));
1042                 }
1043         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && ((!isExtensionActive('cache')) || ($forceDb === true))) {
1044                 // Check database for entry
1045                 $result = SQL_QUERY_ESC("SELECT `has_menu` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
1046                         array($mod), __FUNCTION__, __LINE__);
1047
1048                 // Entry found?
1049                 if (SQL_NUMROWS($result) == 1) {
1050                         // Load "has_menu" column
1051                         $data = SQL_FETCHARRAY($result);
1052
1053                         // Fake cache... ;-)
1054                         $GLOBALS['cache_array']['extension']['ext_menu'][$mod] = $data['has_menu'];
1055
1056                         // Does it have a menu?
1057                         $ret = ($data['has_menu'] == 'Y');
1058                 } // END  - if
1059
1060                 // Free memory
1061                 SQL_FREERESULT($result);
1062         } elseif (!isExtensionInstalled('sql_patches')) {
1063                 // No sql_patches installed, so maybe in admin/guest/member/sponsor area or no admin registered?
1064                 $ret = in_array($mod, array('admin', 'index', 'login', 'sponsor')); // Then there is a menu!
1065         } else {
1066                 // Unsupported state!
1067                 logDebugMessage(__FUNCTION__, __LINE__, 'This should never be reached.');
1068         }
1069
1070         // Return status
1071         return $ret;
1072 }
1073
1074 // Determines the task id for given extension
1075 function determineExtensionTaskId ($ext_name) {
1076         // Default is not found
1077         $data['task_id'] = '0';
1078
1079         // Search for extension task's id
1080         $result = SQL_QUERY_ESC("SELECT `id` AS task_id FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `task_type`='EXTENSION' AND `subject`='[%s:]' LIMIT 1",
1081                 array($ext_name), __FUNCTION__, __LINE__);
1082
1083         // Entry found?
1084         if (SQL_NUMROWS($result) == 1) {
1085                 // Task found so load task's id and register extension...
1086                 $data = SQL_FETCHARRAY($result);
1087         } // END - if
1088
1089         // Free result
1090         SQL_FREERESULT($result);
1091
1092         // Return it
1093         return $data['task_id'];
1094 }
1095
1096 // Determines the task id for given subject
1097 function determineTaskIdBySubject ($subject) {
1098         // Default is not found
1099         $data['task_id'] = '0';
1100
1101         // Search for task id
1102         $result = SQL_QUERY_ESC("SELECT `id` AS task_id FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `subject` LIKE '%s%%' LIMIT 1",
1103                 array($subject), __FUNCTION__, __LINE__);
1104
1105         // Entry found?
1106         if (SQL_NUMROWS($result) == 1) {
1107                 // Task found so load task's id and register extension...
1108                 $data = SQL_FETCHARRAY($result);
1109         } // END - if
1110
1111         // Free result
1112         SQL_FREERESULT($result);
1113
1114         // Return it
1115         return $data['task_id'];
1116 }
1117
1118 // Add updates notes for given version
1119 function addExtensionNotes ($ver) {
1120         // Init notes/content
1121         $out = ''; $content = array();
1122
1123         // Is do we have verbose output enabled?
1124         if ((!isExtensionActive('sql_patches')) || (getConfig('verbose_sql') == 'Y')) {
1125                 // Update notes found?
1126                 if (isExtensionUpdateNoteSet($ver)) {
1127                         // Update notes found
1128                         $content = array(
1129                                 'ver'   => $ver,
1130                                 'notes' => getExtensionUpdateNotes($ver)
1131                         );
1132
1133                         // Reset them
1134                         setExtensionUpdateNotes('', $ver);
1135                 } elseif (($ver == '0.0') || ($ver == '0.0.0')) {
1136                         // Initial release
1137                         $content = array(
1138                                 'ver'   => $ver,
1139                                 'notes' => '{--INITIAL_RELEASE--}'
1140                         );
1141                 } else {
1142                         // No update notes found!
1143                         $content = array(
1144                                 'ver'   => $ver,
1145                                 'notes' => '{--NO_UPDATE_NOTES--}'
1146                         );
1147                 }
1148
1149                 // Load template
1150                 $out = loadTemplate('admin_EXTENSION_notes', true, $content);
1151         } // END - if
1152
1153         // Add the notes
1154         appendExtensionNotes($out);
1155 }
1156
1157 // Getter for CSS files array
1158 function getExtensionCssFiles () {
1159         // By default no additional CSS files are found
1160         $cssFiles = array();
1161
1162         // Is the array there?
1163         if (isset($GLOBALS['css_files'])) {
1164                 // Then use it
1165                 $cssFiles = $GLOBALS['css_files'];
1166         } // END - if
1167
1168         // Return array
1169         return $cssFiles;
1170 }
1171
1172 // Init CSS files array
1173 function initExtensionCssFiles () {
1174         // Simply init it
1175         $GLOBALS['css_files'] = array();
1176 }
1177
1178 // Add new entry
1179 function addExtensionCssFile ($file) {
1180         // Is the array there?
1181         if (!isset($GLOBALS['css_files'])) {
1182                 // Then auto-init them
1183                 initExtensionCssFiles();
1184         } // END - if
1185
1186         // Add the entry
1187         $GLOBALS['css_files'][] = $file;
1188 }
1189
1190 // Setter for EXT_ALWAYS_ACTIVE flag
1191 function setExtensionAlwaysActive ($active) {
1192         $GLOBALS['ext_always_active'][getCurrentExtensionName()] = (string) $active;
1193 }
1194
1195 // Getter for EXT_ALWAYS_ACTIVE flag
1196 function getExtensionAlwaysActive () {
1197         return $GLOBALS['ext_always_active'][getCurrentExtensionName()];
1198 }
1199
1200 // Checks wether the current extension is always active
1201 function isExtensionAlwaysActive () {
1202         return (getExtensionAlwaysActive() == 'Y');
1203 }
1204
1205 // Setter for EXT_VERSION flag
1206 function setThisExtensionVersion ($version) {
1207         $GLOBALS['ext_version'][getCurrentExtensionName()] = (string) $version;
1208 }
1209
1210 // Getter for EXT_VERSION flag
1211 function getThisExtensionVersion () {
1212         return $GLOBALS['ext_version'][getCurrentExtensionName()];
1213 }
1214
1215 // Setter for EXT_DEPRECATED flag
1216 function setExtensionDeprecated ($deprecated) {
1217         $GLOBALS['ext_deprecated'][getCurrentExtensionName()] = (string) $deprecated;
1218 }
1219
1220 // Getter for EXT_DEPRECATED flag
1221 function isExtensionDeprecated () {
1222         return ($GLOBALS['ext_deprecated'][getCurrentExtensionName()] == 'Y');
1223 }
1224
1225 // Setter for EXT_UPDATE_DEPENDS flag
1226 function addExtensionUpdateDependency ($updateDepends) {
1227         //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . '/' . $updateDepends . ' - ENTERED!');
1228         // Is the update depency empty? (NEED TO BE FIXED!)
1229         if (empty($updateDepends)) {
1230                 // Please report this bug!
1231                 debug_report_bug(__FUNCTION__, __LINE__, 'updateDepends is empty: currentExtension=' . getCurrentExtensionName());
1232         } // END - if
1233
1234         // Is it not yet added?
1235         /* DEBUG:
1236         if ((isset($updateDepends, $GLOBALS['ext_running_updates'][getCurrentExtensionName()])) && (in_array($updateDepends, getExtensionUpdatesRunning()))) {
1237                 // Double-adding isn't fine, too
1238                 debug_report_bug(__FUNCTION__, __LINE__, '() called twice: updateDepends=' . $updateDepends . ',currentExtension=' . getCurrentExtensionName());
1239         } // END - if
1240         */
1241
1242         // Add it to the list of extension update depencies map
1243         $GLOBALS['ext_update_depends'][getCurrentExtensionName()][] = (string) $updateDepends;
1244
1245         // Remember it in the list of running updates
1246         $GLOBALS['ext_running_updates'][getCurrentExtensionName()][] = $updateDepends;
1247         //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . '/' . $updateDepends . ' - EXIT!');
1248 }
1249
1250 // Getter for running updates
1251 function getExtensionUpdatesRunning () {
1252         return $GLOBALS['ext_running_updates'][getCurrentExtensionName()];
1253 }
1254
1255 // Checks wether the given extension registration is in progress
1256 function isExtensionRegistrationRunning ($ext_name) {
1257         // Simply check it
1258         $isRunning = ((isset($GLOBALS['ext_register_running'])) && (in_array($ext_name, $GLOBALS['ext_register_running'])));
1259
1260         // Return it
1261         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1262         return $isRunning;
1263 }
1264
1265 // Init EXT_UPDATE_DEPENDS flag
1266 function initExtensionUpdateDependencies () {
1267         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - ENTERED!');
1268
1269         // Init update depency map automatically if not found
1270         if (isExtensionUpdateDependenciesInitialized()) {
1271                 // We need these bug reports as well...
1272                 debug_report_bug(__FUNCTION__, __LINE__, '() is called twice: currName=' . getCurrentExtensionName());
1273         } // END - if
1274
1275         $GLOBALS['ext_update_depends'][getCurrentExtensionName()] = array();
1276
1277         // Init running updates array
1278         initExtensionRuningUpdates();
1279
1280         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - EXIT!');
1281 }
1282
1283 // Adds an extension as "registration in progress"
1284 function addExtensionRunningRegistration ($ext_name) {
1285         // Is it running?
1286         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Registration in progress: ext_name=' . $ext_name . ' - ENTERED!');
1287         if (isExtensionRegistrationRunning($ext_name)) {
1288                 // This is really bad and should not be quietly ignored
1289                 debug_report_bug(__FUNCTION__, __LINE__, '() already called! ext_name=' . $ext_name);
1290         } // END - if
1291
1292         // Then add it!
1293         $GLOBALS['ext_register_running'][] = $ext_name;
1294         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Registration in progress: ext_name=' . $ext_name . ' - EXIT!');
1295 }
1296
1297 // Checks wether EXT_UPDATE_DEPENDS is initialized
1298 function isExtensionUpdateDependenciesInitialized () {
1299         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
1300         return (isset($GLOBALS['ext_update_depends'][getCurrentExtensionName()]));
1301 }
1302
1303 // Checks wether an update is already running for given extension
1304 function isExtensionUpdateRunning ($ext_name) {
1305         // Current and given extensions means whole array
1306         if ($ext_name == getCurrentExtensionName()) {
1307                 // Default is not found
1308                 $isRunning = false;
1309
1310                 // Walk through whole array
1311                 foreach ($GLOBALS['ext_running_updates'] as $ext1=>$depends) {
1312                         // Is it found?
1313                         if (($ext1 == $ext_name) || ($isRunning === true)) {
1314                                 // Found!
1315                                 logDebugMessage(__FUNCTION__, __LINE__, 'ext1=' . $ext1 . ',ext_name=' . $ext_name . ',isRunning=' . intval($isRunning));
1316                                 $isRunning = true;
1317                                 break;
1318                         } // END - if
1319                 } // END - foreach
1320
1321                 // Return result
1322                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1323                 return $isRunning;
1324         } // END - if
1325
1326         // Simply check it
1327         $isRunning = ((isExtensionUpdateDependenciesInitialized()) && (in_array($ext_name, getExtensionRunningUpdates())));
1328
1329         // Return it
1330         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1331         return $isRunning;
1332 }
1333
1334 // Initializes the list of running updates
1335 function initExtensionRuningUpdates () {
1336         // Auto-init ext_running_updates
1337         if (!isset($GLOBALS['ext_running_updates'])) {
1338                 $GLOBALS['ext_running_updates'] = array();
1339                 $GLOBALS['ext_register_running'] = array();
1340         } // END - if
1341 }
1342
1343 // Getter for EXT_UPDATE_DEPENDS flag
1344 function getExtensionUpdateDependencies () {
1345         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1346         return $GLOBALS['ext_update_depends'][getCurrentExtensionName()];
1347 }
1348
1349 // Getter for next iterator depency
1350 function getExtensionUpdateDependenciesIterator () {
1351         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1352         return ($GLOBALS['ext_update_depends'][getCurrentExtensionName()][getExtensionUpdateIterator()]);
1353 }
1354
1355 // Counter for extension update depencies
1356 function countExtensionUpdateDependencies () {
1357         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1358         return count($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1359 }
1360
1361 // Removes given extension from update denpency list
1362 function removeExtensionUpdateDependency ($ext_name) {
1363         // Look it up
1364         $key = array_search($ext_name, getExtensionUpdateDependencies());
1365
1366         // Is it valid?
1367         if ($key !== false) {
1368                 // Then remove it
1369                 unset($GLOBALS['ext_update_depends'][getCurrentExtensionName()][$key]);
1370
1371                 // And sort the array
1372                 ksort($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1373         } // END - if
1374 }
1375
1376 // Init iterator for update depencies
1377 function initExtensionUpdateIterator () {
1378         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1379         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()] = '0';
1380 }
1381
1382 // Getter for depency iterator
1383 function getExtensionUpdateIterator () {
1384         // Auto-init iterator
1385         if (!isset($GLOBALS['ext_depend_iterator'][getCurrentExtensionName()])) initExtensionUpdateIterator();
1386
1387         // Return it
1388         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().'/'.$GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]);
1389         return $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()];
1390 }
1391
1392 // Increments the update iterator
1393 function incrementExtensionUpdateIterator () {
1394         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1395         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]++;
1396 }
1397
1398 // Setter for EXT_REPORTS_FAILURE flag
1399 function setExtensionReportsFailure ($reportsFailure) {
1400         $GLOBALS['ext_reports_failure'] = (bool) $reportsFailure;
1401 }
1402
1403 // Getter for EXT_REPORTS_FAILURE flag
1404 function getExtensionReportsFailure () {
1405         return $GLOBALS['ext_reports_failure'];
1406 }
1407
1408 // Setter for EXT_VER_HISTORY flag
1409 function setExtensionVersionHistory ($verHistory) {
1410         $GLOBALS['ext_ver_history'][getCurrentExtensionName()] = (array) $verHistory;
1411 }
1412
1413 // Getter for EXT_VER_HISTORY array
1414 function getExtensionVersionHistory () {
1415         return $GLOBALS['ext_ver_history'][getCurrentExtensionName()];
1416 }
1417
1418 // Setter for EXT_UPDATE_NOTES
1419 function setExtensionUpdateNotes ($updateNotes, $ver='') {
1420         // . '/' . getCurrentExtensionVersion()
1421         //* DEBUG: */ debug_report_bug(__FUNCTION__.':' . getCurrentExtensionName() . '/' . getExtensionMode() . '/' . $ver . '=' . $updateNotes);
1422         if (empty($ver)) {
1423                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][getCurrentExtensionVersion()] = (string) $updateNotes;
1424         } else {
1425                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ver] = (string) $updateNotes;
1426         }
1427 }
1428
1429 // Getter for EXT_UPDATE_NOTES
1430 function getExtensionUpdateNotes ($ver) {
1431         return $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ver];
1432 }
1433
1434 // Checks if ext_update_notes is set
1435 function isExtensionUpdateNoteSet ($ver) {
1436         return isset($GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ver]);
1437 }
1438
1439 // Init extension notice
1440 function initExtensionNotes () {
1441         $GLOBALS['ext_notes'][getCurrentExtensionName()] = '';
1442 }
1443
1444 // Append extension notice
1445 function appendExtensionNotes ($notes) {
1446         $GLOBALS['ext_notes'][getCurrentExtensionName()] .= (string) trim($notes);
1447 }
1448
1449 // Getter for extension notes
1450 function getExtensionNotes () {
1451         return $GLOBALS['ext_notes'][getCurrentExtensionName()];
1452 }
1453
1454 // Setter for current extension name
1455 function setCurrentExtensionName ($ext_name) {
1456         $GLOBALS['curr_EXTENSION_name'] = (string) trim($ext_name);
1457 }
1458
1459 // Getter for current extension name
1460 function getCurrentExtensionName () {
1461         if (isset($GLOBALS['curr_EXTENSION_name'])) {
1462                 return $GLOBALS['curr_EXTENSION_name'];
1463         } // END - if
1464
1465         // Not set!
1466         debug_report_bug(__FUNCTION__.": curr_EXTENSION_name not initialized. Please execute initExtensionSqls() before calling this function.");
1467 }
1468
1469 // Init SQLs array for current extension
1470 function initExtensionSqls ($force = false) {
1471         // Auto-init the array or if forced
1472         if ((!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) || ($force === true)) {
1473                 // Set the array
1474                 $GLOBALS['ext_sqls'][getCurrentExtensionName()] = array();
1475
1476                 // Initialize the generic array
1477                 initSqls();
1478         } // END - if
1479 }
1480
1481 // Adds SQLs to the SQLs array but "assigns" it with current extension name
1482 function addExtensionSql ($sql) {
1483         // Add it
1484         $GLOBALS['ext_sqls'][getCurrentExtensionName()][getCurrentExtensionVersion()][] = $sql;
1485 }
1486
1487 // Getter for SQLs array for current extension
1488 function getExtensionSqls () {
1489         // Output debug backtrace if not found (SHOULD NOT HAPPEN!)
1490         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1491                 // Not found, should not happen
1492                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("ext_sqls is empty, current extension: %s",
1493                         getCurrentExtensionName()
1494                 ));
1495         } // END - if
1496
1497         // Return the array
1498         return $GLOBALS['ext_sqls'][getCurrentExtensionName()];
1499 }
1500
1501 // Removes SQLs for current extension
1502 function unsetExtensionSqls () {
1503         unset($GLOBALS['ext_sqls'][getCurrentExtensionName()]);
1504 }
1505
1506 // Auto-initializes the removal list
1507 function initExtensionRemovalList () {
1508         // Is the remove list there?
1509         if (!isset($GLOBALS['ext_update_remove'])) {
1510                 // Then create it
1511                 $GLOBALS['ext_update_remove'] = array();
1512         } // END - if
1513 }
1514
1515 // Checks wether the current extension is on the removal list
1516 function isExtensionOnRemovalList () {
1517         // Init removal list
1518         initExtensionRemovalList();
1519
1520         // Is it there?
1521         return (in_array(getCurrentExtensionName(), $GLOBALS['ext_update_remove']));
1522 }
1523
1524 // Adds the current extension to the removal list
1525 function addCurrentExtensionToRemovalList () {
1526         // Simply add it
1527         $GLOBALS['ext_update_remove'][] = getCurrentExtensionName();
1528 }
1529
1530 // Getter for removal list
1531 function getExtensionRemovalList () {
1532         // Return the removal list
1533         return $GLOBALS['ext_update_remove'];
1534 }
1535
1536 // Redirects if the provided extension is not installed
1537 function redirectOnUninstalledExtension ($ext_name) {
1538         // So is the extension there?
1539         if ((!isExtensionInstalled($ext_name)) || (!isExtensionActive($ext_name))) {
1540                 // Redirect to index
1541                 redirectToUrl('modules.php?module=index&amp;code=' . getCode('EXTENSION_PROBLEM') . '&amp;ext=' . $ext_name);
1542         } // END - if
1543 }
1544
1545 // Filter for initialization of all extensions by loading them in 'init' mode
1546 function FILTER_INIT_EXTENSIONS () {
1547         // Do we have some entries?
1548         //* DEBUG */ print __FUNCTION__.': ENTRY!<br />';
1549         if (isset($GLOBALS['cache_array']['extension']['ext_name'])) {
1550                 // Load all found extensions if found
1551                 //* DEBUG */ print __FUNCTION__.': CACHE - START!<br />';
1552                 foreach ($GLOBALS['cache_array']['extension']['ext_name'] as $key => $ext_name) {
1553                         // Load it
1554                         //* DEBUG */ print __FUNCTION__.': '.$ext_name.' - START<br />';
1555                         loadExtension($ext_name, 'init', getExtensionVersion($ext_name));
1556                         //* DEBUG */ print __FUNCTION__.': '.$ext_name.' - END<br />';
1557                 } // END - foreach
1558                 //* DEBUG */ print __FUNCTION__.': CACHE - END!<br />';
1559         } // END - if
1560         //* DEBUG */ print __FUNCTION__.': EXIT!<br />';
1561 }
1562
1563 // Setter for extension mode
1564 function setExtensionMode ($ext_mode) {
1565         $GLOBALS['ext_mode'] = (string) $ext_mode;
1566 }
1567
1568 // Getter for extension mode
1569 function getExtensionMode () {
1570         return $GLOBALS['ext_mode'];
1571 }
1572
1573 // Setter for dry-run
1574 function enableExtensionDryRun ($dry_run = true) {
1575         //* DEBUG: */ debugOutput(__FUNCTION__.': '.getCurrentExtensionName().'='.intval($dry_run));
1576         $GLOBALS['ext_dry_run'] = (bool) $dry_run;
1577 }
1578
1579 // Getter for dry-run
1580 function isExtensionDryRun () {
1581         return $GLOBALS['ext_dry_run'];
1582 }
1583
1584 // Setter for current extension version
1585 function setCurrentExtensionVersion ($ext_ver) {
1586         // ext_ver should never be empty in other modes than 'test'
1587         if ((empty($ext_ver)) && (getExtensionMode() != 'test')) {
1588                 // Please report all these messages
1589                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_ver is empty. Current extension name: ' . getCurrentExtensionName() . ', mode=' . getExtensionMode());
1590         } // END - if
1591
1592         // Add version
1593         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver[' . gettype($ext_ver) . ']=' . $ext_ver);
1594         $GLOBALS['ext_current_version'][getCurrentExtensionName()] = (string) $ext_ver;
1595 }
1596
1597 // Getter for current extension version
1598 function getCurrentExtensionVersion () {
1599         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver=' . $GLOBALS['ext_current_version'][getCurrentExtensionName()]);
1600         return $GLOBALS['ext_current_version'][getCurrentExtensionName()];
1601 }
1602
1603 // Remove the extension from cache array
1604 function removeExtensionFromArray () {
1605         // "Cache" this name
1606         $ext_name = getCurrentExtensionName();
1607
1608         // Now loop through the whole cache
1609         foreach ($GLOBALS['cache_array']['extension'] as $cacheName => $cacheArray) {
1610                 // Is it an element?
1611                 if (isset($cacheArray[$ext_name])) {
1612                         // Array element
1613                         unset($cacheArray[$ext_name]);
1614                         $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1615                 } else {
1616                         // Maybe in array?
1617                         $key = array_search($ext_name, $cacheArray);
1618
1619                         // Is it there?
1620                         if ($key !== false) {
1621                                 // Found, so remove it
1622                                 unset($cacheArray[$key]);
1623                                 $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1624                         } // END - if
1625                 }
1626         } // END - foreach
1627 }
1628
1629 // "Getter" for 'extension has a CSS file' (with same name, of course)
1630 function getExtensionHasCss () {
1631         // Default is no CSS
1632         $hasCss = 'N';
1633
1634         // Construct FQFN for check
1635         $FQFN = sprintf("%stheme/%s/css/%s.css",
1636                 getConfig('PATH'),
1637                 getCurrentTheme(),
1638                 getCurrentExtensionName()
1639         );
1640
1641         // Is it there?
1642         if (isFileReadable($FQFN)) {
1643                 // Readable, so it is there...
1644                 $hasCss = 'Y';
1645         } // END - if
1646
1647         // Return it
1648         return $hasCss;
1649 }
1650
1651 // Checks wether the given extension has a language file
1652 function ifExtensionHasLanguageFile ($ext_name) {
1653         // Default is no language file
1654         $hasLanguage = false;
1655
1656         // Do we have cache?
1657         if (isset($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name])) {
1658                 // Then use it
1659                 $hasLanguage = ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1660
1661                 // Count cache hits
1662                 incrementStatsEntry('cache_hits');
1663         } else {
1664                 // Not readable is default
1665                 $readable = 'N';
1666
1667                 // Is the language file readable for this extension?
1668                 if (isLanguageIncludeReadable($ext_name)) {
1669                         // Readable
1670                         $readable = 'Y';
1671                 } // END - if
1672
1673                 // Put it in cache
1674                 $GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] = 'Y';
1675         }
1676
1677         // Return result
1678         return ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1679 }
1680
1681 // Load an extension's include file
1682 function loadExtensionInclude () {
1683         // Is it readable?
1684         if (!isExtensionIncludeReadable()) {
1685                 // Not readable
1686                 debug_report_bug(__FUNCTION__, __LINE__, 'Extension ' . getCurrentExtensionName() . ' should be loaded, but is not readable.');
1687         } // END - if
1688
1689         // Generate INC name
1690         $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1691
1692         // Load it
1693         loadInclude($INC);
1694 }
1695
1696 // Checks wether an extension is readable
1697 function isExtensionIncludeReadable ($ext_name = '') {
1698         // If empty, use current
1699         if (empty($ext_name)) $ext_name = getCurrentExtensionName();
1700
1701         // Array found?
1702         if (!isset($GLOBALS['ext_inc_readable'][$ext_name])) {
1703                 // Generate INC name
1704                 $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1705
1706                 // Is it readable?
1707                 $GLOBALS['ext_inc_readable'][$ext_name] = isIncludeReadable($INC);
1708         } // END - if
1709
1710         // Return result
1711         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',realable='.intval($GLOBALS['ext_inc_readable'][$ext_name]));
1712         return $GLOBALS['ext_inc_readable'][$ext_name];
1713 }
1714
1715 // Checks if an extension's function file is readable
1716 function isExtensionFunctionFileReadable ($ext_name) {
1717         if (isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name])) {
1718                 // Just count cache hits
1719                 incrementStatsEntry('cache_hits');
1720         } else {
1721                 // Construct FQFN for functions file
1722                 $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
1723
1724                 // Is this include there?
1725                 if ((isFileReadable($funcsInclude)) && (!isset($GLOBALS['ext_loaded']['funcs'][$ext_name])) && (getExtensionMode() == 'test')) {
1726                         // Cache it!
1727                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'Y';
1728                 } else {
1729                         // Cache it!
1730                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'N';
1731                 }
1732         }
1733
1734         // Return result
1735         return ($GLOBALS['cache_array']['extension']['ext_func'][$ext_name] == 'Y');
1736 }
1737
1738 // Adds an admin menu to the SQL queue of the menu entry is not found
1739 function addAdminMenuSql ($action, $what, $title, $descr, $sort) {
1740         // Now check if this menu is there
1741         if (!isMenuActionValid('admin', $action, $what)) {
1742                 // Is what null?
1743                 if (is_null($what)) {
1744                         // Add main menu
1745                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1746                                 $action,
1747                                 $title,
1748                                 $descr,
1749                                 bigintval($sort)
1750                         );
1751                 } else {
1752                         // Add sub menu
1753                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1754                                 $action,
1755                                 $what,
1756                                 $title,
1757                                 $descr,
1758                                 bigintval($sort)
1759                         );
1760                 }
1761
1762                 // Add it to the queue
1763                 addExtensionSql($sql);
1764         } elseif (isDebugModeEnabled()) {
1765                 // Double menus should be located and fixed!
1766                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double admin menu action=%s, what=%s detected.", $action, $what));
1767         }
1768 }
1769
1770 // Adds a guest menu to the SQL queue if the menu entry is not found
1771 function addGuestMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1772         // Now check if this menu is there
1773         if (!isMenuActionValid('guest', $action, $what)) {
1774                 // Is what null?
1775                 if (is_null($what)) {
1776                         // Add main menu
1777                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1778                                 $action,
1779                                 $title,
1780                                 $visible,
1781                                 $locked,
1782                                 bigintval($sort)
1783                         );
1784                 } else {
1785                         // Add sub menu
1786                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1787                                 $action,
1788                                 $what,
1789                                 $title,
1790                                 $visible,
1791                                 $locked,
1792                                 bigintval($sort)
1793                         );
1794                 }
1795
1796                 // Add it to the queue
1797                 addExtensionSql($sql);
1798         } elseif (isDebugModeEnabled()) {
1799                 // Double menus should be located and fixed!
1800                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double guest menu action=%s, what=%s detected.", $action, $what));
1801         }
1802 }
1803
1804 // Adds a member menu to the SQL queue if the menu entry is not found
1805 function addMemberMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1806         // Now check if this menu is there
1807         if (!isMenuActionValid('member', $action, $what)) {
1808                 // Is what null?
1809                 if (is_null($what)) {
1810                         // Add main menu
1811                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1812                                 $action,
1813                                 $title,
1814                                 $visible,
1815                                 $locked,
1816                                 bigintval($sort)
1817                         );
1818                 } else {
1819                         // Add sub menu
1820                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1821                                 $action,
1822                                 $what,
1823                                 $title,
1824                                 $visible,
1825                                 $locked,
1826                                 bigintval($sort)
1827                         );
1828                 }
1829
1830                 // Add it to the queue
1831                 addExtensionSql($sql);
1832         } elseif (isDebugModeEnabled()) {
1833                 // Double menus should be located and fixed!
1834                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double member menu action=%s, what=%s detected.", $action, $what));
1835         }
1836 }
1837
1838 // Adds a sponsor menu to the SQL queue if the menu entry is not found
1839 function addSponsorMenuSql ($action, $what, $title, $active, $sort) {
1840         // Now check if this menu is there, if no ext-sponsor is installed all is not yet added
1841         if ((!isExtensionInstalled('sponsor')) || (!isMenuActionValid('sponsor', $action, $what))) {
1842                 // Is what null?
1843                 if (is_null($what)) {
1844                         // Add main menu
1845                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1846                                 $action,
1847                                 $title,
1848                                 $active,
1849                                 bigintval($sort)
1850                         );
1851                 } else {
1852                         // Add sub menu
1853                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1854                                 $action,
1855                                 $what,
1856                                 $title,
1857                                 $active,
1858                                 bigintval($sort)
1859                         );
1860                 }
1861
1862                 // Add it to the queue
1863                 addExtensionSql($sql);
1864         } elseif (isDebugModeEnabled()) {
1865                 // Double menus should be located and fixed!
1866                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double sponsor menu action=%s, what=%s detected.", $action, $what));
1867         }
1868 }
1869
1870 // Enables/disables productive mode for current extension (used only while
1871 // registration).
1872 function enableExtensionProductive ($isProductive = true) {
1873         $GLOBALS['ext_productive'][getCurrentExtensionName()] = (bool) $isProductive;
1874 }
1875
1876 // Checks wether the extension is in productive phase. If not set, development
1877 // phase (=false) is assumed.
1878 function isExtensionProductive () {
1879         return ((isset($GLOBALS['ext_productive'][getCurrentExtensionName()])) && ($GLOBALS['ext_productive'][getCurrentExtensionName()] === true));
1880 }
1881
1882 // [EOF]
1883 ?>