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