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