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