]> git.mxchange.org Git - mailer.git/blob - inc/extensions-functions.php
Some templates renamed, fixed of double-init of extension notes:
[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 $ext_ver) {
245                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver=' . $ext_ver);
246                         // Load extension in update mode
247                         loadExtension(getCurrentExtensionName(), 'update', $ext_ver, isExtensionDryRun());
248
249                         // Add update notes to our output
250                         addExtensionNotes($ext_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                         } else {
389                                 // Extension has been removed for updates, so all is fine!
390                                 $ret = true;
391                         }
392                 } else {
393                         // No, an error occurs while registering extension :-(
394                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName());
395                         $ret = false;
396                 }
397         } elseif (($taskId > 0) && (getCurrentExtensionName() != '')) {
398                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
399                 // Remove task from system when id and extension's name is valid
400                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `id`=%s AND `status`='NEW' LIMIT 1",
401                         array(bigintval($taskId)), __FUNCTION__, __LINE__);
402         }
403
404         // Is this the sql_patches?
405         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . '/' . getExtensionMode());
406         if ((getCurrentExtensionName() == 'sql_patches') && ((getExtensionMode() == 'register') || (getExtensionMode() == 'remove')) && (!isExtensionDryRun()) && ($test)) {
407                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ': LOAD!');
408                 if ($logout === true) {
409                         // Then redirect to logout
410                         redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . getExtensionMode() . '=sql_patches');
411                 } else {
412                         // Add temporary filter
413                         registerFilter('shutdown', 'REDIRECT_TO_LOGOUT_SQL_PATCHES', true, true);
414                         $GLOBALS['ext_load_mode'] = getExtensionMode();
415                 }
416         } // END - if
417
418         // Return status code
419         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ' - EXIT!');
420         //* DEBUG: */ debugOutput(getCurrentExtensionName().':<pre>'.print_r($ret, true).'</pre>');
421         return $ret;
422 }
423
424 // Run SQL queries for given extension id
425 // @TODO Change from ext_id to ext_name (not just even the variable! ;-) )
426 function doExtensionSqls ($ext_id, $load_mode) {
427         // This shall never do a non-admin user!
428         if (!isAdmin()) return false;
429
430         // Get extension's name
431         $ext_name = getExtensionName($ext_id);
432
433         // Set current SQL name
434         setCurrentExtensionName($ext_name);
435
436         // Init EXT_UPDATE_DEPENDS
437         if (!isExtensionUpdateDependenciesInitialized()) {
438                 // Init here...
439                 initExtensionUpdateDependencies();
440         } // END - if
441
442         // Init array
443         initExtensionSqls();
444
445         // By default no SQL has been executed
446         $sqlRan = false;
447
448         // Load extension in detected mode
449         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ":ext_name[{$ext_id}]=".getCurrentExtensionName()."");
450         loadExtension(getCurrentExtensionName(), $load_mode, '', false);
451
452         // Init these SQLs
453         initSqls();
454         setSqlsArray(getExtensionSqls());
455
456         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ":SQLs::count=".countSqls()."");
457         if (isSqlsValid()) {
458                 // Run SQL commands...
459                 runFilterChain('run_sqls');
460         } // END - if
461
462         // Run any filters depending on the action here
463         runFilterChain('extension_' . $load_mode);
464
465         // Remove cache file(s) if extension is active
466         if (((isExtensionActive('cache')) && ((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == 'activate') || ($load_mode == 'deactivate'))) {
467                 // Run filters
468                 runFilterChain('post_extension_run_sql', getCurrentExtensionName());
469         } // END - if
470
471         // Is this the sql_patches?
472         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": id=".$ext_id.",currName=".getCurrentExtensionName().",loadMode=".$load_mode);
473         if ((getCurrentExtensionName() == 'sql_patches') && (($load_mode == 'register') || ($load_mode == 'remove'))) {
474                 // Then redirect to logout
475                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": LOAD!");
476                 redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . $load_mode . '=sql_patches');
477         } // END - if
478 }
479
480 // Check wether the given extension is installed
481 function isExtensionInstalled ($ext_name) {
482         // We don't like empty extension names here
483         if (empty($ext_name)) {
484                 // Please fix them all
485                 debug_report_bug(__FUNCTION__.': ext_name is empty.');
486         } // END - if
487
488         // By default non is installed
489         $isInstalled = false;
490
491         // Check if there is a cache entry
492         if (isset($GLOBALS['ext_is_installed'][$ext_name])) {
493                 // Use cache built from below queries
494                 $isInstalled = $GLOBALS['ext_is_installed'][$ext_name];
495         } elseif (isset($GLOBALS['cache_array']['extension']['ext_id'][$ext_name])) {
496                 // Found!
497                 $isInstalled = true;
498
499                 // Count cache hits
500                 incrementStatsEntry('cache_hits');
501         } elseif ((isInstallationPhase())) {
502                 // Extensions are all inactive/not installed during installation
503         } else {
504                 // Look in database
505                 $ext_id = getExtensionId($ext_name);
506
507                 // Do we have a record?
508                 $isInstalled = ($ext_id > 0);
509
510                 // Is it installed, then cache the entry
511                 if ($isInstalled === true) {
512                         // Dummy call (get is okay here)
513                         getExtensionId($ext_name, true);
514                 } // END - if
515
516                 // Remember the status
517                 $GLOBALS['ext_is_installed'][$ext_name] = $isInstalled;
518         }
519
520         // Return status
521         return $isInstalled;
522 }
523
524 // Check if given extension is active
525 function isExtensionActive ($ext_name) {
526         // Extensions are all inactive during installation
527         if ((isInstallationPhase()) || (empty($ext_name))) return false;
528
529         // Not active is the default
530         $data['ext_active'] = 'N';
531
532         // Check cache
533         if (isset($GLOBALS['cache_array']['extension']['ext_active'][$ext_name])) {
534                 // Load from cache
535                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
536                 $data['ext_active'] = $GLOBALS['cache_array']['extension']['ext_active'][$ext_name];
537
538                 // Count cache hits
539                 incrementStatsEntry('cache_hits');
540         } elseif (isset($GLOBALS['ext_loaded'][$ext_name])) {
541                 // @TODO Extension is loaded, what next?
542                 debug_report_bug(__FUNCTION__, __LINE__, 'LOADED:' . $ext_name);
543         } elseif (($ext_name == 'cache') || (!isExtensionInstalled('cache'))) {
544                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
545                 // Load from database
546                 $result = SQL_QUERY_ESC("SELECT `ext_active` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
547                         array($ext_name), __FUNCTION__, __LINE__);
548
549                 // Entry found?
550                 if (SQL_NUMROWS($result) == 1) {
551                         // Load entry
552                         $data = SQL_FETCHARRAY($result);
553                 } // END - if
554
555                 // Free result
556                 SQL_FREERESULT($result);
557
558                 // Write cache array
559                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name."[DB]: ".$data['ext_active']."");
560                 $GLOBALS['cache_array']['extension']['ext_active'][$ext_name] = $data['ext_active'];
561         } else {
562                 // Extension not active!
563                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name.": Not active!");
564                 $GLOBALS['cache_array']['extension']['ext_active'][$ext_name] = 'N';
565         }
566
567         // Debug message
568         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name.",active=".$data['ext_active']."");
569
570         // Is this extension activated? (For admins we always have active extensions...)
571         return ($data['ext_active'] == 'Y');
572 }
573
574 // Get version from extensions
575 function getExtensionVersion ($ext_name, $force = false) {
576         // By default no extension is found
577         $data['ext_version'] = 'false';
578
579         // Empty extension name should be fixed!
580         if (empty($ext_name)) {
581                 // Please report this bug!
582                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_name is empty which is not allowed here.');
583         } // END - if
584
585         // Extensions are all inactive during installation
586         if (isInstallationPhase()) return '';
587         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": ext_name=".$ext_name."");
588
589         // Is the cache written?
590         if (isset($GLOBALS['cache_array']['extension']['ext_version'][$ext_name])) {
591                 // Load data from cache
592                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $ext_name . ': CACHE!');
593                 $data['ext_version'] = $GLOBALS['cache_array']['extension']['ext_version'][$ext_name];
594
595                 // Count cache hits
596                 incrementStatsEntry('cache_hits');
597         } elseif ((!isCacheInstanceValid()) || (isset($GLOBALS['cache_array']['extension'])) || (getOutputMode() != 0)) {
598                 // Load from database
599                 $result = SQL_QUERY_ESC("SELECT `ext_version` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
600                         array($ext_name), __FUNCTION__, __LINE__);
601                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, $ext_name . ': DB - '.SQL_NUMROWS($result).'');
602
603                 // Is the extension there?
604                 if (SQL_NUMROWS($result) == 1) {
605                         // Load entry
606                         $data = SQL_FETCHARRAY($result);
607                 } elseif (isDebugModeEnabled()) {
608                         // Not found, please report all
609                         debug_report_bug(__FUNCTION__, __LINE__, sprintf(": Cannot find extension %s in database!", $ext_name));
610                 }
611
612                 // Free result
613                 SQL_FREERESULT($result);
614
615                 // Set cache
616                 $GLOBALS['cache_array']['extension']['ext_version'][$ext_name] = $data['ext_version'];
617         }
618
619         // Extension version should not be invalid
620         if (($data['ext_version'] == 'false') && ($force === false)) {
621                 // Please report this trouble
622                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Extension <span class=\"data\">%s</span> has empty version!", $ext_name));
623         } // END - if
624
625         // Return result
626         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": ret={$data['ext_version']}");
627         return $data['ext_version'];
628 }
629
630 // Updates a given extension with current extension version to latest version
631 function updateExtension ($ext_name, $ext_ver, $dry_run = false) {
632         // Only admins are allowed to update extensions
633         if ((!isAdmin()) || (empty($ext_name))) return false;
634
635         // Set current SQL name
636         setCurrentExtensionName($ext_name);
637
638         // Init arrays
639         initExtensionSqls();
640         initExtensionNotes();
641         initIncludePool('extension');
642
643         // Load extension in test mode
644         loadExtension($ext_name, 'test', $ext_ver, isExtensionDryRun());
645
646         // Save version history
647         $history = getExtensionVersionHistory();
648
649         // Remove old SQLs array to prevent possible bugs
650         initExtensionSqls();
651
652         // Check if version is updated
653         //* DEBUG: */ debugOutput(getCurrentExtensionName().'/'.$ext_name.':'.getThisExtensionVersion().'/'.$ext_ver.'/'.intval(is_array($history)));
654         if (((getThisExtensionVersion() != $ext_ver) || (isExtensionDryRun())) && (is_array($history))) {
655                 // Search for starting point
656                 $start = array_search($ext_ver, $history);
657
658                 // And load SQL queries in order of version history
659                 for ($idx = ($start + 1); $idx < count($history); $idx++) {
660                         // Set extension version
661                         $GLOBALS['update_ver'][getCurrentExtensionName()] = $history[$idx];
662
663                         // Load again...
664                         loadExtension(getCurrentExtensionName(), 'update', $GLOBALS['update_ver'][getCurrentExtensionName()], isExtensionDryRun());
665
666                         // Get all depencies
667                         $depencies = getExtensionUpdateDependencies();
668
669                         // Nothing to apply?
670                         if (count($depencies) > 0) {
671                                 // Apply all extension depencies
672                                 foreach ($depencies as $ext_depend) {
673                                         // Did we already update/register this?
674                                         if (!isset($GLOBALS['ext_updated'][$ext_depend])) {
675                                                 // Set it as current
676                                                 setCurrentExtensionName($ext_depend);
677
678                                                 // Mark it as already updated before we update it
679                                                 $GLOBALS['ext_updated'][$ext_depend] = true;
680
681                                                 // Is the extension there?
682                                                 if (isExtensionInstalled($ext_depend)) {
683                                                         // Update another extension first!
684                                                         $test = updateExtension($ext_depend, getExtensionVersion($ext_depend), isExtensionDryRun());
685                                                 } else {
686                                                         // Register new extension
687                                                         $test = registerExtension($ext_depend, 0, isExtensionDryRun(), false);
688                                                 }
689                                         } // END - if
690                                 } // END - foreach
691
692                                 // Set extension version here
693                                 setCurrentExtensionVersion($ext_ver);
694
695                                 // Set name back
696                                 setCurrentExtensionName($ext_name);
697                         } // END - if
698
699                         // Add notes
700                         addExtensionNotes($history[$idx]);
701                 } // END - for
702
703                 // In real-mode execute any existing includes
704                 if (isExtensionDryRun() === false) {
705                         $GLOBALS['ext_inc_pool'][getCurrentExtensionName()] = getIncludePool('extension');
706                         runFilterChain('load_includes', 'extension');
707                         setIncludePool('extension', $GLOBALS['ext_inc_pool'][getCurrentExtensionName()]);
708                         unset($GLOBALS['ext_inc_pool'][getCurrentExtensionName()]);
709                 } // END - if
710
711                 // Init these SQLs
712                 initSqls();
713                 setSqlsArray(getExtensionSqls());
714
715                 // Run SQLs
716                 runFilterChain('run_sqls', array('dry_run' => isExtensionDryRun()));
717
718                 if (isExtensionDryRun() === false) {
719                         // Run filters on success extension update
720                         runFilterChain('extension_update', getCurrentExtensionName());
721                 } // END - if
722         } // END - if
723 }
724
725 // Output verbose SQL table for extension
726 function addExtensionVerboseSqlTable ($title = '', $dashed = '', $switch = false, $width = '100%') {
727         // Empty title?
728         if (empty($title)) {
729                 // Then fix it to default
730                 $title = '{--ADMIN_SQLS_EXECUTED_ON_REMOVAL--}';
731         } // END - if
732
733         // Init variables
734         $OUT = '';
735
736         // Do we have queries?
737         if ((isExtensionInstalledAndNewer('sql_patches', '0.0.7')) && (getConfig('verbose_sql') == 'Y')) {
738                 // Do we have entries?
739                 if (countExtensionSqls() > 0) {
740                         // Init counter
741                         $idx = 0;
742                         // Get all SQLs
743                         foreach (getExtensionSqls() as $sqls) {
744                                 // New array format is recursive
745                                 foreach ($sqls as $sql) {
746                                         // Trim out spaces
747                                         $sql = trim($sql);
748
749                                         // Output command if set
750                                         if (!empty($sql)) {
751                                                 // Prepare output for template
752                                                 $content = array(
753                                                         'i'   => ($idx + 1),
754                                                         'sql' => $sql
755                                                 );
756
757                                                 // Load row template
758                                                 $OUT .= loadTemplate('admin_extension_sql_row', true, $content);
759
760                                                 // Count up
761                                                 $idx++;
762                                         } // END - if
763                                 } // END - foreach
764                         } // END - foreach
765
766                         // Prepare content for template
767                         $content = array(
768                                 'width'  => $width,
769                                 'dashed' => $dashed,
770                                 'title'  => $title,
771                                 'rows'   => $OUT
772                         );
773
774                         // Load main template
775                         $OUT = loadTemplate('admin_extension_sql_table', true, $content);
776                 } else {
777                         // No addional SQL commands to run
778                         $OUT = loadTemplate('admin_settings_saved', true, '{--ADMIN_NO_ADDITIONAL_SQLS--}');
779                 }
780         } // END - if
781
782         // Return output
783         return $OUT;
784 }
785
786 // Get extension name from id
787 function getExtensionName ($ext_id) {
788         // Init extension name
789         $data['ext_name'] = '';
790
791         // Is cache there?
792         if (isset($GLOBALS['cache_array']['extension']['ext_name'][$ext_id])) {
793                 // Load from cache
794                 $data['ext_name'] = $GLOBALS['cache_array']['extension']['ext_name'][$ext_id];
795
796                 // Count cache hits
797                 incrementStatsEntry('cache_hits');
798         } elseif (!isExtensionActive('cache')) {
799                 // Load from database
800                 $result = SQL_QUERY_ESC("SELECT `ext_name` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `id`=%s LIMIT 1",
801                         array(bigintval($ext_id)), __FUNCTION__, __LINE__);
802
803                 // Is the entry there?
804                 if (SQL_NUMROWS($result) == 1) {
805                         // Get the extension's name from database
806                         $data = SQL_FETCHARRAY($result);
807                 } // END - if
808
809                 // Free result
810                 SQL_FREERESULT($result);
811         }
812
813         // Did we find some extension?
814         if (empty($data['ext_name'])) {
815                 // We should fix these all!
816                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_name is empty. ext_id=' . $ext_id);
817         } // END - if
818
819         // Return the extension name
820         return $data['ext_name'];
821 }
822
823 // Get extension id from name
824 function getExtensionId ($ext_name) {
825         // Init id number
826         $data['ext_id'] = '0';
827
828         // Do we have cache?
829         if (isset($GLOBALS['cache_array']['extension']['ext_id'][$ext_name])) {
830                 // Load from cache
831                 $data['ext_id'] = $GLOBALS['cache_array']['extension']['ext_id'][$ext_name];
832
833                 // Count cache hits
834                 incrementStatsEntry('cache_hits');
835         } else {
836                 // Load from database
837                 $result = SQL_QUERY_ESC("SELECT `id` AS ext_id FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
838                         array($ext_name), __FUNCTION__, __LINE__);
839
840                 // Is the entry there?
841                 if (SQL_NUMROWS($result) == 1) {
842                         // Get the extension's id from database
843                         $data = SQL_FETCHARRAY($result);
844                 } // END - if
845
846                 // Free result
847                 SQL_FREERESULT($result);
848
849                 // Cache it
850                 $GLOBALS['cache_array']['extension']['ext_id'][$ext_name] = $data['ext_id'];
851         }
852
853         // Return value
854         return $data['ext_id'];
855 }
856
857 // Determines wether the given extension name is valid
858 function isExtensionNameValid ($ext_name) {
859         // Do we have cache?
860         if (!isset($GLOBALS['ext_name_valid'][$ext_name])) {
861                 // Generate include file name
862                 $INC = sprintf("inc/extensions/ext-%s.php", $ext_name);
863
864                 // Is there a file in inc/extensions/ ?
865                 $GLOBALS['ext_name_valid'][$ext_name] = isIncludeReadable($INC);
866         } // END - if
867
868         // Return result
869         return $GLOBALS['ext_name_valid'][$ext_name];
870 }
871
872 // Determines wether the given extension id is valid
873 function isExtensionIdValid ($ext_id) {
874         // Default is nothing valid
875         $isValid = false;
876
877         // Check in cache then in database
878         if (isset($GLOBALS['cache_array']['extension']['ext_name'][$ext_id])) {
879                 // Valid!
880                 $isValid = true;
881
882                 // Count cache hits
883                 incrementStatsEntry('cache_hits');
884         } else {
885                 // Query database
886                 $isValid = (countSumTotalData($ext_id, 'extensions', 'id', 'id', true) == 1);
887         }
888
889         // Return result
890         return $isValid;
891 }
892
893 // Activate given extension
894 function doActivateExtension ($ext_name) {
895         // Activate the extension
896         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_active`='Y' WHERE `ext_name`='%s' LIMIT 1",
897                 array($ext_name), __FUNCTION__, __LINE__);
898
899         // Extension has been activated?
900         if (SQL_AFFECTEDROWS() == 1) {
901                 // Then run all queries
902                 doExtensionSqls(getExtensionId($ext_name), 'activate');
903         } // END - if
904 }
905
906 // Deactivate given extension
907 function doDeactivateExtension($ext_name) {
908         // Activate the extension
909         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_active`='N' WHERE `ext_name`='%s' LIMIT 1",
910                 array($ext_name), __FUNCTION__, __LINE__);
911
912         // Extension has been activated?
913         if (SQL_AFFECTEDROWS() == 1) {
914                 // Then run all queries
915                 doExtensionSqls(getExtensionId($ext_name), 'deactivate');
916
917                 // Create new task (we ignore the task id here)
918                 createExtensionDeactivationTask($ext_name);
919
920                 // Notify the admin
921                 sendAdminNotification(
922                         '{--ADMIN_EXTENSION_DEACTIVATED_SUBJECT--}',
923                         'admin_extension_deactivated',
924                         array('ext_name' => $ext_name)
925                 );
926         } // END - if
927 }
928
929 // Checks wether the extension is older than given
930 function isExtensionOlder ($ext_name, $ext_ver) {
931         // Get current extension version
932         $currVersion = getExtensionVersion($ext_name);
933
934         // Remove all dots from both versions
935         $currVersion = str_replace('.', '', $currVersion);
936         $ext_ver = str_replace('.', '', $ext_ver);
937
938         // Now compare both and return the result
939         return ($currVersion < $ext_ver);
940 }
941
942 // Creates a new task for updated extension
943 function createExtensionUpdateTask ($adminId, $ext_name, $ext_ver, $notes) {
944         // Create subject line
945         $subject = '[UPDATE-' . $ext_name . '-' . $ext_ver . ':] {--ADMIN_UPDATE_EXTENSION_SUBJECT--}';
946
947         // Get task id
948         $taskId = determineTaskIdBySubject($subject);
949
950         // Is the extension there?
951         if (isExtensionInstalled($ext_name)) {
952                 // Check if task is not there
953                 if ($taskId == '0') {
954                         // Create extension update-task
955                         $taskId = createNewTask($subject, $notes, 'EXTENSION_UPDATE', 0, $adminId);
956                 } // END - if
957         } else {
958                 // Extension not there! :-(
959                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("Extension <span class=\"data\">%s</span> not found but should be updated?", $ext_name));
960         }
961
962         // Return task id
963         return $taskId;
964 }
965
966 // Creates a new task for newly installed extension
967 function createNewExtensionTask ($ext_name) {
968         // Generate subject line
969         $subject = sprintf("[%s:]", $ext_name);
970
971         // Get task id
972         $taskId = determineTaskIdBySubject($subject);
973
974         // Not installed and do we have created a task for the admin?
975         if (($taskId == '0') && (!isExtensionInstalled($ext_name))) {
976                 // Set default message if ext-foo is missing
977                 $message = getMaskedMessage('ADMIN_EXTENSION_TEXT_FILE_MISSING', $ext_name);
978
979                 // Template file
980                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
981                         getConfig('PATH'),
982                         getLanguage(),
983                         $ext_name
984                 );
985
986                 // Load text for task if found
987                 if (isFileReadable($tpl)) {
988                         // Load extension's own text template (HTML!)
989                         $message = loadTemplate('ext_' . $ext_name, true);
990                 } else {
991                         // Write this in debug.log as well
992                         logDebugMessage(__FUNCTION__, __LINE__, $message);
993                 }
994
995                 // Task not created so it's a brand-new extension which we need to register and create a task for!
996                 $taskId = createNewTask($subject, $message, 'EXTENSION', 0, getCurrentAdminId(), false);
997         } // END - if
998
999         // Return task id
1000         return $taskId;
1001 }
1002
1003 // Creates a task for automatically deactivated (deprecated) extension
1004 function createExtensionDeactivationTask ($ext_name) {
1005         // Create subject line
1006         $subject = sprintf("[%s:] %s", $ext_name, '{--ADMIN_TASK_EXTENSION_DEACTIVATED_SUBJECT--}');
1007
1008         // Get task id
1009         $taskId = determineTaskIdBySubject($subject);
1010
1011         // Not installed and do we have created a task for the admin?
1012         if (($taskId == '0') && (isExtensionInstalled($ext_name))) {
1013                 // Task not created so add it
1014                 $taskId = createNewTask($subject, SQL_ESCAPE(loadTemplate('task_EXTENSION_deactivated', true, $ext_name)), 'EXTENSION_DEACTIVATION');
1015         } // END - if
1016
1017         // Return task id
1018         return $taskId;
1019 }
1020
1021 // Checks if the module has a menu
1022 function ifModuleHasMenu ($mod, $forceDb = false) {
1023         // All is false by default
1024         $ret = false;
1025
1026         // Extension installed and newer than or has version 0.1.2?
1027         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
1028                 // Cache version is okay, so let's check the cache!
1029                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$mod])) {
1030                         // Check module cache and count hit
1031                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$mod] == 'Y');
1032                         incrementStatsEntry('cache_hits');
1033                 } elseif (isset($GLOBALS['cache_array']['extension']['ext_menu'][$mod])) {
1034                         // Check cache and count hit
1035                         $ret = ($GLOBALS['cache_array']['extension']['ext_menu'][$mod] == 'Y');
1036                         incrementStatsEntry('cache_hits');
1037                 } else {
1038                         // Admin/guest/member/sponsor modules have always a menu!
1039                         $ret = in_array($mod, array('admin', 'index', 'login', 'sponsor'));
1040                 }
1041         } elseif ((isExtensionInstalledAndNewer('sql_patches', '0.3.6')) && ((!isExtensionActive('cache')) || ($forceDb === true))) {
1042                 // Check database for entry
1043                 $result = SQL_QUERY_ESC("SELECT `has_menu` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
1044                         array($mod), __FUNCTION__, __LINE__);
1045
1046                 // Entry found?
1047                 if (SQL_NUMROWS($result) == 1) {
1048                         // Load "has_menu" column
1049                         $data = SQL_FETCHARRAY($result);
1050
1051                         // Fake cache... ;-)
1052                         $GLOBALS['cache_array']['extension']['ext_menu'][$mod] = $data['has_menu'];
1053
1054                         // Does it have a menu?
1055                         $ret = ($data['has_menu'] == 'Y');
1056                 } // END  - if
1057
1058                 // Free memory
1059                 SQL_FREERESULT($result);
1060         } elseif (!isExtensionInstalled('sql_patches')) {
1061                 // No sql_patches installed, so maybe in admin/guest/member/sponsor area or no admin registered?
1062                 $ret = in_array($mod, array('admin', 'index', 'login', 'sponsor')); // Then there is a menu!
1063         } else {
1064                 // Unsupported state!
1065                 logDebugMessage(__FUNCTION__, __LINE__, 'This should never be reached.');
1066         }
1067
1068         // Return status
1069         return $ret;
1070 }
1071
1072 // Determines the task id for given extension
1073 function determineExtensionTaskId ($ext_name) {
1074         // Default is not found
1075         $data['task_id'] = '0';
1076
1077         // Search for extension task's id
1078         $result = SQL_QUERY_ESC("SELECT `id` AS task_id FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `task_type`='EXTENSION' AND `subject`='[%s:]' LIMIT 1",
1079                 array($ext_name), __FUNCTION__, __LINE__);
1080
1081         // Entry found?
1082         if (SQL_NUMROWS($result) == 1) {
1083                 // Task found so load task's id and register extension...
1084                 $data = SQL_FETCHARRAY($result);
1085         } // END - if
1086
1087         // Free result
1088         SQL_FREERESULT($result);
1089
1090         // Return it
1091         return $data['task_id'];
1092 }
1093
1094 // Determines the task id for given subject
1095 function determineTaskIdBySubject ($subject) {
1096         // Default is not found
1097         $data['task_id'] = '0';
1098
1099         // Search for task id
1100         $result = SQL_QUERY_ESC("SELECT `id` AS task_id FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `subject` LIKE '%s%%' LIMIT 1",
1101                 array($subject), __FUNCTION__, __LINE__);
1102
1103         // Entry found?
1104         if (SQL_NUMROWS($result) == 1) {
1105                 // Task found so load task's id and register extension...
1106                 $data = SQL_FETCHARRAY($result);
1107         } // END - if
1108
1109         // Free result
1110         SQL_FREERESULT($result);
1111
1112         // Return it
1113         return $data['task_id'];
1114 }
1115
1116 // Add updates notes for given version
1117 function addExtensionNotes ($ext_ver) {
1118         // Init notes/content
1119         $out = '';
1120         $content = array();
1121
1122         // Is do we have verbose output enabled?
1123         if ((!isExtensionActive('sql_patches')) || (getConfig('verbose_sql') == 'Y')) {
1124                 // Update notes found?
1125                 if (isExtensionUpdateNoteSet($ext_ver)) {
1126                         // Update notes found
1127                         $content = array(
1128                                 'ver'   => $ext_ver,
1129                                 'notes' => getExtensionUpdateNotes($ext_ver)
1130                         );
1131
1132                         // Reset them
1133                         setExtensionUpdateNotes('', $ext_ver);
1134                 } elseif (in_array($ext_ver, array('0.0', '0.0.0'))) {
1135                         // Initial release
1136                         $content = array(
1137                                 'ver'   => $ext_ver,
1138                                 'notes' => '{--INITIAL_RELEASE--}'
1139                         );
1140                 } else {
1141                         // No update notes found!
1142                         $content = array(
1143                                 'ver'   => $ext_ver,
1144                                 'notes' => '{--NO_UPDATE_NOTES--}'
1145                         );
1146                 }
1147
1148                 // Load template
1149                 $out = loadTemplate('admin_extension_notes', true, $content);
1150         } // END - if
1151
1152         // Add the notes
1153         appendExtensionNotes($out);
1154 }
1155
1156 // Getter for CSS files array
1157 function getExtensionCssFiles () {
1158         // By default no additional CSS files are found
1159         $cssFiles = array();
1160
1161         // Is the array there?
1162         if (isset($GLOBALS['css_files'])) {
1163                 // Then use it
1164                 $cssFiles = $GLOBALS['css_files'];
1165         } // END - if
1166
1167         // Return array
1168         return $cssFiles;
1169 }
1170
1171 // Init CSS files array
1172 function initExtensionCssFiles () {
1173         // Simply init it
1174         $GLOBALS['css_files'] = array();
1175 }
1176
1177 // Add new entry
1178 function addExtensionCssFile ($file) {
1179         // Is the array there?
1180         if (!isset($GLOBALS['css_files'])) {
1181                 // Then auto-init them
1182                 initExtensionCssFiles();
1183         } // END - if
1184
1185         // Add the entry
1186         $GLOBALS['css_files'][] = $file;
1187 }
1188
1189 // Setter for EXT_ALWAYS_ACTIVE flag
1190 function setExtensionAlwaysActive ($active) {
1191         $GLOBALS['ext_always_active'][getCurrentExtensionName()] = (string) $active;
1192 }
1193
1194 // Getter for EXT_ALWAYS_ACTIVE flag
1195 function getExtensionAlwaysActive () {
1196         return $GLOBALS['ext_always_active'][getCurrentExtensionName()];
1197 }
1198
1199 // Checks wether the current extension is always active
1200 function isExtensionAlwaysActive () {
1201         return (getExtensionAlwaysActive() == 'Y');
1202 }
1203
1204 // Setter for EXT_VERSION flag
1205 function setThisExtensionVersion ($ext_version) {
1206         $GLOBALS['ext_version'][getCurrentExtensionName()] = (string) $ext_version;
1207 }
1208
1209 // Getter for EXT_VERSION flag
1210 function getThisExtensionVersion () {
1211         return $GLOBALS['ext_version'][getCurrentExtensionName()];
1212 }
1213
1214 // Setter for EXT_DEPRECATED flag
1215 function setExtensionDeprecated ($deprecated) {
1216         $GLOBALS['ext_deprecated'][getCurrentExtensionName()] = (string) $deprecated;
1217 }
1218
1219 // Getter for EXT_DEPRECATED flag
1220 function isExtensionDeprecated () {
1221         return ($GLOBALS['ext_deprecated'][getCurrentExtensionName()] == 'Y');
1222 }
1223
1224 // Setter for EXT_UPDATE_DEPENDS flag
1225 function addExtensionUpdateDependency ($updateDepends) {
1226         //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . '/' . $updateDepends . ' - ENTERED!');
1227         // Is the update depency empty? (NEED TO BE FIXED!)
1228         if (empty($updateDepends)) {
1229                 // Please report this bug!
1230                 debug_report_bug(__FUNCTION__, __LINE__, 'updateDepends is empty: currentExtension=' . getCurrentExtensionName());
1231         } // END - if
1232
1233         // Is it not yet added?
1234         /* DEBUG:
1235         if ((isset($updateDepends, $GLOBALS['ext_running_updates'][getCurrentExtensionName()])) && (in_array($updateDepends, getExtensionUpdatesRunning()))) {
1236                 // Double-adding isn't fine, too
1237                 debug_report_bug(__FUNCTION__, __LINE__, '() called twice: updateDepends=' . $updateDepends . ',currentExtension=' . getCurrentExtensionName());
1238         } // END - if
1239         */
1240
1241         // Add it to the list of extension update depencies map
1242         $GLOBALS['ext_update_depends'][getCurrentExtensionName()][] = (string) $updateDepends;
1243
1244         // Remember it in the list of running updates
1245         $GLOBALS['ext_running_updates'][getCurrentExtensionName()][] = $updateDepends;
1246         //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . '/' . $updateDepends . ' - EXIT!');
1247 }
1248
1249 // Getter for running updates
1250 function getExtensionUpdatesRunning () {
1251         return $GLOBALS['ext_running_updates'][getCurrentExtensionName()];
1252 }
1253
1254 // Checks wether the given extension registration is in progress
1255 function isExtensionRegistrationRunning ($ext_name) {
1256         // Simply check it
1257         $isRunning = ((isset($GLOBALS['ext_register_running'])) && (in_array($ext_name, $GLOBALS['ext_register_running'])));
1258
1259         // Return it
1260         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1261         return $isRunning;
1262 }
1263
1264 // Init EXT_UPDATE_DEPENDS flag
1265 function initExtensionUpdateDependencies () {
1266         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - ENTERED!');
1267
1268         // Init update depency map automatically if not found
1269         if (isExtensionUpdateDependenciesInitialized()) {
1270                 // We need these bug reports as well...
1271                 debug_report_bug(__FUNCTION__, __LINE__, '() is called twice: currName=' . getCurrentExtensionName());
1272         } // END - if
1273
1274         $GLOBALS['ext_update_depends'][getCurrentExtensionName()] = array();
1275
1276         // Init running updates array
1277         initExtensionRuningUpdates();
1278
1279         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - EXIT!');
1280 }
1281
1282 // Adds an extension as "registration in progress"
1283 function addExtensionRunningRegistration ($ext_name) {
1284         // Is it running?
1285         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Registration in progress: ext_name=' . $ext_name . ' - ENTERED!');
1286         if (isExtensionRegistrationRunning($ext_name)) {
1287                 // This is really bad and should not be quietly ignored
1288                 debug_report_bug(__FUNCTION__, __LINE__, '() already called! ext_name=' . $ext_name);
1289         } // END - if
1290
1291         // Then add it!
1292         $GLOBALS['ext_register_running'][] = $ext_name;
1293         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Registration in progress: ext_name=' . $ext_name . ' - EXIT!');
1294 }
1295
1296 // Checks wether EXT_UPDATE_DEPENDS is initialized
1297 function isExtensionUpdateDependenciesInitialized () {
1298         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
1299         return (isset($GLOBALS['ext_update_depends'][getCurrentExtensionName()]));
1300 }
1301
1302 // Checks wether an update is already running for given extension
1303 function isExtensionUpdateRunning ($ext_name) {
1304         // Current and given extensions means whole array
1305         if ($ext_name == getCurrentExtensionName()) {
1306                 // Default is not found
1307                 $isRunning = false;
1308
1309                 // Walk through whole array
1310                 foreach ($GLOBALS['ext_running_updates'] as $ext1=>$depends) {
1311                         // Is it found?
1312                         if (($ext1 == $ext_name) || ($isRunning === true)) {
1313                                 // Found!
1314                                 logDebugMessage(__FUNCTION__, __LINE__, 'ext1=' . $ext1 . ',ext_name=' . $ext_name . ',isRunning=' . intval($isRunning));
1315                                 $isRunning = true;
1316                                 break;
1317                         } // END - if
1318                 } // END - foreach
1319
1320                 // Return result
1321                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1322                 return $isRunning;
1323         } // END - if
1324
1325         // Simply check it
1326         $isRunning = ((isExtensionUpdateDependenciesInitialized()) && (in_array($ext_name, getExtensionRunningUpdates())));
1327
1328         // Return it
1329         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1330         return $isRunning;
1331 }
1332
1333 // Initializes the list of running updates
1334 function initExtensionRuningUpdates () {
1335         // Auto-init ext_running_updates
1336         if (!isset($GLOBALS['ext_running_updates'])) {
1337                 $GLOBALS['ext_running_updates'] = array();
1338                 $GLOBALS['ext_register_running'] = array();
1339         } // END - if
1340 }
1341
1342 // Getter for EXT_UPDATE_DEPENDS flag
1343 function getExtensionUpdateDependencies () {
1344         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1345         return $GLOBALS['ext_update_depends'][getCurrentExtensionName()];
1346 }
1347
1348 // Getter for next iterator depency
1349 function getExtensionUpdateDependenciesIterator () {
1350         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1351         return ($GLOBALS['ext_update_depends'][getCurrentExtensionName()][getExtensionUpdateIterator()]);
1352 }
1353
1354 // Counter for extension update depencies
1355 function countExtensionUpdateDependencies () {
1356         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1357         return count($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1358 }
1359
1360 // Removes given extension from update denpency list
1361 function removeExtensionUpdateDependency ($ext_name) {
1362         // Look it up
1363         $key = array_search($ext_name, getExtensionUpdateDependencies());
1364
1365         // Is it valid?
1366         if ($key !== false) {
1367                 // Then remove it
1368                 unset($GLOBALS['ext_update_depends'][getCurrentExtensionName()][$key]);
1369
1370                 // And sort the array
1371                 ksort($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1372         } // END - if
1373 }
1374
1375 // Init iterator for update depencies
1376 function initExtensionUpdateIterator () {
1377         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1378         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()] = '0';
1379 }
1380
1381 // Getter for depency iterator
1382 function getExtensionUpdateIterator () {
1383         // Auto-init iterator
1384         if (!isset($GLOBALS['ext_depend_iterator'][getCurrentExtensionName()])) initExtensionUpdateIterator();
1385
1386         // Return it
1387         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().'/'.$GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]);
1388         return $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()];
1389 }
1390
1391 // Increments the update iterator
1392 function incrementExtensionUpdateIterator () {
1393         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1394         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]++;
1395 }
1396
1397 // Setter for EXT_REPORTS_FAILURE flag
1398 function setExtensionReportsFailure ($reportsFailure) {
1399         $GLOBALS['ext_reports_failure'] = (bool) $reportsFailure;
1400 }
1401
1402 // Getter for EXT_REPORTS_FAILURE flag
1403 function getExtensionReportsFailure () {
1404         return $GLOBALS['ext_reports_failure'];
1405 }
1406
1407 // Setter for EXT_VER_HISTORY flag
1408 function setExtensionVersionHistory ($versionHistory) {
1409         $GLOBALS['ext_ver_history'][getCurrentExtensionName()] = (array) $versionHistory;
1410 }
1411
1412 // Getter for EXT_VER_HISTORY array
1413 function getExtensionVersionHistory () {
1414         return $GLOBALS['ext_ver_history'][getCurrentExtensionName()];
1415 }
1416
1417 // Setter for EXT_UPDATE_NOTES
1418 function setExtensionUpdateNotes ($updateNotes, $ext_ver = '') {
1419         // . '/' . getCurrentExtensionVersion()
1420         //* DEBUG: */ debug_report_bug(__FUNCTION__.':' . getCurrentExtensionName() . '/' . getExtensionMode() . '/' . $ext_ver . '=' . $updateNotes);
1421         if (empty($ext_ver)) {
1422                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][getCurrentExtensionVersion()] = (string) $updateNotes;
1423         } else {
1424                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ext_ver] = (string) $updateNotes;
1425         }
1426 }
1427
1428 // Getter for EXT_UPDATE_NOTES
1429 function getExtensionUpdateNotes ($ext_ver) {
1430         return $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ext_ver];
1431 }
1432
1433 // Checks if ext_update_notes is set
1434 function isExtensionUpdateNoteSet ($ext_ver) {
1435         return isset($GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ext_ver]);
1436 }
1437
1438 // Init extension notice
1439 function initExtensionNotes () {
1440         // Is it already initialized?
1441         if (isset($GLOBALS['ext_notes'][getCurrentExtensionName()])) {
1442                 // This is mostly not wanted, so please report it
1443                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_notes already set for extension ' . getCurrentExtensionName());
1444         } // END - if
1445
1446         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getCurrentExtensionName()=' . getCurrentExtensionName());
1447         $GLOBALS['ext_notes'][getCurrentExtensionName()] = '';
1448 }
1449
1450 // Append extension notice
1451 function appendExtensionNotes ($notes) {
1452         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getCurrentExtensionName()=' . getCurrentExtensionName() . ', notes()=' . strlen($notes));
1453         $GLOBALS['ext_notes'][getCurrentExtensionName()] .= (string) trim($notes);
1454 }
1455
1456 // Getter for extension notes
1457 function getExtensionNotes () {
1458         return $GLOBALS['ext_notes'][getCurrentExtensionName()];
1459 }
1460
1461 // Setter for current extension name
1462 function setCurrentExtensionName ($ext_name) {
1463         $GLOBALS['curr_extension_name'] = (string) trim($ext_name);
1464 }
1465
1466 // Getter for current extension name
1467 function getCurrentExtensionName () {
1468         if (!isset($GLOBALS['curr_extension_name'])) {
1469                 // Not set!
1470                 debug_report_bug(__FUNCTION__, __LINE__, 'curr_extension_name not initialized. Please execute initExtensionSqls() before calling this function.');
1471         } // END - if
1472
1473         // Return it
1474         return $GLOBALS['curr_extension_name'];
1475 }
1476
1477 // Init SQLs array for current extension
1478 function initExtensionSqls ($force = false) {
1479         // Auto-init the array or if forced
1480         if ((!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) || ($force === true)) {
1481                 // Set the array
1482                 $GLOBALS['ext_sqls'][getCurrentExtensionName()] = array();
1483
1484                 // Initialize the generic array
1485                 initSqls();
1486         } // END - if
1487 }
1488
1489 // Adds SQLs to the SQLs array but "assigns" it with current extension name
1490 function addExtensionSql ($sql) {
1491         // Add it
1492         $GLOBALS['ext_sqls'][getCurrentExtensionName()][getCurrentExtensionVersion()][] = $sql;
1493 }
1494
1495 // Getter for SQLs array for current extension
1496 function getExtensionSqls () {
1497         // Output debug backtrace if not found (SHOULD NOT HAPPEN!)
1498         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1499                 // Not found, should not happen
1500                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("ext_sqls is empty, current extension: %s",
1501                         getCurrentExtensionName()
1502                 ));
1503         } // END - if
1504
1505         // Return the array
1506         return $GLOBALS['ext_sqls'][getCurrentExtensionName()];
1507 }
1508
1509 // Count SQLs for current extension
1510 function countExtensionSqls () {
1511         // Output debug backtrace if not found (SHOULD NOT HAPPEN!)
1512         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1513                 // Not found, should not happen
1514                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("ext_sqls is empty, current extension: %s",
1515                         getCurrentExtensionName()
1516                 ));
1517         } // END - if
1518
1519         // Count them all
1520         return count($GLOBALS['ext_sqls'][getCurrentExtensionName()]);
1521 }
1522
1523 // Removes SQLs for current extension
1524 function unsetExtensionSqls () {
1525         unset($GLOBALS['ext_sqls'][getCurrentExtensionName()]);
1526 }
1527
1528 // Auto-initializes the removal list
1529 function initExtensionRemovalList () {
1530         // Is the remove list there?
1531         if (!isset($GLOBALS['ext_update_remove'])) {
1532                 // Then create it
1533                 $GLOBALS['ext_update_remove'] = array();
1534         } // END - if
1535 }
1536
1537 // Checks wether the current extension is on the removal list
1538 function isExtensionOnRemovalList () {
1539         // Init removal list
1540         initExtensionRemovalList();
1541
1542         // Is it there?
1543         return (in_array(getCurrentExtensionName(), $GLOBALS['ext_update_remove']));
1544 }
1545
1546 // Adds the current extension to the removal list
1547 function addCurrentExtensionToRemovalList () {
1548         // Simply add it
1549         $GLOBALS['ext_update_remove'][] = getCurrentExtensionName();
1550 }
1551
1552 // Getter for removal list
1553 function getExtensionRemovalList () {
1554         // Return the removal list
1555         return $GLOBALS['ext_update_remove'];
1556 }
1557
1558 // Redirects if the provided extension is not installed
1559 function redirectOnUninstalledExtension ($ext_name) {
1560         // So is the extension there?
1561         if ((!isExtensionInstalled($ext_name)) || (!isExtensionActive($ext_name))) {
1562                 // Redirect to index
1563                 redirectToUrl('modules.php?module=index&amp;code=' . getCode('EXTENSION_PROBLEM') . '&amp;ext=' . $ext_name);
1564         } // END - if
1565 }
1566
1567 // Filter for initialization of all extensions by loading them in 'init' mode
1568 function FILTER_INIT_EXTENSIONS () {
1569         // Do we have some entries?
1570         //* DEBUG */ print __FUNCTION__.': ENTRY!<br />';
1571         if (isset($GLOBALS['cache_array']['extension']['ext_name'])) {
1572                 // Load all found extensions if found
1573                 //* DEBUG */ print __FUNCTION__.': CACHE - START!<br />';
1574                 foreach ($GLOBALS['cache_array']['extension']['ext_name'] as $key => $ext_name) {
1575                         // Load it
1576                         //* DEBUG */ print __FUNCTION__.': '.$ext_name.' - START<br />';
1577                         loadExtension($ext_name, 'init', getExtensionVersion($ext_name));
1578                         //* DEBUG */ print __FUNCTION__.': '.$ext_name.' - END<br />';
1579                 } // END - foreach
1580                 //* DEBUG */ print __FUNCTION__.': CACHE - END!<br />';
1581         } // END - if
1582         //* DEBUG */ print __FUNCTION__.': EXIT!<br />';
1583 }
1584
1585 // Setter for extension mode
1586 function setExtensionMode ($ext_mode) {
1587         $GLOBALS['ext_mode'] = (string) $ext_mode;
1588 }
1589
1590 // Getter for extension mode
1591 function getExtensionMode () {
1592         return $GLOBALS['ext_mode'];
1593 }
1594
1595 // Setter for dry-run
1596 function enableExtensionDryRun ($dry_run = true) {
1597         //* DEBUG: */ debugOutput(__FUNCTION__.': '.getCurrentExtensionName().'='.intval($dry_run));
1598         $GLOBALS['ext_dry_run'] = (bool) $dry_run;
1599 }
1600
1601 // Getter for dry-run
1602 function isExtensionDryRun () {
1603         return $GLOBALS['ext_dry_run'];
1604 }
1605
1606 // Setter for current extension version
1607 function setCurrentExtensionVersion ($ext_ver) {
1608         // ext_ver should never be empty in other modes than 'test'
1609         if ((empty($ext_ver)) && (getExtensionMode() != 'test')) {
1610                 // Please report all these messages
1611                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_ver is empty. Current extension name: ' . getCurrentExtensionName() . ', mode=' . getExtensionMode());
1612         } // END - if
1613
1614         // Add version
1615         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver[' . gettype($ext_ver) . ']=' . $ext_ver);
1616         $GLOBALS['ext_current_version'][getCurrentExtensionName()] = (string) $ext_ver;
1617 }
1618
1619 // Getter for current extension version
1620 function getCurrentExtensionVersion () {
1621         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver=' . $GLOBALS['ext_current_version'][getCurrentExtensionName()]);
1622         return $GLOBALS['ext_current_version'][getCurrentExtensionName()];
1623 }
1624
1625 // Remove the extension from cache array
1626 function removeExtensionFromArray () {
1627         // "Cache" this name
1628         $ext_name = getCurrentExtensionName();
1629
1630         // Now loop through the whole cache
1631         foreach ($GLOBALS['cache_array']['extension'] as $cacheName => $cacheArray) {
1632                 // Is it an element?
1633                 if (isset($cacheArray[$ext_name])) {
1634                         // Array element
1635                         unset($cacheArray[$ext_name]);
1636                         $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1637                 } else {
1638                         // Maybe in array?
1639                         $key = array_search($ext_name, $cacheArray);
1640
1641                         // Is it there?
1642                         if ($key !== false) {
1643                                 // Found, so remove it
1644                                 unset($cacheArray[$key]);
1645                                 $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1646                         } // END - if
1647                 }
1648         } // END - foreach
1649 }
1650
1651 // "Getter" for 'extension has a CSS file' (with same name, of course)
1652 function getExtensionHasCss () {
1653         // Default is no CSS
1654         $hasCss = 'N';
1655
1656         // Construct FQFN for check
1657         $FQFN = sprintf("%stheme/%s/css/%s.css",
1658                 getConfig('PATH'),
1659                 getCurrentTheme(),
1660                 getCurrentExtensionName()
1661         );
1662
1663         // Is it there?
1664         if (isFileReadable($FQFN)) {
1665                 // Readable, so it is there...
1666                 $hasCss = 'Y';
1667         } // END - if
1668
1669         // Return it
1670         return $hasCss;
1671 }
1672
1673 // Checks wether the given extension has a language file
1674 function ifExtensionHasLanguageFile ($ext_name) {
1675         // Default is no language file
1676         $hasLanguage = false;
1677
1678         // Do we have cache?
1679         if (isset($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name])) {
1680                 // Then use it
1681                 $hasLanguage = ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1682
1683                 // Count cache hits
1684                 incrementStatsEntry('cache_hits');
1685         } else {
1686                 // Not readable is default
1687                 $readable = 'N';
1688
1689                 // Is the language file readable for this extension?
1690                 if (isLanguageIncludeReadable($ext_name)) {
1691                         // Readable
1692                         $readable = 'Y';
1693                 } // END - if
1694
1695                 // Put it in cache
1696                 $GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] = 'Y';
1697         }
1698
1699         // Return result
1700         return ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1701 }
1702
1703 // Load an extension's include file
1704 function loadExtensionInclude () {
1705         // Is it readable?
1706         if (!isExtensionIncludeReadable()) {
1707                 // Not readable
1708                 debug_report_bug(__FUNCTION__, __LINE__, 'Extension ' . getCurrentExtensionName() . ' should be loaded, but is not readable.');
1709         } // END - if
1710
1711         // Generate INC name
1712         $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1713
1714         // Load it
1715         loadInclude($INC);
1716 }
1717
1718 // Checks wether an extension is readable
1719 function isExtensionIncludeReadable ($ext_name = '') {
1720         // If empty, use current
1721         if (empty($ext_name)) $ext_name = getCurrentExtensionName();
1722
1723         // Array found?
1724         if (!isset($GLOBALS['ext_inc_readable'][$ext_name])) {
1725                 // Generate INC name
1726                 $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1727
1728                 // Is it readable?
1729                 $GLOBALS['ext_inc_readable'][$ext_name] = isIncludeReadable($INC);
1730         } // END - if
1731
1732         // Return result
1733         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',realable='.intval($GLOBALS['ext_inc_readable'][$ext_name]));
1734         return $GLOBALS['ext_inc_readable'][$ext_name];
1735 }
1736
1737 // Checks if an extension's function file is readable
1738 function isExtensionFunctionFileReadable ($ext_name) {
1739         if (isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name])) {
1740                 // Just count cache hits
1741                 incrementStatsEntry('cache_hits');
1742         } else {
1743                 // Construct FQFN for functions file
1744                 $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
1745
1746                 // Is this include there?
1747                 if ((isFileReadable($funcsInclude)) && (!isset($GLOBALS['ext_loaded']['funcs'][$ext_name])) && (getExtensionMode() == 'test')) {
1748                         // Cache it!
1749                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'Y';
1750                 } else {
1751                         // Cache it!
1752                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'N';
1753                 }
1754         }
1755
1756         // Return result
1757         return ($GLOBALS['cache_array']['extension']['ext_func'][$ext_name] == 'Y');
1758 }
1759
1760 // Adds an admin menu to the SQL queue of the menu entry is not found
1761 function addAdminMenuSql ($action, $what, $title, $descr, $sort) {
1762         // Now check if this menu is there
1763         if (!isMenuActionValid('admin', $action, $what)) {
1764                 // Is what null?
1765                 if (is_null($what)) {
1766                         // Add main menu
1767                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1768                                 $action,
1769                                 $title,
1770                                 $descr,
1771                                 bigintval($sort)
1772                         );
1773                 } else {
1774                         // Add sub menu
1775                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1776                                 $action,
1777                                 $what,
1778                                 $title,
1779                                 $descr,
1780                                 bigintval($sort)
1781                         );
1782                 }
1783
1784                 // Add it to the queue
1785                 addExtensionSql($sql);
1786         } elseif (isDebugModeEnabled()) {
1787                 // Double menus should be located and fixed!
1788                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double admin menu action=%s, what=%s detected.", $action, $what));
1789         }
1790 }
1791
1792 // Adds a guest menu to the SQL queue if the menu entry is not found
1793 function addGuestMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1794         // Now check if this menu is there
1795         if (!isMenuActionValid('guest', $action, $what)) {
1796                 // Is what null?
1797                 if (is_null($what)) {
1798                         // Add main menu
1799                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1800                                 $action,
1801                                 $title,
1802                                 $visible,
1803                                 $locked,
1804                                 bigintval($sort)
1805                         );
1806                 } else {
1807                         // Add sub menu
1808                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1809                                 $action,
1810                                 $what,
1811                                 $title,
1812                                 $visible,
1813                                 $locked,
1814                                 bigintval($sort)
1815                         );
1816                 }
1817
1818                 // Add it to the queue
1819                 addExtensionSql($sql);
1820         } elseif (isDebugModeEnabled()) {
1821                 // Double menus should be located and fixed!
1822                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double guest menu action=%s, what=%s detected.", $action, $what));
1823         }
1824 }
1825
1826 // Adds a member menu to the SQL queue if the menu entry is not found
1827 function addMemberMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1828         // Now check if this menu is there
1829         if (!isMenuActionValid('member', $action, $what)) {
1830                 // Is what null?
1831                 if (is_null($what)) {
1832                         // Add main menu
1833                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1834                                 $action,
1835                                 $title,
1836                                 $visible,
1837                                 $locked,
1838                                 bigintval($sort)
1839                         );
1840                 } else {
1841                         // Add sub menu
1842                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1843                                 $action,
1844                                 $what,
1845                                 $title,
1846                                 $visible,
1847                                 $locked,
1848                                 bigintval($sort)
1849                         );
1850                 }
1851
1852                 // Add it to the queue
1853                 addExtensionSql($sql);
1854         } elseif (isDebugModeEnabled()) {
1855                 // Double menus should be located and fixed!
1856                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double member menu action=%s, what=%s detected.", $action, $what));
1857         }
1858 }
1859
1860 // Adds a sponsor menu to the SQL queue if the menu entry is not found
1861 function addSponsorMenuSql ($action, $what, $title, $active, $sort) {
1862         // Now check if this menu is there, if no ext-sponsor is installed all is not yet added
1863         if ((!isExtensionInstalled('sponsor')) || (!isMenuActionValid('sponsor', $action, $what))) {
1864                 // Is what null?
1865                 if (is_null($what)) {
1866                         // Add main menu
1867                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1868                                 $action,
1869                                 $title,
1870                                 $active,
1871                                 bigintval($sort)
1872                         );
1873                 } else {
1874                         // Add sub menu
1875                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1876                                 $action,
1877                                 $what,
1878                                 $title,
1879                                 $active,
1880                                 bigintval($sort)
1881                         );
1882                 }
1883
1884                 // Add it to the queue
1885                 addExtensionSql($sql);
1886         } elseif (isDebugModeEnabled()) {
1887                 // Double menus should be located and fixed!
1888                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double sponsor menu action=%s, what=%s detected.", $action, $what));
1889         }
1890 }
1891
1892 // Enables/disables productive mode for current extension (used only while
1893 // registration).
1894 function enableExtensionProductive ($isProductive = true) {
1895         $GLOBALS['ext_productive'][getCurrentExtensionName()] = (bool) $isProductive;
1896 }
1897
1898 // Checks wether the extension is in productive phase. If not set, development
1899 // phase (=false) is assumed.
1900 function isExtensionProductive () {
1901         return ((isset($GLOBALS['ext_productive'][getCurrentExtensionName()])) && ($GLOBALS['ext_productive'][getCurrentExtensionName()] === true));
1902 }
1903
1904 // [EOF]
1905 ?>