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