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