Extension loader rewritten and no more needed cache elements removed
[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) {
42         global $EXT_LOADED, $_CONFIG, $CSS, $cacheMode;
43
44         // Is the extension already loaded?
45         if (isset($EXT_LOADED[$ext_name])) {
46                 // Debug message
47                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s already loaded.", $ext_name));
48                 return false;
49         }
50
51         // Construct FQFN for extension file
52         $extInclude = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
53
54         // Is the extension file NOT there?
55         if (!FILE_READABLE($extInclude)) {
56                 // Debug message
57                 DEBUG_LOG(__FUNCTION__, __LINE__, sprintf("Extension %s not found.", $ext_name));
58
59                 // Abort here
60                 return false;
61         } // END - if
62
63         // Construct FQFN for language file
64         $langInclude = sprintf("%sinc/language/%s_%s.php", PATH, $ext_name, GET_LANGUAGE());
65
66         // Is this include there?
67         if (FILE_READABLE($langInclude)) {
68                 // Then load it
69                 require($langInclude);
70         } // END - if
71
72         // Construct FQFN for functions file
73         $funcsInclude = sprintf("%sinc/libs/%s_functions.php", PATH, $ext_name);
74
75         // Is this include there?
76         if (FILE_READABLE($funcsInclude)) {
77                 // Then load it
78                 require($funcsInclude);
79         } // END - if
80
81         // Set extension load mode to nothing (default)
82         $EXT_LOAD_MODE = "";
83
84         // Include the extension file
85         require($extInclude);
86
87         // Mark it as loaded
88         $EXT_LOADED[$ext_name] = true;
89
90         // All fine!
91         return true;
92 }
93
94 //
95 function EXTENSION_REGISTER ($ext_name, $id, $dry_run=false) {
96         global $NOTES, $_CONFIG, $INC_POOL, $cacheInstance;
97
98         // This shall never do a non-admin user!
99         if (!IS_ADMIN()) return false;
100
101         // Is this extension already installed?
102         if (EXT_IS_ACTIVE($ext_name)) return false;
103
104         // We want to register an extension and registration status is by default "failed" (= false)
105         $EXT_LOAD_MODE = "register"; $ret = false; $SQLs = array();
106         $INC_POOL = array();
107
108         // By default the language prefix is the extension's name
109         // @TODO: Do we really need this one anymore? Can't we just take $ext_name and done?
110         // By default we have no failtures
111         $EXT_REPORTS_FAILURE = false;
112
113         // Generate file name
114         $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
115
116         // Does this extension exists?
117         if (FILE_READABLE($file)) {
118                 // Extension was found so we can load it in registration mode
119                 $EXT_ALWAYS_ACTIVE = "N";
120                 require($file);
121
122                 // And run possible updates
123                 $EXT_LOAD_MODE = "update"; $EXT_UPDATE_DEPENDS = "";
124                 foreach ($EXT_VER_HISTORY as $EXT_VER) {
125                         // Load extension in update mode
126                         require($file);
127
128                         // Do we have an update?
129                         if (((GET_EXT_VERSION("sql_patches") != "") && ($_CONFIG['verbose_sql'] == "Y")) || (!EXT_IS_ACTIVE("sql_patches"))) {
130                                 if (!empty($UPDATE_NOTES)) {
131                                         // Update notes found
132                                         $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".$UPDATE_NOTES."<br /><br />\n";
133                                         $UPDATE_NOTES = "";
134                                 } elseif (($EXT_VER == "0.0") || ($EXT_VER == "0.0.0")) {
135                                         // Initial release
136                                         $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".INITIAL_RELEASE."<br /><br />\n";
137                                 } else {
138                                         // No update notes found!
139                                         $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br /><I>".NO_UPDATE_NOTES."</I><br /><br />\n";
140                                 }
141                         } // END - if
142                 } // END - foreach
143
144                 // Does this extension depends on an outstanding update of another update?
145                 if (!empty($EXT_UPDATE_DEPENDS)) {
146                         // Backup SQL commands and clear current
147                         $SQLs2 = $SQLs;
148                         $SQLs  = array();
149                         $test  = false;
150
151                         // Load required extension also in update mode
152                         $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $EXT_UPDATE_DEPENDS);
153
154                         // Check for required file
155                         if (FILE_READABLE($file)) {
156                                 // Bacup version number
157                                 $VER_BACKUP = $EXT_VERSION;
158
159                                 // Save the Parrent $EXT_ALWAYS_ACTIVE for later!
160                                 $EXT_ALWAYS_ACTIVE_PARRENT = $EXT_ALWAYS_ACTIVE;
161
162                                 // Set EXT_ALWAYS_ACTIVE for update
163                                 $EXT_ALWAYS_ACTIVE = "N";
164
165                                 // File exists so let's load it
166                                 require($file);
167
168                                 // If versions mismatch update extension first
169                                 $ext_ver = GET_EXT_VERSION($EXT_UPDATE_DEPENDS);
170
171                                 // Extension version set? If empty the extension is not registered
172                                 if (empty($ext_ver)) {
173                                         // Extension not registered so far so first load task's ID...
174                                         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE task_type='EXTENSION' AND subject LIKE '[%s:]%%' LIMIT 1",
175                                          array($EXT_UPDATE_DEPENDS), __FILE__, __LINE__);
176
177                                         // Entry found?
178                                         if (SQL_NUMROWS($result) == 1) {
179                                                 // Task found so load task's ID and register extension...
180                                                 list($task) = SQL_FETCHROW($result);
181
182                                                 // Try to register the extension
183                                                 $test = EXTENSION_REGISTER($EXT_UPDATE_DEPENDS, $task, $dry_run);
184                                         } // END - if
185
186                                         // Free result
187                                         SQL_FREERESULT($result);
188                                 } elseif ($ext_ver != $EXT_VERSION) {
189                                         // Ok, update this extension now
190                                         EXTENSION_UPDATE(basename($file), $EXT_UPDATE_DEPENDS, $ext_ver, $dry_run);
191
192                                         // All okay!
193                                         $test = true;
194                                 } else {
195                                         // Nothing to register / update before...
196                                         $test = true;
197                                 }
198
199                                 // Restore version number
200                                 $EXT_VERSION = $VER_BACKUP;
201
202                                 // Restore $EXT_ALWAYS_ACTIVE with the value from parrent
203                                 $EXT_ALWAYS_ACTIVE = $EXT_ALWAYS_ACTIVE_PARRENT;
204                         } else {
205                                 // Required file for update does not exists!
206                                 $test = true;
207                                 // But this is fine for the first time...
208                         }
209
210                         // Finally restore previous SQLs
211                         $SQLs = $SQLs2; unset($SQLs2);
212                 } else {
213                         // Does not depend on an other extension
214                         $test = true;
215                 }
216
217                 // Switch back to register mode
218                 $EXT_LOAD_MODE = "register";
219
220                 // Remains true if extension registration reports no failtures
221                 $test = ($test && !$EXT_REPORTS_FAILURE);
222
223                 // Does everthing before wents ok?
224                 if ($test) {
225                         // "Dry-run-mode" activated?
226                         if (!$dry_run) {
227                                 // Run all SQLs
228                                 foreach ($SQLs as $sql) {
229                                         // Trim spaces away which we don't need
230                                         $sql = trim($sql);
231
232                                         // Is there still an SQL query?
233                                         if (!empty($sql)) {
234                                                 // Do we have an "ALTER TABLE" command?
235                                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
236                                                         // Analyse the alteration command
237                                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
238                                                 } else {
239                                                         // Run regular SQL command
240                                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
241                                                 }
242                                         } // END - if
243                                 } // END - foreach
244
245                                 // Remove cache file(s) if extension is active
246                                 if ((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) {
247                                         //* DEBUG: */ echo __LINE__.": DESTROY!<br />\n";
248                                         // Remove cache files
249                                         if ($cacheInstance->loadCacheFile("extensions", true)) $cacheInstance->destroyCacheFile();
250                                         if ($cacheInstance->loadCacheFile("mod_reg"))          $cacheInstance->destroyCacheFile();
251                                         if ($cacheInstance->loadCacheFile("config"))           $cacheInstance->destroyCacheFile();
252                                 } // END - if
253
254                                 // Check for added include files
255                                 if (count($INC_POOL > 0)) {
256                                         // Loads every include file
257                                         foreach ($INC_POOL as $inc) {
258                                                 require_once($inc);
259                                         } // END - foreach
260
261                                         // Remove array
262                                         unset($INC_POOL);
263                                 } // END - if
264
265                                 // Register extension
266                                 $result = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_extensions (ext_name, ext_active, ext_version) VALUES ('%s','%s','%s','%s')",
267                                  array($ext_name, $EXT_ALWAYS_ACTIVE, $EXT_VERSION), __FILE__, __LINE__);
268
269                                 // Update task management
270                                 ADMIN_SOLVE_TASK($id);
271
272                                 // @TODO This causes the whole (!) menu cache being purged
273                                 CACHE_PURGE_ADMIN_MENU();
274
275                                 // In normal mode return a true on success
276                                 $ret = true;
277
278                                 // Remove SQLs
279                                 unset($SQLs);
280                         } else {
281                                 // Rewrite SQL command to keep { and } inside
282                                 foreach ($SQLs as $key => $sql) {
283                                         $sql = str_replace('{', "&#123;", str_replace('}', "&#125;", $sql));
284                                         $SQLs[$key] = $sql;
285                                 } // END - foreach
286
287                                 // In  "dry-run" mode return array with all SQL commands
288                                 $ret = $SQLs;
289
290                                 // Remove all SQL commands
291                                 unset($SQLs);
292                         }
293                 } else {
294                         // No, an error occurs while registering extension :-(
295                         $ret = false;
296                 }
297         } elseif (($id > 0) && (!empty($ext_name))) {
298                 // Remove task from system when id and extension's name is valid
299                 $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_task_system WHERE id=%s AND status='NEW' LIMIT 1",
300                  array(bigintval($id)), __FILE__, __LINE__);
301         }
302
303         // Is this the sql_patches?
304         //* DEBUG: */ echo __LINE__.":{$ext_name}/{$EXT_LOAD_MODE}<br />\n";
305         if (($ext_name == "sql_patches") && (($EXT_LOAD_MODE == "register") || ($EXT_LOAD_MODE == "remove")) && (!$dry_run) && ($test)) {
306                 // Then redirect to logout
307                 //* DEBUG: */ echo __LINE__.": LOAD!<br />\n";
308                 LOAD_URL("modules.php?module=admin&logout=1&".$EXT_LOAD_MODE."=sql_patches");
309         } // END - if
310
311         // Return status code
312         return $ret;
313 }
314 //
315 function EXTENSION_RUN_SQLS($id, $EXT_LOAD_MODE) {
316         global $cacheInstance, $_CONFIG;
317         $SQLs = array();
318
319         // Extensions are never active by default
320         $EXT_ALWAYS_ACTIVE = "N";
321
322         // By default no SQL has been executed
323         $sqlRan = false;
324
325         // This shall never do a non-admin user!
326         if (!IS_ADMIN()) return false;
327
328         // Get extension's name
329         $ext_name = GET_EXT_NAME($id);
330         if (empty($ext_name)) return false;
331
332         // Load extension in detected mode
333         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):ext_name[{$id}]={$ext_name}<br />\n";
334         $file = sprintf("%sinc/extensions/ext-%s.php", PATH, $ext_name);
335         if (FILE_READABLE($file)) {
336                 // Load the include
337                 require($file);
338         } // END - if
339
340         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):SQLs::count=".count($SQLs)."<br />\n";
341         if ((is_array($SQLs) && (sizeof($SQLs) > 0))) {
342                 // Run SQL commands...
343                 foreach ($SQLs as $sql) {
344                         // Trim spaces away which we don't need
345                         $sql = trim($sql);
346
347                         // Is there still an SQL query?
348                         if (!empty($sql)) {
349                                 // Do we have an "ALTER TABLE" command?
350                                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):SQL={$SQL}<br />\n";
351                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
352                                         // Analyse the alteration command
353                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
354                                 } else {
355                                         // Run regular SQL command
356                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
357                                 }
358
359                                 // An SQL has been executed
360                                 $sqlRan = true;
361                         } // END - if
362                 } // END - foreach
363
364                 // Removal mode?
365                 if ($EXT_LOAD_MODE == "remove") {
366                         // Delete this extension (remember to remove it from your server *before* you click on welcome!
367                         $result = SQL_QUERY_ESC("DELETE LOW_PRIORITY FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
368                          array($id), __FILE__, __LINE__);
369                 } // END - if
370
371                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>):mode={$EXT_LOAD_MODE}<br />\n";
372
373                 // Is this the sql_patches?
374                 //* DEBUG: */ echo __LINE__.": {$id}/{$ext_name}/{$EXT_LOAD_MODE}<br />\n";
375                 if (($ext_name == "sql_patches") && (($EXT_LOAD_MODE == "register") || ($EXT_LOAD_MODE == "remove"))) {
376                         // Then redirect to logout
377                         //* DEBUG: */ echo __LINE__.": LOAD!<br />\n";
378                         LOAD_URL("modules.php?module=admin&logout=1&".$EXT_LOAD_MODE."=sql_patches");
379                 } // END - if
380         } // END - if
381
382         // Remove cache file(s) if extension is active
383         if (((EXT_IS_ACTIVE("cache")) || (GET_EXT_VERSION("cache") != "")) && (((SQL_AFFECTEDROWS() == 1)) || ($sqlRan === true) || ($EXT_LOAD_MODE == "activate") || ($EXT_LOAD_MODE == "deactivate"))) {
384                 //* DEBUG: */ echo __LINE__.": DESTROY!<br />\n";
385                 // Remove cache files
386                 if ($cacheInstance->loadCacheFile("extensions", true)) $cacheInstance->destroyCacheFile();
387                 if ($cacheInstance->loadCacheFile("mod_reg"))    $cacheInstance->destroyCacheFile();
388                 if ($cacheInstance->loadCacheFile("config"))     $cacheInstance->destroyCacheFile();
389
390                 // @TODO This causes the whole (!) menu cache being purged
391                 CACHE_PURGE_ADMIN_MENU();
392         } // END - if
393 }
394 // Check if given extension is active
395 function EXT_IS_ACTIVE ($ext_name) {
396         global $cacheArray, $_CONFIG;
397
398         // Extensions are all inactive during installation
399         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing')) || (empty($ext_name))) return false;
400
401         // Not active is the default
402         $active = "N";
403
404         // Check cache
405         if (!empty($cacheArray['extensions']['ext_active'][$ext_name])) {
406                 // Load from cache
407                 //* DEBUG: */ echo "CACHE! ext_name={$ext_name}<br />\n";
408                 $active = $cacheArray['extensions']['ext_active'][$ext_name];
409
410                 // Count cache hits
411                 if (isset($_CONFIG['cache_hits'])) $_CONFIG['cache_hits']++;
412         } elseif (($ext_name == "cache") || (GET_EXT_VERSION("cache") == "")) {
413                 //* DEBUG: */ echo "DB! ext_name={$ext_name}<br />\n";
414                 // Load from database
415                 $result = SQL_QUERY_ESC("SELECT ext_active FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
416                  array($ext_name), __FILE__, __LINE__);
417                 if (SQL_NUMROWS($result) == 0) {
418                         // Extension was not found!
419                         return false;
420                 }
421
422                 // Load entry
423                 list($active) = SQL_FETCHROW($result);
424
425                 // Free result
426                 SQL_FREERESULT($result);
427
428
429                 // Write cache array
430                 //* DEBUG: */ echo $ext_name."[DB]: {$active}<br />\n";
431                 $cacheArray['extensions']['ext_active'][$ext_name] = $active;
432         } else {
433                 // Extension not active!
434                 //* DEBUG: */ echo $ext_name.": Not active!<br />\n";
435                 $cacheArray['extensions']['ext_active'][$ext_name] = "N";
436         }
437
438         // Debug message
439         //* DEBUG: */ DEBUG_LOG(__FUNCTION__, __LINE__, " ext_name={$ext_name},active={$active}");
440
441         // Is this extension activated? (For admins we always have active extensions...)
442         return ($active == "Y");
443 }
444 // Get version from extensions
445 function GET_EXT_VERSION ($ext_name) {
446         global $cacheArray, $_CONFIG, $cacheInstance;
447         $ret = false;
448
449         // Extensions are all inactive during installation
450         if ((!isBooleanConstantAndTrue('mxchange_installed')) || (isBooleanConstantAndTrue('mxchange_installing'))) return "";
451         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ext_name={$ext_name}<br />\n";
452
453         // Is the cache written?
454         if (!empty($cacheArray['extensions']['ext_version'][$ext_name])) {
455                 // Load data from cache
456                 //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): CACHE!<br />\n";
457                 $ret = $cacheArray['extensions']['ext_version'][$ext_name];
458
459                 // Count cache hits
460                 if (isset($_CONFIG['cache_hits'])) $_CONFIG['cache_hits']++; else $_CONFIG['cache_hits'] = 1;
461         } elseif (!is_object($cacheInstance)) {
462                 // Load from database
463                 $result = SQL_QUERY_ESC("SELECT ext_version FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
464                  array($ext_name), __FILE__, __LINE__);
465                 list($ret) = SQL_FETCHROW($result);
466                 SQL_FREERESULT($result);
467
468                 // Set cache
469                 $cacheArray['extensions']['ext_version'][$ext_name] = $ret;
470         }
471
472         // Return result
473         //* DEBUG: */ print __FUNCTION__."(<font color=\"#0000aa\">".__LINE__."</font>): ret={$ret}<br />\n";
474         return $ret;
475 }
476 //
477 function EXTENSION_UPDATE($file, $ext, $EXT_VER, $dry_run=false)
478 {
479         // This shall never do a non-admin user!
480         global $cacheInstance, $_CONFIG, $NOTES;
481
482         // Init arrays
483         $SQLs = array(); $INC_POOL = array();
484
485         // Only admins are allowed to update extensions
486         if ((!IS_ADMIN()) || (empty($ext))) return false;
487
488         // Load extension in update mode
489         $EXT_LOAD_MODE = "update"; $EXT_UPDATE_DEPENDS = ""; $NOTES = "";
490
491         // Load extension file
492         include(sprintf("%sinc/extensions/%s", PATH, $file));
493
494         if (!empty($EXT_UPDATE_DEPENDS)) {
495                 // Update another extension first!
496                 $test = EXTENSION_UPDATE(("ext-".$EXT_UPDATE_DEPENDS.".php"), $EXT_UPDATE_DEPENDS, GET_EXT_VERSION($EXT_UPDATE_DEPENDS), $dry_run);
497         }
498
499         // Check if version is updated
500         if ((($EXT_VERSION != $EXT_VER) || ($dry_run)) && (is_array($EXT_VER_HISTORY)))
501         {
502                 // Search for starting point
503                 $start = array_search($EXT_VER, $EXT_VER_HISTORY);
504                 $NOTES = "";
505
506                 // And load SQL queries in order of version history
507                 for ($idx = ($start + 1); $idx < sizeof($EXT_VER_HISTORY); $idx++)
508                 {
509                         // Remove old SQLs array to prevent possible bugs
510                         if (!$dry_run) { unset($SQLs); $SQLs = array(); }
511
512                         // Set version
513                         $EXT_VER = $EXT_VER_HISTORY[$idx];
514
515                         // Include again...
516                         include(PATH."inc/extensions/".$file);
517
518                         // Add notes
519                         if ($_CONFIG['verbose_sql'] == "Y")
520                         {
521                                 $EXT_VER = $EXT_VER_HISTORY[$idx];
522                                 if (!empty($UPDATE_NOTES))
523                                 {
524                                         // Update notes found
525                                         $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".$UPDATE_NOTES."<br /><br />\n";
526                                         $UPDATE_NOTES = "";
527                                 }
528                                  elseif ($EXT_VER == "0.0")
529                                 {
530                                         // Initial release
531                                         $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br />".INITIAL_RELEASE."<br /><br />\n";
532                                 }
533                                  else
534                                 {
535                                         $NOTES .= "<STRONG>v".$EXT_VER.":</STRONG><br /><I>".NO_UPDATE_NOTES."</I><br /><br />\n";
536                                 }
537                         }
538
539                         // In real-mode execute any existing includes
540                         if ((!$dry_run) && (count($INC_POOL) > 0)) {
541                                 // Include all files
542                                 foreach ($INC_POOL as $fqfn) {
543                                         require_once($fqfn);
544                                 } // END - foreach
545                         } // END - if
546
547                         // Run SQLs
548                         if ((is_array($SQLs)) && (!$dry_run)) {
549                                 // Run SQL commands
550                                 foreach ($SQLs as $sql)
551                                 {
552                                         $sql = trim($sql);
553                                         if (!empty($sql))
554                                         {
555                                                 // Do we have an "ALTER TABLE" command?
556                                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
557                                                         // Analyse the alteration command
558                                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
559                                                 } else {
560                                                         // Run regular SQL command
561                                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
562                                                 }
563                                         }
564                                 }
565                         } elseif (GET_EXT_VERSION("sql_patches") == "") {
566                                 // Remove SQLs if extension is not installed
567                                 $SQLs = array();
568                         }
569                 }
570
571                 if (!$dry_run)
572                 {
573                         // In normal mode insert task and update extension's version...
574                         $ext_subj = "[UPDATE-".$ext."-".$EXT_VERSION.":] ".ADMIN_UPDATE_EXT_SUBJ;
575
576                         // Create task
577                         CREATE_EXTENSION_UPDATE_TASK(GET_ADMIN_ID(get_session('admin_login')), $ext_subj, addslashes($NOTES));
578
579                         // Update extension's version
580                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
581                          array($EXT_VERSION, $ext), __FILE__, __LINE__);
582
583                         // Update cache
584                         if (EXT_IS_ACTIVE("cache")) {
585                                 if ($cacheInstance->loadCacheFile("extensions", true)) $cacheInstance->destroyCacheFile();
586                                 if ($cacheInstance->loadCacheFile("config")) $cacheInstance->destroyCacheFile();
587                                 if ($cacheInstance->loadCacheFile("mod_reg")) $cacheInstance->destroyCacheFile();
588                         } // END - if
589
590                         // Remove array
591                         unset($SQLs);
592                 } else {
593                         // In "dry-run" mode return array with SQL commands
594                         return $SQLs;
595                 }
596         }
597 }
598
599 // Output verbose SQL table for extension
600 function EXTENSION_VERBOSE_TABLE($SQLs, $title = ADMIN_SQLS_EXECUTED_ON_REMOVAL, $dashed = "", $switch = false, $WIDTH = "480") {
601         global $_CONFIG;
602
603         $S = false; $SW = 2; $i = 1;
604         $OUT = "";
605         if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && ($_CONFIG['verbose_sql'] == "Y")) {
606                 $OUT  = "<DIV align=\"center\">
607 <TABLE border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"".$WIDTH."\" align=\"center\"".$dashed.">
608 <TR>
609   <TD colspan=\"2\" align=\"center\" class=\"admin_title bottom2\" height=\"24\">
610     <STRONG>".$title.":</STRONG>
611   </TD>
612 </TR>\n";
613                 foreach ($SQLs as $idx => $sql) {
614                         $sql = trim($sql);
615                         if (!empty($sql)) {
616                                 $S = true;
617                                 $OUT .= "<TR>
618   <TD class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 2px\" width=\"30\">".$i.".</TD>
619   <TD class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 5px; padding-right: 5px\">
620     ".$sql."
621   </TD>
622 </TR>\n";
623                                 if ($switch) $SW = 3 - $SW;
624                                 $i++;
625                         }
626                 }
627         }
628
629         if ((!$S) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && ($_CONFIG['verbose_sql'] == "Y")) {
630                 // No addional SQL commands to run
631                 $OUT .= "<TR>
632   <TD colspan=\"2\" align=\"center\" class=\"switch_sw2 bottom2\" height=\"24\">
633     <FONT class=\"admin_note\">".ADMIN_NO_ADDIONAL_SQLS."</FONT>
634   </TD>
635 </TR>\n";
636         }
637
638         if (!empty($OUT)) {
639                 // Add missing close-table tag
640                 $OUT .= "</TABLE>
641 </DIV>\n";
642         }
643
644         // Return output
645         return $OUT;
646 }
647
648 // Get extension name from id
649 function GET_EXT_NAME ($id) {
650         $ret = "";
651         global $cacheArray, $_CONFIG;
652         if (!empty($cacheArray['extensions']['ext_name'][$id])) {
653                 // Load from cache
654                 $ret = $cacheArray['extensions']['ext_name'][$id];
655
656                 // Count cache hits
657                 if (isset($_CONFIG['cache_hits'])) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
658         } elseif (!EXT_IS_ACTIVE("cache")) {
659                 // Load from database
660                 $result = SQL_QUERY_ESC("SELECT ext_name FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
661                  array(bigintval($id)), __FILE__, __LINE__);
662                 list($ret) = SQL_FETCHROW($result);
663                 SQL_FREERESULT($result);
664         }
665         return $ret;
666 }
667
668 // Get extension id from name
669 function GET_EXT_ID($name) {
670         $ret = 0;
671         global $cacheArray, $_CONFIG;
672         if (isset($cacheArray['extensions']['ext_id'][$name])) {
673                 // Load from cache
674                 $ret = $cacheArray['extensions']['ext_id'][$name];
675
676                 // Count cache hits
677                 if (isset($_CONFIG['cache_hits'])) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
678         } elseif (!EXT_IS_ACTIVE("cache")) {
679                 // Load from database
680                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
681                  array($name), __FILE__, __LINE__);
682                 list($ret) = SQL_FETCHROW($result);
683                 SQL_FREERESULT($result);
684         }
685
686         // Return value
687         return $ret;
688 }
689
690 // Activate given extension
691 function ACTIVATE_EXTENSION($ext_name) {
692         // Activate the extension
693         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
694                 array($ext_name), __FILE__, __LINE__);
695
696         // Extension has been activated?
697         if (SQL_AFFECTEDROWS() == 1) {
698                 // Then run all queries
699                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
700         } // END - if
701 }
702
703 // Checks wether the extension is older than given
704 function EXT_VERSION_IS_OLDER ($ext_name, $ext_ver) {
705         // Get current extension version
706         $currVersion = GET_EXT_VERSION($ext_name);
707
708         // Remove all dots from both versions
709         $currVersion = str_replace(".", "", $currVersion);
710         $ext_ver = str_replace(".", "", $ext_ver);
711
712         // Now compare both and return the result
713         return ($currVersion < $ext_ver);
714 }
715 //
716 ?>