7d599905f74250189931dcae43dc5e56d90048e8
[mailer.git] / inc / extensions.php
1 <?php
2 /************************************************************************
3  * MXChange v0.2.1                                    Start: 03/25/2004 *
4  * ===============                              Last change: 09/29/2004 *
5  *                                                                      *
6  * -------------------------------------------------------------------- *
7  * File              : extensions.php                                   *
8  * -------------------------------------------------------------------- *
9  * Short description : Extension management                             *
10  * -------------------------------------------------------------------- *
11  * Kurzbeschreibung  : Erweiterungen-Management                         *
12  * -------------------------------------------------------------------- *
13  *                                                                      *
14  * -------------------------------------------------------------------- *
15  * Copyright (c) 2003 - 2008 by Roland Haeder                           *
16  * For more information visit: http://www.mxchange.org                  *
17  *                                                                      *
18  * This program is free software; you can redistribute it and/or modify *
19  * it under the terms of the GNU General Public License as published by *
20  * the Free Software Foundation; either version 2 of the License, or    *
21  * (at your option) any later version.                                  *
22  *                                                                      *
23  * This program is distributed in the hope that it will be useful,      *
24  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
25  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
26  * GNU General Public License for more details.                         *
27  *                                                                      *
28  * You should have received a copy of the GNU General Public License    *
29  * along with this program; if not, write to the Free Software          *
30  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,               *
31  * MA  02110-1301  USA                                                  *
32  ************************************************************************/
33
34 // Some security stuff...
35 if (!defined('__SECURITY')) {
36         $INC = substr(dirname(__FILE__), 0, strpos(dirname(__FILE__), "/inc") + 4) . "/security.php";
37         require($INC);
38 }
39
40 // Load the extension and maybe found language and function files.
41 function LOAD_EXTENSION ($ext_name, $EXT_LOAD_MODE = "", $EXT_VER = "", $dry_run = false) {
42         global $INC_POOL;
43
44         // Init array
45         $INC_POOL = array();
46
47         // Is the extension already loaded?
48         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Loading extension {$ext_name}, mode={$EXT_LOAD_MODE}, ver={$EXT_VER}.");
49         if ((isset($GLOBALS['ext_loaded']['ext'][$ext_name])) && (empty($EXT_LOAD_MODE))) {
50                 // Debug message
51                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s already loaded.", $ext_name));
52                 return false;
53         } // END - if
54
55         // Construct FQFN for extension file
56         $FQFN = sprintf("%sinc/extensions/ext-%s.php",
57                 constant('PATH'),
58                 $ext_name
59         );
60
61         // Is the extension file NOT there?
62         if (!FILE_READABLE($FQFN)) {
63                 // Debug message
64                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s not found.", $ext_name));
65
66                 // Abort here
67                 return false;
68         } // END - if
69
70         // Construct FQFN for language file
71         $langInclude = sprintf("inc/language/%s_%s.php", $ext_name, GET_LANGUAGE());
72
73         // Is this include there?
74         if ((FILE_READABLE($langInclude)) && (!isset($GLOBALS['ext_loaded']['lang'][$ext_name]))) {
75                 // Then load it
76                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "--- Language loaded.");
77                 $GLOBALS['ext_loaded']['lang'][$ext_name] = true;
78                 LOAD_INC_ONCE($langInclude);
79         } // END - if
80
81         // Construct FQFN for functions file
82         $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
83
84         // Is this include there?
85         if ((FILE_READABLE($funcsInclude)) && (!isset($GLOBALS['ext_loaded']['funcs'][$ext_name]))) {
86                 // Then load it
87                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "--- Functions loaded.");
88                 $GLOBALS['ext_loaded']['funcs'][$ext_name] = true;
89                 LOAD_INC_ONCE($funcsInclude);
90         } // END - if
91
92         // Extensions are not deprecated by default
93         EXT_SET_DEPRECATED("N");
94
95         // Extensions are not always active by default
96         EXT_SET_ALWAYS_ACTIVE("N");
97
98         // By default an extension update does not depend on other extensions
99         EXT_SET_UPDATE_DEPENDS("");
100
101         // Extension update notes
102         EXT_SET_UPDATE_NOTES("");
103
104         // Include the extension file
105         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Extension loaded.");
106         require($FQFN);
107
108         // Is this extension deprecated?
109         if (EXT_GET_DEPRECATED() == "Y") {
110                 // Deactivate the extension
111                 DEACTIVATE_EXTENSION($ext_name);
112
113                 // Abort here
114                 return false;
115         } // END - if
116
117         // Mark it as loaded in normal mode
118         if (empty($EXT_LOAD_MODE)) {
119                 // Mark it now...
120                 $GLOBALS['ext_loaded']['ext'][$ext_name] = true;
121         } // END - if
122
123         // All fine!
124         return true;
125 }
126
127 // Registeres an extension and possible update depencies
128 function EXTENSION_REGISTER ($ext_name, $task_id, $dry_run = false, $logout = true) {
129         global $INC_POOL;
130         global $NOTES;
131
132         // This shall never do a non-admin user!
133         if (!IS_ADMIN()) return false;
134
135         // Is this extension already installed?
136         if (EXT_IS_ACTIVE($ext_name)) return false;
137
138         // Init queries
139         INIT_SQLS();
140
141         // Init variables
142         $ret = false;
143         $NOTES = "";
144         $INC_POOL = array();
145
146         // By default we have no failures
147         EXT_SET_REPORTS_FAILURE(false);
148
149         // Does this extension exists?
150         if (LOAD_EXTENSION($ext_name, "register", "", $dry_run)) {
151                 // And run possible updates
152                 $history = EXT_GET_VER_HISTORY();
153                 foreach ($history as $ver) {
154                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ext_name={$ext_name}, ext_ver={$ver}");
155                         // Load extension in update mode
156                         LOAD_EXTENSION($ext_name, "update", $ver, $dry_run);
157
158                         // Add update notes to our output
159                         $NOTES .= ADD_EXTENSION_NOTES($ver);
160                 } // END - foreach
161
162                 // Does this extension depends on an outstanding update of another update?
163                 if (EXT_GET_UPDATE_DEPENDS() != "") {
164                         // Backup SQL commands and clear current
165                         $SQLs2 = GET_SQLS();
166                         INIT_SQLS();
167                         $test  = false;
168                         $ext_update = EXT_GET_UPDATE_DEPENDS();
169
170                         // Check for required file
171                         if (LOAD_EXTENSION($ext_update, "register", "", $dry_run)) {
172                                 // If versions mismatch update extension first
173                                 $ext_ver = GET_EXT_VERSION($ext_update);
174
175                                 // Extension version set? If empty the extension is not registered
176                                 if (empty($ext_ver)) {
177                                         // Extension not registered so far so first load task's ID...
178                                         $task = DETERMINE_EXTENSION_TASK_ID($ext_update);
179
180                                         // Entry found?
181                                         if ($task > 0) {
182                                                 // Try to register the extension
183                                                 $test = EXTENSION_REGISTER($ext_update, $task, $dry_run, false);
184                                         } // END - if
185                                 } elseif ($ext_ver != EXT_GET_VERSION()) {
186                                         // Ok, update this extension now
187                                         EXTENSION_UPDATE($ext_update, $ext_ver, $dry_run);
188
189                                         // All okay!
190                                         $test = true;
191                                 } else {
192                                         // Nothing to register / update before...
193                                         $test = true;
194                                 }
195                         } else {
196                                 // Required file for update does not exists!
197                                 $test = true;
198                                 // But this is fine for the first time...
199                         }
200
201                         // Finally restore previous SQLs
202                         SET_SQLS($SQLs2); unset($SQLs2);
203                 } else {
204                         // Does not depend on an other extension
205                         $test = true;
206                 }
207
208                 // Switch back to register mode
209                 $EXT_LOAD_MODE = "register";
210
211                 // Remains true if extension registration reports no failures
212                 $test = (($test === true) && (EXT_GET_REPORTS_FAILURE() === false));
213
214                 // Does everthing before wents ok?
215                 if ($test) {
216                         // "Dry-run-mode" activated?
217                         if (!$dry_run) {
218                                 // Run installation pre-installation filters
219                                 RUN_FILTER('pre_extension_installed', array('dry_run' => $dry_run));
220
221                                 // Register extension
222                                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_extensions` (ext_name, ext_active, ext_version) VALUES ('%s','%s','%s')",
223                                         array($ext_name, EXT_GET_ALWAYS_ACTIVE(), EXT_GET_VERSION()), __FILE__, __LINE__);
224
225                                 // Remove cache file(s) if extension is active
226                                 RUN_FILTER('post_extension_installed', array('ext_name' => $ext_name, 'task_id' => $task_id, 'inc_pool' => $INC_POOL));
227
228                                 // In normal mode return a true on success
229                                 $ret = true;
230                         } else {
231                                 // Rewrite SQL command to keep { and } inside
232                                 foreach (GET_SQLS() as $key => $sql) {
233                                         $sql = str_replace('{', "&#123;", str_replace('}', "&#125;", $sql));
234                                         SET_SQL_KEY($key, $sql);
235                                 } // END - foreach
236
237                                 // In  "dry-run" mode return array with all SQL commands
238                                 $ret = GET_SQLS();
239
240                                 // Remove all SQL commands
241                                 UNSET_SQLS();
242                         }
243                 } else {
244                         // No, an error occurs while registering extension :-(
245                         $ret = false;
246                 }
247         } elseif (($task_id > 0) && (!empty($ext_name))) {
248                 // Remove task from system when id and extension's name is valid
249                 SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_task_system` WHERE id=%s AND `status`='NEW' LIMIT 1",
250                         array(bigintval($task_id)), __FILE__, __LINE__);
251         }
252
253         // Is this the sql_patches?
254         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":{$ext_name}/{$EXT_LOAD_MODE}");
255         if (($ext_name == "sql_patches") && (($EXT_LOAD_MODE == "register") || ($EXT_LOAD_MODE == "remove")) && (!$dry_run) && ($test)) {
256                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
257                 if ($logout) {
258                         // Then redirect to logout
259                         LOAD_URL("modules.php?module=admin&amp;logout=1&amp;".$EXT_LOAD_MODE."=sql_patches");
260                 } else {
261                         // Add temporary filter
262                         REGISTER_FILTER('shutdown', 'REDIRECT_TO_LOGOUT_SQL_PATCHES', true, true);
263                         $GLOBALS['ext_load_mode'] = $EXT_LOAD_MODE;
264                 }
265         } // END - if
266
267         // Return status code
268         return $ret;
269 }
270
271 // Run SQL queries for given extension id
272 // @TODO Change from ext_id to ext_name (not just even the variable! ;-) )
273 function EXTENSION_RUN_SQLS ($ext_id, $load_mode) {
274         // This shall never do a non-admin user!
275         if (!IS_ADMIN()) return false;
276
277         // Init array
278         INIT_SQLS();
279
280         // By default no SQL has been executed
281         $sqlRan = false;
282
283         // Get extension's name
284         $ext_name = GET_EXT_NAME($ext_id);
285         // If it is not set then maybe there is no extension for that ID number
286         if (empty($ext_name)) return false;
287
288         // Load extension in detected mode
289         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":ext_name[{$ext_id}]={$ext_name}");
290         LOAD_EXTENSION($ext_name, $load_mode, "", false);
291
292         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":SQLs::count=".COUNT_SQLS()."");
293         if ((IS_SQLS_VALID() && (COUNT_SQLS() > 0))) {
294                 // Run SQL commands...
295                 RUN_FILTER('run_sqls', array('dry_run' => false));
296
297                 // Removal mode?
298                 if ($load_mode == "remove") {
299                         // Delete this extension (remember to remove it from your server *before* you click on welcome!
300                         SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
301                                 array($ext_name), __FILE__, __LINE__);
302                 } // END - if
303         } // END - if
304
305         // Remove cache file(s) if extension is active
306         if (((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) && (((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == "activate") || ($load_mode == "deactivate"))) {
307                 // Run filters
308                 RUN_FILTER('post_extension_run_sql', $ext_name);
309         } // END - if
310
311         // Is this the sql_patches?
312         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": {$ext_id}/{$ext_name}/{$load_mode}");
313         if (($ext_name == "sql_patches") && (($load_mode == "register") || ($load_mode == "remove"))) {
314                 // Then redirect to logout
315                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
316                 LOAD_URL("modules.php?module=admin&amp;logout=1&amp;".$load_mode."=sql_patches");
317         } // END - if
318 }
319
320 // Check if given extension is active
321 function EXT_IS_ACTIVE ($ext_name) {
322         // Extensions are all inactive during installation
323         if ((!isInstalled()) || (isInstalling()) || (empty($ext_name))) return false;
324
325         // Not active is the default
326         $active = "N";
327
328         // Check cache
329         if (isset($GLOBALS['cache_array']['extensions']['ext_active'][$ext_name])) {
330                 // Load from cache
331                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
332                 $active = $GLOBALS['cache_array']['extensions']['ext_active'][$ext_name];
333
334                 // Count cache hits
335                 incrementConfigEntry('cache_hits');
336         } elseif (isset($GLOBALS['ext_loaded'][$ext_name])) {
337                 // Extension is loaded!
338                 die("LOADED:$ext_name");
339         } elseif (($ext_name == "cache") || (GET_EXT_VERSION("cache") == "")) {
340                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
341                 // Load from database
342                 $result = SQL_QUERY_ESC("SELECT ext_active FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
343                         array($ext_name), __FILE__, __LINE__);
344
345                 // Entry found?
346                 if (SQL_NUMROWS($result) == 1) {
347                         // Load entry
348                         list($active) = SQL_FETCHROW($result);
349                 } // END - if
350
351                 // Free result
352                 SQL_FREERESULT($result);
353
354                 // Write cache array
355                 //* DEBUG: */ echo $ext_name."[DB]: {$active}");
356                 $GLOBALS['cache_array']['extensions']['ext_active'][$ext_name] = $active;
357         } else {
358                 // Extension not active!
359                 //* DEBUG: */ echo $ext_name.": Not active!");
360                 $GLOBALS['cache_array']['extensions']['ext_active'][$ext_name] = "N";
361         }
362
363         // Debug message
364         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " ext_name={$ext_name},active={$active}");
365
366         // Is this extension activated? (For admins we always have active extensions...)
367         return ($active == "Y");
368 }
369 // Get version from extensions
370 function GET_EXT_VERSION ($ext_name) {
371         // By default no extension is found
372         $ext_ver = false;
373
374         // Extensions are all inactive during installation
375         if ((!isInstalled()) || (isInstalling())) return "";
376         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ext_name={$ext_name}");
377
378         // Is the cache written?
379         if (isset($GLOBALS['cache_array']['extensions']['ext_version'][$ext_name])) {
380                 // Load data from cache
381                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": CACHE!");
382                 $ext_ver = $GLOBALS['cache_array']['extensions']['ext_version'][$ext_name];
383
384                 // Count cache hits
385                 incrementConfigEntry('cache_hits');
386         } elseif ((!isset($GLOBALS['cache_instance'])) || (!is_object($GLOBALS['cache_instance']))) {
387                 // Load from database
388                 $result = SQL_QUERY_ESC("SELECT ext_version FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
389                         array($ext_name), __FILE__, __LINE__);
390
391                 // Is the extension there?
392                 if (SQL_NUMROWS($result) == 1) {
393                         // Load entry
394                         list($ext_ver) = SQL_FETCHROW($result);
395                 } // END - if
396
397                 // Free result
398                 SQL_FREERESULT($result);
399
400                 // Set cache
401                 $GLOBALS['cache_array']['extensions']['ext_version'][$ext_name] = $ext_ver;
402         }
403
404         // Return result
405         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ret={$ext_ver}");
406         return $ext_ver;
407 }
408
409 // Updates a given extension with current extension version to latest version
410 function EXTENSION_UPDATE ($ext_name, $ext_ver, $dry_run = false) {
411         // This shall never do a non-admin user!
412         global $NOTES;
413         global $INC_POOL;
414
415         // Init arrays
416         INIT_SQLS();
417         $INC_POOL = array();
418
419         // Init notes
420         $NOTES = "";
421
422         // Only admins are allowed to update extensions
423         if ((!IS_ADMIN()) || (empty($ext_name))) return false;
424
425         // Load extension in test mode
426         LOAD_EXTENSION($ext_name, "test", $ext_ver, $dry_run);
427
428         // Save version history
429         $history = EXT_GET_VER_HISTORY();
430
431         // Remove old SQLs array to prevent possible bugs
432         INIT_SQLS();
433
434         // Check if version is updated
435         if (((EXT_GET_VERSION() != $ext_ver) || ($dry_run)) && (is_array($history))) {
436                 // Search for starting point
437                 $start = array_search($ext_ver, $history);
438
439                 // And load SQL queries in order of version history
440                 for ($idx = ($start + 1); $idx < sizeof($history); $idx++) {
441                         // Set extension version
442                         $GLOBALS['cache_array']['update_ver'][$ext_name] = $history[$idx];
443
444                         // Load again...
445                         LOAD_EXTENSION($ext_name, "update", $GLOBALS['cache_array']['update_ver'][$ext_name], $dry_run);
446
447                         if (EXT_GET_UPDATE_DEPENDS() != "") {
448                                 // Backup current SQL queries
449                                 $GLOBALS['cache_array']['update_sqls'][$ext_name] = GET_SQLS();
450
451                                 // Is the extension there?
452                                 if (GET_EXT_VERSION(EXT_GET_UPDATE_DEPENDS()) != "") {
453                                         // Update another extension first!
454                                         $test = EXTENSION_UPDATE(EXT_GET_UPDATE_DEPENDS(), GET_EXT_VERSION(EXT_GET_UPDATE_DEPENDS()), $dry_run);
455                                 } else {
456                                         // Register new extension
457                                         $test = EXTENSION_REGISTER(EXT_GET_UPDATE_DEPENDS(), 0, $dry_run, false);
458                                 }
459
460                                 // Restore previous SQL queries
461                                 SET_SQLS($GLOBALS['cache_array']['update_sqls'][$ext_name]);
462                                 unset($GLOBALS['cache_array']['update_sqls'][$ext_name]);
463                         } // END - if
464
465                         // Add notes
466                         $NOTES .= ADD_EXTENSION_NOTES($GLOBALS['cache_array']['update_ver'][$ext_name]);
467                 } // END - for
468
469                 // In real-mode execute any existing includes
470                 if (!$dry_run) {
471                         $GLOBALS['cache_array']['inc_pool'][$ext_name] = $INC_POOL;
472                         RUN_FILTER('load_includes', $INC_POOL);
473                         $INC_POOL = $GLOBALS['cache_array']['inc_pool'][$ext_name];
474                         unset($GLOBALS['cache_array']['inc_pool'][$ext_name]);
475                 } // END - if
476
477                 // Run SQLs
478                 RUN_FILTER('run_sqls', array('dry_run' => $dry_run));
479
480                 if (!$dry_run) {
481                         // Create task
482                         CREATE_EXTENSION_UPDATE_TASK(GET_CURRENT_ADMIN_ID(), $ext_name, $GLOBALS['cache_array']['update_ver'][$ext_name], SQL_ESCAPE($NOTES));
483
484                         // Update extension's version
485                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_extensions` SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
486                                 array($GLOBALS['cache_array']['update_ver'][$ext_name], $ext_name), __FILE__, __LINE__);
487
488                         // Remove arrays
489                         UNSET_SQLS();
490                         unset($GLOBALS['cache_array']['update_ver'][$ext_name]);
491
492                         // Run filters on success extension update
493                         RUN_FILTER('extension_update', $ext_name);
494                 } // END - if
495         } // END - if
496 }
497
498 // Output verbose SQL table for extension
499 function EXTENSION_VERBOSE_TABLE ($queries = array(), $title = "", $dashed = "", $switch = false, $width = "100%") {
500         // Empty title?
501         if (empty($title)) {
502                 // Then fix it to default
503                 $title = getMessage('ADMIN_SQLS_EXECUTED_ON_REMOVAL');
504         } // END - if
505
506         // Are there some queries in $queries?
507         if (count($queries) > 0) {
508                 // Then use them instead!
509                 SET_SQLS($queries);
510         } // END - if
511
512         // Init variables
513         $SW = 2; $i = 1;
514         $OUT = "";
515
516         // Do we have queries?
517         if ((IS_SQLS_VALID()) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
518                 foreach (GET_SQLS() as $idx => $sql) {
519                         // Trim out spaces
520                         $sql = trim($sql);
521
522                         // Output command if set
523                         if (!empty($sql)) {
524                                 // Prepare output for template
525                                 $content = array(
526                                         'sw'  => $SW,
527                                         'i'   => $i,
528                                         'sql' => $sql
529                                 );
530
531                                 // Load row template
532                                 $OUT .= LOAD_TEMPLATE("admin_ext_sql_row", true, $content);
533
534                                 // Switch color and count up
535                                 $SW = 3 - $SW;
536                                 $i++;
537                         } // END - if
538                 } // END - foreach
539
540                 // Prepare content for template
541                 $content = array(
542                         'width'  => $width,
543                         'dashed' => $dashed,
544                         'title'  => $title,
545                         'out'    => $OUT
546                 );
547
548                 // Load main template
549                 $OUT = LOAD_TEMPLATE("admin_ext_sql_table", true, $content);
550         } elseif ((GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
551                 // No addional SQL commands to run
552                 $OUT = LOAD_TEMPLATE("admin_settings_saved", true, getMessage('ADMIN_NO_ADDITIONAL_SQLS'));
553         } // END - if
554
555         // Return output
556         return $OUT;
557 }
558
559 // Get extension name from id
560 function GET_EXT_NAME ($ext_id) {
561         // Init extension name
562         $ret = "";
563
564         // Is cache there?
565         if (isset($GLOBALS['cache_array']['extensions']['ext_name'][$ext_id])) {
566                 // Load from cache
567                 $ret = $GLOBALS['cache_array']['extensions']['ext_name'][$ext_id];
568
569                 // Count cache hits
570                 incrementConfigEntry('cache_hits');
571         } elseif (!EXT_IS_ACTIVE("cache")) {
572                 // Load from database
573                 $result = SQL_QUERY_ESC("SELECT ext_name FROM `{!_MYSQL_PREFIX!}_extensions` WHERE id=%s LIMIT 1",
574                         array(bigintval($ext_id)), __FILE__, __LINE__);
575                 list($ret) = SQL_FETCHROW($result);
576                 SQL_FREERESULT($result);
577         }
578         return $ret;
579 }
580
581 // Get extension id from name
582 function GET_EXT_ID ($ext_name) {
583         // Init ID number
584         $ret = 0;
585         if (isset($GLOBALS['cache_array']['extensions']['ext_id'][$ext_name])) {
586                 // Load from cache
587                 $ret = $GLOBALS['cache_array']['extensions']['ext_id'][$ext_name];
588
589                 // Count cache hits
590                 incrementConfigEntry('cache_hits');
591         } elseif (!EXT_IS_ACTIVE("cache")) {
592                 // Load from database
593                 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
594                         array($ext_name), __FILE__, __LINE__);
595                 list($ret) = SQL_FETCHROW($result);
596                 SQL_FREERESULT($result);
597         }
598
599         // Return value
600         return $ret;
601 }
602
603 // Activate given extension
604 function ACTIVATE_EXTENSION ($ext_name) {
605         // Activate the extension
606         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_extensions` SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
607                 array($ext_name), __FILE__, __LINE__);
608
609         // Extension has been activated?
610         if (SQL_AFFECTEDROWS() == 1) {
611                 // Then run all queries
612                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
613         } // END - if
614 }
615
616 // Deactivate given extension
617 function DEACTIVATE_EXTENSION($ext_name) {
618         // Activate the extension
619         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_extensions` SET ext_active='N' WHERE ext_name='%s' LIMIT 1",
620                 array($ext_name), __FILE__, __LINE__);
621
622         // Extension has been activated?
623         if (SQL_AFFECTEDROWS() == 1) {
624                 // Then run all queries
625                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "deactivate");
626
627                 // Create new task
628                 CREATE_EXTENSION_DEACTIVATION_TASK($ext_name);
629
630                 // Notify the admin
631                 SEND_ADMIN_NOTIFICATION(
632                         getMessage('ADMIN_SUBJECT_EXTENSION_DEACTIVATED'),
633                         "admin_ext_deactivated",
634                         array('ext_name' => $ext_name)
635                 );
636         } // END - if
637 }
638
639 // Checks wether the extension is older than given
640 function EXT_VERSION_IS_OLDER ($ext_name, $ext_ver) {
641         // Get current extension version
642         $currVersion = GET_EXT_VERSION($ext_name);
643
644         // Remove all dots from both versions
645         $currVersion = str_replace(".", "", $currVersion);
646         $ext_ver = str_replace(".", "", $ext_ver);
647
648         // Now compare both and return the result
649         return ($currVersion < $ext_ver);
650 }
651
652 // Creates a new task for updated extension
653 function CREATE_EXTENSION_UPDATE_TASK ($admin_id, $ext_name, $ext_ver, $notes) {
654         // Create subject line
655         $subject = "[UPDATE-".$ext_name."-".$ext_ver.":] {--ADMIN_UPDATE_EXT_SUBJ--}";
656
657         // Is the extension there?
658         if (GET_EXT_VERSION($ext_name) != "") {
659                 // Check if task is not there
660                 if (DETERMINE_TASK_ID_BY_SUBJECT($subject) == 0) {
661                         // Task not created so it's a brand-new extension which we need to register and create a task for!
662                         SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_task_system` (assigned_admin, userid, status, task_type, subject, text, task_created) VALUES ('%s','0','NEW','EXTENSION_UPDATE','%s','%s', UNIX_TIMESTAMP())",
663                                 array($admin_id, $subject, $notes), __FILE__, __LINE__);
664                 } // END - if
665         } // END - if
666 }
667
668 // Creates a new task for newly installed extension
669 function CREATE_NEW_EXTENSION_TASK ($admin_id, $subject, $ext) {
670         // Not installed and do we have created a task for the admin?
671         if ((DETERMINE_TASK_ID_BY_SUBJECT($subject) == 0) && (GET_EXT_VERSION($ext) == "")) {
672                 // Template file
673                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
674                         constant('PATH'),
675                         GET_LANGUAGE(),
676                         $ext
677                 );
678
679                 // Load text for task
680                 if (FILE_READABLE($tpl)) {
681                         // Load extension's own text template (HTML!)
682                         $msg = LOAD_TEMPLATE("ext_".$ext, true);
683                 } else {
684                         // Load default message
685                         $msg = LOAD_TEMPLATE("admin_new_ext", "", 0);
686                 }
687
688                 // Task not created so it's a brand-new extension which we need to register and create a task for!
689                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_task_system` (assigned_admin, userid, status, task_type, subject, text, task_created)
690 VALUES (%s,0,'NEW','EXTENSION','%s','%s',UNIX_TIMESTAMP())",
691                         array(
692                                 $admin_id,
693                                 $subject,
694                                 SQL_ESCAPE($msg),
695                         ),  __FILE__, __LINE__, true, false
696                 );
697         } // END - if
698 }
699
700 // Creates a task for automatically deactivated (deprecated) extension
701 function CREATE_EXTENSION_DEACTIVATION_TASK ($ext) {
702         // Create subject line
703         $subject = sprintf("[%s:] %s", $ext, getMessage('TASK_SUBJ_EXTENSION_DEACTIVATED'));
704
705         // Not installed and do we have created a task for the admin?
706         if ((DETERMINE_TASK_ID_BY_SUBJECT($subject) == 0) && (GET_EXT_VERSION($ext) != "")) {
707                 // Task not created so add it
708                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_task_system` (assigned_admin, userid, status, task_type, subject, text, task_created)
709 VALUES (0,0,'NEW','EXTENSION_DEACTIVATION','%s','%s',UNIX_TIMESTAMP())",
710                         array(
711                                 $subject,
712                                 SQL_ESCAPE(LOAD_TEMPLATE("task_ext_deactivated", true, $ext)),
713                         ),  __FILE__, __LINE__, true, false
714                 );
715         } // END - if
716 }
717
718 // Checks if the module has a menu
719 function MODULE_HAS_MENU ($mod, $forceDb = false) {
720         // All is false by default
721         $ret = false;
722
723         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):mod={$mod},cache=".GET_EXT_VERSION("cache")."<br />\n";
724         if (GET_EXT_VERSION("cache") >= "0.1.2") {
725                 // Cache version is okay, so let's check the cache!
726                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$mod])) {
727                         // Check module cache and count hit
728                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$mod] == "Y");
729                         incrementConfigEntry('cache_hits');
730                 } elseif (isset($GLOBALS['cache_array']['extensions']['ext_menu'][$mod])) {
731                         // Check cache and count hit
732                         $ret = ($GLOBALS['cache_array']['extensions']['ext_menu'][$mod] == "Y");
733                         incrementConfigEntry('cache_hits');
734                 } elseif ((IS_ADMIN()) && ($mod == "admin")) {
735                         // Admin module has always a menu!
736                         $ret = true;
737                 }
738         } elseif ((GET_EXT_VERSION("sql_patches") >= "0.3.6") && ((!EXT_IS_ACTIVE("cache")) || ($forceDb === true))) {
739                 // Check database for entry
740                 $result = SQL_QUERY_ESC("SELECT has_menu FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE module='%s' LIMIT 1",
741                         array($mod), __FILE__, __LINE__);
742
743                 // Entry found?
744                 if (SQL_NUMROWS($result) == 1) {
745                         // Load "has_menu" column
746                         list($has_menu) = SQL_FETCHROW($result);
747
748                         // Fake cache... ;-)
749                         $GLOBALS['cache_array']['extensions']['ext_menu'][$mod] = $has_menu;
750
751                         // Does it have a menu?
752                         $ret = ($has_menu == "Y");
753                 } // END  - if
754
755                 // Free memory
756                 SQL_FREERESULT($result);
757         } elseif (GET_EXT_VERSION("sql_patches") == "") {
758                 // No sql_patches installed, so maybe in admin area or no admin registered?
759                 $ret = (((IS_ADMIN()) || (!isAdminRegistered())) && ($mod == "admin")); // Then there is a menu!
760         }
761
762         // Return status
763         //* DEBUG: */ var_dump($ret);
764         return $ret;
765 }
766
767 // Determines the task id for given extension
768 function DETERMINE_EXTENSION_TASK_ID ($ext_name) {
769         // Default is not found
770         $task_id = 0;
771
772         // Search for extension task's id
773         $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_task_system` WHERE task_type='EXTENSION' AND subject='[%s:]' LIMIT 1",
774                 array($ext_name), __FILE__, __LINE__);
775
776         // Entry found?
777         if (SQL_NUMROWS($result) == 1) {
778                 // Task found so load task's ID and register extension...
779                 list($task_id) = SQL_FETCHROW($result);
780         } // END - if
781
782         // Free result
783         SQL_FREERESULT($result);
784
785         // Return it
786         return $task_id;
787 }
788
789 // Determines the task id for given subject
790 function DETERMINE_TASK_ID_BY_SUBJECT ($subject) {
791         // Default is not found
792         $task_id = 0;
793
794         // Search for task id
795         $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_task_system` WHERE subject LIKE '%s%%' LIMIT 1",
796                 array($subject), __FILE__, __LINE__);
797
798         // Entry found?
799         if (SQL_NUMROWS($result) == 1) {
800                 // Task found so load task's ID and register extension...
801                 list($task_id) = SQL_FETCHROW($result);
802         } // END - if
803
804         // Free result
805         SQL_FREERESULT($result);
806
807         // Return it
808         return $task_id;
809 }
810
811 // Add updates notes for given version
812 function ADD_EXTENSION_NOTES ($ver) {
813         // Init notes/content
814         $out = ""; $content = array();
815
816         // Is do we have verbose output enabled?
817         if ((getConfig('verbose_sql') == "Y") || (!EXT_IS_ACTIVE("sql_patches"))) {
818
819                 // Update notes found?
820                 if (EXT_GET_UPDATE_NOTES() != "") {
821                         // Update notes found
822                         $content = array(
823                                 'ver'   => $ver,
824                                 'notes' => EXT_GET_UPDATE_NOTES()
825                         );
826                         EXT_SET_UPDATE_NOTES("");
827                 } elseif (($ver == "0.0") || ($ver == "0.0.0")) {
828                         // Initial release
829                         $content = array(
830                                 'ver'   => $ver,
831                                 'notes' => getMessage('INITIAL_RELEASE')
832                         );
833                 } else {
834                         // No update notes found!
835                         $content = array(
836                                 'ver'   => $ver,
837                                 'notes' => getMessage('NO_UPDATE_NOTES')
838                         );
839                 }
840
841                 // Load template
842                 $out = LOAD_TEMPLATE("admin_ext_notes", true, $content);
843         } // END - if
844
845         // Return the output
846         return $out;
847 }
848
849 // Getter for CSS files array
850 function EXT_GET_CSS_FILES () {
851         // By default no additional CSS files are found
852         $cssFiles = array();
853
854         // Is the array there?
855         if (isset($GLOBALS['css_files'])) {
856                 // Then use it
857                 $cssFiles = $GLOBALS['css_files'];
858         } // END - if
859
860         // Return array
861         return $cssFiles;
862 }
863
864 // Init CSS files array
865 function EXT_INIT_CSS_FILES () {
866         // Simply init it
867         $GLOBALS['css_files'] = array();
868 }
869
870 // Add new entry
871 function EXT_ADD_CSS_FILE ($file) {
872         // Is the array there?
873         if (!isset($GLOBALS['css_files'])) {
874                 // Then auto-init them
875                 EXT_INIT_CSS_FILES();
876         } // END - if
877
878         // Add the entry
879         $GLOBALS['css_files'][] = $file;
880 }
881
882 // Setter for EXT_ALWAYS_ACTIVE flag
883 function EXT_SET_ALWAYS_ACTIVE ($active) {
884         $GLOBALS['ext_always_active'] = $active;
885 }
886
887 // Getter for EXT_ALWAYS_ACTIVE flag
888 function EXT_GET_ALWAYS_ACTIVE () {
889         return $GLOBALS['ext_always_active'];
890 }
891
892 // Setter for EXT_VERSION flag
893 function EXT_SET_VERSION ($version) {
894         $GLOBALS['ext_version'] = $version;
895 }
896
897 // Getter for EXT_VERSION flag
898 function EXT_GET_VERSION () {
899         return $GLOBALS['ext_version'];
900 }
901
902 // Setter for EXT_DEPRECATED flag
903 function EXT_SET_DEPRECATED ($deprecated) {
904         $GLOBALS['ext_deprecated'] = $deprecated;
905 }
906
907 // Getter for EXT_DEPRECATED flag
908 function EXT_GET_DEPRECATED () {
909         return $GLOBALS['ext_deprecated'];
910 }
911
912 // Setter for EXT_UPDATE_DEPENDS flag
913 function EXT_SET_UPDATE_DEPENDS ($updateDepends) {
914         $GLOBALS['ext_update_depends'] = $updateDepends;
915 }
916
917 // Getter for EXT_UPDATE_DEPENDS flag
918 function EXT_GET_UPDATE_DEPENDS () {
919         return $GLOBALS['ext_update_depends'];
920 }
921
922 // Setter for EXT_REPORTS_FAILURE flag
923 function EXT_SET_REPORTS_FAILURE ($reportsFailure) {
924         $GLOBALS['ext_reports_failure'] = $reportsFailure;
925 }
926
927 // Getter for EXT_REPORTS_FAILURE flag
928 function EXT_GET_REPORTS_FAILURE () {
929         return $GLOBALS['ext_reports_failure'];
930 }
931
932 // Setter for EXT_VER_HISTORY flag
933 function EXT_SET_VER_HISTORY ($verHistory) {
934         $GLOBALS['ext_ver_history'] = (array) $verHistory;
935 }
936
937 // Getter for EXT_VER_HISTORY flag
938 function EXT_GET_VER_HISTORY () {
939         return $GLOBALS['ext_ver_history'];
940 }
941
942 // Setter for EXT_UPDATE_NOTES flag
943 function EXT_SET_UPDATE_NOTES ($updateNotes) {
944         $GLOBALS['ext_update_notes'] = (array) $updateNotes;
945 }
946
947 // Getter for EXT_UPDATE_NOTES flag
948 function EXT_GET_UPDATE_NOTES () {
949         return $GLOBALS['ext_update_notes'];
950 }
951
952 //
953 ?>