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