a6a2e372cc7487910e7451b10345dab6fcab9661
[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                         // Initial release
1109                         $content = array(
1110                                 'ver'   => $ext_ver,
1111                                 'notes' => '{--INITIAL_RELEASE--}'
1112                         );
1113                 } else {
1114                         // No update notes found
1115                         $content = array(
1116                                 'ver'   => $ext_ver,
1117                                 'notes' => '{--NO_UPDATE_NOTES--}'
1118                         );
1119                 }
1120
1121                 // Load template
1122                 $out = loadTemplate('admin_extension_notes', true, $content);
1123         } // END - if
1124
1125         // Add the notes
1126         appendExtensionNotes($out);
1127 }
1128
1129 // Getter for CSS files array
1130 function getExtensionCssFiles () {
1131         // By default no additional CSS files are found
1132         $cssFiles = array();
1133
1134         // Is the array there?
1135         if (isset($GLOBALS['css_files'])) {
1136                 // Then use it
1137                 $cssFiles = $GLOBALS['css_files'];
1138         } // END - if
1139
1140         // Return array
1141         return $cssFiles;
1142 }
1143
1144 // Init CSS files array
1145 function initExtensionCssFiles () {
1146         // Simply init it
1147         $GLOBALS['css_files'] = array();
1148 }
1149
1150 // Add new entry
1151 function addExtensionCssFile ($file) {
1152         // Is the array there?
1153         if (!isset($GLOBALS['css_files'])) {
1154                 // Then auto-init them
1155                 initExtensionCssFiles();
1156         } // END - if
1157
1158         // Add the entry
1159         $GLOBALS['css_files'][] = $file;
1160 }
1161
1162 // Setter for EXT_ALWAYS_ACTIVE flag
1163 function setExtensionAlwaysActive ($active) {
1164         $GLOBALS['ext_always_active'][getCurrentExtensionName()] = (string) $active;
1165 }
1166
1167 // Getter for EXT_ALWAYS_ACTIVE flag
1168 function getThisExtensionAlwaysActive () {
1169         return $GLOBALS['ext_always_active'][getCurrentExtensionName()];
1170 }
1171
1172 // Checks wether the current extension is always active
1173 function isThisExtensionAlwaysActive () {
1174         return (getThisExtensionAlwaysActive() == 'Y');
1175 }
1176
1177 // Setter for EXT_VERSION flag
1178 function setThisExtensionVersion ($ext_version) {
1179         $GLOBALS['ext_version'][getCurrentExtensionName()] = (string) $ext_version;
1180 }
1181
1182 // Getter for EXT_VERSION flag
1183 function getThisExtensionVersion () {
1184         return $GLOBALS['ext_version'][getCurrentExtensionName()];
1185 }
1186
1187 // Setter for EXT_DEPRECATED flag
1188 function setExtensionDeprecated ($deprecated) {
1189         $GLOBALS['ext_deprecated'][getCurrentExtensionName()] = (string) $deprecated;
1190 }
1191
1192 // Getter for EXT_DEPRECATED flag
1193 function isExtensionDeprecated () {
1194         return ($GLOBALS['ext_deprecated'][getCurrentExtensionName()] == 'Y');
1195 }
1196
1197 // Setter for EXT_UPDATE_DEPENDS flag
1198 function addExtensionDependency ($updateDepends) {
1199         // Is the update depency empty? (NEED TO BE FIXED!)
1200         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . '/' . $updateDepends . ',extensionMode=' . getExtensionMode() . ' - ENTERED!');
1201         if (empty($updateDepends)) {
1202                 // Please report this bug!
1203                 debug_report_bug(__FUNCTION__, __LINE__, 'updateDepends is empty: currentExtension=' . getCurrentExtensionName());
1204         } // END - if
1205
1206         // Is it not yet added?
1207         if ((isset($updateDepends, $GLOBALS['ext_running_updates'][getCurrentExtensionName()])) && (in_array($updateDepends, getExtensionUpdatesRunning()))) {
1208                 /*
1209                  * Double-adding isn't fine, too. This may mean that
1210                  * addExtensionDependency() was called outside the switch() command in
1211                  * the extension's file which requires fixing.
1212                  */
1213                 debug_report_bug(__FUNCTION__, __LINE__, 'updateDepends=' . $updateDepends . ',extensionMode=' . getExtensionMode() . ',currentExtension=' . getCurrentExtensionName() . ' - CALLED TWICE!');
1214         } // END - if
1215
1216         // Add it to the list of extension update depencies map
1217         $GLOBALS['ext_update_depends'][getCurrentExtensionName()][] = (string) $updateDepends;
1218
1219         // Remember it in the list of running updates
1220         $GLOBALS['ext_running_updates'][getCurrentExtensionName()][] = $updateDepends;
1221         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . '/' . $updateDepends . ',extensionMode=' . getExtensionMode() . ' - EXIT!');
1222 }
1223
1224 // Getter for running updates
1225 function getExtensionUpdatesRunning () {
1226         return $GLOBALS['ext_running_updates'][getCurrentExtensionName()];
1227 }
1228
1229 // Checks wether the given extension registration is in progress
1230 function isExtensionRegistrationRunning ($ext_name) {
1231         // Simply check it
1232         $isRunning = ((isset($GLOBALS['ext_register_running'])) && (in_array($ext_name, $GLOBALS['ext_register_running'])));
1233
1234         // Return it
1235         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1236         return $isRunning;
1237 }
1238
1239 // Init EXT_UPDATE_DEPENDS flag
1240 function initExtensionUpdateDependencies () {
1241         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - ENTERED!');
1242
1243         // Init update depency map automatically if not found
1244         if (isExtensionUpdateDependenciesInitialized()) {
1245                 // We need these bug reports as well...
1246                 debug_report_bug(__FUNCTION__, __LINE__, '() is called twice: currName=' . getCurrentExtensionName());
1247         } // END - if
1248
1249         $GLOBALS['ext_update_depends'][getCurrentExtensionName()] = array();
1250
1251         // Init running updates array
1252         initExtensionRuningUpdates();
1253
1254         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName() . ' - EXIT!');
1255 }
1256
1257 // Adds an extension as "registration in progress"
1258 function addExtensionRunningRegistration ($ext_name) {
1259         // Is it running?
1260         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Registration in progress: ext_name=' . $ext_name . ' - ENTERED!');
1261         if (isExtensionRegistrationRunning($ext_name)) {
1262                 // This is really bad and should not be quietly ignored
1263                 debug_report_bug(__FUNCTION__, __LINE__, '() already called! ext_name=' . $ext_name);
1264         } // END - if
1265
1266         // Then add it!
1267         $GLOBALS['ext_register_running'][] = $ext_name;
1268         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'Registration in progress: ext_name=' . $ext_name . ' - EXIT!');
1269 }
1270
1271 // Checks wether EXT_UPDATE_DEPENDS is initialized
1272 function isExtensionUpdateDependenciesInitialized () {
1273         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currName=' . getCurrentExtensionName());
1274         return (isset($GLOBALS['ext_update_depends'][getCurrentExtensionName()]));
1275 }
1276
1277 // Checks wether an update is already running for given extension
1278 function isExtensionUpdateRunning ($ext_name) {
1279         // Current and given extensions means whole array
1280         if ($ext_name == getCurrentExtensionName()) {
1281                 // Default is not found
1282                 $isRunning = false;
1283
1284                 // Walk through whole array
1285                 foreach ($GLOBALS['ext_running_updates'] as $ext1=>$depends) {
1286                         // Is it found?
1287                         if (($ext1 == $ext_name) || ($isRunning === true)) {
1288                                 // Found
1289                                 $isRunning = true;
1290                                 logDebugMessage(__FUNCTION__, __LINE__, 'ext1=' . $ext1 . ',ext_name=' . $ext_name . ',isRunning=' . intval($isRunning));
1291                                 break;
1292                         } // END - if
1293                 } // END - foreach
1294
1295                 // Return result
1296                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1297                 return $isRunning;
1298         } // END - if
1299
1300         // Simply check it
1301         $isRunning = ((isExtensionUpdateDependenciesInitialized()) && (in_array($ext_name, getExtensionRunningUpdates())));
1302
1303         // Return it
1304         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'currentExtension=' . getCurrentExtensionName() . ',ext_name=' . $ext_name . ', isRunning=' . intval($isRunning));
1305         return $isRunning;
1306 }
1307
1308 // Initializes the list of running updates
1309 function initExtensionRuningUpdates () {
1310         // Auto-init ext_running_updates
1311         if (!isset($GLOBALS['ext_running_updates'])) {
1312                 $GLOBALS['ext_running_updates'] = array();
1313                 $GLOBALS['ext_register_running'] = array();
1314         } // END - if
1315 }
1316
1317 // Getter for EXT_UPDATE_DEPENDS flag
1318 function getExtensionUpdateDependencies () {
1319         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1320         return $GLOBALS['ext_update_depends'][getCurrentExtensionName()];
1321 }
1322
1323 // Getter for next iterator depency
1324 function getExtensionUpdateDependenciesIterator () {
1325         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1326         return ($GLOBALS['ext_update_depends'][getCurrentExtensionName()][getExtensionUpdateIterator()]);
1327 }
1328
1329 // Counter for extension update depencies
1330 function countExtensionUpdateDependencies () {
1331         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1332         return count($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1333 }
1334
1335 // Removes given extension from update denpency list
1336 function removeExtensionDependency ($ext_name) {
1337         // Look it up
1338         $key = array_search($ext_name, getExtensionUpdateDependencies());
1339
1340         // Is it valid?
1341         if ($key !== false) {
1342                 // Then remove it
1343                 unset($GLOBALS['ext_update_depends'][getCurrentExtensionName()][$key]);
1344
1345                 // And sort the array
1346                 ksort($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1347         } // END - if
1348 }
1349
1350 // Init iterator for update depencies
1351 function initExtensionUpdateIterator () {
1352         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1353         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()] = '0';
1354 }
1355
1356 // Getter for depency iterator
1357 function getExtensionUpdateIterator () {
1358         // Auto-init iterator
1359         if (!isset($GLOBALS['ext_depend_iterator'][getCurrentExtensionName()])) initExtensionUpdateIterator();
1360
1361         // Return it
1362         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().'/'.$GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]);
1363         return $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()];
1364 }
1365
1366 // Increments the update iterator
1367 function incrementExtensionUpdateIterator () {
1368         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1369         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]++;
1370 }
1371
1372 // Setter for EXT_REPORTS_FAILURE flag
1373 function setExtensionReportsFailure ($reportsFailure) {
1374         $GLOBALS['ext_reports_failure'] = (bool) $reportsFailure;
1375 }
1376
1377 // Getter for EXT_REPORTS_FAILURE flag
1378 function getExtensionReportsFailure () {
1379         return $GLOBALS['ext_reports_failure'];
1380 }
1381
1382 // Setter for EXT_VER_HISTORY flag
1383 function setExtensionVersionHistory ($versionHistory) {
1384         $GLOBALS['ext_ver_history'][getCurrentExtensionName()] = (array) $versionHistory;
1385 }
1386
1387 // Getter for EXT_VER_HISTORY array
1388 function getExtensionVersionHistory () {
1389         return $GLOBALS['ext_ver_history'][getCurrentExtensionName()];
1390 }
1391
1392 // Setter for EXT_UPDATE_NOTES
1393 function setExtensionUpdateNotes ($updateNotes, $ext_ver = '') {
1394         // . '/' . getCurrentExtensionVersion()
1395         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getCurrentExtensionName()=' . getCurrentExtensionName() . ',getExtensionMode()=' . getExtensionMode() . ',ext_ver=' . $ext_ver . ',updateNotes()=' . strlen($updateNotes));
1396         if (empty($ext_ver)) {
1397                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][getCurrentExtensionVersion()] = (string) $updateNotes;
1398         } else {
1399                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ext_ver] = (string) $updateNotes;
1400         }
1401 }
1402
1403 // Getter for EXT_UPDATE_NOTES
1404 function getExtensionUpdateNotes ($ext_ver) {
1405         return $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ext_ver];
1406 }
1407
1408 // Checks if ext_update_notes is set
1409 function isExtensionUpdateNoteSet ($ext_ver) {
1410         return isset($GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ext_ver]);
1411 }
1412
1413 // Init extension notice
1414 function initExtensionNotes ($force = false) {
1415         // Is it already initialized?
1416         if (($force === false) && (isset($GLOBALS['ext_notes'][getCurrentExtensionName()]))) {
1417                 // This is mostly not wanted, so please report it
1418                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_notes already set for extension ' . getCurrentExtensionName());
1419         } // END - if
1420
1421         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getCurrentExtensionName()=' . getCurrentExtensionName());
1422         $GLOBALS['ext_notes'][getCurrentExtensionName()] = '';
1423 }
1424
1425 // Append extension notice
1426 function appendExtensionNotes ($notes) {
1427         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getCurrentExtensionName()=' . getCurrentExtensionName() . ', notes()=' . strlen($notes));
1428         $GLOBALS['ext_notes'][getCurrentExtensionName()] .= (string) trim($notes);
1429 }
1430
1431 // Getter for extension notes
1432 function getExtensionNotes () {
1433         return $GLOBALS['ext_notes'][getCurrentExtensionName()];
1434 }
1435
1436 // Setter for current extension name
1437 function setCurrentExtensionName ($ext_name) {
1438         $GLOBALS['curr_extension_name'] = (string) trim($ext_name);
1439 }
1440
1441 // Getter for current extension name
1442 function getCurrentExtensionName () {
1443         if (!isset($GLOBALS['curr_extension_name'])) {
1444                 // Not set!
1445                 debug_report_bug(__FUNCTION__, __LINE__, 'curr_extension_name not initialized. Please execute initExtensionSqls() before calling this function.');
1446         } // END - if
1447
1448         // Return it
1449         return $GLOBALS['curr_extension_name'];
1450 }
1451
1452 // Init SQLs array for current extension
1453 function initExtensionSqls ($force = false) {
1454         // Auto-init the array or if forced
1455         if (($force === true) || (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()]))) {
1456                 // Set the array
1457                 $GLOBALS['ext_sqls'][getCurrentExtensionName()] = array();
1458
1459                 // Initialize the generic array
1460                 initSqls();
1461         } // END - if
1462 }
1463
1464 // Adds SQLs to the SQLs array but "assigns" it with current extension name
1465 function addExtensionSql ($sql) {
1466         // Add it
1467         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ',ext_version=' . getCurrentExtensionVersion() . ',sql=' . $sql);
1468         $GLOBALS['ext_sqls'][getCurrentExtensionName()][getCurrentExtensionVersion()][] = $sql;
1469 }
1470
1471 // Getter for SQLs array for current extension
1472 function getExtensionSqls () {
1473         // Output debug backtrace if not found (SHOULD NOT HAPPEN!)
1474         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1475                 // Not found, should not happen
1476                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("ext_sqls is empty, current extension: %s",
1477                         getCurrentExtensionName()
1478                 ));
1479         } // END - if
1480
1481         // Return the array
1482         return $GLOBALS['ext_sqls'][getCurrentExtensionName()];
1483 }
1484
1485 // Count SQLs for current extension
1486 function countExtensionSqls () {
1487         // Output debug backtrace if not found (SHOULD NOT HAPPEN!)
1488         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1489                 // Not found, should not happen
1490                 debug_report_bug(__FUNCTION__, __LINE__, sprintf("ext_sqls is empty, current extension: %s",
1491                         getCurrentExtensionName()
1492                 ));
1493         } // END - if
1494
1495         // Count them all
1496         return count($GLOBALS['ext_sqls'][getCurrentExtensionName()]);
1497 }
1498
1499 // Removes SQLs for current extension
1500 function unsetExtensionSqls () {
1501         unset($GLOBALS['ext_sqls'][getCurrentExtensionName()]);
1502 }
1503
1504 // Auto-initializes the removal list
1505 function initExtensionRemovalList () {
1506         // Is the remove list there?
1507         if (!isset($GLOBALS['ext_update_remove'])) {
1508                 // Then create it
1509                 $GLOBALS['ext_update_remove'] = array();
1510         } // END - if
1511 }
1512
1513 // Checks wether the current extension is on the removal list
1514 function isExtensionOnRemovalList () {
1515         // Init removal list
1516         initExtensionRemovalList();
1517
1518         // Is it there?
1519         return (in_array(getCurrentExtensionName(), $GLOBALS['ext_update_remove']));
1520 }
1521
1522 // Adds the current extension to the removal list
1523 function addCurrentExtensionToRemovalList () {
1524         // Simply add it
1525         $GLOBALS['ext_update_remove'][] = getCurrentExtensionName();
1526 }
1527
1528 // Getter for removal list
1529 function getExtensionRemovalList () {
1530         // Return the removal list
1531         return $GLOBALS['ext_update_remove'];
1532 }
1533
1534 // Redirects if the provided extension is not installed
1535 function redirectOnUninstalledExtension ($ext_name) {
1536         // So is the extension there?
1537         if ((!isExtensionInstalled($ext_name)) || (!isExtensionActive($ext_name))) {
1538                 // Redirect to index
1539                 redirectToUrl('modules.php?module=index&amp;code=' . getCode('EXTENSION_PROBLEM') . '&amp;ext=' . $ext_name);
1540         } // END - if
1541 }
1542
1543 // Filter for initialization of all extensions by loading them in 'init' mode
1544 function FILTER_INIT_EXTENSIONS () {
1545         // Do we have some entries?
1546         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ENTRY!');
1547         if (isset($GLOBALS['cache_array']['extension']['ext_name'])) {
1548                 // Load all found extensions if found
1549                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHE - START!');
1550                 foreach ($GLOBALS['cache_array']['extension']['ext_name'] as $key => $ext_name) {
1551                         // Load it
1552                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name='.$ext_name.' - START');
1553                         loadExtension($ext_name, 'init', getExtensionVersion($ext_name));
1554                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name='.$ext_name.' - END');
1555                 } // END - foreach
1556                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'CACHE - END!');
1557         } // END - if
1558         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'EXIT!');
1559 }
1560
1561 // Setter for extension mode
1562 function setExtensionMode ($ext_mode) {
1563         $GLOBALS['ext_mode'] = (string) $ext_mode;
1564 }
1565
1566 // Getter for extension mode
1567 function getExtensionMode () {
1568         return $GLOBALS['ext_mode'];
1569 }
1570
1571 // Setter for dry-run
1572 function enableExtensionDryRun ($dry_run = true) {
1573         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'getCurrentExtensionName()='.getCurrentExtensionName().',dry_run='.intval($dry_run));
1574         $GLOBALS['ext_dry_run'] = (bool) $dry_run;
1575 }
1576
1577 // Getter for dry-run
1578 function isExtensionDryRun () {
1579         return $GLOBALS['ext_dry_run'];
1580 }
1581
1582 // Setter for current extension version
1583 function setCurrentExtensionVersion ($ext_ver) {
1584         // ext_ver should never be empty in other modes than 'test'
1585         if ((empty($ext_ver)) && (getExtensionMode() != 'test')) {
1586                 // Please report all these messages
1587                 debug_report_bug(__FUNCTION__, __LINE__, 'ext_ver is empty. Current extension name: ' . getCurrentExtensionName() . ', mode=' . getExtensionMode());
1588         } // END - if
1589
1590         // Add version
1591         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver[' . gettype($ext_ver) . ']=' . $ext_ver);
1592         $GLOBALS['ext_current_version'][getCurrentExtensionName()] = (string) $ext_ver;
1593 }
1594
1595 // Getter for current extension version
1596 function getCurrentExtensionVersion () {
1597         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . getCurrentExtensionName() . ', ext_ver=' . $GLOBALS['ext_current_version'][getCurrentExtensionName()]);
1598         return $GLOBALS['ext_current_version'][getCurrentExtensionName()];
1599 }
1600
1601 // Remove the extension from cache array
1602 function removeExtensionFromArray () {
1603         // "Cache" this name
1604         $ext_name = getCurrentExtensionName();
1605
1606         // Now loop through the whole cache
1607         foreach ($GLOBALS['cache_array']['extension'] as $cacheName => $cacheArray) {
1608                 // Is it an element?
1609                 if (isset($cacheArray[$ext_name])) {
1610                         // Array element
1611                         unset($cacheArray[$ext_name]);
1612                         $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1613                 } else {
1614                         // Maybe in array?
1615                         $key = array_search($ext_name, $cacheArray);
1616
1617                         // Is it there?
1618                         if ($key !== false) {
1619                                 // Found, so remove it
1620                                 unset($cacheArray[$key]);
1621                                 $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1622                         } // END - if
1623                 }
1624         } // END - foreach
1625 }
1626
1627 // "Getter" for 'extension has a CSS file' (with same name, of course)
1628 function getExtensionHasCss () {
1629         // Default is no CSS
1630         $hasCss = 'N';
1631
1632         // Construct FQFN for check
1633         $FQFN = sprintf("%stheme/%s/css/%s.css",
1634                 getPath(),
1635                 getCurrentTheme(),
1636                 getCurrentExtensionName()
1637         );
1638
1639         // Is it there?
1640         if (isFileReadable($FQFN)) {
1641                 // Readable, so it is there...
1642                 $hasCss = 'Y';
1643         } // END - if
1644
1645         // Return it
1646         return $hasCss;
1647 }
1648
1649 // Checks wether the given extension has a language file
1650 function ifExtensionHasLanguageFile ($ext_name) {
1651         // Do we have cache?
1652         if (isset($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name])) {
1653                 // Count cache hits
1654                 incrementStatsEntry('cache_hits');
1655         } else {
1656                 // Not readable is default
1657                 $readable = 'N';
1658
1659                 // Is the language file readable for this extension?
1660                 if (isLanguageIncludeReadable($ext_name)) {
1661                         // Readable
1662                         $readable = 'Y';
1663                 } // END - if
1664
1665                 // Put it in cache
1666                 $GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] = $readable;
1667         }
1668
1669         // Return result
1670         return ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1671 }
1672
1673 // Load current extension's include file
1674 function loadCurrentExtensionInclude () {
1675         // Is it readable?
1676         if (!isExtensionIncludeReadable()) {
1677                 // Not readable
1678                 debug_report_bug(__FUNCTION__, __LINE__, 'Extension ' . getCurrentExtensionName() . ' should be loaded, but is not readable.');
1679         } // END - if
1680
1681         // Generate INC name
1682         $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1683
1684         // Load it
1685         loadInclude($INC);
1686 }
1687
1688 // Checks wether an extension is readable
1689 function isExtensionIncludeReadable ($ext_name = '') {
1690         // If empty, use current
1691         if (empty($ext_name)) {
1692                 $ext_name = getCurrentExtensionName();
1693         } // END - if
1694
1695         // Array found?
1696         if (!isset($GLOBALS['ext_inc_readable'][$ext_name])) {
1697                 // Generate INC name
1698                 $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1699
1700                 // Is it readable?
1701                 $GLOBALS['ext_inc_readable'][$ext_name] = isIncludeReadable($INC);
1702         } // END - if
1703
1704         // Return result
1705         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',realable='.intval($GLOBALS['ext_inc_readable'][$ext_name]));
1706         return $GLOBALS['ext_inc_readable'][$ext_name];
1707 }
1708
1709 // Checks if an extension's function file is readable
1710 function isExtensionFunctionFileReadable ($ext_name) {
1711         // Is cache there?
1712         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name);
1713         if (isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name])) {
1714                 // Just count cache hits
1715                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',ext_func=' . $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] .' - CACHE!');
1716                 incrementStatsEntry('cache_hits');
1717         } else {
1718                 // Construct IFN for functions file
1719                 $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
1720
1721                 // Is this include there?
1722                 if ((isFileReadable($funcsInclude)) && (!isExtensionLibraryLoaded($ext_name)) && (getExtensionMode() == 'test')) {
1723                         // Cache it!
1724                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',ext_func=Y - FOUND!');
1725                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'Y';
1726                 } else {
1727                         // Cache it!
1728                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',ext_func=N - NOT FOUND!');
1729                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'N';
1730                 }
1731         }
1732
1733         // Return result
1734         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, 'ext_name=' . $ext_name . ',ext_func=' . $GLOBALS['cache_array']['extension']['ext_func'][$ext_name]);
1735         return ($GLOBALS['cache_array']['extension']['ext_func'][$ext_name] == 'Y');
1736 }
1737
1738 // Adds a CREATE TABLE statement if the requested table is not there
1739 function addCreateTableSql ($tableName, $sql) {
1740         // Is the table not there?
1741         if (!isSqlTableCreated($tableName)) {
1742                 // Is not found, so add it
1743                 addExtensionSql('CREATE TABLE `{?_MYSQL_PREFIX?}_' . $tableName . '` ' . $sql);
1744         } else {
1745                 // Is already there, which should not happen
1746                 debug_report_bug(__FUNCTION__, __LINE__, 'The table ' . $tableName . ' is already created which should not happen.');
1747         }
1748 }
1749
1750 // Adds a DROP TABLE statement if the requested tabled is there
1751 function addDropTableSql ($tableName) {
1752         // Is the table there?
1753         if (isSqlTableCreated($tableName)) {
1754                 // Then add it, non-existing tables can be ignored because it will
1755                 // happen with every newly installed extension.
1756                 addExtensionSql('DROP TABLE `{?_MYSQL_PREFIX?}_' . $tableName . '`');
1757
1758                 // Mark it as gone
1759                 $GLOBALS['isSqlTableCreated'][$tableName] = false;
1760         } // END - if
1761 }
1762
1763 // Adds an admin menu to the SQL queue of the menu entry is not found
1764 function addAdminMenuSql ($action, $what, $title, $descr, $sort) {
1765         // Now check if this menu is there
1766         if (!isMenuActionValid('admin', $action, $what)) {
1767                 // Is what null?
1768                 if (is_null($what)) {
1769                         // Add main menu
1770                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1771                                 $action,
1772                                 $title,
1773                                 $descr,
1774                                 bigintval($sort)
1775                         );
1776                 } else {
1777                         // Add sub menu
1778                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1779                                 $action,
1780                                 $what,
1781                                 $title,
1782                                 $descr,
1783                                 bigintval($sort)
1784                         );
1785                 }
1786
1787                 // Add it to the queue
1788                 addExtensionSql($sql);
1789         } elseif (isDebugModeEnabled()) {
1790                 // Double menus should be located and fixed!
1791                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double admin menu action=%s,what=%s,title=%s detected.", $action, $what, $title));
1792         }
1793 }
1794
1795 // Adds a guest menu to the SQL queue if the menu entry is not found
1796 function addGuestMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1797         // Now check if this menu is there
1798         if (!isMenuActionValid('guest', $action, $what)) {
1799                 // Is what null?
1800                 if (is_null($what)) {
1801                         // Add main menu
1802                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1803                                 $action,
1804                                 $title,
1805                                 $visible,
1806                                 $locked,
1807                                 bigintval($sort)
1808                         );
1809                 } else {
1810                         // Add sub menu
1811                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1812                                 $action,
1813                                 $what,
1814                                 $title,
1815                                 $visible,
1816                                 $locked,
1817                                 bigintval($sort)
1818                         );
1819                 }
1820
1821                 // Add it to the queue
1822                 addExtensionSql($sql);
1823         } elseif (isDebugModeEnabled()) {
1824                 // Double menus should be located and fixed!
1825                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double guest menu action=%s,what=%s,title=%s,locked=%s,visible=%s detected.", $action, $what, $title, $locked, $visible));
1826         }
1827 }
1828
1829 // Adds a member menu to the SQL queue if the menu entry is not found
1830 function addMemberMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1831         // Now check if this menu is there
1832         if (!isMenuActionValid('member', $action, $what)) {
1833                 // Is what null?
1834                 if (is_null($what)) {
1835                         // Add main menu
1836                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1837                                 $action,
1838                                 $title,
1839                                 $visible,
1840                                 $locked,
1841                                 bigintval($sort)
1842                         );
1843                 } else {
1844                         // Add sub menu
1845                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1846                                 $action,
1847                                 $what,
1848                                 $title,
1849                                 $visible,
1850                                 $locked,
1851                                 bigintval($sort)
1852                         );
1853                 }
1854
1855                 // Add it to the queue
1856                 addExtensionSql($sql);
1857         } elseif (isDebugModeEnabled()) {
1858                 // Double menus should be located and fixed!
1859                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double member menu action=%s,what=%s,title=%s,visivle=%s,locked=%s detected.", $action, $what, $title, $visible, $locked));
1860         }
1861 }
1862
1863 // Adds a sponsor menu to the SQL queue if the menu entry is not found
1864 function addSponsorMenuSql ($action, $what, $title, $active, $sort) {
1865         // Now check if this menu is there, if no ext-sponsor is installed all is not yet added
1866         if ((!isExtensionInstalled('sponsor')) || (!isMenuActionValid('sponsor', $action, $what))) {
1867                 // Is what null?
1868                 if (is_null($what)) {
1869                         // Add main menu
1870                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1871                                 $action,
1872                                 $title,
1873                                 $active,
1874                                 bigintval($sort)
1875                         );
1876                 } else {
1877                         // Add sub menu
1878                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1879                                 $action,
1880                                 $what,
1881                                 $title,
1882                                 $active,
1883                                 bigintval($sort)
1884                         );
1885                 }
1886
1887                 // Add it to the queue
1888                 addExtensionSql($sql);
1889         } elseif (isDebugModeEnabled()) {
1890                 // Double menus should be located and fixed!
1891                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double sponsor menu action=%s,what=%s,title=%s,active=%s detected.", $action, $what, $title, $active));
1892         }
1893 }
1894
1895 // Add configuration entry if not found for actual extension
1896 function addConfigAddSql ($columnName, $columnSql) {
1897         // Is the column there?
1898         if (!isSqlTableColumnFound('{?_MYSQL_PREFIX?}_config', $columnName)) {
1899                 // Not found, so add it
1900                 addExtensionSql('ALTER TABLE `{?_MYSQL_PREFIX?}_config` ADD `' . $columnName . '` ' . $columnSql);
1901         } elseif (isDebugModeEnabled()) {
1902                 // Add debug line
1903                 logDebugMessage(__FUNCTION__, __LINE__, 'Configuration entry ' . $columnName . ' already created. columnSql=' . $columnSql);
1904         }
1905 }
1906
1907 // Drop configuration entry if found for actual extension
1908 function addConfigDropSql ($columnName) {
1909         // Is the column there?
1910         if (isSqlTableColumnFound('{?_MYSQL_PREFIX?}_config', $columnName)) {
1911                 // Found, so add it
1912                 addExtensionSql('ALTER TABLE `{?_MYSQL_PREFIX?}_config` DROP `' . $columnName . '`');
1913         } elseif (isDebugModeEnabled()) {
1914                 // Add debug line, debug_report_bug() would cause some extenion updates fail
1915                 logDebugMessage(__FUNCTION__, __LINE__, 'Configuration entry ' . $columnName . ' not found.');
1916         }
1917 }
1918
1919 // Change configuration entry for actual extension
1920 function addConfigChangeSql ($oldColumnName, $newColumnName, $columnSql) {
1921         // Add the SQL statement
1922         addExtensionSql('ALTER TABLE `{?_MYSQL_PREFIX?}_config` CHANGE `' . $oldColumnName . '` `' . $newColumnName . '` ' . $columnSql);
1923 }
1924
1925 // Enables/disables productive mode for current extension (used only while
1926 // registration).
1927 // @TODO This should be rewrittten to allow, more development states, e.g. 'planing','alpha','beta','beta2','stable'
1928 function enableExtensionProductive ($isProductive = true) {
1929         // Log debug message
1930         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ext_name=%s,isProductive=%d", getCurrentExtensionName(), intval($isProductive)));
1931
1932         // Set it
1933         $GLOBALS['ext_productive'][getCurrentExtensionName()] = (bool) $isProductive;
1934 }
1935
1936 // Checks wether the extension is in productive phase. If not set, development
1937 // phase (=false) is assumed.
1938 function isExtensionProductive ($ext_name = '') {
1939         // Is the extension name empty? Then use current
1940         if (empty($ext_name)) {
1941                 // Get current extension name
1942                 $ext_name = getCurrentExtensionName();
1943         } // END - if
1944
1945         // Do we have cache?
1946         if (!isset($GLOBALS[__FUNCTION__][$ext_name])) {
1947                 // Load extension only if not yet loaded
1948                 if (!isset($GLOBALS['ext_productive'][$ext_name])) {
1949                         // Load extension in test mode
1950                         loadExtension($ext_name, 'test');
1951                 } // END - if
1952
1953                 // Determine it
1954                 $GLOBALS[__FUNCTION__][$ext_name] = ((isset($GLOBALS['ext_productive'][$ext_name])) && ($GLOBALS['ext_productive'][$ext_name] === true));
1955         } // END - if
1956
1957         // Log debug message
1958         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ext_name=%s,isProductive=%s", $ext_name, intval($GLOBALS[__FUNCTION__][$ext_name])));
1959
1960         // Return result
1961         return $GLOBALS[__FUNCTION__][$ext_name];
1962 }
1963
1964 // Mark extension file as loaded
1965 function markExtensionAsLoaded ($ext_name) {
1966         // Is it already loaded?
1967         if (isExtensionLoaded($ext_name)) {
1968                 // Then abort here
1969                 debug_report_bug(__FUNCTION__, __LINE__, 'Extension ' . $ext_name . ' is already marked as loaded!');
1970         } // END - if
1971
1972         // Mark it
1973         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, sprintf("ext_name=%s,ext_loaded=true", $ext_name));
1974         $GLOBALS['ext_loaded']['ext_name'][$ext_name] = true;
1975 }
1976
1977 // Determine wether the given extension is already loaded
1978 function isExtensionLoaded ($ext_name) {
1979         // Is it there?
1980         return ((isset($GLOBALS['ext_loaded']['ext_name'][$ext_name])) && ($GLOBALS['ext_loaded']['ext_name'][$ext_name] === true));
1981 }
1982
1983 // Mark extension's library file as loaded
1984 function markExtensionLibraryAsLoaded ($ext_name) {
1985         // Is it already loaded?
1986         if (isExtensionLibraryLoaded($ext_name)) {
1987                 // Then abort here
1988                 debug_report_bug(__FUNCTION__, __LINE__, 'Extension library ' . $ext_name . ' is already marked as loaded!');
1989         } // END - if
1990
1991         // Mark it
1992         $GLOBALS['ext_loaded']['library'][$ext_name] = true;
1993 }
1994
1995 // Determine wether the given extension's library is already loaded
1996 function isExtensionLibraryLoaded ($ext_name) {
1997         // Is it there?
1998         return ((isset($GLOBALS['ext_loaded']['library'][$ext_name])) && ($GLOBALS['ext_loaded']['library'][$ext_name] === true));
1999 }
2000
2001 // [EOF]
2002 ?>