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