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