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