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