SQL removal list table is now 100%, SQL error in ext-bonus fixed (thanks to schatty)
[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") != "") && (getConfig('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 (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
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 (getConfig('cache_hits') > 0) $_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, $EXT_VER_HISTORY;
475         global $EXT_UPDATE_DEPENDS, $EXT_VERSION;
476
477         // Init arrays
478         $SQLs = array(); $INC_POOL = array();
479
480         // Only admins are allowed to update extensions
481         if ((!IS_ADMIN()) || (empty($ext_name))) return false;
482
483         // Load extension in update mode
484         LOAD_EXTENSION($ext_name, "update". $ext_ver, $dry_run);
485
486         if (!empty($EXT_UPDATE_DEPENDS)) {
487                 // Update another extension first!
488                 $test = EXTENSION_UPDATE(("ext-".$EXT_UPDATE_DEPENDS.".php"), $EXT_UPDATE_DEPENDS, GET_EXT_VERSION($EXT_UPDATE_DEPENDS), $dry_run);
489         }
490
491         // Save version history
492         $history = $EXT_VER_HISTORY;
493
494         // Check if version is updated
495         if ((($EXT_VERSION != $ext_ver) || ($dry_run)) && (is_array($history))) {
496                 // Search for starting point
497                 $start = array_search($ext_ver, $history);
498                 $NOTES = "";
499
500                 // And load SQL queries in order of version history
501                 for ($idx = ($start + 1); $idx < sizeof($history); $idx++) {
502                         // Remove old SQLs array to prevent possible bugs
503                         if (!$dry_run) { unset($SQLs); $SQLs = array(); }
504
505                         // Set extension version
506                         $ver = $history[$idx];
507
508                         // Load again...
509                         LOAD_EXTENSION($ext_name, "update", $ver, $dry_run);
510
511                         // Add notes
512                         if (getConfig('verbose_sql') == "Y") {
513                                 if (!empty($UPDATE_NOTES)) {
514                                         // Update notes found
515                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".$UPDATE_NOTES."</div>");
516                                         $UPDATE_NOTES = "";
517                                 } elseif ($ver == "0.0") {
518                                         // Initial release
519                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br />".INITIAL_RELEASE."</div>");
520                                 } else {
521                                         $NOTES .= ("<div class=\"update_notes\"><strong>v".$ver.":</strong><br /><I>".NO_UPDATE_NOTES."</I></div>");
522                                 }
523                         } // END - if
524
525                         // In real-mode execute any existing includes
526                         if ((!$dry_run) && (count($INC_POOL) > 0)) {
527                                 // Include all files
528                                 foreach ($INC_POOL as $fqfn) {
529                                         require_once($fqfn);
530                                 } // END - foreach
531                         } // END - if
532
533                         // Run SQLs
534                         if ((is_array($SQLs)) && (!$dry_run)) {
535                                 // Run SQL commands
536                                 foreach ($SQLs as $sql)
537                                 {
538                                         $sql = trim($sql);
539                                         if (!empty($sql))
540                                         {
541                                                 // Do we have an "ALTER TABLE" command?
542                                                 if (substr(strtolower($sql), 0, 11) == "alter table") {
543                                                         // Analyse the alteration command
544                                                         SQL_ALTER_TABLE($sql, __FILE__, __LINE__);
545                                                 } else {
546                                                         // Run regular SQL command
547                                                         $result = SQL_QUERY($sql, __FILE__, __LINE__, false);
548                                                 }
549                                         }
550                                 }
551                         } elseif (GET_EXT_VERSION("sql_patches") == "") {
552                                 // Remove SQLs if extension is not installed
553                                 $SQLs = array();
554                         }
555                 } // END - for
556
557                 if (!$dry_run) {
558                         // In normal mode insert task and update extension's version...
559                         $ext_subj = "[UPDATE-".$ext_name."-".$EXT_VERSION.":] ".ADMIN_UPDATE_EXT_SUBJ;
560
561                         // Create task
562                         CREATE_EXTENSION_UPDATE_TASK(GET_CURRENT_ADMIN_ID(), $ext_subj, addslashes($NOTES));
563
564                         // Update extension's version
565                         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_version='%s' WHERE ext_name='%s' LIMIT 1",
566                                 array($EXT_VERSION, $ext_name), __FILE__, __LINE__);
567
568                         // Remove array
569                         unset($SQLs);
570
571                         // Run filters on success extension update
572                         RUN_FILTER('extension_update', $ext_name);
573                 } else {
574                         // In "dry-run" mode return array with SQL commands
575                         return $SQLs;
576                 }
577         }
578 }
579
580 // Output verbose SQL table for extension
581 function EXTENSION_VERBOSE_TABLE ($queries = array(), $title = ADMIN_SQLS_EXECUTED_ON_REMOVAL, $dashed = "", $switch = false, $width = "100%") {
582         global $_CONFIG, $SQLs;
583
584         // Are there some queries in $queries?
585         if (count($queries) > 0) {
586                 // Then use them instead!
587                 $SQLs = $queries;
588         } // END - if
589
590         // Init variables
591         $S = false; $SW = 2; $i = 1;
592         $OUT = "";
593
594         // Do we have queries?
595         if ((is_array($SQLs)) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
596                 $OUT  = "<div align=\"center\">
597 <table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"".$width."\" align=\"center\"".$dashed.">
598 <tr>
599   <td colspan=\"2\" align=\"center\" class=\"admin_title bottom2\" height=\"24\">
600     <strong>".$title.":</strong>
601   </td>
602 </tr>\n";
603                 foreach ($SQLs as $idx => $sql) {
604                         $sql = trim($sql);
605                         if (!empty($sql)) {
606                                 $S = true;
607                                 $OUT .= "<tr>
608   <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 2px\" width=\"30\">".$i.".</td>
609   <td class=\"switch_sw".(3 - $SW)." bottom2\" style=\"padding-left: 5px; padding-right: 5px\">
610     ".$sql."
611   </td>
612 </tr>\n";
613                                 if ($switch) $SW = 3 - $SW;
614                                 $i++;
615                         }
616                 }
617         }
618
619         if ((!$S) && (GET_EXT_VERSION("sql_patches") >= "0.0.7") && (getConfig('verbose_sql') == "Y")) {
620                 // No addional SQL commands to run
621                 $OUT .= "<tr>
622   <td colspan=\"2\" align=\"center\" class=\"switch_sw2 bottom2\" height=\"24\">
623     <font class=\"admin_note\">".ADMIN_NO_ADDIONAL_SQLS."</font>
624   </td>
625 </tr>\n";
626         }
627
628         if (!empty($OUT)) {
629                 // Add missing close-table tag
630                 $OUT .= "</table>
631 </div>\n";
632         }
633
634         // Return output
635         return $OUT;
636 }
637
638 // Get extension name from id
639 function GET_EXT_NAME ($ext_id) {
640         global $cacheArray, $_CONFIG;
641
642         // Init extension name
643         $ret = "";
644
645         // Is cache there?
646         if (!empty($cacheArray['extensions']['ext_name'][$ext_id])) {
647                 // Load from cache
648                 $ret = $cacheArray['extensions']['ext_name'][$ext_id];
649
650                 // Count cache hits
651                 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
652         } elseif (!EXT_IS_ACTIVE("cache")) {
653                 // Load from database
654                 $result = SQL_QUERY_ESC("SELECT ext_name FROM "._MYSQL_PREFIX."_extensions WHERE id=%s LIMIT 1",
655                         array(bigintval($ext_id)), __FILE__, __LINE__);
656                 list($ret) = SQL_FETCHROW($result);
657                 SQL_FREERESULT($result);
658         }
659         return $ret;
660 }
661
662 // Get extension id from name
663 function GET_EXT_ID ($ext_name) {
664         global $cacheArray, $_CONFIG;
665
666         // Init ID number
667         $ret = 0;
668         if (isset($cacheArray['extensions']['ext_id'][$ext_name])) {
669                 // Load from cache
670                 $ret = $cacheArray['extensions']['ext_id'][$ext_name];
671
672                 // Count cache hits
673                 if (getConfig('cache_hits') > 0) { $_CONFIG['cache_hits']++; } else { $_CONFIG['cache_hits'] = 1; }
674         } elseif (!EXT_IS_ACTIVE("cache")) {
675                 // Load from database
676                 $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_extensions WHERE ext_name='%s' LIMIT 1",
677                         array($ext_name), __FILE__, __LINE__);
678                 list($ret) = SQL_FETCHROW($result);
679                 SQL_FREERESULT($result);
680         }
681
682         // Return value
683         return $ret;
684 }
685
686 // Activate given extension
687 function ACTIVATE_EXTENSION ($ext_name) {
688         // Activate the extension
689         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='Y' WHERE ext_name='%s' LIMIT 1",
690                 array($ext_name), __FILE__, __LINE__);
691
692         // Extension has been activated?
693         if (SQL_AFFECTEDROWS() == 1) {
694                 // Then run all queries
695                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "activate");
696         } // END - if
697 }
698
699 // Deactivate given extension
700 function DEACTIVATE_EXTENSION($ext_name) {
701         // Activate the extension
702         $result = SQL_QUERY_ESC("UPDATE "._MYSQL_PREFIX."_extensions SET ext_active='N' WHERE ext_name='%s' LIMIT 1",
703                 array($ext_name), __FILE__, __LINE__);
704
705         // Extension has been activated?
706         if (SQL_AFFECTEDROWS() == 1) {
707                 // Then run all queries
708                 EXTENSION_RUN_SQLS(GET_EXT_ID($ext_name), "deactivate");
709
710                 // Create new task
711                 CREATE_EXTENSION_DEACTIVATION_TASK($ext_name);
712
713                 // Notify the admin
714                 SEND_ADMIN_NOTIFICATION(ADMIN_SUBJECT_EXTENSION_DEACTIVATED, "admin_ext_deactivated", array('ext_name' => $ext_name));
715         } // END - if
716 }
717
718 // Checks wether the extension is older than given
719 function EXT_VERSION_IS_OLDER ($ext_name, $ext_ver) {
720         // Get current extension version
721         $currVersion = GET_EXT_VERSION($ext_name);
722
723         // Remove all dots from both versions
724         $currVersion = str_replace(".", "", $currVersion);
725         $ext_ver = str_replace(".", "", $ext_ver);
726
727         // Now compare both and return the result
728         return ($currVersion < $ext_ver);
729 }
730
731 // Creates a new task for updated extension
732 function CREATE_EXTENSION_UPDATE_TASK ($admin_id, $subject, $notes) {
733         // Check if task is not there
734         $result = SQL_QUERY_ESC("SELECT id FROM "._MYSQL_PREFIX."_task_system WHERE subject='%s' LIMIT 1",
735                 array($subject), __FILE__, __LINE__);
736         if (SQL_NUMROWS($result) == 0) {
737                 // Task not created so it's a brand-new extension which we need to register and create a task for!
738                 $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())",
739                         array($admin_id, $subject, $notes), __FILE__, __LINE__);
740         } // END - if
741
742         // Free memory
743         SQL_FREERESULT($result);
744 }
745
746 // Creates a new task for newly installed extension
747 function CREATE_NEW_EXTENSION_TASK ($admin_id, $subject, $ext) {
748         // Not installed and do we have created a task for the admin?
749         $result = SQL_QUERY_ESC("SELECT `id` FROM `"._MYSQL_PREFIX."_task_system` WHERE `subject` LIKE '%s%%' LIMIT 1",
750                 array($subject), __FILE__, __LINE__);
751         if ((SQL_NUMROWS($result) == 0) && (GET_EXT_VERSION($ext) == "")) {
752                 // Template file
753                 $tpl = sprintf("%stemplates/%s/html/ext/ext_%s.tpl",
754                         PATH,
755                         GET_LANGUAGE(),
756                         $ext
757                 );
758
759                 // Load text for task
760                 if (FILE_READABLE($tpl)) {
761                         // Load extension's own text template (HTML!)
762                         $msg = LOAD_TEMPLATE("ext_".$ext, true);
763                 } else {
764                         // Load default message
765                         $msg = LOAD_TEMPLATE("admin_new_ext", "", 0);
766                 }
767
768                 // Task not created so it's a brand-new extension which we need to register and create a task for!
769                 $result_insert = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created)
770 VALUES (%s,0,'NEW','EXTENSION','%s','%s',UNIX_TIMESTAMP())",
771                         array(
772                                 $admin_id,
773                                 $subject,
774                                 addslashes($msg),
775                         ),  __FILE__, __LINE__, true, false
776                 );
777         } // END - if
778
779         // Free memory
780         SQL_FREERESULT($result);
781 }
782
783 // Creates a task for automatically deactivated (deprecated) extension
784 function CREATE_EXTENSION_DEACTIVATION_TASK ($ext) {
785         // Create subject line
786         $subject = sprintf("[%s:] %s", $ext, TASK_SUBJ_EXTENSION_DEACTIVATED);
787
788         // Not installed and do we have created a task for the admin?
789         $result = SQL_QUERY_ESC("SELECT `id` FROM `"._MYSQL_PREFIX."_task_system` WHERE `subject` = '%s' LIMIT 1",
790                 array($subject), __FILE__, __LINE__);
791         if ((SQL_NUMROWS($result) == 0) && (GET_EXT_VERSION($ext) != "")) {
792                 // Task not created so add it
793                 $result_insert = SQL_QUERY_ESC("INSERT INTO "._MYSQL_PREFIX."_task_system (assigned_admin, userid, status, task_type, subject, text, task_created)
794 VALUES (0,0,'NEW','EXTENSION_DEACTIVATION','%s','%s',UNIX_TIMESTAMP())",
795                         array(
796                                 $subject,
797                                 addslashes(LOAD_TEMPLATE("task_ext_deactivated", true, $ext)),
798                         ),  __FILE__, __LINE__, true, false
799                 );
800         } // END - if
801
802         // Free memory
803         SQL_FREERESULT($result);
804 }
805
806 //
807 ?>