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