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