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