Complete rewrite of and , wrapper functions added, see bug #101
[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, &$SQLs = array()) {
42         global $EXT_LOADED, $_CONFIG, $EXT_VER_HISTORY;
43         global $INC_POOL, $EXT_UPDATE_DEPENDS, $EXT_DEPRECATED, $UPDATE_NOTES;
44         global $EXT_VERSION, $EXT_ALWAYS_ACTIVE;
45
46         // Init array
47         $INC_POOL = array();
48
49         // Is the extension already loaded?
50         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Loading extension {$ext_name}, mode={$EXT_LOAD_MODE}, ver={$EXT_VER}.");
51         if ((isset($EXT_LOADED['ext'][$ext_name])) && (empty($EXT_LOAD_MODE))) {
52                 // Debug message
53                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s already loaded.", $ext_name));
54                 return false;
55         } // END - if
56
57         // Construct FQFN for extension file
58         $FQFN = sprintf("%sinc/extensions/ext-%s.php",
59                 constant('PATH'),
60                 $ext_name
61         );
62
63         // Is the extension file NOT there?
64         if (!FILE_READABLE($FQFN)) {
65                 // Debug message
66                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s not found.", $ext_name));
67
68                 // Abort here
69                 return false;
70         } // END - if
71
72         // Construct FQFN for language file
73         $langInclude = sprintf("inc/language/%s_%s.php", $ext_name, GET_LANGUAGE());
74
75         // Is this include there?
76         if ((FILE_READABLE($langInclude)) && (!isset($EXT_LOADED['lang'][$ext_name]))) {
77                 // Then load it
78                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "--- Language loaded.");
79                 $EXT_LOADED['lang'][$ext_name] = true;
80                 LOAD_INC_ONCE($langInclude);
81         } // END - if
82
83         // Construct FQFN for functions file
84         $funcsInclude = sprintf("inc/libs/%s_functions.php", $ext_name);
85
86         // Is this include there?
87         if ((FILE_READABLE($funcsInclude)) && (!isset($EXT_LOADED['funcs'][$ext_name]))) {
88                 // Then load it
89                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "--- Functions loaded.");
90                 $EXT_LOADED['funcs'][$ext_name] = true;
91                 LOAD_INC_ONCE($funcsInclude);
92         } // END - if
93
94         // Extensions are not deprecated by default
95         $EXT_DEPRECATED = "N";
96
97         // Extensions are not always active by default
98         $EXT_ALWAYS_ACTIVE = "N";
99
100         // By default an extension update does not depend on other extensions
101         $EXT_UPDATE_DEPENDS = "";
102
103         // Extension update notes
104         $UPDATE_NOTES = "";
105
106         // Include the extension file
107         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "Extension loaded.");
108         require($FQFN);
109
110         // Is this extension deprecated?
111         if ($EXT_DEPRECATED == "Y") {
112                 // Deactivate the extension
113                 DEACTIVATE_EXTENSION($ext_name);
114
115                 // Abort here
116                 return false;
117         } // END - if
118
119         // Mark it as loaded in normal mode
120         if (empty($EXT_LOAD_MODE)) {
121                 // Mark it now...
122                 $EXT_LOADED['ext'][$ext_name] = true;
123         } // END - if
124
125         // All fine!
126         return true;
127 }
128
129 // Registeres an extension and possible update depencies
130 function EXTENSION_REGISTER ($ext_name, $task_id, $dry_run = false, $logout = true) {
131         global $UPDATE_NOTES, $INC_POOL;
132         global $EXT_VER_HISTORY, $NOTES, $EXT_ALWAYS_ACTIVE, $EXT_VERSION;
133         global $EXT_UPDATE_DEPENDS;
134
135         // This shall never do a non-admin user!
136         if (!IS_ADMIN()) return false;
137
138         // Is this extension already installed?
139         if (EXT_IS_ACTIVE($ext_name)) return false;
140
141         // Init variables
142         $ret = false; $SQLs = array();
143         $NOTES = "";
144         $INC_POOL = array();
145
146         // By default we have no failures
147         $EXT_REPORTS_FAILURE = false;
148
149         // Does this extension exists?
150         if (LOAD_EXTENSION($ext_name, "register", "", $dry_run, $SQLs)) {
151                 // And run possible updates
152                 $history = $EXT_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, $SQLs);
157
158                         // Add update notes to our output
159                         $NOTES .= ADD_EXTENSION_NOTES($ver, $UPDATE_NOTES);
160                 } // END - foreach
161
162                 // Does this extension depends on an outstanding update of another update?
163                 if (!empty($EXT_UPDATE_DEPENDS)) {
164                         // Backup SQL commands and clear current
165                         $SQLs2 = $SQLs;
166                         $SQLs  = array();
167                         $test  = false;
168                         $ext_update = $EXT_UPDATE_DEPENDS;
169
170                         // Check for required file
171                         if (LOAD_EXTENSION($ext_update, "register", "", $dry_run, $SQLs)) {
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_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                         $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 && !$EXT_REPORTS_FAILURE);
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, 'sqls' => $SQLs));
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_ALWAYS_ACTIVE, $EXT_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 ($SQLs as $key => $sql) {
233                                         $sql = str_replace('{', "&#123;", str_replace('}', "&#125;", $sql));
234                                         $SQLs[$key] = $sql;
235                                 } // END - foreach
236
237                                 // In  "dry-run" mode return array with all SQL commands
238                                 $ret = $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&logout=1&".$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         $SQLs = array();
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, $SQLs);
291
292         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":SQLs::count=".count($SQLs)."");
293         if ((is_array($SQLs) && (sizeof($SQLs) > 0))) {
294                 // Run SQL commands...
295                 RUN_FILTER('run_sqls', array('dry_run' => false, 'sqls' => $SQLs));
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&logout=1&".$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 ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing')) || (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 (($ext_name == "cache") || (GET_EXT_VERSION("cache") == "")) {
337                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
338                 // Load from database
339                 $result = SQL_QUERY_ESC("SELECT ext_active FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
340                         array($ext_name), __FILE__, __LINE__);
341
342                 // Entry found?
343                 if (SQL_NUMROWS($result) == 1) {
344                         // Load entry
345                         list($active) = SQL_FETCHROW($result);
346                 } // END - if
347
348                 // Free result
349                 SQL_FREERESULT($result);
350
351                 // Write cache array
352                 //* DEBUG: */ echo $ext_name."[DB]: {$active}");
353                 $GLOBALS['cache_array']['extensions']['ext_active'][$ext_name] = $active;
354         } else {
355                 // Extension not active!
356                 //* DEBUG: */ echo $ext_name.": Not active!");
357                 $GLOBALS['cache_array']['extensions']['ext_active'][$ext_name] = "N";
358         }
359
360         // Debug message
361         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " ext_name={$ext_name},active={$active}");
362
363         // Is this extension activated? (For admins we always have active extensions...)
364         return ($active == "Y");
365 }
366 // Get version from extensions
367 function GET_EXT_VERSION ($ext_name) {
368         // By default no extension is found
369         $ext_ver = false;
370
371         // Extensions are all inactive during installation
372         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing'))) return "";
373         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ext_name={$ext_name}");
374
375         // Is the cache written?
376         if (isset($GLOBALS['cache_array']['extensions']['ext_version'][$ext_name])) {
377                 // Load data from cache
378                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": CACHE!");
379                 $ext_ver = $GLOBALS['cache_array']['extensions']['ext_version'][$ext_name];
380
381                 // Count cache hits
382                 incrementConfigEntry('cache_hits');
383         } elseif (!is_object($GLOBALS['cache_instance'])) {
384                 // Load from database
385                 $result = SQL_QUERY_ESC("SELECT ext_version FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
386                         array($ext_name), __FILE__, __LINE__);
387
388                 // Is the extension there?
389                 if (SQL_NUMROWS($result) == 1) {
390                         // Load entry
391                         list($ext_ver) = SQL_FETCHROW($result);
392                 } // END - if
393
394                 // Free result
395                 SQL_FREERESULT($result);
396
397                 // Set cache
398                 $GLOBALS['cache_array']['extensions']['ext_version'][$ext_name] = $ext_ver;
399         }
400
401         // Return result
402         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ret={$ext_ver}");
403         return $ext_ver;
404 }
405
406 // Updates a given extension with current extension version to latest version
407 function EXTENSION_UPDATE ($ext_name, $ext_ver, $dry_run = false) {
408         // This shall never do a non-admin user!
409         global $UPDATE_NOTES, $NOTES, $EXT_VER_HISTORY;
410         global $EXT_UPDATE_DEPENDS, $EXT_VERSION, $INC_POOL, $SQLs;
411
412         // Init arrays
413         $SQLs = array(); $INC_POOL = array();
414
415         // Init notes
416         $NOTES = "";
417
418         // Only admins are allowed to update extensions
419         if ((!IS_ADMIN()) || (empty($ext_name))) return false;
420
421         // Load extension in test mode
422         LOAD_EXTENSION($ext_name, "test", $ext_ver, $dry_run, $SQLs);
423
424         // Save version history
425         $history = $EXT_VER_HISTORY;
426
427         // Remove old SQLs array to prevent possible bugs
428         $SQLs = array();
429
430         // Check if version is updated
431         if ((($EXT_VERSION != $ext_ver) || ($dry_run)) && (is_array($history))) {
432                 // Search for starting point
433                 $start = array_search($ext_ver, $history);
434
435                 // And load SQL queries in order of version history
436                 for ($idx = ($start + 1); $idx < sizeof($history); $idx++) {
437                         // Set extension version
438                         $GLOBALS['cache_array']['update_ver'][$ext_name] = $history[$idx];
439
440                         // Load again...
441                         LOAD_EXTENSION($ext_name, "update", $GLOBALS['cache_array']['update_ver'][$ext_name], $dry_run, $SQLs);
442
443                         if (!empty($EXT_UPDATE_DEPENDS)) {
444                                 // Backup current SQL queries
445                                 $GLOBALS['cache_array']['update_sqls'][$ext_name] = $SQLs;
446
447                                 // Is the extension there?
448                                 if (GET_EXT_VERSION($EXT_UPDATE_DEPENDS) != "") {
449                                         // Update another extension first!
450                                         $test = EXTENSION_UPDATE($EXT_UPDATE_DEPENDS, GET_EXT_VERSION($EXT_UPDATE_DEPENDS), $dry_run);
451                                 } else {
452                                         // Register new extension
453                                         $test = EXTENSION_REGISTER($EXT_UPDATE_DEPENDS, 0, $dry_run, false);
454                                 }
455
456                                 // Restore previous SQL queries
457                                 $SQLs = $GLOBALS['cache_array']['update_sqls'][$ext_name];
458                                 unset($GLOBALS['cache_array']['update_sqls'][$ext_name]);
459                         } // END - if
460
461                         // Add notes
462                         $NOTES .= ADD_EXTENSION_NOTES($GLOBALS['cache_array']['update_ver'][$ext_name], $UPDATE_NOTES);
463                 } // END - for
464
465                 // In real-mode execute any existing includes
466                 if (!$dry_run) {
467                         $GLOBALS['cache_array']['inc_pool'][$ext_name] = $INC_POOL;
468                         RUN_FILTER('load_includes', $INC_POOL);
469                         $INC_POOL = $GLOBALS['cache_array']['inc_pool'][$ext_name];
470                         unset($GLOBALS['cache_array']['inc_pool'][$ext_name]);
471                 } // END - if
472
473                 // Run SQLs
474                 RUN_FILTER('run_sqls', array('dry_run' => $dry_run, 'sqls' => $SQLs));
475
476                 if (!$dry_run) {
477                         // Create task
478                         CREATE_EXTENSION_UPDATE_TASK(GET_CURRENT_ADMIN_ID(), $ext_name, $GLOBALS['cache_array']['update_ver'][$ext_name], SQL_ESCAPE($NOTES));
479
480                         // Update extension's version
481                         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_extensions` SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
482                                 array($GLOBALS['cache_array']['update_ver'][$ext_name], $ext_name), __FILE__, __LINE__);
483
484                         // Remove arrays
485                         unset($SQLs);
486                         unset($GLOBALS['cache_array']['update_ver'][$ext_name]);
487
488                         // Run filters on success extension update
489                         RUN_FILTER('extension_update', $ext_name);
490                 } else {
491                         // In "dry-run" mode return array with SQL commands
492                         return $SQLs;
493                 }
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         global $SQLs;
500
501         // Empty title?
502         if (empty($title)) {
503                 // Then fix it to default
504                 $title = getMessage('ADMIN_SQLS_EXECUTED_ON_REMOVAL');
505         } // END - if
506
507         // Are there some queries in $queries?
508         if (count($queries) > 0) {
509                 // Then use them instead!
510                 $SQLs = $queries;
511         } // END - if
512
513         // Init variables
514         $SW = 2; $i = 1;
515         $OUT = "";
516
517         // Do we have queries?
518         if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
519                 foreach ($SQLs as $idx => $sql) {
520                         // Trim out spaces
521                         $sql = trim($sql);
522
523                         // Output command if set
524                         if (!empty($sql)) {
525                                 // Prepare output for template
526                                 $content = array(
527                                         'sw'  => $SW,
528                                         'i'   => $i,
529                                         'sql' => $sql
530                                 );
531
532                                 // Load row template
533                                 $OUT .= LOAD_TEMPLATE("admin_ext_sql_row", true, $content);
534
535                                 // Switch color and count up
536                                 $SW = 3 - $SW;
537                                 $i++;
538                         } // END - if
539                 } // END - foreach
540
541                 // Prepare content for template
542                 $content = array(
543                         'width'  => $width,
544                         'dashed' => $dashed,
545                         'title'  => $title,
546                         'out'    => $OUT
547                 );
548
549                 // Load main template
550                 $OUT = LOAD_TEMPLATE("admin_ext_sql_table", true, $content);
551         } elseif ((GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
552                 // No addional SQL commands to run
553                 $OUT = LOAD_TEMPLATE("admin_settings_saved", true, getMessage('ADMIN_NO_ADDITIONAL_SQLS'));
554         } // END - if
555
556         // Return output
557         return $OUT;
558 }
559
560 // Get extension name from id
561 function GET_EXT_NAME ($ext_id) {
562         // Init extension name
563         $ret = "";
564
565         // Is cache there?
566         if (isset($GLOBALS['cache_array']['extensions']['ext_name'][$ext_id])) {
567                 // Load from cache
568                 $ret = $GLOBALS['cache_array']['extensions']['ext_name'][$ext_id];
569
570                 // Count cache hits
571                 incrementConfigEntry('cache_hits');
572         } elseif (!EXT_IS_ACTIVE("cache")) {
573                 // Load from database
574                 $result = SQL_QUERY_ESC("SELECT ext_name FROM `{!_MYSQL_PREFIX!}_extensions` WHERE id=%s LIMIT 1",
575                         array(bigintval($ext_id)), __FILE__, __LINE__);
576                 list($ret) = SQL_FETCHROW($result);
577                 SQL_FREERESULT($result);
578         }
579         return $ret;
580 }
581
582 // Get extension id from name
583 function GET_EXT_ID ($ext_name) {
584         // Init ID number
585         $ret = 0;
586         if (isset($GLOBALS['cache_array']['extensions']['ext_id'][$ext_name])) {
587                 // Load from cache
588                 $ret = $GLOBALS['cache_array']['extensions']['ext_id'][$ext_name];
589
590                 // Count cache hits
591                 incrementConfigEntry('cache_hits');
592         } elseif (!EXT_IS_ACTIVE("cache")) {
593                 // Load from database
594                 $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_extensions` WHERE ext_name='%s' LIMIT 1",
595                         array($ext_name), __FILE__, __LINE__);
596                 list($ret) = SQL_FETCHROW($result);
597                 SQL_FREERESULT($result);
598         }
599
600         // Return value
601         return $ret;
602 }
603
604 // Activate given extension
605 function ACTIVATE_EXTENSION ($ext_name) {
606         // Activate the extension
607         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_extensions` SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
608                 array($ext_name), __FILE__, __LINE__);
609
610         // Extension has been activated?
611         if (SQL_AFFECTEDROWS() == 1) {
612                 // Then run all queries
613                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
614         } // END - if
615 }
616
617 // Deactivate given extension
618 function DEACTIVATE_EXTENSION($ext_name) {
619         // Activate the extension
620         SQL_QUERY_ESC("UPDATE `{!_MYSQL_PREFIX!}_extensions` SET ext_active='N' WHERE ext_name='%s' LIMIT 1",
621                 array($ext_name), __FILE__, __LINE__);
622
623         // Extension has been activated?
624         if (SQL_AFFECTEDROWS() == 1) {
625                 // Then run all queries
626                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "deactivate");
627
628                 // Create new task
629                 CREATE_EXTENSION_DEACTIVATION_TASK($ext_name);
630
631                 // Notify the admin
632                 SEND_ADMIN_NOTIFICATION(
633                         getMessage('ADMIN_SUBJECT_EXTENSION_DEACTIVATED'),
634                         "admin_ext_deactivated",
635                         array('ext_name' => $ext_name)
636                 );
637         } // END - if
638 }
639
640 // Checks wether the extension is older than given
641 function EXT_VERSION_IS_OLDER ($ext_name, $ext_ver) {
642         // Get current extension version
643         $currVersion = GET_EXT_VERSION($ext_name);
644
645         // Remove all dots from both versions
646         $currVersion = str_replace(".", "", $currVersion);
647         $ext_ver = str_replace(".", "", $ext_ver);
648
649         // Now compare both and return the result
650         return ($currVersion < $ext_ver);
651 }
652
653 // Creates a new task for updated extension
654 function CREATE_EXTENSION_UPDATE_TASK ($admin_id, $ext_name, $ext_ver, $notes) {
655         // Create subject line
656         $subject = "[UPDATE-".$ext_name."-".$ext_ver.":] {--ADMIN_UPDATE_EXT_SUBJ--}";
657
658         // Is the extension there?
659         if (GET_EXT_VERSION($ext_name) != "") {
660                 // Check if task is not there
661                 if (DETERMINE_TASK_ID_BY_SUBJECT($subject) == 0) {
662                         // Task not created so it's a brand-new extension which we need to register and create a task for!
663                         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())",
664                                 array($admin_id, $subject, $notes), __FILE__, __LINE__);
665                 } // END - if
666         } // END - if
667 }
668
669 // Creates a new task for newly installed extension
670 function CREATE_NEW_EXTENSION_TASK ($admin_id, $subject, $ext) {
671         // Not installed and do we have created a task for the admin?
672         if ((DETERMINE_TASK_ID_BY_SUBJECT($subject) == 0) && (GET_EXT_VERSION($ext) == "")) {
673                 // Template file
674                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
675                         constant('PATH'),
676                         GET_LANGUAGE(),
677                         $ext
678                 );
679
680                 // Load text for task
681                 if (FILE_READABLE($tpl)) {
682                         // Load extension's own text template (HTML!)
683                         $msg = LOAD_TEMPLATE("ext_".$ext, true);
684                 } else {
685                         // Load default message
686                         $msg = LOAD_TEMPLATE("admin_new_ext", "", 0);
687                 }
688
689                 // Task not created so it's a brand-new extension which we need to register and create a task for!
690                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_task_system` (assigned_admin, userid, status, task_type, subject, text, task_created)
691 VALUES (%s,0,'NEW','EXTENSION','%s','%s',UNIX_TIMESTAMP())",
692                         array(
693                                 $admin_id,
694                                 $subject,
695                                 SQL_ESCAPE($msg),
696                         ),  __FILE__, __LINE__, true, false
697                 );
698         } // END - if
699 }
700
701 // Creates a task for automatically deactivated (deprecated) extension
702 function CREATE_EXTENSION_DEACTIVATION_TASK ($ext) {
703         // Create subject line
704         $subject = sprintf("[%s:] %s", $ext, getMessage('TASK_SUBJ_EXTENSION_DEACTIVATED'));
705
706         // Not installed and do we have created a task for the admin?
707         if ((DETERMINE_TASK_ID_BY_SUBJECT($subject) == 0) && (GET_EXT_VERSION($ext) != "")) {
708                 // Task not created so add it
709                 SQL_QUERY_ESC("INSERT INTO `{!_MYSQL_PREFIX!}_task_system` (assigned_admin, userid, status, task_type, subject, text, task_created)
710 VALUES (0,0,'NEW','EXTENSION_DEACTIVATION','%s','%s',UNIX_TIMESTAMP())",
711                         array(
712                                 $subject,
713                                 SQL_ESCAPE(LOAD_TEMPLATE("task_ext_deactivated", true, $ext)),
714                         ),  __FILE__, __LINE__, true, false
715                 );
716         } // END - if
717 }
718
719 // Checks if the module has a menu
720 function MODULE_HAS_MENU ($mod, $forceDb = false) {
721         // All is false by default
722         $ret = false;
723
724         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):mod={$mod},cache=".GET_EXT_VERSION("cache")."<br />\n";
725         if (GET_EXT_VERSION("cache") >= "0.1.2") {
726                 // Cache version is okay, so let's check the cache!
727                 if (isset($GLOBALS['cache_array']['modules']['has_menu'][$mod])) {
728                         // Check module cache and count hit
729                         $ret = ($GLOBALS['cache_array']['modules']['has_menu'][$mod] == "Y");
730                         incrementConfigEntry('cache_hits');
731                 } elseif (isset($GLOBALS['cache_array']['extensions']['ext_menu'][$mod])) {
732                         // Check cache and count hit
733                         $ret = ($GLOBALS['cache_array']['extensions']['ext_menu'][$mod] == "Y");
734                         incrementConfigEntry('cache_hits');
735                 } elseif ((IS_ADMIN()) && ($mod == "admin")) {
736                         // Admin module has always a menu!
737                         $ret = true;
738                 }
739         } elseif ((GET_EXT_VERSION("sql_patches") >= "0.3.6") && ((!EXT_IS_ACTIVE("cache")) || ($forceDb === true))) {
740                 // Check database for entry
741                 $result = SQL_QUERY_ESC("SELECT has_menu FROM `{!_MYSQL_PREFIX!}_mod_reg` WHERE module='%s' LIMIT 1",
742                         array($mod), __FILE__, __LINE__);
743
744                 // Entry found?
745                 if (SQL_NUMROWS($result) == 1) {
746                         // Load "has_menu" column
747                         list($has_menu) = SQL_FETCHROW($result);
748
749                         // Fake cache... ;-)
750                         $GLOBALS['cache_array']['extensions']['ext_menu'][$mod] = $has_menu;
751
752                         // Does it have a menu?
753                         $ret = ($has_menu == "Y");
754                 } // END  - if
755
756                 // Free memory
757                 SQL_FREERESULT($result);
758         } elseif (GET_EXT_VERSION("sql_patches") == "") {
759                 // No sql_patches installed, so maybe in admin area?
760                 $ret = ((IS_ADMIN()) && ($mod == "admin")); // Then there is a menu!
761         }
762
763         // Return status
764         //* DEBUG: */ var_dump($ret);
765         return $ret;
766 }
767
768 // Determines the task id for given extension
769 function DETERMINE_EXTENSION_TASK_ID ($ext_name) {
770         // Default is not found
771         $task_id = 0;
772
773         // Search for extension task's id
774         $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_task_system` WHERE task_type='EXTENSION' AND subject='[%s:]' LIMIT 1",
775                 array($ext_name), __FILE__, __LINE__);
776
777         // Entry found?
778         if (SQL_NUMROWS($result) == 1) {
779                 // Task found so load task's ID and register extension...
780                 list($task_id) = SQL_FETCHROW($result);
781         } // END - if
782
783         // Free result
784         SQL_FREERESULT($result);
785
786         // Return it
787         return $task_id;
788 }
789
790 // Determines the task id for given subject
791 function DETERMINE_TASK_ID_BY_SUBJECT ($subject) {
792         // Default is not found
793         $task_id = 0;
794
795         // Search for task id
796         $result = SQL_QUERY_ESC("SELECT id FROM `{!_MYSQL_PREFIX!}_task_system` WHERE subject LIKE '%s%%' LIMIT 1",
797                 array($subject), __FILE__, __LINE__);
798
799         // Entry found?
800         if (SQL_NUMROWS($result) == 1) {
801                 // Task found so load task's ID and register extension...
802                 list($task_id) = SQL_FETCHROW($result);
803         } // END - if
804
805         // Free result
806         SQL_FREERESULT($result);
807
808         // Return it
809         return $task_id;
810 }
811
812 // Add updates notes for given version
813 function ADD_EXTENSION_NOTES ($ver, &$UPDATE_NOTES) {
814         // Init notes/content
815         $out = ""; $content = array();
816
817         // Is do we have verbose output enabled?
818         if ((getConfig('verbose_sql') == "Y") || (!EXT_IS_ACTIVE("sql_patches"))) {
819
820                 // Update notes found?
821                 if (!empty($UPDATE_NOTES)) {
822                         // Update notes found
823                         $content = array(
824                                 'ver'   => $ver,
825                                 'notes' => $UPDATE_NOTES
826                         );
827                         $UPDATE_NOTES = "";
828                 } elseif (($ver == "0.0") || ($ver == "0.0.0")) {
829                         // Initial release
830                         $content = array(
831                                 'ver'   => $ver,
832                                 'notes' => getMessage('INITIAL_RELEASE')
833                         );
834                 } else {
835                         // No update notes found!
836                         $content = array(
837                                 'ver'   => $ver,
838                                 'notes' => getMessage('NO_UPDATE_NOTES')
839                         );
840                 }
841
842                 // Load template
843                 $out = LOAD_TEMPLATE("admin_ext_notes", true, $content);
844         } // END - if
845
846         // Return the output
847         return $out;
848 }
849
850 // Getter for CSS files array
851 function EXT_GET_CSS_FILES () {
852         // By default no additional CSS files are found
853         $cssFiles = array();
854
855         // Is the array there?
856         if (isset($GLOBALS['css_files'])) {
857                 // Then use it
858                 $cssFiles = $GLOBALS['css_files'];
859         } // END - if
860
861         // Return array
862         return $cssFiles;
863 }
864
865 // Init CSS files array
866 function EXT_INIT_CSS_FILES () {
867         // Simply init it
868         $GLOBALS['css_files'] = array();
869 }
870
871 // Add new entry
872 function EXT_ADD_CSS_FILE ($file) {
873         // Is the array there?
874         if (!isset($GLOBALS['css_files'])) {
875                 // Then auto-init them
876                 EXT_INIT_CSS_FILES();
877         } // END - if
878
879         // Add the entry
880         $GLOBALS['css_files'][] = $file;
881 }
882
883 //
884 ?>