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