Fixes for extension removal, now directly sent to [UN]REGISTER_FILTER()
[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, $INC_POOL, $cacheInstance;
129         global $EXT_VER_HISTORY, $NOTES, $EXT_ALWAYS_ACTIVE, $EXT_VERSION;
130         global $EXT_UPDATE_DEPENDS, $SQLs;
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, $SQLs;
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                 RUN_FILTER('run_sqls');
308
309                 // Removal mode?
310                 if ($load_mode == "remove") {
311                         // Delete this extension (remember to remove it from your server *before* you click on welcome!
312                         $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
313                                 array($ext_name), __FILE__, __LINE__);
314                 } // END - if
315         } // END - if
316
317         // Remove cache file(s) if extension is active
318         if (((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) && (((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == "activate") || ($load_mode == "deactivate"))) {
319                 // Run filters
320                 RUN_FILTER('post_extension_run_sql', $ext_name);
321         } // END - if
322
323         // Is this the sql_patches?
324         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": {$ext_id}/{$ext_name}/{$load_mode}");
325         if (($ext_name == "sql_patches") && (($load_mode == "register") || ($load_mode == "remove"))) {
326                 // Then redirect to logout
327                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
328                 LOAD_URL("modules.php?module=admin&logout=1&".$load_mode."=sql_patches");
329         } // END - if
330 }
331
332 // Check if given extension is active
333 function EXT_IS_ACTIVE ($ext_name) {
334         global $cacheArray, $_CONFIG;
335
336         // Extensions are all inactive during installation
337         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing')) || (empty($ext_name))) return false;
338
339         // Not active is the default
340         $active = "N";
341
342         // Check cache
343         if (isset($cacheArray['extensions']['ext_active'][$ext_name])) {
344                 // Load from cache
345                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
346                 $active = $cacheArray['extensions']['ext_active'][$ext_name];
347
348                 // Count cache hits
349                 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
350         } elseif (($ext_name == "cache") || (GET_EXT_VERSION("cache") == "")) {
351                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
352                 // Load from database
353                 $result = SQL_QUERY_ESC("SELECT ext_active FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
354                         array($ext_name), __FILE__, __LINE__);
355
356                 // Entry found?
357                 if (SQL_NUMROWS($result) == 1) {
358                         // Load entry
359                         list($active) = SQL_FETCHROW($result);
360                 } // END - if
361
362                 // Free result
363                 SQL_FREERESULT($result);
364
365                 // Write cache array
366                 //* DEBUG: */ echo $ext_name."[DB]: {$active}");
367                 $cacheArray['extensions']['ext_active'][$ext_name] = $active;
368         } else {
369                 // Extension not active!
370                 //* DEBUG: */ echo $ext_name.": Not active!");
371                 $cacheArray['extensions']['ext_active'][$ext_name] = "N";
372         }
373
374         // Debug message
375         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " ext_name={$ext_name},active={$active}");
376
377         // Is this extension activated? (For admins we always have active extensions...)
378         return ($active == "Y");
379 }
380 // Get version from extensions
381 function GET_EXT_VERSION ($ext_name) {
382         global $cacheArray, $_CONFIG, $cacheInstance;
383         $ext_ver = false;
384
385         // Extensions are all inactive during installation
386         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing'))) return "";
387         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ext_name={$ext_name}");
388
389         // Is the cache written?
390         if (isset($cacheArray['extensions']['ext_version'][$ext_name])) {
391                 // Load data from cache
392                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": CACHE!");
393                 $ext_ver = $cacheArray['extensions']['ext_version'][$ext_name];
394
395                 // Count cache hits
396                 if (getConfig('cache_hits') > 0) $_CONFIG['cache_hits']++; else $_CONFIG['cache_hits'] = 1;
397         } elseif (!is_object($cacheInstance)) {
398                 // Load from database
399                 $result = SQL_QUERY_ESC("SELECT ext_version FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
400                         array($ext_name), __FILE__, __LINE__);
401
402                 // Is the extension there?
403                 if (SQL_NUMROWS($result) == 1) {
404                         // Load entry
405                         list($ext_ver) = SQL_FETCHROW($result);
406                 } // END - if
407
408                 // Free result
409                 SQL_FREERESULT($result);
410
411                 // Set cache
412                 $cacheArray['extensions']['ext_version'][$ext_name] = $ext_ver;
413         }
414
415         // Return result
416         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ret={$ext_ver}");
417         return $ext_ver;
418 }
419
420 // Updates a given extension with current extension version to latest version
421 function EXTENSION_UPDATE ($ext_name, $ext_ver, $dry_run = false) {
422         // This shall never do a non-admin user!
423         global $cacheInstance, $UPDATE_NOTES, $NOTES, $EXT_VER_HISTORY;
424         global $EXT_UPDATE_DEPENDS, $EXT_VERSION, $INC_POOL, $cacheArray;
425
426         // Init arrays
427         $SQLs = array(); $INC_POOL = array();
428
429         // Only admins are allowed to update extensions
430         if ((!IS_ADMIN()) || (empty($ext_name))) return false;
431
432         // Load extension in test mode
433         LOAD_EXTENSION($ext_name, "test", $ext_ver, $dry_run, $SQLs);
434
435         // Save version history
436         $history = $EXT_VER_HISTORY;
437
438         // Remove old SQLs array to prevent possible bugs
439         $SQLs = array();
440
441         // Check if version is updated
442         if ((($EXT_VERSION != $ext_ver) || ($dry_run)) && (is_array($history))) {
443                 // Search for starting point
444                 $start = array_search($ext_ver, $history);
445                 $NOTES = "";
446
447                 // And load SQL queries in order of version history
448                 for ($idx = ($start + 1); $idx < sizeof($history); $idx++) {
449                         // Set extension version
450                         $cacheArray['update_ver'][$ext_name] = $history[$idx];
451
452                         // Load again...
453                         LOAD_EXTENSION($ext_name, "update", $cacheArray['update_ver'][$ext_name], $dry_run, $SQLs);
454
455                         if (!empty($EXT_UPDATE_DEPENDS)) {
456                                 // Backup current SQL queries
457                                 $cacheArray['update_sqls'][$ext_name] = $SQLs;
458
459                                 // Is the extension there?
460                                 if (GET_EXT_VERSION($EXT_UPDATE_DEPENDS) != "") {
461                                         // Update another extension first!
462                                         $test = EXTENSION_UPDATE($EXT_UPDATE_DEPENDS, GET_EXT_VERSION($EXT_UPDATE_DEPENDS), $dry_run);
463                                 } else {
464                                         // Register new extension
465                                         $test = EXTENSION_REGISTER($EXT_UPDATE_DEPENDS, 0, $dry_run, false);
466                                 }
467
468                                 // Restore previous SQL queries
469                                 $SQLs = $cacheArray['update_sqls'][$ext_name];
470                                 unset($cacheArray['update_sqls'][$ext_name]);
471                         } // END - if
472
473                         // Add notes
474                         if (getConfig('verbose_sql') == "Y") {
475                                 if (!empty($UPDATE_NOTES)) {
476                                         // Update notes found
477                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$cacheArray['update_ver'][$ext_name].":</strong><br />".$UPDATE_NOTES."</div>");
478                                         $UPDATE_NOTES = "";
479                                 } elseif ($cacheArray['update_ver'][$ext_name] == "0.0") {
480                                         // Initial release
481                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$cacheArray['update_ver'][$ext_name].":</strong><br />".INITIAL_RELEASE."</div>");
482                                 } else {
483                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$cacheArray['update_ver'][$ext_name].":</strong><br /><I>".NO_UPDATE_NOTES."</I></div>");
484                                 }
485                         } // END - if
486                 } // END - for
487
488                 // In real-mode execute any existing includes
489                 if (!$dry_run) {
490                         $cacheArray['inc_pool'][$ext_name] = $INC_POOL;
491                         RUN_FILTER('load_includes');
492                         $INC_POOL = $cacheArray['inc_pool'][$ext_name];
493                         unset($cacheArray['inc_pool'][$ext_name]);
494                 } // END - if
495
496                 // Run SQLs
497                 RUN_FILTER('run_sqls', $dry_run);
498
499                 if (!$dry_run) {
500                         // Create task
501                         CREATE_EXTENSION_UPDATE_TASK(GET_CURRENT_ADMIN_ID(), $ext_name, $cacheArray['update_ver'][$ext_name], addslashes($NOTES));
502
503                         // Update extension's version
504                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
505                                 array($cacheArray['update_ver'][$ext_name], $ext_name), __FILE__, __LINE__);
506
507                         // Remove arrays
508                         unset($SQLs);
509                         unset($cacheArray['update_ver'][$ext_name]);
510
511                         // Run filters on success extension update
512                         RUN_FILTER('extension_update', $ext_name);
513                 } else {
514                         // In "dry-run" mode return array with SQL commands
515                         return $SQLs;
516                 }
517         }
518 }
519
520 // Output verbose SQL table for extension
521 function EXTENSION_VERBOSE_TABLE ($queries = array(), $title = ADMIN_SQLS_EXECUTED_ON_REMOVAL, $dashed = "", $switch = false, $width = "100%") {
522         global $SQLs;
523
524         // Are there some queries in $queries?
525         if (count($queries) > 0) {
526                 // Then use them instead!
527                 $SQLs = $queries;
528         } // END - if
529
530         // Init variables
531         $S = false; $SW = 2; $i = 1;
532         $OUT = "";
533
534         // Do we have queries?
535         if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
536                 $OUT  = "<div align=\"center\">
537 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"".$width."\" align=\"center\"".$dashed.">
538 <tr>
539   <td colspan=\"2\" align=\"center\" class=\"admin_title bottom2\" height=\"24\">
540     <strong>".$title.":</strong>
541   </td>
542 </tr>\n";
543                 foreach ($SQLs as $idx => $sql) {
544                         $sql = trim($sql);
545                         if (!empty($sql)) {
546                                 $S = true;
547                                 $OUT .= "<tr>
548   <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 2px\" width=\"30\">".$i.".</td>
549   <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 5px; padding-right: 5px\">
550     ".$sql."
551   </td>
552 </tr>\n";
553                                 if ($switch) $SW = 3 - $SW;
554                                 $i++;
555                         }
556                 }
557         }
558
559         if ((!$S) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
560                 // No addional SQL commands to run
561                 $OUT .= "<tr>
562   <td colspan=\"2\" align=\"center\" class=\"switch_sw2 bottom2\" height=\"24\">
563     <font class=\"admin_note\">".ADMIN_NO_ADDIONAL_SQLS."</font>
564   </td>
565 </tr>\n";
566         }
567
568         if (!empty($OUT)) {
569                 // Add missing close-table tag
570                 $OUT .= "</table>
571 </div>\n";
572         }
573
574         // Return output
575         return $OUT;
576 }
577
578 // Get extension name from id
579 function GET_EXT_NAME ($ext_id) {
580         global $cacheArray, $_CONFIG;
581
582         // Init extension name
583         $ret = "";
584
585         // Is cache there?
586         if (isset($cacheArray['extensions']['ext_name'][$ext_id])) {
587                 // Load from cache
588                 $ret = $cacheArray['extensions']['ext_name'][$ext_id];
589
590                 // Count cache hits
591                 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
592         } elseif (!EXT_IS_ACTIVE("cache")) {
593                 // Load from database
594                 $result = SQL_QUERY_ESC("SELECT ext_name FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
595                         array(bigintval($ext_id)), __FILE__, __LINE__);
596                 list($ret) = SQL_FETCHROW($result);
597                 SQL_FREERESULT($result);
598         }
599         return $ret;
600 }
601
602 // Get extension id from name
603 function GET_EXT_ID ($ext_name) {
604         global $cacheArray, $_CONFIG;
605
606         // Init ID number
607         $ret = 0;
608         if (isset($cacheArray['extensions']['ext_id'][$ext_name])) {
609                 // Load from cache
610                 $ret = $cacheArray['extensions']['ext_id'][$ext_name];
611
612                 // Count cache hits
613                 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
614         } elseif (!EXT_IS_ACTIVE("cache")) {
615                 // Load from database
616                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
617                         array($ext_name), __FILE__, __LINE__);
618                 list($ret) = SQL_FETCHROW($result);
619                 SQL_FREERESULT($result);
620         }
621
622         // Return value
623         return $ret;
624 }
625
626 // Activate given extension
627 function ACTIVATE_EXTENSION ($ext_name) {
628         // Activate the extension
629         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
630                 array($ext_name), __FILE__, __LINE__);
631
632         // Extension has been activated?
633         if (SQL_AFFECTEDROWS() == 1) {
634                 // Then run all queries
635                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
636         } // END - if
637 }
638
639 // Deactivate given extension
640 function DEACTIVATE_EXTENSION($ext_name) {
641         // Activate the extension
642         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='N' WHERE ext_name='%s' LIMIT 1",
643                 array($ext_name), __FILE__, __LINE__);
644
645         // Extension has been activated?
646         if (SQL_AFFECTEDROWS() == 1) {
647                 // Then run all queries
648                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "deactivate");
649
650                 // Create new task
651                 CREATE_EXTENSION_DEACTIVATION_TASK($ext_name);
652
653                 // Notify the admin
654                 SEND_ADMIN_NOTIFICATION(ADMIN_SUBJECT_EXTENSION_DEACTIVATED, "admin_ext_deactivated", array('ext_name' => $ext_name));
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                         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                 $result_insert = 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                                 addslashes($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, 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                 $result_insert = 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                                 addslashes(LOAD_TEMPLATE("task_ext_deactivated", true, $ext)),
732                         ),  __FILE__, __LINE__, true, false
733                 );
734         } // END - if
735
736         // Free memory
737         SQL_FREERESULT($result);
738 }
739
740 // Checks if the module has a menu
741 function MODULE_HAS_MENU ($mod, $forceDb = false) {
742         global $cacheArray, $_CONFIG;
743
744         // All is false by default
745         $ret = false;
746         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):mod={$mod},cache=".GET_EXT_VERSION("cache")."<br />\n";
747         if (GET_EXT_VERSION("cache") >= "0.1.2") {
748                 // Cache version is okay, so let's check the cache!
749                 if (isset($cacheArray['modules']['has_menu'][$mod])) {
750                         // Check module cache and count hit
751                         $ret = ($cacheArray['modules']['has_menu'][$mod] == "Y");
752                         if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
753                 } elseif (isset($cacheArray['extensions']['ext_menu'][$mod])) {
754                         // Check cache and count hit
755                         $ret = ($cacheArray['extensions']['ext_menu'][$mod] == "Y");
756                         if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
757                 } elseif ((IS_ADMIN()) && ($mod == "admin")) {
758                         // Admin module has always a menu!
759                         $ret = true;
760                 }
761         } elseif ((GET_EXT_VERSION("sql_patches") >= "0.3.6") && ((!EXT_IS_ACTIVE("cache")) || ($forceDb === true))) {
762                 // Check database for entry
763                 $result = SQL_QUERY_ESC("SELECT has_menu FROM "._MYSQL_PREFIX."_mod_reg WHERE module='%s' LIMIT 1",
764                         array($mod), __FILE__, __LINE__);
765
766                 // Entry found?
767                 if (SQL_NUMROWS($result) == 1) {
768                         // Load "has_menu" column
769                         list($has_menu) = SQL_FETCHROW($result);
770
771                         // Fake cache... ;-)
772                         $cacheArray['extensions']['ext_menu'][$mod] = $has_menu;
773
774                         // Does it have a menu?
775                         $ret = ($has_menu == "Y");
776                 } // END  - if
777
778                 // Free memory
779                 SQL_FREERESULT($result);
780         } elseif (GET_EXT_VERSION("sql_patches") == "") {
781                 // No sql_patches installed, so maybe in admin area?
782                 $ret = ((IS_ADMIN()) && ($mod == "admin")); // Then there is a menu!
783         }
784
785         // Return status
786         //* DEBUG: */ var_dump($ret);
787         return $ret;
788 }
789
790 // Determines the task id for given extension
791 function DETERMINE_EXTENSION_TASK_ID ($ext_name) {
792         // Default is not found
793         $task_id = 0;
794
795         // Search for extension task's id
796         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE task_type='EXTENSION' AND subject='[%s:]' LIMIT 1",
797                 array($ext_name), __FILE__, __LINE__);
798
799         // Entry found?
800         if (SQL_NUMROWS($result) == 1) {
801                 // Task found so load task's ID and register extension...
802                 list($task_id) = SQL_FETCHROW($result);
803         } // END - if
804
805         // Free result
806         SQL_FREERESULT($result);
807
808         // Return it
809         return $task_id;
810 }
811
812 // Determines the task id for given subject
813 function DETERMINE_TASK_ID_BY_SUBJECT ($subject) {
814         // Default is not found
815         $task_id = 0;
816
817         // Search for task id
818         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE subject LIKE '%s%%' LIMIT 1",
819                 array($subject), __FILE__, __LINE__);
820
821         // Entry found?
822         if (SQL_NUMROWS($result) == 1) {
823                 // Task found so load task's ID and register extension...
824                 list($task_id) = SQL_FETCHROW($result);
825         } // END - if
826
827         // Free result
828         SQL_FREERESULT($result);
829
830         // Return it
831         return $task_id;
832 }
833
834 //
835 ?>