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