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