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