Fixes for fix_menu.php and SQL_ALTER_TABLE()
[mailer.git] / inc / extensions-functions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    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  * Needs to be in all Files and every File needs "svn propset           *
18  * svn:keywords Date Revision" (autoprobset!) at least!!!!!!            *
19  * -------------------------------------------------------------------- *
20  * Copyright (c) 2003 - 2009 by Roland Haeder                           *
21  * For more information visit: http://www.mxchange.org                  *
22  *                                                                      *
23  * This program is free software; you can redistribute it and/or modify *
24  * it under the terms of the GNU General Public License as published by *
25  * the Free Software Foundation; either version 2 of the License, or    *
26  * (at your option) any later version.                                  *
27  *                                                                      *
28  * This program is distributed in the hope that it will be useful,      *
29  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
30  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
31  * GNU General Public License for more details.                         *
32  *                                                                      *
33  * You should have received a copy of the GNU General Public License    *
34  * along with this program; if not, write to the Free Software          *
35  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
36  * MA  02110-1301  USA                                                  *
37  ************************************************************************/
38
39 // Some security stuff...
40 if (!defined('__SECURITY')) {
41         die();
42 } // END - if
43
44 // Load the extension and maybe found language and function files.
45 function loadExtension ($ext_name, $ext_mode = 'init', $ext_ver = '', $dry_run = false) {
46         // Set current extension name
47         setCurrentExtensionName($ext_name);
48
49         // Set current extension version
50         setCurrentExtensionVersion($ext_ver);
51
52         // Set extension mode
53         setExtensionMode($ext_mode);
54
55         // Set dry-run
56         enableExtensionDryRun($dry_run);
57
58         // Init array
59         initIncludePool('extension');
60
61         // Init EXT_UPDATE_DEPENDS
62         initExtensionUpdateDependencies();
63
64         // Init current extension name list
65         initExtensionSqls();
66
67         // Is the extension already loaded?
68         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Loading extension {$ext_name}, mode=".getExtensionMode().", ver=".getCurrentExtensionVersion()."");
69         if ((isset($GLOBALS['ext_loaded']['ext'][$ext_name])) && (getExtensionMode() == 'init')) {
70                 // Debug message
71                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension %s already loaded.", $ext_name));
72
73                 // Abort here
74                 return false;
75         } // END - if
76
77         // Is the extension file NOT there?
78         if (!isExtensionNameValid($ext_name)) {
79                 // Debug message
80                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Extension %s not found or not readable.", $ext_name));
81
82                 // Abort here
83                 return false;
84         } // END - if
85
86         // Load extension's own language file if not in test mode
87         if ((getExtensionMode() != 'test') && (ifExtensionHasLanguageFile($ext_name))) {
88                 // Load it
89                 loadLanguageFile($ext_name);
90         } // END - if
91
92         // Do we have cache?
93         if (isExtensionFunctionFileReadable($ext_name)) {
94                 // Not yet loaded?
95                 if ((($GLOBALS['cache_array']['extension']['ext_func'][$ext_name] == 'Y') || (!isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name]))) && (!isset($GLOBALS['ext_loaded']['funcs'][$ext_name]))) {
96                         // Construct FQFN for functions file
97                         $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
98
99                         // Mark it as loaded
100                         $GLOBALS['ext_loaded']['funcs'][$ext_name] = true;
101
102                         // Download functions file
103                         loadIncludeOnce($funcsInclude);
104                 } // END - if
105         } elseif ((!isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name])) && (isDebugModeEnabled()) && (getOutputMode() == 0) && ($ext_name != 'sql_patches') && (substr($ext_name, 0, 10) != 'admintheme') && (getExtensionMode() == 'test')) {
106                 // No functions file is not so good...
107                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("NOTICE: Extension %s has no own functions file or we cannot read from it. mode=%s",
108                         $ext_name,
109                         getExtensionMode()
110                 ));
111         }
112
113         // Extensions are not deprecated by default
114         setExtensionDeprecated('N');
115
116         // Extensions are not always active by default
117         setExtensionAlwaysActive('N');
118
119         // Extension update notes
120         setExtensionUpdateNotes('');
121
122         // Include the extension file
123         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "Extension loaded.");
124         loadExtensionInclude();
125
126         // Is this extension deprecated?
127         if (isExtensionDeprecated()) {
128                 // Deactivate the extension
129                 doDeactivateExtension($ext_name);
130
131                 // Abort here
132                 return false;
133         } // END - if
134
135         // Mark it as loaded in normal mode
136         if (getExtensionMode() == '') {
137                 // Mark it now...
138                 $GLOBALS['ext_loaded']['ext'][$ext_name] = true;
139         } // END - if
140
141         // All fine!
142         return true;
143 }
144
145 // Registeres an extension and possible update depencies
146 function registerExtension ($ext_name, $task_id, $dry_run = false, $logout = true) {
147         // Set current extension name
148         setCurrentExtensionName($ext_name);
149
150         // Enable dry-run
151         enableExtensionDryRun($dry_run);
152
153         // By default all extensions are in productive phase
154         enableExtensionProductive();
155
156         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()." - ENTERED!");
157         // This shall never do a non-admin user or if the extension is active (already installed)
158         if ((!isAdmin()) || (isExtensionInstalled($ext_name))) {
159                 return false;
160         } // END - if
161
162         // When this extension is already in install/update phase, all is fine
163         if (isExtensionRegisterRunning($ext_name)) {
164                 // Then abort here which is fine
165                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()." - ALREADY!");
166                 return true;
167         } // END - if
168
169         // This registration is running
170         addExtensionRunningRegistration($ext_name);
171
172         // Init EXT_UPDATE_DEPENDS
173         initExtensionUpdateDependencies();
174
175         // Is the task id zero? Then we need to auto-fix it here
176         if ($task_id == 0) {
177                 // Try to find the task
178                 $task_id = determineExtensionTaskId(getCurrentExtensionName());
179
180                 // Still zero and not in dry-run?
181                 if (($task_id == 0) && (!getExtensionDryRun())) {
182                         // Then request a bug report
183                         debug_report_bug(sprintf("%s: task_id is still zero after determineExtensionTaskId(%s)",
184                                 __FUNCTION__,
185                                 getCurrentExtensionName()
186                         ));
187                 } // END - if
188         } // END - if
189
190         // Init queries and notes
191         initExtensionSqls();
192         initExtensionNotes();
193
194         // Init variables
195         $ret = false;
196         $test = false;
197         initIncludePool('extension');
198
199         // By default we have no failures
200         setExtensionReportsFailure(false);
201
202         // Does this extension exists?
203         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()."");
204         if (loadExtension(getCurrentExtensionName(), 'register', '', getExtensionDryRun())) {
205                 // Set current extension name again
206                 setCurrentExtensionName($ext_name);
207
208                 // And run possible updates
209                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "".getCurrentExtensionName());
210                 $history = getExtensionVersionHistory();
211                 foreach ($history as $ver) {
212                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".getCurrentExtensionName().", ext_ver={$ver}");
213                         // Load extension in update mode
214                         loadExtension(getCurrentExtensionName(), 'update', $ver, getExtensionDryRun());
215
216                         // Add update notes to our output
217                         addExtensionNotes($ver);
218                 } // END - foreach
219
220                 // Does this extension depends on an outstanding update of another update?
221                 for ($dmy = getExtensionUpdateIterator(); getExtensionUpdateIterator() < countExtensionUpdateDependencies();) {
222                         // Get next update
223                         $ext_update = getExtensionUpdateDependenciesIterator();
224
225                         // Increment here to avoid endless loop
226                         incrementExtensionUpdateIterator();
227
228                         // Check for required file
229                         if (loadExtension($ext_update, 'register', '', getExtensionDryRun())) {
230                                 // Set current extension name again
231                                 setCurrentExtensionName($ext_name);
232
233                                 // If versions mismatch update extension first
234                                 $ext_ver = '';
235                                 if (isExtensionInstalled($ext_update)) {
236                                         // Get version only if installed
237                                         $ext_ver = getExtensionVersion($ext_update);
238                                 } // END - if
239
240                                 // Extension version set? If empty the extension is not registered
241                                 if (empty($ext_ver)) {
242                                         // Extension not registered so far so first load task's ID...
243                                         $task = determineExtensionTaskId($ext_update);
244
245                                         // Entry found?
246                                         if ($task > 0) {
247                                                 // Try to register the extension
248                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().":ext_update=".$ext_update.",taskId=".$task."");
249                                                 $test = registerExtension($ext_update, $task, getExtensionDryRun(), false);
250
251                                                 // Reset extension name
252                                                 setCurrentExtensionName($ext_name);
253                                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()); print getCurrentExtensionName().':<pre>'.print_r($test);
254                                         } // END - if
255                                 } elseif ($ext_ver != getCurrentExtensionVersion()) {
256                                         // Ok, update this extension now
257                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().",ext_update=".$ext_update.",ext_ver=".$ext_ver."/".getCurrentExtensionVersion()."");
258                                         $GLOBALS['ext_backup'][$ext_update][$ext_ver] = getCurrentExtensionName();
259                                         updateExtension($ext_update, $ext_ver, getExtensionDryRun());
260                                         setCurrentExtensionName($GLOBALS['ext_backup'][$ext_update][$ext_ver]);
261                                         unset($GLOBALS['ext_backup'][$ext_update][$ext_ver]);
262                                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()."");
263
264                                         // All okay!
265                                         $test = true;
266                                 } else {
267                                         // Nothing to register / update before...
268                                         $test = true;
269                                 }
270                         } else {
271                                 // Required file for update does not exists!
272                                 $test = true;
273                                 // But this is fine for the first time...
274                         }
275
276                         // Restore the current extension name
277                         setCurrentExtensionName($ext_name);
278                 } // END - for
279
280                 // Is there no update?
281                 if (countExtensionUpdateDependencies(getCurrentExtensionName()) == 0) {
282                         // Then test is passed!
283                         $test = true;
284                 } // END - if
285
286                 // Switch back to register mode
287                 setExtensionMode('register');
288
289                 // Remains true if extension registration reports no failures
290                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()); print getCurrentExtensionName().':<pre>'.print_r($test, true).'</pre>';
291                 $test = (($test === true) && (getExtensionReportsFailure() === false));
292                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()); print getCurrentExtensionName().':<pre>'.print_r($test, true).'</pre>';
293
294                 // Does everthing before wents ok?
295                 if ($test === true) {
296                         // "Dry-run-mode" activated?
297                         if ((getExtensionDryRun() === false) && (!isExtensionOnRemovalList())) {
298                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".getCurrentExtensionName());
299                                 // Init SQLs and transfer ext->generic
300                                 initSqls();
301                                 setSqlsArray(getExtensionSqls());
302
303                                 // Run installation pre-installation filters
304                                 runFilterChain('pre_extension_installed', array('dry_run' => getExtensionDryRun()));
305
306                                 // Register extension
307                                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "insert=".getCurrentExtensionName().'/'.getCurrentExtensionVersion()." - INSERT!");
308                                 if (isExtensionInstalledAndNewer('sql_patches', '0.0.6')) {
309                                         // New way, with CSS
310                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_extensions` (`ext_name`, `ext_active`, `ext_version`,`ext_has_css`) VALUES ('%s','%s','%s','%s')",
311                                                 array(getCurrentExtensionName(), getExtensionAlwaysActive(), getCurrentExtensionVersion(), getExtensionHasCss()), __FUNCTION__, __LINE__);
312                                 } else {
313                                         // Old way, no CSS
314                                         SQL_QUERY_ESC("INSERT INTO `{?_MYSQL_PREFIX?}_extensions` (`ext_name`, `ext_active`, `ext_version`) VALUES ('%s','%s','%s')",
315                                                 array(getCurrentExtensionName(), getExtensionAlwaysActive(), getCurrentExtensionVersion()), __FUNCTION__, __LINE__);
316                                 }
317
318                                 // Remove cache file(s) if extension is active
319                                 runFilterChain('post_extension_installed', array(
320                                         'pool'     => 'extension',
321                                         'ext_name' => getCurrentExtensionName(),
322                                         'task_id'  => $task_id
323                                 ));
324
325                                 // Remove all SQL commands
326                                 unsetSqls();
327
328                                 // Mark it as installed
329                                 $GLOBALS['ext_is_installed'][getCurrentExtensionName()] = true;
330
331                                 // In normal mode return a true on success
332                                 $ret = true;
333                         } elseif (getExtensionDryRun() === true) {
334                                 // In  "dry-run" mode return array with all SQL commands
335                                 $ret = getExtensionSqls();
336
337                                 // Remove all SQL commands
338                                 unsetSqls();
339                         } else {
340                                 // Extension has been removed for updates, so all is fine!
341                                 $ret = true;
342                         }
343                 } else {
344                         // No, an error occurs while registering extension :-(
345                         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "".getCurrentExtensionName());
346                         $ret = false;
347                 }
348         } elseif (($task_id > 0) && (getCurrentExtensionName() != '')) {
349                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()."");
350                 // Remove task from system when id and extension's name is valid
351                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `id`=%s AND `status`='NEW' LIMIT 1",
352                         array(bigintval($task_id)), __FUNCTION__, __LINE__);
353         }
354
355         // Is this the sql_patches?
356         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ':'.getCurrentExtensionName()."/".getExtensionMode()."");
357         if ((getCurrentExtensionName() == 'sql_patches') && ((getExtensionMode() == 'register') || (getExtensionMode() == 'remove')) && (!getExtensionDryRun()) && ($test)) {
358                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": LOAD!");
359                 if ($logout === true) {
360                         // Then redirect to logout
361                         redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . getExtensionMode() . '=sql_patches');
362                 } else {
363                         // Add temporary filter
364                         registerFilter('shutdown', 'REDIRECT_TO_LOGOUT_SQL_PATCHES', true, true);
365                         $GLOBALS['ext_load_mode'] = getExtensionMode();
366                 }
367         } // END - if
368
369         // Return status code
370         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()." - LEFT!");
371         //* DEBUG: */ print getCurrentExtensionName().':<pre>'.print_r($ret, true).'</pre>';
372         return $ret;
373 }
374
375 // Run SQL queries for given extension id
376 // @TODO Change from ext_id to ext_name (not just even the variable! ;-) )
377 function doExtensionSqls ($ext_id, $load_mode) {
378         // This shall never do a non-admin user!
379         if (!isAdmin()) return false;
380
381         // Get extension's name
382         $ext_name = getExtensionName($ext_id);
383
384         // Set current SQL name
385         setCurrentExtensionName($ext_name);
386
387         // Init EXT_UPDATE_DEPENDS
388         initExtensionUpdateDependencies();
389
390         // Init array
391         initExtensionSqls();
392
393         // By default no SQL has been executed
394         $sqlRan = false;
395
396         // Load extension in detected mode
397         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ":ext_name[{$ext_id}]=".getCurrentExtensionName()."");
398         loadExtension(getCurrentExtensionName(), $load_mode, '', false);
399
400         // Init these SQLs
401         initSqls();
402         setSqlsArray(getExtensionSqls());
403
404         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ":SQLs::count=".countSqls()."");
405         if (isSqlsValid()) {
406                 // Run SQL commands...
407                 runFilterChain('run_sqls');
408         } // END - if
409
410         // Run any filters depending on the action here
411         runFilterChain('extension_' . $load_mode);
412
413         // Remove cache file(s) if extension is active
414         if (((isExtensionActive('cache')) && ((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == 'activate') || ($load_mode == 'deactivate'))) {
415                 // Run filters
416                 runFilterChain('post_extension_run_sql', getCurrentExtensionName());
417         } // END - if
418
419         // Is this the sql_patches?
420         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": id=".$ext_id.",currName=".getCurrentExtensionName().",loadMode=".$load_mode);
421         if ((getCurrentExtensionName() == 'sql_patches') && (($load_mode == 'register') || ($load_mode == 'remove'))) {
422                 // Then redirect to logout
423                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": LOAD!");
424                 redirectToUrl('modules.php?module=admin&amp;logout=1&amp;' . $load_mode . '=sql_patches');
425         } // END - if
426 }
427
428 // Check wether the given extension is installed
429 function isExtensionInstalled ($ext_name) {
430         // We don't like empty extension names here
431         if (empty($ext_name)) {
432                 // Please fix them all
433                 debug_report_bug(__FUNCTION__.': ext_name is empty.');
434         } // END - if
435
436         // By default non is installed
437         $isInstalled = false;
438
439         // Check if there is a cache entry
440         if (isset($GLOBALS['ext_is_installed'][$ext_name])) {
441                 // Use cache built from below queries
442                 $isInstalled = $GLOBALS['ext_is_installed'][$ext_name];
443         } elseif (isset($GLOBALS['cache_array']['extension']['ext_id'][$ext_name])) {
444                 // Found!
445                 $isInstalled = true;
446
447                 // Count cache hits
448                 incrementStatsEntry('cache_hits');
449         } elseif ((isInstallationPhase())) {
450                 // Extensions are all inactive/not installed during installation
451         } else {
452                 // Look in database
453                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
454                         array($ext_name), __FILE__, __LINE__);
455
456                 // Do we have a record?
457                 $isInstalled = (SQL_NUMROWS($result) == 1);
458
459                 // Is it installed, then cache the entry
460                 if ($isInstalled === true) {
461                         // Dummy call (get is okay here)
462                         getExtensionId($ext_name, true);
463                 } // END - if
464
465                 // Free result
466                 SQL_FREERESULT($result);
467
468                 // Remember the status
469                 $GLOBALS['ext_is_installed'][$ext_name] = $isInstalled;
470         }
471
472         // Return status
473         return $isInstalled;
474 }
475
476 // Check if given extension is active
477 function isExtensionActive ($ext_name) {
478         // Extensions are all inactive during installation
479         if ((isInstallationPhase()) || (empty($ext_name))) return false;
480
481         // Not active is the default
482         $active = 'N';
483
484         // Check cache
485         if (isset($GLOBALS['cache_array']['extension']['ext_active'][$ext_name])) {
486                 // Load from cache
487                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
488                 $active = $GLOBALS['cache_array']['extension']['ext_active'][$ext_name];
489
490                 // Count cache hits
491                 incrementStatsEntry('cache_hits');
492         } elseif (isset($GLOBALS['ext_loaded'][$ext_name])) {
493                 // @TODO Extension is loaded, what next?
494                 app_die(__FUNCTION__, __LINE__, "LOADED:$ext_name");
495         } elseif (($ext_name == 'cache') || (!isExtensionInstalled('cache'))) {
496                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
497                 // Load from database
498                 $result = SQL_QUERY_ESC("SELECT `ext_active` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
499                         array($ext_name), __FUNCTION__, __LINE__);
500
501                 // Entry found?
502                 if (SQL_NUMROWS($result) == 1) {
503                         // Load entry
504                         list($active) = SQL_FETCHROW($result);
505                 } // END - if
506
507                 // Free result
508                 SQL_FREERESULT($result);
509
510                 // Write cache array
511                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name."[DB]: {$active}");
512                 $GLOBALS['cache_array']['extension']['ext_active'][$ext_name] = $active;
513         } else {
514                 // Extension not active!
515                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name=".$ext_name.": Not active!");
516                 $GLOBALS['cache_array']['extension']['ext_active'][$ext_name] = 'N';
517         }
518
519         // Debug message
520         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "ext_name={$ext_name},active={$active}");
521
522         // Is this extension activated? (For admins we always have active extensions...)
523         return ($active == 'Y');
524 }
525
526 // Get version from extensions
527 function getExtensionVersion ($ext_name) {
528         // By default no extension is found
529         $ext_ver = 'invalid';
530
531         // Empty extension name should be fixed!
532         if (empty($ext_name)) {
533                 // Please report this bug!
534                 debug_report_bug(__FUNCTION__ . ': ext_name is empty which is not allowed here.');
535         } // END - if
536
537         // Extensions are all inactive during installation
538         if (isInstallationPhase()) return '';
539         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": ext_name={$ext_name}");
540
541         // Is the cache written?
542         if (isset($GLOBALS['cache_array']['extension']['ext_version'][$ext_name])) {
543                 // Load data from cache
544                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": CACHE!");
545                 $ext_ver = $GLOBALS['cache_array']['extension']['ext_version'][$ext_name];
546
547                 // Count cache hits
548                 incrementStatsEntry('cache_hits');
549         } elseif ((!isCacheInstanceValid()) || (isset($GLOBALS['cache_array']['extension'])) || (getOutputMode() != 0)) {
550                 // Load from database
551                 $result = SQL_QUERY_ESC("SELECT `ext_version` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
552                         array($ext_name), __FUNCTION__, __LINE__);
553                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": DB - ".SQL_NUMROWS($result)."");
554
555                 // Is the extension there?
556                 if (SQL_NUMROWS($result) == 1) {
557                         // Load entry
558                         list($ext_ver) = SQL_FETCHROW($result);
559                 } elseif (isDebugModeEnabled()) {
560                         // Not found!
561                         logDebugMessage(__FUNCTION__, __LINE__, sprintf(": Cannot find extension %s in database!", $ext_name));
562                 }
563
564                 // Free result
565                 SQL_FREERESULT($result);
566
567                 // Set cache
568                 $GLOBALS['cache_array']['extension']['ext_version'][$ext_name] = $ext_ver;
569         }
570
571         // Extension version should not be invalid
572         if ($ext_ver == 'invalid') {
573                 // Please report this trouble
574                 debug_report_bug(sprintf("Extension <strong>%s</strong> has empty version!", $ext_name));
575         } // END - if
576
577         // Return result
578         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, ": ret={$ext_ver}");
579         return $ext_ver;
580 }
581
582 // Updates a given extension with current extension version to latest version
583 function updateExtension ($ext_name, $ext_ver, $dry_run = false) {
584         // Only admins are allowed to update extensions
585         if ((!isAdmin()) || (empty($ext_name))) return false;
586
587         // Set current SQL name
588         setCurrentExtensionName($ext_name);
589
590         // Init arrays
591         initExtensionSqls();
592         initExtensionNotes();
593         initIncludePool('extension');
594
595         // Load extension in test mode
596         loadExtension($ext_name, 'test', $ext_ver, getExtensionDryRun());
597
598         // Save version history
599         $history = getExtensionVersionHistory();
600
601         // Remove old SQLs array to prevent possible bugs
602         initExtensionSqls();
603
604         // Check if version is updated
605         //* DEBUG: */ print getCurrentExtensionName().'/'.$ext_name.':'.getThisExtensionVersion().'/'.$ext_ver.'/'.intval(is_array($history)).'<br />';
606         if (((getThisExtensionVersion() != $ext_ver) || (getExtensionDryRun())) && (is_array($history))) {
607                 // Search for starting point
608                 $start = array_search($ext_ver, $history);
609
610                 // And load SQL queries in order of version history
611                 for ($idx = ($start + 1); $idx < count($history); $idx++) {
612                         // Set extension version
613                         $GLOBALS['update_ver'][getCurrentExtensionName()] = $history[$idx];
614
615                         // Load again...
616                         loadExtension(getCurrentExtensionName(), 'update', $GLOBALS['update_ver'][getCurrentExtensionName()], getExtensionDryRun());
617
618                         // Get all depencies
619                         $depencies = getExtensionUpdateDependencies();
620
621                         // Nothing to apply?
622                         if (count($depencies) > 0) {
623                                 // Apply all extension depencies
624                                 foreach ($depencies as $ext_depend) {
625                                         // Did we already update/register this?
626                                         if (!isset($GLOBALS['ext_updated'][$ext_depend])) {
627                                                 // Set it as current
628                                                 setCurrentExtensionName($ext_depend);
629
630                                                 // Mark it as already updated before we update it
631                                                 $GLOBALS['ext_updated'][$ext_depend] = true;
632
633                                                 // Is the extension there?
634                                                 if (isExtensionInstalled($ext_depend)) {
635                                                         // Update another extension first!
636                                                         $test = updateExtension($ext_depend, getExtensionVersion($ext_depend), getExtensionDryRun());
637                                                 } else {
638                                                         // Register new extension
639                                                         $test = registerExtension($ext_depend, 0, getExtensionDryRun(), false);
640                                                 }
641                                         } // END - if
642                                 } // END - foreach
643
644                                 // Set name back
645                                 setCurrentExtensionName($ext_name);
646                         } // END - if
647
648                         // Add notes
649                         addExtensionNotes($history[$idx]);
650                 } // END - for
651
652                 // In real-mode execute any existing includes
653                 if (getExtensionDryRun() === false) {
654                         $GLOBALS['ext_inc_pool'][getCurrentExtensionName()] = getIncludePool('extension');
655                         runFilterChain('load_includes', 'extension');
656                         setIncludePool('extension', $GLOBALS['ext_inc_pool'][getCurrentExtensionName()]);
657                         unset($GLOBALS['ext_inc_pool'][getCurrentExtensionName()]);
658                 } // END - if
659
660                 // Init these SQLs
661                 initSqls();
662                 setSqlsArray(getExtensionSqls());
663
664                 // Run SQLs
665                 runFilterChain('run_sqls', array('dry_run' => getExtensionDryRun()));
666
667                 if (getExtensionDryRun() === false) {
668                         // Run filters on success extension update
669                         runFilterChain('extension_update', getCurrentExtensionName());
670                 } // END - if
671         } // END - if
672 }
673
674 // Output verbose SQL table for extension
675 function addExtensionVerboseSqlTable ($title = '', $dashed = '', $switch = false, $width = '100%') {
676         // Empty title?
677         if (empty($title)) {
678                 // Then fix it to default
679                 $title = getMessage('ADMIN_SQLS_EXECUTED_ON_REMOVAL');
680         } // END - if
681
682         // Init variables
683         $OUT = '';
684
685         // Do we have queries?
686         if ((getExtensionVersion('sql_patches') >= '0.0.7') && (getConfig('verbose_sql') == 'Y')) {
687                 // Init switch color
688                 $SW = 2;
689
690                 // Get all SQLs
691                 foreach (getExtensionSqls() as $sqls) {
692                         // New array format is recursive
693                         foreach ($sqls as $idx => $sql) {
694                                 // Trim out spaces
695                                 $sql = trim($sql);
696
697                                 // Output command if set
698                                 if (!empty($sql)) {
699                                         // Prepare output for template
700                                         $content = array(
701                                                 'sw'  => $SW,
702                                                 'i'   => ($idx+1),
703                                                 'sql' => $sql
704                                         );
705
706                                         // Load row template
707                                         $OUT .= loadTemplate('admin_ext_sql_row', true, $content);
708
709                                         // Switch color
710                                         $SW = 3 - $SW;
711                                 } // END - if
712                         } // END - foreach
713                 } // END - foreach
714
715                 // Prepare content for template
716                 $content = array(
717                         'width'  => $width,
718                         'dashed' => $dashed,
719                         'title'  => $title,
720                         'rows'   => $OUT
721                 );
722
723                 // Load main template
724                 $OUT = loadTemplate('admin_ext_sql_table', true, $content);
725         } elseif ((getExtensionVersion('sql_patches') >= '0.0.7') && (getConfig('verbose_sql') == 'Y')) {
726                 // No addional SQL commands to run
727                 $OUT = loadTemplate('admin_settings_saved', true, getMessage('ADMIN_NO_ADDITIONAL_SQLS'));
728         } // END - if
729
730         // Return output
731         return $OUT;
732 }
733
734 // Get extension name from id
735 function getExtensionName ($ext_id) {
736         // Init extension name
737         $ret = '';
738
739         // Is cache there?
740         if (isset($GLOBALS['cache_array']['extension']['ext_name'][$ext_id])) {
741                 // Load from cache
742                 $ret = $GLOBALS['cache_array']['extension']['ext_name'][$ext_id];
743
744                 // Count cache hits
745                 incrementStatsEntry('cache_hits');
746         } elseif (!isExtensionActive('cache')) {
747                 // Load from database
748                 $result = SQL_QUERY_ESC("SELECT `ext_name` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `id`=%s LIMIT 1",
749                         array(bigintval($ext_id)), __FUNCTION__, __LINE__);
750
751                 // Is the entry there?
752                 if (SQL_NUMROWS($result) == 1) {
753                         // Get the extension's name from database
754                         list($ret) = SQL_FETCHROW($result);
755                 } // END - if
756
757                 // Free result
758                 SQL_FREERESULT($result);
759         }
760
761         // Did we find some extension?
762         if (empty($ret)) {
763                 // We should fix these all!
764                 debug_report_bug(__FUNCTION__ . ': ext_name is empty. ext_id=' . $ext_id);
765         } // END - if
766
767         // Return the extension name
768         return $ret;
769 }
770
771 // Get extension id from name
772 function getExtensionId ($ext_name, $forceDb = false) {
773         // Init ID number
774         $ret = 0;
775
776         if (isset($GLOBALS['cache_array']['extension']['ext_id'][$ext_name])) {
777                 // Load from cache
778                 $ret = $GLOBALS['cache_array']['extension']['ext_id'][$ext_name];
779
780                 // Count cache hits
781                 incrementStatsEntry('cache_hits');
782         } elseif (($forceDb === true) || (!isExtensionActive('cache'))) {
783                 // Load from database
784                 $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_extensions` WHERE `ext_name`='%s' LIMIT 1",
785                         array($ext_name), __FUNCTION__, __LINE__);
786
787                 // Is the entry there?
788                 if (SQL_NUMROWS($result) == 1) {
789                         // Get the extension's id from database
790                         list($ret) = SQL_FETCHROW($result);
791                 } // END - if
792
793                 // Free result
794                 SQL_FREERESULT($result);
795
796                 // Cache it
797                 $GLOBALS['cache_array']['extension']['ext_id'][$ext_name] = $ret;
798         }
799
800         if ($ret == 0) {
801                 // We should fix these all!
802                 debug_report_bug(__FUNCTION__ . ': Invalid extension name found. ext_name=' . $ext_name);
803         } // END - if
804
805         // Return value
806         return $ret;
807 }
808
809 // Determines wether the given extension name is valid
810 function isExtensionNameValid ($ext_name) {
811         // Do we have cache?
812         if (!isset($GLOBALS['ext_name_valid'][$ext_name])) {
813                 // Generate include file name
814                 $INC = sprintf("inc/extensions/ext-%s.php", $ext_name);
815
816                 // Is there a file in inc/extensions/ ?
817                 $GLOBALS['ext_name_valid'][$ext_name] = isIncludeReadable($INC);
818         } // END - if
819
820         // Return result
821         return $GLOBALS['ext_name_valid'][$ext_name];
822 }
823
824 // Determines wether the given extension id is valid
825 function isExtensionIdValid ($ext_id) {
826         // Default is nothing valid
827         $isValid = false;
828
829         // Check in cache then in database
830         if (isset($GLOBALS['cache_array']['extension']['ext_name'][$ext_id])) {
831                 // Valid!
832                 $isValid = true;
833
834                 // Count cache hits
835                 incrementStatsEntry('cache_hits');
836         } else {
837                 // Query database
838                 $isValid = (countSumTotalData($ext_id, 'extensions', 'id', 'id', true) == 1);
839         }
840
841         // Return result
842         return $isValid;
843 }
844
845 // Activate given extension
846 function doActivateExtension ($ext_name) {
847         // Activate the extension
848         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_active`='Y' WHERE `ext_name`='%s' LIMIT 1",
849                 array($ext_name), __FUNCTION__, __LINE__);
850
851         // Extension has been activated?
852         if (SQL_AFFECTEDROWS() == 1) {
853                 // Then run all queries
854                 doExtensionSqls(getExtensionId($ext_name), 'activate');
855         } // END - if
856 }
857
858 // Deactivate given extension
859 function doDeactivateExtension($ext_name) {
860         // Activate the extension
861         SQL_QUERY_ESC("UPDATE `{?_MYSQL_PREFIX?}_extensions` SET `ext_active`='N' WHERE `ext_name`='%s' LIMIT 1",
862                 array($ext_name), __FUNCTION__, __LINE__);
863
864         // Extension has been activated?
865         if (SQL_AFFECTEDROWS() == 1) {
866                 // Then run all queries
867                 doExtensionSqls(getExtensionId($ext_name), 'deactivate');
868
869                 // Create new task
870                 createExtensionDeactivationTask($ext_name);
871
872                 // Notify the admin
873                 sendAdminNotification(
874                 getMessage('ADMIN_SUBJECT_EXTENSION_DEACTIVATED'),
875                         'admin_ext_deactivated',
876                         array('ext_name' => $ext_name)
877                 );
878         } // END - if
879 }
880
881 // Checks wether the extension is older than given
882 function isExtensionOlder ($ext_name, $ext_ver) {
883         // Get current extension version
884         $currVersion = getExtensionVersion($ext_name);
885
886         // Remove all dots from both versions
887         $currVersion = str_replace('.', '', $currVersion);
888         $ext_ver = str_replace('.', '', $ext_ver);
889
890         // Now compare both and return the result
891         return ($currVersion < $ext_ver);
892 }
893
894 // Creates a new task for updated extension
895 function createExtensionUpdateTask ($adminId, $ext_name, $ext_ver, $notes) {
896         // Create subject line
897         $subject = '[UPDATE-' . $ext_name . '-' . $ext_ver . ':] {--ADMIN_UPDATE_EXT_SUBJ--}';
898
899         // Is the extension there?
900         if (isExtensionInstalled($ext_name)) {
901                 // Check if task is not there
902                 if (determineTaskIdBySubject($subject) == 0) {
903                         // Create extension update-task
904                         createNewTask($subject, $notes, 'EXTENSION_UPDATE', 0, $adminId);
905                 } // END - if
906         } else {
907                 // Extension not there! :-(
908                 debug_report_bug(sprintf("Extension <strong>%s</strong> not found but should be updated?", $ext_name));
909         }
910 }
911
912 // Creates a new task for newly installed extension
913 function createNewExtensionTask ($adminId, $subject, $ext) {
914         // Not installed and do we have created a task for the admin?
915         if ((determineTaskIdBySubject($subject) == 0) && (!isExtensionInstalled($ext))) {
916                 // Set default message if ext-foo is missing
917                 $message = sprintf(getMessage('ADMIN_EXT_TEXT_FILE_MISSING'), $ext);
918
919                 // Template file
920                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
921                         getConfig('PATH'),
922                         getLanguage(),
923                         $ext
924                 );
925
926                 // Load text for task if found
927                 if (isFileReadable($tpl)) {
928                         // Load extension's own text template (HTML!)
929                         $message = loadTemplate('ext_' . $ext, true);
930                 } else {
931                         // Write this in debug.log as well
932                         logDebugMessage(__FUNCTION__, __LINE__, $message);
933                 }
934
935                 // Task not created so it's a brand-new extension which we need to register and create a task for!
936                 createNewTask($subject, $message, 'EXTENSION', 0, $adminId, false);
937         } // END - if
938 }
939
940 // Creates a task for automatically deactivated (deprecated) extension
941 function createExtensionDeactivationTask ($ext) {
942         // Create subject line
943         $subject = sprintf("[%s:] %s", $ext, getMessage('TASK_SUBJ_EXTENSION_DEACTIVATED'));
944
945         // Not installed and do we have created a task for the admin?
946         if ((determineTaskIdBySubject($subject) == 0) && (getExtensionVersion($ext) != '')) {
947                 // Task not created so add it
948                 createNewTask($subject, SQL_ESCAPE(loadTemplate('task_ext_deactivated', true, $ext)), 'EXTENSION_DEACTIVATION');
949         } // END - if
950 }
951
952 // Checks if the module has a menu
953 function ifModuleHasMenu ($mod, $forceDb = false) {
954         // All is false by default
955         $ret = false;
956
957         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "mod={$mod},cache=".getExtensionVersion('cache'));
958         if (isExtensionInstalledAndNewer('cache', '0.1.2')) {
959                 // Cache version is okay, so let's check the cache!
960                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$mod])) {
961                         // Check module cache and count hit
962                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$mod] == 'Y');
963                         incrementStatsEntry('cache_hits');
964                 } elseif (isset($GLOBALS['cache_array']['extension']['ext_menu'][$mod])) {
965                         // Check cache and count hit
966                         $ret = ($GLOBALS['cache_array']['extension']['ext_menu'][$mod] == 'Y');
967                         incrementStatsEntry('cache_hits');
968                 } elseif ($mod == 'admin') {
969                         // Admin module has always a menu!
970                         $ret = true;
971                 }
972         } elseif ((isExtensionInstalled('sql_patches')) && (getExtensionVersion('sql_patches') >= '0.3.6') && ((!isExtensionActive('cache')) || ($forceDb === true))) {
973                 // Check database for entry
974                 $result = SQL_QUERY_ESC("SELECT `has_menu` FROM `{?_MYSQL_PREFIX?}_mod_reg` WHERE `module`='%s' LIMIT 1",
975                         array($mod), __FUNCTION__, __LINE__);
976
977                 // Entry found?
978                 if (SQL_NUMROWS($result) == 1) {
979                         // Load "has_menu" column
980                         list($has_menu) = SQL_FETCHROW($result);
981
982                         // Fake cache... ;-)
983                         $GLOBALS['cache_array']['extension']['ext_menu'][$mod] = $has_menu;
984
985                         // Does it have a menu?
986                         $ret = ($has_menu == 'Y');
987                 } // END  - if
988
989                 // Free memory
990                 SQL_FREERESULT($result);
991         } elseif (!isExtensionInstalled('sql_patches')) {
992                 // No sql_patches installed, so maybe in admin area or no admin registered?
993                 $ret = (((isAdmin()) || (!isAdminRegistered())) && ($mod == 'admin')); // Then there is a menu!
994         }
995
996         // Return status
997         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().intval($ret));
998         return $ret;
999 }
1000
1001 // Determines the task id for given extension
1002 function determineExtensionTaskId ($ext_name) {
1003         // Default is not found
1004         $task_id = 0;
1005
1006         // Search for extension task's id
1007         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `task_type`='EXTENSION' AND `subject`='[%s:]' LIMIT 1",
1008                 array($ext_name), __FUNCTION__, __LINE__);
1009
1010         // Entry found?
1011         if (SQL_NUMROWS($result) == 1) {
1012                 // Task found so load task's ID and register extension...
1013                 list($task_id) = SQL_FETCHROW($result);
1014         } // END - if
1015
1016         // Free result
1017         SQL_FREERESULT($result);
1018
1019         // Return it
1020         return $task_id;
1021 }
1022
1023 // Determines the task id for given subject
1024 function determineTaskIdBySubject ($subject) {
1025         // Default is not found
1026         $task_id = 0;
1027
1028         // Search for task id
1029         $result = SQL_QUERY_ESC("SELECT `id` FROM `{?_MYSQL_PREFIX?}_task_system` WHERE `subject` LIKE '%s%%' LIMIT 1",
1030                 array($subject), __FUNCTION__, __LINE__);
1031
1032         // Entry found?
1033         if (SQL_NUMROWS($result) == 1) {
1034                 // Task found so load task's ID and register extension...
1035                 list($task_id) = SQL_FETCHROW($result);
1036         } // END - if
1037
1038         // Free result
1039         SQL_FREERESULT($result);
1040
1041         // Return it
1042         return $task_id;
1043 }
1044
1045 // Add updates notes for given version
1046 function addExtensionNotes ($ver) {
1047         // Init notes/content
1048         $out = ''; $content = array();
1049
1050         // Is do we have verbose output enabled?
1051         if ((!isExtensionActive('sql_patches')) || (getConfig('verbose_sql') == 'Y')) {
1052                 // Update notes found?
1053                 if (getExtensionUpdateNotes($ver) != '') {
1054                         // Update notes found
1055                         $content = array(
1056                                 'ver'   => $ver,
1057                                 'notes' => getExtensionUpdateNotes($ver)
1058                         );
1059
1060                         // Reset them
1061                         setExtensionUpdateNotes('', $ver);
1062                 } elseif (($ver == '0.0') || ($ver == '0.0.0')) {
1063                         // Initial release
1064                         $content = array(
1065                                 'ver'   => $ver,
1066                                 'notes' => getMessage('INITIAL_RELEASE')
1067                         );
1068                 } else {
1069                         // No update notes found!
1070                         $content = array(
1071                                 'ver'   => $ver,
1072                                 'notes' => getMessage('NO_UPDATE_NOTES')
1073                         );
1074                 }
1075
1076                 // Load template
1077                 $out = loadTemplate('admin_ext_notes', true, $content);
1078         } // END - if
1079
1080         // Add the notes
1081         appendExtensionNotes($out);
1082 }
1083
1084 // Getter for CSS files array
1085 function getExtensionCssFiles () {
1086         // By default no additional CSS files are found
1087         $cssFiles = array();
1088
1089         // Is the array there?
1090         if (isset($GLOBALS['css_files'])) {
1091                 // Then use it
1092                 $cssFiles = $GLOBALS['css_files'];
1093         } // END - if
1094
1095         // Return array
1096         return $cssFiles;
1097 }
1098
1099 // Init CSS files array
1100 function initExtensionCssFiles () {
1101         // Simply init it
1102         $GLOBALS['css_files'] = array();
1103 }
1104
1105 // Add new entry
1106 function addExtensionCssFile ($file) {
1107         // Is the array there?
1108         if (!isset($GLOBALS['css_files'])) {
1109                 // Then auto-init them
1110                 initExtensionCssFiles();
1111         } // END - if
1112
1113         // Add the entry
1114         $GLOBALS['css_files'][] = $file;
1115 }
1116
1117 // Setter for EXT_ALWAYS_ACTIVE flag
1118 function setExtensionAlwaysActive ($active) {
1119         $GLOBALS['ext_always_active'][getCurrentExtensionName()] = (string) $active;
1120 }
1121
1122 // Getter for EXT_ALWAYS_ACTIVE flag
1123 function getExtensionAlwaysActive () {
1124         return $GLOBALS['ext_always_active'][getCurrentExtensionName()];
1125 }
1126
1127 // Setter for EXT_VERSION flag
1128 function setThisExtensionVersion ($version) {
1129         $GLOBALS['ext_version'][getCurrentExtensionName()] = (string) $version;
1130 }
1131
1132 // Getter for EXT_VERSION flag
1133 function getThisExtensionVersion () {
1134         return $GLOBALS['ext_version'][getCurrentExtensionName()];
1135 }
1136
1137 // Setter for EXT_DEPRECATED flag
1138 function setExtensionDeprecated ($deprecated) {
1139         $GLOBALS['ext_deprecated'][getCurrentExtensionName()] = (string) $deprecated;
1140 }
1141
1142 // Getter for EXT_DEPRECATED flag
1143 function isExtensionDeprecated () {
1144         return ($GLOBALS['ext_deprecated'][getCurrentExtensionName()] == 'Y');
1145 }
1146
1147 // Setter for EXT_UPDATE_DEPENDS flag
1148 function addExtensionUpdateDependency ($updateDepends) {
1149         // Is the update depency empty? (NEED TO BE FIXED!)
1150         if (empty($updateDepends)) {
1151                 // Please report this bug!
1152                 debug_report_bug("updateDepends is left empty!");
1153         } // END - if
1154
1155         // Is it not yet added?
1156         if (!in_array($updateDepends, $GLOBALS['ext_running_updates'])) {
1157                 //* DEBUG */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().'/'.$updateDepends);
1158                 // Add it to the list of extension update depencies map
1159                 $GLOBALS['ext_update_depends'][getCurrentExtensionName()][] = (string) $updateDepends;
1160
1161                 // Remember it in the list of running updates
1162                 $GLOBALS['ext_running_updates'][] = $updateDepends;
1163         } // END - if
1164 }
1165
1166 // Checks wether the given extension registration is in progress
1167 function isExtensionRegisterRunning ($ext_name) {
1168         return ((isset($GLOBALS['ext_register_running'])) && (in_array($ext_name, $GLOBALS['ext_register_running'])));
1169 }
1170
1171 // Init EXT_UPDATE_DEPENDS flag
1172 function initExtensionUpdateDependencies () {
1173         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1174
1175         // Init update depency map automatically if not found
1176         if (!isExtensionUpdateDependenciesInitialized()) {
1177                 //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName()." - INIT!");
1178                 $GLOBALS['ext_update_depends'][getCurrentExtensionName()] = array();
1179         } // END - if
1180
1181         // Init running updates array
1182         initExtensionRuningUpdates();
1183 }
1184
1185 // Adds an extension as "registration in progress"
1186 function addExtensionRunningRegistration ($ext_name) {
1187         // Is it running?
1188         if (!isExtensionRegisterRunning($ext_name)) {
1189                 // Then add it!
1190                 $GLOBALS['ext_register_running'][] = $ext_name;
1191         } // END - if
1192 }
1193
1194 // Checks wether EXT_UPDATE_DEPENDS is initialized
1195 function isExtensionUpdateDependenciesInitialized () {
1196         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1197         return (isset($GLOBALS['ext_update_depends'][getCurrentExtensionName()]));
1198 }
1199
1200 // Initializes the list of running updates
1201 function initExtensionRuningUpdates () {
1202         // Auto-init ext_running_updates
1203         if (!isset($GLOBALS['ext_running_updates'])) {
1204                 $GLOBALS['ext_running_updates'] = array();
1205                 $GLOBALS['ext_register_running'] = array();
1206         } // END - if
1207 }
1208
1209 // Getter for EXT_UPDATE_DEPENDS flag
1210 function getExtensionUpdateDependencies () {
1211         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1212         return $GLOBALS['ext_update_depends'][getCurrentExtensionName()];
1213 }
1214
1215 // Getter for next iterator depency
1216 function getExtensionUpdateDependenciesIterator () {
1217         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1218         return ($GLOBALS['ext_update_depends'][getCurrentExtensionName()][getExtensionUpdateIterator()]);
1219 }
1220
1221 // Counter for extension update depencies
1222 function countExtensionUpdateDependencies () {
1223         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1224         return count($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1225 }
1226
1227 // Removes given extension from update denpency list
1228 function removeExtensionUpdateDependency ($ext_name) {
1229         // Look it up
1230         $key = array_search($ext_name, getExtensionUpdateDependencies());
1231
1232         // Is it valid?
1233         if ($key !== false) {
1234                 // Then remove it
1235                 unset($GLOBALS['ext_update_depends'][getCurrentExtensionName()][$key]);
1236
1237                 // And sort the array
1238                 ksort($GLOBALS['ext_update_depends'][getCurrentExtensionName()]);
1239         } // END - if
1240 }
1241
1242 // Init iterator for update depencies
1243 function initExtensionUpdateIterator () {
1244         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1245         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()] = 0;
1246 }
1247
1248 // Getter for depency iterator
1249 function getExtensionUpdateIterator () {
1250         // Auto-init iterator
1251         if (!isset($GLOBALS['ext_depend_iterator'][getCurrentExtensionName()])) initExtensionUpdateIterator();
1252
1253         // Return it
1254         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName().'/'.$GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]);
1255         return $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()];
1256 }
1257
1258 // Increments the update iterator
1259 function incrementExtensionUpdateIterator () {
1260         //* DEBUG: */ logDebugMessage(__FUNCTION__, __LINE__, "currName=".getCurrentExtensionName());
1261         $GLOBALS['ext_depend_iterator'][getCurrentExtensionName()]++;
1262 }
1263
1264 // Setter for EXT_REPORTS_FAILURE flag
1265 function setExtensionReportsFailure ($reportsFailure) {
1266         $GLOBALS['ext_reports_failure'] = (bool) $reportsFailure;
1267 }
1268
1269 // Getter for EXT_REPORTS_FAILURE flag
1270 function getExtensionReportsFailure () {
1271         return $GLOBALS['ext_reports_failure'];
1272 }
1273
1274 // Setter for EXT_VER_HISTORY flag
1275 function setExtensionVersionHistory ($verHistory) {
1276         $GLOBALS['ext_ver_history'][getCurrentExtensionName()] = (array) $verHistory;
1277 }
1278
1279 // Getter for EXT_VER_HISTORY array
1280 function getExtensionVersionHistory () {
1281         return $GLOBALS['ext_ver_history'][getCurrentExtensionName()];
1282 }
1283
1284 // Setter for EXT_UPDATE_NOTES
1285 function setExtensionUpdateNotes ($updateNotes, $ver='') {
1286         //* DEBUG: */ print __FUNCTION__.':'.getCurrentExtensionName().'/'.getCurrentExtensionVersion().'/'.$ver.'='.$updateNotes.'<br />';
1287         if (empty($ver)) {
1288                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][getCurrentExtensionVersion()] = (string) $updateNotes;
1289         } else {
1290                 $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ver] = (string) $updateNotes;
1291         }
1292 }
1293
1294 // Getter for EXT_UPDATE_NOTES
1295 function getExtensionUpdateNotes ($ver) {
1296         return $GLOBALS['ext_update_notes'][getCurrentExtensionName()][$ver];
1297 }
1298
1299 // Init extension notice
1300 function initExtensionNotes () {
1301         $GLOBALS['ext_notes'][getCurrentExtensionName()] = '';
1302 }
1303
1304 // Append extension notice
1305 function appendExtensionNotes ($notes) {
1306         $GLOBALS['ext_notes'][getCurrentExtensionName()] .= (string) trim($notes);
1307 }
1308
1309 // Getter for extension notes
1310 function getExtensionNotes () {
1311         return $GLOBALS['ext_notes'][getCurrentExtensionName()];
1312 }
1313
1314 // Setter for current extension name
1315 function setCurrentExtensionName ($ext_name) {
1316         $GLOBALS['curr_ext_name'] = (string) trim($ext_name);
1317 }
1318
1319 // Getter for current extension name
1320 function getCurrentExtensionName () {
1321         if (isset($GLOBALS['curr_ext_name'])) {
1322                 return $GLOBALS['curr_ext_name'];
1323         } // END - if
1324
1325         // Not set!
1326         debug_report_bug(__FUNCTION__.": curr_ext_name not initialized. Please execute initExtensionSqls() before calling this function.");
1327 }
1328
1329 // Init SQLs array for current extension
1330 function initExtensionSqls () {
1331         // Auto-init the array now...
1332         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1333                 $GLOBALS['ext_sqls'][getCurrentExtensionName()] = array();
1334         } // END - if
1335 }
1336
1337 // Adds SQLs to the SQLs array but "assigns" it with current extension name
1338 function addExtensionSql ($sql) {
1339         // Add it
1340         $GLOBALS['ext_sqls'][getCurrentExtensionName()][getCurrentExtensionVersion()][] = $sql;
1341 }
1342
1343 // Getter for SQLs array for current extension
1344 function getExtensionSqls () {
1345         // Output debug backtrace if not found (SHOULD NOT HAPPEN!)
1346         if (!isset($GLOBALS['ext_sqls'][getCurrentExtensionName()])) {
1347                 // Not found, should not happen
1348                 debug_report_bug(sprintf("ext_sqls is empty, current extension: %s",
1349                         getCurrentExtensionName()
1350                 ));
1351         } // END - if
1352
1353         // Return the array
1354         return $GLOBALS['ext_sqls'][getCurrentExtensionName()];
1355 }
1356
1357 // Removes SQLs for current extension
1358 function unsetExtensionSqls () {
1359         unset($GLOBALS['ext_sqls'][getCurrentExtensionName()]);
1360 }
1361
1362 // Auto-initializes the removal list
1363 function initExtensionRemovalList () {
1364         // Is the remove list there?
1365         if (!isset($GLOBALS['ext_update_remove'])) {
1366                 // Then create it
1367                 $GLOBALS['ext_update_remove'] = array();
1368         } // END - if
1369 }
1370
1371 // Checks wether the current extension is on the removal list
1372 function isExtensionOnRemovalList () {
1373         // Init removal list
1374         initExtensionRemovalList();
1375
1376         // Is it there?
1377         return (in_array(getCurrentExtensionName(), $GLOBALS['ext_update_remove']));
1378 }
1379
1380 // Adds the current extension to the removal list
1381 function addCurrentExtensionToRemovalList () {
1382         // Simply add it
1383         $GLOBALS['ext_update_remove'][] = getCurrentExtensionName();
1384 }
1385
1386 // Getter for removal list
1387 function getExtensionRemovalList () {
1388         // Return the removal list
1389         return $GLOBALS['ext_update_remove'];
1390 }
1391
1392 // Redirects if the provided extension is not installed
1393 function redirectOnUninstalledExtension ($ext_name) {
1394         // So is the extension there?
1395         if ((!isExtensionInstalled($ext_name)) || (!isExtensionActive($ext_name))) {
1396                 // Redirect to index
1397                 redirectToUrl('modules.php?module=index&amp;code=' . getCode('EXTENSION_PROBLEM') . '&amp;ext=' . $ext_name);
1398         } // END - if
1399 }
1400
1401 // Filter for initialization of all extensions by loading them in 'init' mode
1402 function FILTER_INIT_EXTENSIONS () {
1403         // Do we have some entries?
1404         //* DEBUG */ print __FUNCTION__.': ENTRY!<br />';
1405         if (isset($GLOBALS['cache_array']['extension']['ext_name'])) {
1406                 // Load all found extensions if found
1407                 //* DEBUG */ print __FUNCTION__.': CACHE - START!<br />';
1408                 foreach ($GLOBALS['cache_array']['extension']['ext_name'] as $key => $ext_name) {
1409                         // Load it
1410                         //* DEBUG */ print __FUNCTION__.': '.$ext_name.' - START<br />';
1411                         loadExtension($ext_name, 'init');
1412                         //* DEBUG */ print __FUNCTION__.': '.$ext_name.' - END<br />';
1413                 } // END - foreach
1414                 //* DEBUG */ print __FUNCTION__.': CACHE - END!<br />';
1415         } // END - if
1416         //* DEBUG */ print __FUNCTION__.': EXIT!<br />';
1417 }
1418
1419 // Setter for extension mode
1420 function setExtensionMode ($ext_mode) {
1421         $GLOBALS['ext_mode'] = (string) $ext_mode;
1422 }
1423
1424 // Getter for extension mode
1425 function getExtensionMode () {
1426         return $GLOBALS['ext_mode'];
1427 }
1428
1429 // Setter for dry-run
1430 function enableExtensionDryRun ($dry_run = true) {
1431         //* DEBUG: */ print __FUNCTION__.': '.getCurrentExtensionName().'='.intval($dry_run).'<br />';
1432         $GLOBALS['ext_dry_run'] = (bool) $dry_run;
1433 }
1434
1435 // Getter for dry-run
1436 function getExtensionDryRun () {
1437         return $GLOBALS['ext_dry_run'];
1438 }
1439
1440 // Setter for current extension version
1441 function setCurrentExtensionVersion ($ext_ver) {
1442         if (empty($ext_ver)) {
1443                 // 0.0 is okay here
1444                 $GLOBALS['ext_current_version'] = '0.0';
1445         } else {
1446                 // Add version
1447                 $GLOBALS['ext_current_version'] = (string) $ext_ver;
1448         }
1449 }
1450
1451 // Getter for current extension version
1452 function getCurrentExtensionVersion () {
1453         return $GLOBALS['ext_current_version'];
1454 }
1455
1456 // Remove the extension from global cache array
1457 function removeExtensionFromArray () {
1458         // "Cache" this name
1459         $ext_name = getCurrentExtensionName();
1460
1461         // Now loop through the whole cache
1462         foreach ($GLOBALS['cache_array']['extension'] as $cacheName=>$cacheArray) {
1463                 // Is it an element?
1464                 if (isset($cacheArray[$ext_name])) {
1465                         // Array element
1466                         unset($cacheArray[$ext_name]);
1467                         $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1468                 } else {
1469                         // Maybe in array?
1470                         $key = array_search($ext_name, $cacheArray);
1471
1472                         // Is it there?
1473                         if ($key !== false) {
1474                                 // Found, so remove it
1475                                 unset($cacheArray[$key]);
1476                                 $GLOBALS['cache_array']['extension'][$cacheName] = $cacheArray;
1477                         } // END - if
1478                 }
1479         } // END - foreach
1480 }
1481
1482 // "Getter" for 'extension has a CSS file' (with same name, of course)
1483 function getExtensionHasCss () {
1484         // Default is no CSS
1485         $hasCss = 'N';
1486
1487         // Construct FQFN for check
1488         $FQFN = sprintf("%stheme/%s/css/%s.css",
1489                 getConfig('PATH'),
1490                 getCurrentTheme(),
1491                 getCurrentExtensionName()
1492         );
1493
1494         // Is it there?
1495         if (isFileReadable($FQFN)) {
1496                 // Readable, so it is there...
1497                 $hasCss = 'Y';
1498         } // END - if
1499
1500         // Return it
1501         return $hasCss;
1502 }
1503
1504 // Checks wether the given extension has a language file
1505 function ifExtensionHasLanguageFile ($ext_name) {
1506         // Default is no language file
1507         $hasLanguage = false;
1508
1509         // Do we have cache?
1510         if (isset($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name])) {
1511                 // Then use it
1512                 $hasLanguage = ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1513
1514                 // Count cache hits
1515                 incrementStatsEntry('cache_hits');
1516         } else {
1517                 // Not readable is default
1518                 $readable = 'N';
1519
1520                 // Is the language file readable for this extension?
1521                 if (isLanguageIncludeReadable($ext_name)) {
1522                         // Readable
1523                         $readable = 'Y';
1524                 } // END - if
1525
1526                 // Put it in cache
1527                 $GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] = 'Y';
1528         }
1529
1530         // Return result
1531         return ($GLOBALS['cache_array']['extension']['ext_lang'][$ext_name] == 'Y');
1532 }
1533
1534 // Load an extension's include file
1535 function loadExtensionInclude () {
1536         // Is it readable?
1537         if (!isExtensionIncludeReadable()) {
1538                 // Not readable
1539                 debug_report_bug('Extension ' . getCurrentExtensionName() . ' should be loaded, but is not readable.');
1540         } // END - if
1541
1542         // Generate INC name
1543         $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1544
1545         // Load it
1546         loadInclude($INC);
1547 }
1548
1549 // Checks wether an extension is readable
1550 function isExtensionIncludeReadable ($ext_name = '') {
1551         // If empty, use current
1552         if (empty($ext_name)) $ext_name = getCurrentExtensionName();
1553
1554         // Array found?
1555         if (!isset($GLOBALS['ext_inc_readable'][$ext_name])) {
1556                 // Generate INC name
1557                 $INC = sprintf("inc/extensions/ext-%s.php", getCurrentExtensionName());
1558
1559                 // Is it readable?
1560                 $GLOBALS['ext_inc_readable'][$ext_name] = isIncludeReadable($INC);
1561         } // END - if
1562
1563         // Return result
1564         //* DEBUG: */ print __FUNCTION__.': '.$ext_name.'='.intval($GLOBALS['ext_inc_readable'][$ext_name]).'<br />';
1565         return $GLOBALS['ext_inc_readable'][$ext_name];
1566 }
1567
1568 // Checks if an extension's function file is readable
1569 function isExtensionFunctionFileReadable ($ext_name) {
1570         if (isset($GLOBALS['cache_array']['extension']['ext_func'][$ext_name])) {
1571                 // Just count cache hits
1572                 incrementStatsEntry('cache_hits');
1573         } else {
1574                 // Construct FQFN for functions file
1575                 $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
1576
1577                 // Is this include there?
1578                 if ((isFileReadable($funcsInclude)) && (!isset($GLOBALS['ext_loaded']['funcs'][$ext_name])) && (getExtensionMode() == 'test')) {
1579                         // Cache it!
1580                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'Y';
1581                 } else {
1582                         // Cache it!
1583                         $GLOBALS['cache_array']['extension']['ext_func'][$ext_name] = 'N';
1584                 }
1585         }
1586
1587         // Return result
1588         return ($GLOBALS['cache_array']['extension']['ext_func'][$ext_name] == 'Y');
1589 }
1590
1591 // Adds an admin menu to the SQL queue of the menu entry is not found
1592 function addAdminMenuSql ($action, $what, $title, $descr, $sort) {
1593         // Now check if this menu is there
1594         if (!isMenuActionValid('admin', $action, $what)) {
1595                 // Is what null?
1596                 if (is_null($what)) {
1597                         // Add main menu
1598                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1599                                 $action,
1600                                 $title,
1601                                 $descr,
1602                                 bigintval($sort)
1603                         );
1604                 } else {
1605                         // Add sub menu
1606                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_admin_menu` (`action`,`what`,`title`,`descr`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1607                                 $action,
1608                                 $what,
1609                                 $title,
1610                                 $descr,
1611                                 bigintval($sort)
1612                         );
1613                 }
1614
1615                 // Add it to the queue
1616                 addExtensionSql($sql);
1617         } elseif (isDebugModeEnabled()) {
1618                 // Double menus should be located and fixed!
1619                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double admin menu action=%s, what=%s detected.", $action, $what));
1620         }
1621 }
1622
1623 // Adds a guest menu to the SQL queue if the menu entry is not found
1624 function addGuestMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1625         // Now check if this menu is there
1626         if (!isMenuActionValid('guest', $action, $what)) {
1627                 // Is what null?
1628                 if (is_null($what)) {
1629                         // Add main menu
1630                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1631                                 $action,
1632                                 $title,
1633                                 $visible,
1634                                 $locked,
1635                                 bigintval($sort)
1636                         );
1637                 } else {
1638                         // Add sub menu
1639                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_guest_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1640                                 $action,
1641                                 $what,
1642                                 $title,
1643                                 $visible,
1644                                 $locked,
1645                                 bigintval($sort)
1646                         );
1647                 }
1648
1649                 // Add it to the queue
1650                 addExtensionSql($sql);
1651         } elseif (isDebugModeEnabled()) {
1652                 // Double menus should be located and fixed!
1653                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double guest menu action=%s, what=%s detected.", $action, $what));
1654         }
1655 }
1656
1657 // Adds a member menu to the SQL queue if the menu entry is not found
1658 function addMemberMenuSql ($action, $what, $title, $visible, $locked, $sort) {
1659         // Now check if this menu is there
1660         if (!isMenuActionValid('member', $action, $what)) {
1661                 // Is what null?
1662                 if (is_null($what)) {
1663                         // Add main menu
1664                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s',NULL,'%s','%s','%s',%s)",
1665                                 $action,
1666                                 $title,
1667                                 $visible,
1668                                 $locked,
1669                                 bigintval($sort)
1670                         );
1671                 } else {
1672                         // Add sub menu
1673                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_member_menu` (`action`,`what`,`title`,`visible`,`locked`,`sort`) VALUES('%s','%s','%s','%s','%s',%s)",
1674                                 $action,
1675                                 $what,
1676                                 $title,
1677                                 $visible,
1678                                 $locked,
1679                                 bigintval($sort)
1680                         );
1681                 }
1682
1683                 // Add it to the queue
1684                 addExtensionSql($sql);
1685         } elseif (isDebugModeEnabled()) {
1686                 // Double menus should be located and fixed!
1687                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double member menu action=%s, what=%s detected.", $action, $what));
1688         }
1689 }
1690
1691 // Adds a sponsor menu to the SQL queue if the menu entry is not found
1692 function addSponsorMenuSql ($action, $what, $title, $active, $sort) {
1693         // Now check if this menu is there, if no ext-sponsor is installed all is not yet added
1694         if ((!isExtensionInstalled('sponsor')) || (!isMenuActionValid('sponsor', $action, $what))) {
1695                 // Is what null?
1696                 if (is_null($what)) {
1697                         // Add main menu
1698                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s',NULL,'%s','%s',%s)",
1699                                 $action,
1700                                 $title,
1701                                 $active,
1702                                 bigintval($sort)
1703                         );
1704                 } else {
1705                         // Add sub menu
1706                         $sql = sprintf("INSERT INTO `{?_MYSQL_PREFIX?}_sponsor_menu` (`action`,`what`,`title`,`active`,`sort`) VALUES('%s','%s','%s','%s',%s)",
1707                                 $action,
1708                                 $what,
1709                                 $title,
1710                                 $active,
1711                                 bigintval($sort)
1712                         );
1713                 }
1714
1715                 // Add it to the queue
1716                 addExtensionSql($sql);
1717         } elseif (isDebugModeEnabled()) {
1718                 // Double menus should be located and fixed!
1719                 logDebugMessage(__FUNCTION__, __LINE__, sprintf("Double sponsor menu action=%s, what=%s detected.", $action, $what));
1720         }
1721 }
1722
1723 // Enables/disables productive mode for current extension (used only while
1724 // registration).
1725 function enableExtensionProductive ($isProductive = true) {
1726         $GLOBALS['ext_productive'][getCurrentExtensionName()] = (bool) $isProductive;
1727 }
1728
1729 // Checks wether the extension is in productive phase. If not set, development
1730 // phase (=false) is assumed.
1731 function isExtensionProductive () {
1732         return ((isset($GLOBALS['ext_productive'][getCurrentExtensionName()])) && ($GLOBALS['ext_productive'][getCurrentExtensionName()] === true));
1733 }
1734
1735 // [EOF]
1736 ?>