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