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