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