More fixes for cache, extension and filter sub-system
[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) {
42         global $EXT_LOADED, $_CONFIG, $CSS, $cacheMode, $SQLs, $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 //
127 function EXTENSION_REGISTER ($ext_name, $task_id, $dry_run=false) {
128         global $UPDATE_NOTES, $_CONFIG, $INC_POOL, $cacheInstance;
129         global $EXT_VER_HISTORY, $SQLs, $NOTES, $EXT_ALWAYS_ACTIVE, $EXT_VERSION;
130
131         // This shall never do a non-admin user!
132         if (!IS_ADMIN()) return false;
133
134         // Is this extension already installed?
135         if (EXT_IS_ACTIVE($ext_name)) return false;
136
137         // Init variables
138         $ret = false; $SQLs = array();
139         $NOTES = "";
140         $INC_POOL = array();
141
142         // By default the language prefix is the extension's name
143         // @TODO: Do we really need this one anymore? Can't we just take $ext_name and done?
144         // By default we have no failtures
145         $EXT_REPORTS_FAILURE = false;
146
147         // Does this extension exists?
148         if (LOAD_EXTENSION($ext_name, "register", "", $dry_run)) {
149                 // And run possible updates
150                 $history = $EXT_VER_HISTORY;
151                 foreach ($history as $ver) {
152                         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "ext_name={$ext_name}, ext_ver={$ver}");
153                         // Load extension in update mode
154                         LOAD_EXTENSION($ext_name, "update", $ver, $dry_run);
155
156                         // Do we have an update?
157                         if (((GET_EXT_VERSION("sql_patches") != "") && ($_CONFIG['verbose_sql'] == "Y")) || (!EXT_IS_ACTIVE("sql_patches"))) {
158                                 if (!empty($UPDATE_NOTES)) {
159                                         // Update notes found
160                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".$UPDATE_NOTES."</div>");
161                                         $UPDATE_NOTES = "";
162                                 } elseif (($ver == "0.0") || ($ver == "0.0.0")) {
163                                         // Initial release
164                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".INITIAL_RELEASE."</div>");
165                                 } else {
166                                         // No update notes found!
167                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br /><I>".NO_UPDATE_NOTES."</I></div>");
168                                 }
169                         } // END - if
170                 } // END - foreach
171
172                 // Does this extension depends on an outstanding update of another update?
173                 if (!empty($EXT_UPDATE_DEPENDS)) {
174                         // Backup SQL commands and clear current
175                         $SQLs2 = $SQLs;
176                         $SQLs  = array();
177                         $test  = false;
178
179                         // Check for required file
180                         if (LOAD_EXTENSION($EXT_UPDATE_DEPENDS, "register", "", $dry_run)) {
181                                 // If versions mismatch update extension first
182                                 $ext_ver = GET_EXT_VERSION($EXT_UPDATE_DEPENDS);
183
184                                 // Extension version set? If empty the extension is not registered
185                                 if (empty($ext_ver)) {
186                                         // Extension not registered so far so first load task's ID...
187                                         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE task_type='EXTENSION' AND subject LIKE '[%s:]%%' LIMIT 1",
188                                                 array($EXT_UPDATE_DEPENDS), __FILE__, __LINE__);
189
190                                         // Entry found?
191                                         if (SQL_NUMROWS($result) == 1) {
192                                                 // Task found so load task's ID and register extension...
193                                                 list($task) = SQL_FETCHROW($result);
194
195                                                 // Try to register the extension
196                                                 $test = EXTENSION_REGISTER($EXT_UPDATE_DEPENDS, $task, $dry_run);
197                                         } // END - if
198
199                                         // Free result
200                                         SQL_FREERESULT($result);
201                                 } elseif ($ext_ver != $EXT_VERSION) {
202                                         // Ok, update this extension now
203                                         EXTENSION_UPDATE(basename($file), $EXT_UPDATE_DEPENDS, $ext_ver, $dry_run);
204
205                                         // All okay!
206                                         $test = true;
207                                 } else {
208                                         // Nothing to register / update before...
209                                         $test = true;
210                                 }
211                         } else {
212                                 // Required file for update does not exists!
213                                 $test = true;
214                                 // But this is fine for the first time...
215                         }
216
217                         // Finally restore previous SQLs
218                         $SQLs = $SQLs2; unset($SQLs2);
219                 } else {
220                         // Does not depend on an other extension
221                         $test = true;
222                 }
223
224                 // Switch back to register mode
225                 $EXT_LOAD_MODE = "register";
226
227                 // Remains true if extension registration reports no failtures
228                 $test = ($test && !$EXT_REPORTS_FAILURE);
229
230                 // Does everthing before wents ok?
231                 if ($test) {
232                         // "Dry-run-mode" activated?
233                         if (!$dry_run) {
234                                 // Run all SQLs
235                                 foreach ($SQLs as $sql) {
236                                         // Trim spaces away which we don't need
237                                         $sql = trim($sql);
238
239                                         // Is there still an SQL query?
240                                         if (!empty($sql)) {
241                                                 // Do we have an "ALTER TABLE" command?
242                                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
243                                                         // Analyse the alteration command
244                                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
245                                                 } else {
246                                                         // Run regular SQL command
247                                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
248                                                 }
249                                         } // END - if
250                                 } // END - foreach
251
252                                 // Remove cache file(s) if extension is active
253                                 RUN_FILTER('post_extension_installed', $ext_name);
254
255                                 // Check for added include files
256                                 if (count($INC_POOL > 0)) {
257                                         // Loads every include file
258                                         foreach ($INC_POOL as $inc) {
259                                                 require_once($inc);
260                                         } // END - foreach
261
262                                         // Remove array
263                                         unset($INC_POOL);
264                                 } // END - if
265
266                                 // Register extension
267                                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_extensions (ext_name, ext_active, ext_version) VALUES ('%s','%s','%s')",
268                                         array($ext_name, $EXT_ALWAYS_ACTIVE, $EXT_VERSION), __FILE__, __LINE__);
269
270                                 // Update task management
271                                 ADMIN_SOLVE_TASK($task_id);
272
273                                 // @TODO This causes the whole (!) menu cache being purged
274                                 CACHE_PURGE_ADMIN_MENU();
275
276                                 // In normal mode return a true on success
277                                 $ret = true;
278
279                                 // Remove SQLs
280                                 unset($SQLs);
281                         } else {
282                                 // Rewrite SQL command to keep { and } inside
283                                 foreach ($SQLs as $key => $sql) {
284                                         $sql = str_replace('{', "&#123;", str_replace('}', "&#125;", $sql));
285                                         $SQLs[$key] = $sql;
286                                 } // END - foreach
287
288                                 // In  "dry-run" mode return array with all SQL commands
289                                 $ret = $SQLs;
290
291                                 // Remove all SQL commands
292                                 unset($SQLs);
293                         }
294                 } else {
295                         // No, an error occurs while registering extension :-(
296                         $ret = false;
297                 }
298         } elseif (($task_id > 0) && (!empty($ext_name))) {
299                 // Remove task from system when id and extension's name is valid
300                 $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_task_system WHERE id=%s AND status='NEW' LIMIT 1",
301                  array(bigintval($task_id)), __FILE__, __LINE__);
302         }
303
304         // Is this the sql_patches?
305         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":{$ext_name}/{$EXT_LOAD_MODE}");
306         if (($ext_name == "sql_patches") && (($EXT_LOAD_MODE == "register") || ($EXT_LOAD_MODE == "remove")) && (!$dry_run) && ($test)) {
307                 // Then redirect to logout
308                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
309                 LOAD_URL("modules.php?module=admin&logout=1&".$EXT_LOAD_MODE."=sql_patches");
310         } // END - if
311
312         // Return status code
313         return $ret;
314 }
315
316 // Run SQL queries for given extension id
317 // @TODO Change from ext_id to ext_name (not just even the variable! ;-) )
318 function EXTENSION_RUN_SQLS ($ext_id, $load_mode) {
319         global $cacheInstance, $_CONFIG, $SQLs;
320
321         // Extensions are never active by default
322         $EXT_ALWAYS_ACTIVE = "N";
323
324         // By default no SQL has been executed
325         $sqlRan = false;
326
327         // This shall never do a non-admin user!
328         if (!IS_ADMIN()) return false;
329
330         // Get extension's name
331         $ext_name = GET_EXT_NAME($ext_id);
332         if (empty($ext_name)) return false;
333
334         // Load extension in detected mode
335         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":ext_name[{$ext_id}]={$ext_name}");
336         LOAD_EXTENSION($ext_name, $load_mode);
337
338         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":SQLs::count=".count($SQLs)."");
339         if ((is_array($SQLs) && (sizeof($SQLs) > 0))) {
340                 // Run SQL commands...
341                 foreach ($SQLs as $sql) {
342                         // Trim spaces away which we don't need
343                         $sql = trim($sql);
344
345                         // Is there still an SQL query?
346                         if (!empty($sql)) {
347                                 // Do we have an "ALTER TABLE" command?
348                                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ":SQL={$SQL}");
349                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
350                                         // Analyse the alteration command
351                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
352                                 } else {
353                                         // Run regular SQL command
354                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
355                                 }
356
357                                 // An SQL has been executed
358                                 $sqlRan = true;
359                         } // END - if
360                 } // END - foreach
361
362                 // Removal mode?
363                 if ($load_mode == "remove") {
364                         // Delete this extension (remember to remove it from your server *before* you click on welcome!
365                         $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
366                                 array($ext_name), __FILE__, __LINE__);
367                 } // END - if
368         } // END - if
369
370         // Remove cache file(s) if extension is active
371         if (((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) && (((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($load_mode == "activate") || ($load_mode == "deactivate"))) {
372                 // Run filters
373                 RUN_FILTER('post_extension_run_sql', $ext_name);
374
375                 // @TODO This causes the whole (!) menu cache being purged
376                 CACHE_PURGE_ADMIN_MENU();
377         } // END - if
378
379         // Is this the sql_patches?
380         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": {$ext_id}/{$ext_name}/{$load_mode}");
381         if (($ext_name == "sql_patches") && (($load_mode == "register") || ($load_mode == "remove"))) {
382                 // Then redirect to logout
383                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": LOAD!");
384                 LOAD_URL("modules.php?module=admin&logout=1&".$load_mode."=sql_patches");
385         } // END - if
386 }
387
388 // Check if given extension is active
389 function EXT_IS_ACTIVE ($ext_name) {
390         global $cacheArray, $_CONFIG;
391
392         // Extensions are all inactive during installation
393         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing')) || (empty($ext_name))) return false;
394
395         // Not active is the default
396         $active = "N";
397
398         // Check cache
399         if (!empty($cacheArray['extensions']['ext_active'][$ext_name])) {
400                 // Load from cache
401                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "CACHE! ext_name={$ext_name}");
402                 $active = $cacheArray['extensions']['ext_active'][$ext_name];
403
404                 // Count cache hits
405                 if (isset($_CONFIG['cache_hits'])) $_CONFIG['cache_hits']++;
406         } elseif (($ext_name == "cache") || (GET_EXT_VERSION("cache") == "")) {
407                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, "DB! ext_name={$ext_name}");
408                 // Load from database
409                 $result = SQL_QUERY_ESC("SELECT ext_active FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
410                         array($ext_name), __FILE__, __LINE__);
411
412                 // Entry found?
413                 if (SQL_NUMROWS($result) == 0) {
414                         // Extension was not found!
415                         return false;
416                 } // END - if
417
418                 // Load entry
419                 list($active) = SQL_FETCHROW($result);
420
421                 // Free result
422                 SQL_FREERESULT($result);
423
424                 // Write cache array
425                 //* DEBUG: */ echo $ext_name."[DB]: {$active}");
426                 $cacheArray['extensions']['ext_active'][$ext_name] = $active;
427         } else {
428                 // Extension not active!
429                 //* DEBUG: */ echo $ext_name.": Not active!");
430                 $cacheArray['extensions']['ext_active'][$ext_name] = "N";
431         }
432
433         // Debug message
434         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " ext_name={$ext_name},active={$active}");
435
436         // Is this extension activated? (For admins we always have active extensions...)
437         return ($active == "Y");
438 }
439 // Get version from extensions
440 function GET_EXT_VERSION ($ext_name) {
441         global $cacheArray, $_CONFIG, $cacheInstance;
442         $ret = false;
443
444         // Extensions are all inactive during installation
445         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing'))) return "";
446         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ext_name={$ext_name}");
447
448         // Is the cache written?
449         if (!empty($cacheArray['extensions']['ext_version'][$ext_name])) {
450                 // Load data from cache
451                 //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": CACHE!");
452                 $ret = $cacheArray['extensions']['ext_version'][$ext_name];
453
454                 // Count cache hits
455                 if (isset($_CONFIG['cache_hits'])) $_CONFIG['cache_hits']++; else $_CONFIG['cache_hits'] = 1;
456         } elseif (!is_object($cacheInstance)) {
457                 // Load from database
458                 $result = SQL_QUERY_ESC("SELECT ext_version FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
459                  array($ext_name), __FILE__, __LINE__);
460                 list($ret) = SQL_FETCHROW($result);
461                 SQL_FREERESULT($result);
462
463                 // Set cache
464                 $cacheArray['extensions']['ext_version'][$ext_name] = $ret;
465         }
466
467         // Return result
468         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, ": ret={$ret}");
469         return $ret;
470 }
471 //
472 function EXTENSION_UPDATE ($file, $ext_name, $ext_ver, $dry_run=false) {
473         // This shall never do a non-admin user!
474         global $cacheInstance, $_CONFIG, $UPDATE_NOTES, $NOTES;
475
476         // Init arrays
477         $SQLs = array(); $INC_POOL = array();
478
479         // Only admins are allowed to update extensions
480         if ((!IS_ADMIN()) || (empty($ext_name))) return false;
481
482         // Load extension in update mode
483         LOAD_EXTENSION($ext_name, "update". $ext_ver, $dry_run);
484
485         if (!empty($EXT_UPDATE_DEPENDS)) {
486                 // Update another extension first!
487                 $test = EXTENSION_UPDATE(("ext-".$EXT_UPDATE_DEPENDS.".php"), $EXT_UPDATE_DEPENDS, GET_EXT_VERSION($EXT_UPDATE_DEPENDS), $dry_run);
488         }
489
490         // Save version history
491         $history = $EXT_VER_HISTORY;
492
493         // Check if version is updated
494         if ((($EXT_VERSION != $ext_ver) || ($dry_run)) && (is_array($history))) {
495                 // Search for starting point
496                 $start = array_search($ext_ver, $history);
497                 $NOTES = "";
498
499                 // And load SQL queries in order of version history
500                 for ($idx = ($start + 1); $idx < sizeof($history); $idx++) {
501                         // Remove old SQLs array to prevent possible bugs
502                         if (!$dry_run) { unset($SQLs); $SQLs = array(); }
503
504                         // Set extension version
505                         $ver = $history[$idx];
506
507                         // Load again...
508                         LOAD_EXTENSION($ext_name, "update", $ver, $dry_run);
509
510                         // Add notes
511                         if ($_CONFIG['verbose_sql'] == "Y") {
512                                 if (!empty($UPDATE_NOTES)) {
513                                         // Update notes found
514                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".$UPDATE_NOTES."</div>");
515                                         $UPDATE_NOTES = "";
516                                 } elseif ($ver == "0.0") {
517                                         // Initial release
518                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".INITIAL_RELEASE."</div>");
519                                 } else {
520                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br /><I>".NO_UPDATE_NOTES."</I></div>");
521                                 }
522                         } // END - if
523
524                         // In real-mode execute any existing includes
525                         if ((!$dry_run) && (count($INC_POOL) > 0)) {
526                                 // Include all files
527                                 foreach ($INC_POOL as $fqfn) {
528                                         require_once($fqfn);
529                                 } // END - foreach
530                         } // END - if
531
532                         // Run SQLs
533                         if ((is_array($SQLs)) && (!$dry_run)) {
534                                 // Run SQL commands
535                                 foreach ($SQLs as $sql)
536                                 {
537                                         $sql = trim($sql);
538                                         if (!empty($sql))
539                                         {
540                                                 // Do we have an "ALTER TABLE" command?
541                                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
542                                                         // Analyse the alteration command
543                                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
544                                                 } else {
545                                                         // Run regular SQL command
546                                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
547                                                 }
548                                         }
549                                 }
550                         } elseif (GET_EXT_VERSION("sql_patches") == "") {
551                                 // Remove SQLs if extension is not installed
552                                 $SQLs = array();
553                         }
554                 } // END - for
555
556                 if (!$dry_run) {
557                         // In normal mode insert task and update extension's version...
558                         $ext_subj = "[UPDATE-".$ext_name."-".$EXT_VERSION.":] ".ADMIN_UPDATE_EXT_SUBJ;
559
560                         // Create task
561                         CREATE_EXTENSION_UPDATE_TASK(GET_CURRENT_ADMIN_ID(), $ext_subj, addslashes($NOTES));
562
563                         // Update extension's version
564                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
565                                 array($EXT_VERSION, $ext_name), __FILE__, __LINE__);
566
567                         // Remove array
568                         unset($SQLs);
569
570                         // Run filters on success extension update
571                         RUN_FILTER('extension_update', $ext_name);
572                 } else {
573                         // In "dry-run" mode return array with SQL commands
574                         return $SQLs;
575                 }
576         }
577 }
578
579 // Output verbose SQL table for extension
580 function EXTENSION_VERBOSE_TABLE ($queries = array(), $title = ADMIN_SQLS_EXECUTED_ON_REMOVAL, $dashed = "", $switch = false, $width = "480") {
581         global $_CONFIG, $SQLs;
582
583         // Are there some queries in $queries?
584         if (count($queries) > 0) {
585                 // Then use them instead!
586                 $SQLs = $queries;
587         } // END - if
588
589         // Init variables
590         $S = false; $SW = 2; $i = 1;
591         $OUT = "";
592
593         // Do we have queries?
594         if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && ($_CONFIG['verbose_sql'] == "Y")) {
595                 $OUT  = "<div align=\"center\">
596 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"".$width."\" align=\"center\"".$dashed.">
597 <tr>
598   <td colspan=\"2\" align=\"center\" class=\"admin_title bottom2\" height=\"24\">
599     <strong>".$title.":</strong>
600   </td>
601 </tr>\n";
602                 foreach ($SQLs as $idx => $sql) {
603                         $sql = trim($sql);
604                         if (!empty($sql)) {
605                                 $S = true;
606                                 $OUT .= "<tr>
607   <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 2px\" width=\"30\">".$i.".</td>
608   <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 5px; padding-right: 5px\">
609     ".$sql."
610   </td>
611 </tr>\n";
612                                 if ($switch) $SW = 3 - $SW;
613                                 $i++;
614                         }
615                 }
616         }
617
618         if ((!$S) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && ($_CONFIG['verbose_sql'] == "Y")) {
619                 // No addional SQL commands to run
620                 $OUT .= "<tr>
621   <td colspan=\"2\" align=\"center\" class=\"switch_sw2 bottom2\" height=\"24\">
622     <font class=\"admin_note\">".ADMIN_NO_ADDIONAL_SQLS."</font>
623   </td>
624 </tr>\n";
625         }
626
627         if (!empty($OUT)) {
628                 // Add missing close-table tag
629                 $OUT .= "</table>
630 </div>\n";
631         }
632
633         // Return output
634         return $OUT;
635 }
636
637 // Get extension name from id
638 function GET_EXT_NAME ($ext_id) {
639         global $cacheArray, $_CONFIG;
640
641         // Init extension name
642         $ret = "";
643
644         // Is cache there?
645         if (!empty($cacheArray['extensions']['ext_name'][$ext_id])) {
646                 // Load from cache
647                 $ret = $cacheArray['extensions']['ext_name'][$ext_id];
648
649                 // Count cache hits
650                 if (isset($_CONFIG['cache_hits'])) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
651         } elseif (!EXT_IS_ACTIVE("cache")) {
652                 // Load from database
653                 $result = SQL_QUERY_ESC("SELECT ext_name FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
654                         array(bigintval($ext_id)), __FILE__, __LINE__);
655                 list($ret) = SQL_FETCHROW($result);
656                 SQL_FREERESULT($result);
657         }
658         return $ret;
659 }
660
661 // Get extension id from name
662 function GET_EXT_ID ($ext_name) {
663         global $cacheArray, $_CONFIG;
664
665         // Init ID number
666         $ret = 0;
667         if (isset($cacheArray['extensions']['ext_id'][$ext_name])) {
668                 // Load from cache
669                 $ret = $cacheArray['extensions']['ext_id'][$ext_name];
670
671                 // Count cache hits
672                 if (isset($_CONFIG['cache_hits'])) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
673         } elseif (!EXT_IS_ACTIVE("cache")) {
674                 // Load from database
675                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
676                         array($ext_name), __FILE__, __LINE__);
677                 list($ret) = SQL_FETCHROW($result);
678                 SQL_FREERESULT($result);
679         }
680
681         // Return value
682         return $ret;
683 }
684
685 // Activate given extension
686 function ACTIVATE_EXTENSION ($ext_name) {
687         // Activate the extension
688         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
689                 array($ext_name), __FILE__, __LINE__);
690
691         // Extension has been activated?
692         if (SQL_AFFECTEDROWS() == 1) {
693                 // Then run all queries
694                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
695         } // END - if
696 }
697
698 // Deactivate given extension
699 function DEACTIVATE_EXTENSION($ext_name) {
700         // Activate the extension
701         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='N' WHERE ext_name='%s' LIMIT 1",
702                 array($ext_name), __FILE__, __LINE__);
703
704         // Extension has been activated?
705         if (SQL_AFFECTEDROWS() == 1) {
706                 // Then run all queries
707                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "deactivate");
708
709                 // Create new task
710                 CREATE_EXTENSION_DEACTIVATION_TASK($ext_name);
711
712                 // Notify the admin
713                 SEND_ADMIN_NOTIFICATION(ADMIN_SUBJECT_EXTENSION_DEACTIVATED, "admin_ext_deactivated", array('ext_name' => $ext_name));
714         } // END - if
715 }
716
717 // Checks wether the extension is older than given
718 function EXT_VERSION_IS_OLDER ($ext_name, $ext_ver) {
719         // Get current extension version
720         $currVersion = GET_EXT_VERSION($ext_name);
721
722         // Remove all dots from both versions
723         $currVersion = str_replace(".", "", $currVersion);
724         $ext_ver = str_replace(".", "", $ext_ver);
725
726         // Now compare both and return the result
727         return ($currVersion < $ext_ver);
728 }
729
730 // Creates a new task for updated extension
731 function CREATE_EXTENSION_UPDATE_TASK ($admin_id, $subject, $notes) {
732         // Check if task is not there
733         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE subject='%s' LIMIT 1",
734                 array($subject), __FILE__, __LINE__);
735         if (SQL_NUMROWS($result) == 0) {
736                 // Task not created so it's a brand-new extension which we need to register and create a task for!
737                 $result = 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())",
738                         array($admin_id, $subject, $notes), __FILE__, __LINE__);
739         } // END - if
740
741         // Free memory
742         SQL_FREERESULT($result);
743 }
744
745 // Creates a new task for newly installed extension
746 function CREATE_NEW_EXTENSION_TASK ($admin_id, $subject, $ext) {
747         // Not installed and do we have created a task for the admin?
748         $result = SQL_QUERY_ESC("SELECT `id` FROM `"._MYSQL_PREFIX."_task_system` WHERE `subject` LIKE '%s%%' LIMIT 1",
749                 array($subject), __FILE__, __LINE__);
750         if ((SQL_NUMROWS($result) == 0) && (GET_EXT_VERSION($ext) == "")) {
751                 // Template file
752                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
753                         PATH,
754                         GET_LANGUAGE(),
755                         $ext
756                 );
757
758                 // Load text for task
759                 if (FILE_READABLE($tpl)) {
760                         // Load extension's own text template (HTML!)
761                         $msg = LOAD_TEMPLATE("ext_".$ext, true);
762                 } else {
763                         // Load default message
764                         $msg = LOAD_TEMPLATE("admin_new_ext", "", 0);
765                 }
766
767                 // Task not created so it's a brand-new extension which we need to register and create a task for!
768                 $result_insert = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created)
769 VALUES (%s,0,'NEW','EXTENSION','%s','%s',UNIX_TIMESTAMP())",
770                         array(
771                                 $admin_id,
772                                 $subject,
773                                 addslashes($msg),
774                         ),  __FILE__, __LINE__, true, false
775                 );
776         } // END - if
777
778         // Free memory
779         SQL_FREERESULT($result);
780 }
781
782 // Creates a task for automatically deactivated (deprecated) extension
783 function CREATE_EXTENSION_DEACTIVATION_TASK ($ext) {
784         // Create subject line
785         $subject = sprintf("[%s:] %s", $ext, TASK_SUBJ_EXTENSION_DEACTIVATED);
786
787         // Not installed and do we have created a task for the admin?
788         $result = SQL_QUERY_ESC("SELECT `id` FROM `"._MYSQL_PREFIX."_task_system` WHERE `subject` = '%s' LIMIT 1",
789                 array($subject), __FILE__, __LINE__);
790         if ((SQL_NUMROWS($result) == 0) && (GET_EXT_VERSION($ext) != "")) {
791                 // Task not created so add it
792                 $result_insert = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created)
793 VALUES (0,0,'NEW','EXTENSION_DEACTIVATION','%s','%s',UNIX_TIMESTAMP())",
794                         array(
795                                 $subject,
796                                 addslashes(LOAD_TEMPLATE("task_ext_deactivated", true, $ext)),
797                         ),  __FILE__, __LINE__, true, false
798                 );
799         } // END - if
800
801         // Free memory
802         SQL_FREERESULT($result);
803 }
804
805 //
806 ?>