OSDN Git Service

move sqlite
[nucleus-jp/nucleus-plugins.git] / tags / sqlite0853 / sqlite / nucleus / sqlite / sqlite.php
1 <?php
2     /***************************************
3     * SQLite-MySQL wrapper for Nucleus     *
4     *                           ver 0.8.5.2*
5     * Written by Katsumi                   *
6     ***************************************/
7 //
8 //  The licence of this script is GPL
9 //
10 //                ACKOWLEDGMENT
11 //
12 //  I thank all the people of Nucleus JP forum 
13 //  who discussed this project. Especially, I 
14 //  thank kosugiatkips, mekyo, and nakahara21 
15 //  for ideas of some part of code.
16 //  I also thank Jon Jensen for his generous
17 //  acceptance for using his PHP code in this
18 //  script.
19 //
20 //  The features that are supported by this script but not
21 //  generally by SQLite are as follows:
22 //
23 //  CREATE TABLE IF NOT EXISTS, auto_increment,
24 //  DROP TABLE IF EXISTS, ALTER TABLE, 
25 //  INSERT INTO ... SET xx=xx, xx=xx,
26 //  REPLACE INTO ... SET xx=xx, xx=xx,
27 //  SHOW KEYS FROM, SHOW INDEX FROM,
28 //  SHOW FIELDS FROM, SHOW COLUMNS FROM,
29 //  CREATE TABLE ... KEYS xxx (xxx,xxx)
30 //  SHOW TABLES LIKE, TRUNCATE TABLE
31 //  SHOW TABLES
32 //
33 // Release note:
34 //  Version 0.8.0
35 //    -This is the first established version and
36 //     exactly the same as ver 0.7.8b.
37 //
38 //  Version 0.8.1
39 //    -Execute "PRAGMA short_column_names=1" first.
40 //    -Avoid executing outside php file in some very specfic environment.
41 //    -Avoid executing multiple queries using ";" as delimer.
42 //    -Add check routine for the installed SQLite
43 //
44 //  Version 0.8.5
45 //    -Use SQLite_Functions class
46 //    -'PRAGMA synchronous = off;' when installing
47
48 // Check SQLite installed
49
50 if (!function_exists('sqlite_open')) exit('Sorry, SQLite is not installed in the server.');
51
52 // Initializiation stuff
53 require_once dirname(__FILE__) . '/sqliteconfig.php';
54 $SQLITE_DBHANDLE=sqlite_open($SQLITECONF['DBFILENAME']);
55 require_once dirname(__FILE__) . '/sqlitequeryfunctions.php';
56 $SQLITECONF['VERSION']='0.8.5';
57
58 //Following thing may work if MySQL is NOT installed in server.
59 if (!function_exists('mysql_query')) {
60         define ("MYSQL_ASSOC", SQLITE_ASSOC);
61         define ("MYSQL_BOTH", SQLITE_BOTH);
62         define ("MYSQL_NUM", SQLITE_NUM);
63         function mysql_connect(){
64                 global $SQLITECONF;
65                 $SQLITECONF['OVERRIDEMODE']=true;
66                 $args=func_get_args();
67                 return call_user_func_array('nucleus_mysql_connect',$args);
68         }
69         foreach (array('mysql_affected_rows','mysql_change_user','mysql_client_encoding','mysql_close',
70                 'mysql_create_db','mysql_data_seek','mysql_db_name','mysql_db_query','mysql_drop_db','mysql_errno',
71                 'mysql_error','mysql_escape_string','mysql_fetch_array','mysql_fetch_assoc','mysql_fetch_field','mysql_fetch_lengths',
72                 'mysql_fetch_object','mysql_fetch_row','mysql_field_flags','mysql_field_len','mysql_field_name','mysql_field_seek',
73                 'mysql_field_table','mysql_field_type','mysql_free_result','mysql_get_client_info','mysql_get_host_info',
74                 'mysql_get_proto_info','mysql_get_server_info','mysql_info','mysql_insert_id','mysql_list_dbs',
75                 'mysql_list_fields','mysql_list_processes','mysql_list_tables','mysql_num_fields','mysql_num_rows','mysql_numrows',
76                 'mysql_pconnect','mysql_ping','mysql_query','mysql_real_escape_string','mysql_result','mysql_select_db',
77                 'mysql_stat','mysql_tablename','mysql_thread_id','mysql_unbuffered_query')
78                  as $value) eval(
79                 "function $value(){\n".
80                 "  \$args=func_get_args();\n".
81                 "  return call_user_func_array('nucleus_$value',\$args);\n".
82                 "}\n");
83 }
84
85 // Empty object for mysql_fetch_object().
86 class SQLITE_OBJECT {}
87
88 function sqlite_ReturnWithError($text='Not supported',$more=''){
89         // Show warning when error_reporting() is set.
90         if (!(error_reporting() & E_WARNING)) return false;
91         
92         // Seek the file and line that originally called sql function.
93         $a=debug_backtrace();
94         foreach($a as $key=>$btrace) {
95                 if (!($templine=$btrace['line'])) continue;
96                 if (!($tempfile=$btrace['file'])) continue;
97                 $file=str_replace("\\",'/',$file);
98                 if (!$line && !$file && strpos($tempfile,'/sqlite.php')===false && strpos($tempfile,'/sqlitequeryfunctions.php')===false) {
99                         $line=$templine;
100                         $file=$tempfile;
101                 }
102                 echo "\n<!--$tempfile line:$templine-->\n";
103         }
104         echo "Warning from SQLite-MySQL wrapper: $text<br />\n";
105         if ($line && $file) echo "in <b>$file</b> on line <b>$line</b><br />\n";
106         echo $more;
107         return false;
108 }
109 function sqlite_DebugMessage($text=''){
110         global $SQLITECONF;
111         if (!$SQLITECONF['DEBUGREPORT']) return;
112         if ($text) $SQLITECONF['DEBUGMESSAGE'].="\n".$text."\n";
113         if (headers_sent()) {
114                 echo '<!--sqlite_DebugMessage'.$SQLITECONF['DEBUGMESSAGE'].'sqlite_DebugMessage-->';
115                 unset($SQLITECONF['DEBUGMESSAGE']);
116         }
117 }
118
119 // nucleus_mysql_XXXX() functions follow.
120
121 function nucleus_mysql_connect($p1=null,$p2=null,$p3=null,$p4=null,$p5=null){
122         // All prameters are ignored.
123         global $SQLITE_DBHANDLE,$SQLITECONF;
124         if (!$SQLITE_DBHANDLE) $SQLITE_DBHANDLE=sqlite_open($SQLITECONF['DBFILENAME']);
125         // Initialization queries.
126         foreach($SQLITECONF['INITIALIZE'] as $value) nucleus_mysql_query($value);
127         return $SQLITE_DBHANDLE;
128 }
129
130 function nucleus_mysql_close($p1=null){
131         global $SQLITE_DBHANDLE;
132         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
133         $SQLITE_DBHANDLE='';
134         return sqlite_close ($dbhandle);
135 }
136
137 function nucleus_mysql_select_db($p1,$p2=null){
138         // SQLite does not support multiple databases in a file.
139         // So this function do nothing and always returns true.
140         // Note: mysql_select_db() function returns true/false,
141         // not link-ID.
142         return true;
143 }
144
145 function nucleus_mysql_query($p1,$p2=null,$unbuffered=false){//echo htmlspecialchars($p1)."<br />\n";
146         global $SQLITE_DBHANDLE,$SQLITECONF;
147         if (!($dbhandle=$p2)) $dbhandle=$SQLITE_DBHANDLE;
148         $query=trim($p1);
149         if (strpos($query,"\xEF\xBB\xBF")===0) $query=substr($query,3);// UTF-8 stuff
150         if (substr($query,-1)==';') $query=substr($query,0,strlen($query)-1);
151         
152         // Escape style is changed from MySQL type to SQLite type here.
153         // This is important to avoid possible SQL-injection.
154         $strpositions=array();// contains the data show where the strings are (startposition => endposition)
155         if (strpos($query,'`')!==false || strpos($query,'"')!==false || strpos($query,"'")!==false)
156                 $strpositions=sqlite_changeQuote($query);
157         //echo "<br />".htmlspecialchars($p1)."<br /><br />\n".htmlspecialchars($query)."<hr />\n";
158
159         // Debug mode
160         if ($SQLITECONF['DEBUGMODE']) $query=sqlite_mysql_query_debug($query);
161         
162         // Anyway try it.
163         if ($unbuffered) {
164                 if ($ret=@sqlite_unbuffered_query($dbhandle,$query)) return $ret;
165         } else {
166                 if ($ret=@sqlite_query($dbhandle,$query)) return $ret;
167         }
168         
169         // Error occured. Query must be translated.
170         return sqlite_mysql_query_sub($dbhandle,$query,$strpositions,$p1,$unbuffered);
171 }
172 function sqlite_mysql_query_sub($dbhandle,$query,$strpositions=array(),$p1=null,$unbuffered=false){//echo htmlspecialchars($p1)."<br />\n";
173         // Query translation is needed, especially when changing the data in database.
174         // So far, this routine is written for 'CREATE TABLE','DROP TABLE', 'INSERT INTO',
175         // 'SHOW TABLES LIKE', 'SHOW KEYS FROM', 'SHOW INDEX FROM'
176         // and several functions used in query.
177         // How about 'UPDATE' ???
178         global $SQLITE_DBHANDLE,$SQLITECONF;
179         $beforetrans=time()+microtime();
180         if (!$p1) $p1=$query;
181         $morequeries=array();
182         $uquery=strtoupper($query);
183         if (strpos($uquery,'CREATE TABLE')===0 || ($temptable=(strpos($uquery,'CREATE TEMPORARY TABLE')===0))) {
184                 if (!($i=strpos($query,'('))) return sqlite_ReturnWithError('nucleus_mysql_query: '.$p1);
185                 //check if the command is 'CREATE TABLE IF NOT EXISTS'
186                 if (strpos(strtoupper($uquery),'CREATE TABLE IF NOT EXISTS')===0) {
187                         $tablename=trim(substr($query,26,$i-26));
188                         if (substr($tablename,0,1)!="'") $tablename="'$tablename'";
189                         $res=sqlite_query($dbhandle,"SELECT tbl_name FROM sqlite_master WHERE tbl_name=$tablename LIMIT 1");
190                         if (nucleus_mysql_num_rows($res)) return true;
191                 } else {
192                         $tablename=trim(substr($query,12,$i-12));
193                         if (substr($tablename,0,1)!="'") $tablename="'$tablename'";
194                 }
195                 
196                 $query=trim(substr($query,$i+1));
197                 for ($i=strlen($query);0<$i;$i--) if ($query[$i]==')') break;
198                 $query=substr($query,0,$i);
199                 $auto_increment=false;
200                 $commands=sqlite_splitByComma($query);
201                 $query=' (';
202                 $first=true;
203                 foreach($commands as $key => $value) {
204                         if (strpos(strtolower($value),'auto_increment')==strlen($value)-14) $auto_increment=true;
205                         $isint=preg_match('/int\(([0-9]*?)\)/i',$value);
206                         $isint=$isint | preg_match('/tinyint\(([0-9]*?)\)/i',$value);
207                         $value=preg_replace('/int\(([0-9]*?)\)[\s]+unsigned/i','int($1)',$value);
208                         $value=preg_replace('/int\([0-9]*?\)[\s]+NOT NULL[\s]+auto_increment$/i',' INTEGER NOT NULL PRIMARY KEY',$value);
209                         $value=preg_replace('/int\([0-9]*?\)[\s]+auto_increment$/i',' INTEGER PRIMARY KEY',$value);
210                         if ($auto_increment) $value=preg_replace('/^PRIMARY KEY(.*?)$/i','',$value);
211                         while (preg_match('/PRIMARY KEY[\s]*\((.*)\([0-9]+\)(.*)\)/i',$value)) // Remove '(100)' from 'PRIMARY KEY (`xxx` (100))'
212                                 $value=preg_replace('/PRIMARY KEY[\s]*\((.*)\([0-9]+\)(.*)\)/i','PRIMARY KEY ($1 $2)',$value);
213                         
214                         // CREATE KEY queries for SQLite (corresponds to KEY 'xxxx'('xxxx', ...) of MySQL
215                         if (preg_match('/^FULLTEXT KEY(.*?)$/i',$value,$matches)) {
216                                 array_push($morequeries,'CREATE INDEX '.str_replace('('," ON $tablename (",$matches[1]));
217                                 $value='';
218                         } else if (preg_match('/^UNIQUE KEY(.*?)$/i',$value,$matches)) {
219                                 array_push($morequeries,'CREATE UNIQUE INDEX '.str_replace('('," ON $tablename (",$matches[1]));
220                                 $value='';
221                         } else if (preg_match('/^KEY(.*?)$/i',$value,$matches)) {
222                                 array_push($morequeries,'CREATE INDEX '.str_replace('('," ON $tablename (",$matches[1]));
223                                 $value='';
224                         }
225                         
226                         // Check if 'DEFAULT' is set when 'NOT NULL'
227                         $uvalue=strtoupper($value);
228                         if (strpos($uvalue,'NOT NULL')!==false && 
229                                         strpos($uvalue,'DEFAULT')===false &&
230                                         strpos($uvalue,'INTEGER NOT NULL PRIMARY KEY')===false) {
231                                 if ($isint) $value.=" DEFAULT 0";
232                                 else $value.=" DEFAULT ''";
233                         }
234                         
235                         if ($value) {
236                                 if ($first) $first=false;
237                                 else $query.=',';
238                                  $query.=' '.$value;
239                         }
240                 }
241                 $query.=' )';
242                 if ($temptable) $query='CREATE TEMPORARY TABLE '.$tablename.$query;
243                 else $query='CREATE TABLE '.$tablename.$query;
244                 //echo "<br />".htmlspecialchars($p1)."<br /><br />\n".htmlspecialchars($query)."<hr />\n";
245         } else if (strpos($uquery,'DROP TABLE IF EXISTS')===0) {
246                 if (!($i=strpos($query,';'))) $i=strlen($query);
247                 $tablename=trim(substr($query,20,$i-20));
248                 if (substr($tablename,0,1)!="'") $tablename="'$tablename'";
249                 $res=sqlite_query($dbhandle,"SELECT tbl_name FROM sqlite_master WHERE tbl_name=$tablename LIMIT 1");
250                 if (!nucleus_mysql_num_rows($res)) return true;
251                 $query='DROP TABLE '.$tablename;
252         } else if (strpos($uquery,'ALTER TABLE ')===0) {
253                 $query=trim(substr($query,11));
254                 if ($i=strpos($query,' ')) {
255                         $tablename=trim(substr($query,0,$i));
256                         $query=trim(substr($query,$i));
257                         $ret =sqlite_altertable($tablename,$query,$dbhandle);
258                         if (!$ret) sqlite_ReturnWithError('SQL error',"<br /><i>".nucleus_mysql_error()."</i><br />".htmlspecialchars($p1)."<br /><br />\n".htmlspecialchars("ALTER TABLE $tablename $query")."<hr />\n");
259                         return $ret;
260                 }
261                 // Syntax error
262                 $query=='DROP TABLE '.$query;
263         } else if (strpos($uquery,'INSERT INTO ')===0 || strpos($uquery,'REPLACE INTO ')===0 ||
264                         strpos($uquery,'INSERT IGNORE INTO ')===0 || strpos($uquery,'REPLACE IGNORE INTO ')===0) {
265                 $buff=str_replace(' IGNORE ',' OR IGNORE ',substr($uquery,0,($i=strpos($uquery,' INTO ')+6)));
266                 $query=trim(substr($query,$i));
267                 if ($i=strpos($query,' ')) {
268                         $buff.=trim(substr($query,0,$i+1));
269                         $query=trim(substr($query,$i));
270                 }
271                 if ($i=strpos($query,' ')) {
272                         if (strpos(strtoupper($query),'SET')===0) {
273                                 $query=trim(substr($query,3));
274                                 $commands=sqlite_splitByComma($query);
275                                 $query=' VALUES(';
276                                 $buff.=' (';
277                                 foreach($commands as $key=>$value){
278                                         //echo "[".htmlspecialchars($value)."]";
279                                         if (0<$key) {
280                                                 $buff.=', ';
281                                                 $query.=', ';
282                                         }
283                                         if ($i=strpos($value,'=')) {
284                                                 $buff.=trim(substr($value,0,$i));
285                                                 $query.=substr($value,$i+1);
286                                         }
287                                 }
288                                 $buff.=')';
289                                 $query.=')';
290                         } else {
291                                 $beforevalues='';
292                                 $commands=sqlite_splitByComma($query);
293                                 $query='';
294                                 foreach($commands as $key=>$value){
295                                         if ($beforevalues=='' && preg_match('/^(.*)\)\s+VALUES\s+\(/i',$value,$matches)) {
296                                                 $beforevalues=$buff.' '.$query.$matches[1].')';
297                                         }
298                                         if (0<$key) $query.=$beforevalues.' VALUES ';// supports multiple insertion
299                                         $query.=$value.';';
300                                 }
301                         }
302                 }
303                 $query=$buff.' '.$query;
304         } else if (strpos($uquery,'SHOW TABLES LIKE ')===0) {
305                 $query='SELECT name FROM sqlite_master WHERE type=\'table\' AND name LIKE '.substr($query,17);
306         } else if (strpos($uquery,'SHOW TABLES')===0) {
307                 $query='SELECT name FROM sqlite_master WHERE type=\'table\'';
308         } else if (strpos($uquery,'SHOW KEYS FROM ')===0) {
309                 $query=sqlite_showKeysFrom(trim(substr($query,15)),$dbhandle);
310         } else if (strpos($uquery,'SHOW INDEX FROM ')===0) {
311                 $query=sqlite_showKeysFrom(trim(substr($query,16)),$dbhandle);
312         } else if (strpos($uquery,'SHOW FIELDS FROM ')===0) {
313                 $query=sqlite_showFieldsFrom(trim(substr($query,17)),$dbhandle);
314         } else if (strpos($uquery,'SHOW COLUMNS FROM ')===0) {
315                 $query=sqlite_showFieldsFrom(trim(substr($query,18)),$dbhandle);
316         } else if (strpos($uquery,'TRUNCATE TABLE ')===0) {
317                 $query='DELETE FROM '.substr($query,15);
318         } else SQLite_Functions::sqlite_modifyQueryForUserFunc($query,$strpositions);
319
320         //Throw query again.
321         $aftertrans=time()+microtime();
322         if ($unbuffered) {
323                 $ret=sqlite_unbuffered_query($dbhandle,$query);
324         } else {
325                 $ret=sqlite_query($dbhandle,$query);
326         }
327
328         $afterquery=time()+microtime();
329         if ($SQLITECONF['MEASURESPEED']) sqlite_DebugMessage("translated query:$query\n".
330                 'translation: '.($aftertrans-$beforetrans).'sec, query: '.($afterquery-$aftertrans).'sec');
331         if (!$ret) sqlite_ReturnWithError('SQL error',"<br /><i>".nucleus_mysql_error()."</i><br />".htmlspecialchars($p1)."<br /><br />\n".htmlspecialchars($query)."<hr />\n");
332         foreach ($morequeries as $value) if ($value) @sqlite_query($dbhandle,$value);
333         return $ret;
334 }
335 function sqlite_changeQuote(&$query){
336         // This function is most important.
337         // When you modify this function, do it very carefully.
338         // Otherwise, you may allow crackers to do SQL-injection.
339         // This function returns array that shows where the strings are.
340         $sarray=array();
341         $ret='';
342         $qlen=strlen($query);
343         for ($i=0;$i<$qlen;$i++) {
344                 // Go to next quote
345                 if (($i1=strpos($query,'"',$i))===false) $i1=$qlen;
346                 if (($i2=strpos($query,"'",$i))===false) $i2=$qlen;
347                 if (($i3=strpos($query,'`',$i))===false) $i3=$qlen;
348                 if ($i1==$qlen && $i2==$qlen && $i3==$qlen) {
349                         $ret.=($temp=substr($query,$i));
350                         if (strstr($temp,';')) exit('Warning: try to use more than two queries?');
351                         break;
352                 }
353                 if ($i2<($j=$i1)) $j=$i2;
354                 if ($i3<$j) $j=$i3;
355                 $ret.=($temp=substr($query,$i,$j-$i));
356                 $c=$query[($i=$j)]; // $c keeps the type of quote.
357                 if (strstr($temp,';')) exit('Warning: try to use more than two queries?');
358                 
359                 // Check between quotes.
360                 // $j shows the begging positioin.
361                 // $i will show the ending position.
362                 $j=(++$i);
363                 while ($i<$qlen) {
364                         if (($i1=strpos($query,$c,$i))===false) $i1=$qlen;
365                         if (($i2=strpos($query,"\\",$i))===false) $i2=$qlen;
366                         if ($i2<$i1) {
367                                 // \something. Skip two characters.
368                                 $i=$i2+2;
369                                 continue;
370                         } if ($i1<($qlen-1) && $query[$i1+1]==$c) {
371                                 // "", '' or ``.  Skip two characters.
372                                 $i=$i1+2;
373                                 continue;
374                         } else {// OK. Reached the end position
375                                 $i=$i1;
376                                 break;
377                         }
378                 }
379                 $i1=strlen($ret);
380                 $ret.="'".sqlite_changeslashes(substr($query,$j,$i-$j));
381                 if ($i<$qlen) $ret.="'"; //else Syntax error in query.
382                 $i2=strlen($ret);
383                 $sarray[$i1]=$i2;
384         }//echo htmlspecialchars($query).'<br />'.htmlspecialchars($ret).'<br />';
385         $query=$ret;
386         return $sarray;
387 }
388 function sqlite_splitByComma($query) {
389         // The query is splitted by comma and the data will be put into an array.
390         // The commas in quoted strings are ignored.
391         $commands=array();
392         $i=0;
393         $in=false;
394         while ($query) {
395                 if ($query[$i]=="'") {
396                         $i++;
397                         while ($i<strlen($query)) {
398                                 if ($query[$i++]!="'") continue;
399                                 if ($query[$i]!="'") break;
400                                 $i++;
401                         }
402                         continue;
403                 } else if ($query[$i]=='(') $in=true;
404                 else if ($query[$i]==')') $in=false;
405                 else if ($query[$i]==',' && (!$in)) {
406                         $commands[]=trim(substr($query,0,$i));
407                         $query=trim(substr($query,$i+1));
408                         $i=0;
409                         continue;
410                 } // Do NOT add 'else' statement here! '$i++' is important in the following line.
411                 if (strlen($query)<=($i++)) break;
412         }
413         if ($query) $commands[]=$query;
414         return $commands;
415 }
416 function sqlite_changeslashes(&$text){
417         // By SQLite, "''" is used in the quoted string instead of "\'".
418         // In addition, only "'" seems to be allowed for perfect quotation of string.
419         // This routine is used for the conversion from MySQL type to SQL type.
420         // Do NOT use stripslashes() but use stripcslashes().  Otherwise, "\r\n" is not converted.
421         if ($text==='') return '';
422         return (sqlite_escape_string (stripcslashes((string)$text)));
423 }
424 function sqlite_altertable($table,$alterdefs,$dbhandle){
425         // This function originaly came from Jon Jensen's PHP class, SQLiteDB.
426         // There are some modifications by Katsumi.
427         $table=str_replace("'",'',$table);
428         if (!$alterdefs) return false;
429         $result = sqlite_query($dbhandle,"SELECT sql,name,type FROM sqlite_master WHERE tbl_name = '".$table."' ORDER BY type DESC");
430         if(!sqlite_num_rows($result)) return sqlite_ReturnWithError('no such table: '.$table);
431         $row = sqlite_fetch_array($result); //table sql
432         if (function_exists('microtime')) $tmpname='t'.str_replace('.','',str_replace(' ','',microtime()));
433         else $tmpname = 't'.rand(0,999999).time();
434         $origsql = trim(preg_replace("/[\s]+/"," ",str_replace(",",", ",preg_replace("/[\(]/","( ",$row['sql'],1))));
435         $createtemptableSQL = 'CREATE TEMPORARY '.substr(trim(preg_replace("'".$table."'",$tmpname,$origsql,1)),6);
436         $createindexsql = array();
437         while ($row = sqlite_fetch_array($result)) {//index sql
438                 $createindexsql[]=$row['sql'];
439         }
440         $i = 0;
441         $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY);
442         $prevword = $table;
443         $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY);
444         $newcols = array();
445         for($i=0;$i<sizeof($oldcols);$i++){
446                 $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY);
447                 $oldcols[$i] = $colparts[0];
448                 $newcols[$colparts[0]] = $colparts[0];
449         }
450         $newcolumns = '';
451         $oldcolumns = '';
452         reset($newcols);
453         while(list($key,$val) = each($newcols)){
454                 if (strtoupper($val)!='PRIMARY' && strtoupper($key)!='PRIMARY' &&
455                     strtoupper($val)!='UNIQUE'  && strtoupper($key)!='UNIQUE'){
456                         $newcolumns .= ($newcolumns?', ':'').$val;
457                         $oldcolumns .= ($oldcolumns?', ':'').$key;
458                 }
459         }
460         $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
461         $dropoldsql = 'DROP TABLE '.$table;
462         $createtesttableSQL = $createtemptableSQL;
463         foreach($defs as $def){
464                 $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY);
465                 $action = strtolower($defparts[0]);
466                 switch($action){
467                 case 'modify':
468                         // Modification does not mean anything for SQLite, so just return true.
469                         // But this command will be supported in future???
470                         break;
471                 case 'add':
472                         if(($i=sizeof($defparts)) <= 2) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error');
473                         
474                         // ignore if there is already such table
475                         $exists=false;
476                         foreach($oldcols as $value) if (str_replace("'",'',$defparts[1])==str_replace("'",'',$value)) $exists=true;
477                         if ($exists) break;
478                         
479                         // Ignore 'AFTER xxxx' statement.
480                         // Ignore 'FIRST' statement.
481                         // Maybe this feature will be supprted later.
482                         if (4<=$i && strtoupper($defparts[$i-2])=='AFTER') unset($defparts[$i-1],$defparts[$i-2]);
483                         else if (3<=$i && strtoupper($defparts[$i-1])=='FIRST') unset($defparts[$i-1]);
484                         
485                         $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
486                         for($i=1;$i<sizeof($defparts);$i++) $createtesttableSQL.=' '.$defparts[$i];
487                         $createtesttableSQL.=')';
488                         break;
489                 case 'change':
490                         if(sizeof($defparts) <= 3) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error');
491                         if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
492                                 if($newcols[$defparts[1]] != $defparts[1]){
493                                         sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
494                                         return false;
495                                 }
496                                 $newcols[$defparts[1]] = $defparts[2];
497                                 $nextcommapos = strpos($createtesttableSQL,',',$severpos);
498                                 $insertval = '';
499                                 for($i=2;$i<sizeof($defparts);$i++) $insertval.=' '.$defparts[$i];
500                                 if($nextcommapos) $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
501                                 else $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
502                         } else  return sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
503                         break;
504                 case 'drop':
505                         if(sizeof($defparts) < 2) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error');
506                         if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
507                                 $nextcommapos = strpos($createtesttableSQL,',',$severpos);
508                                 if($nextcommapos) $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
509                                 else $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
510                                 unset($newcols[$defparts[1]]);
511                         } else  return sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
512                         break;
513                 default:
514                         return sqlite_ReturnWithError('near "'.$prevword.'": syntax error');
515                         break;
516                 }
517                 $prevword = $defparts[sizeof($defparts)-1];
518         }
519
520         //this block of code generates a test table simply to verify that the columns specifed are valid in an sql statement
521         //this ensures that no reserved words are used as columns, for example
522         if (!sqlite_query($dbhandle,$createtesttableSQL)) return false;
523         $droptempsql = 'DROP TABLE '.$tmpname;
524         sqlite_query($dbhandle,$droptempsql);
525         //end block
526
527         $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
528         $newcolumns = '';
529         $oldcolumns = '';
530         reset($newcols);
531         while(list($key,$val) = each($newcols)) {
532                 if (strtoupper($val)!='PRIMARY' && strtoupper($key)!='PRIMARY' &&
533                     strtoupper($val)!='UNIQUE'  && strtoupper($key)!='UNIQUE'){
534                         $newcolumns .= ($newcolumns?', ':'').$val;
535                         $oldcolumns .= ($oldcolumns?', ':'').$key;
536                 }
537         }
538         $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
539
540         sqlite_query($dbhandle,$createtemptableSQL); //create temp table
541         sqlite_query($dbhandle,$copytotempsql); //copy to table
542         sqlite_query($dbhandle,$dropoldsql); //drop old table
543
544         sqlite_query($dbhandle,$createnewtableSQL); //recreate original table
545         foreach($createindexsql as $sql) sqlite_query($dbhandle,$sql); //recreate index
546         sqlite_query($dbhandle,$copytonewsql); //copy back to original table
547         sqlite_query($dbhandle,$droptempsql); //drop temp table
548         return true;
549 }
550 function sqlite_showKeysFrom($tname,$dbhandle) {
551         // This function is for supporing 'SHOW KEYS FROM' and 'SHOW INDEX FROM'.
552         // For making the same result as obtained by MySQL, temporary table is made.
553         $tname=str_replace("'",'',$tname);
554         
555         // Create a temporary table for making result
556         if (function_exists('microtime')) $tmpname='t'.str_replace('.','',str_replace(' ','',microtime()));
557         else $tmpname = 't'.rand(0,999999).time();
558         sqlite_query($dbhandle,"CREATE TEMPORARY TABLE $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
559                 " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')"); 
560         
561         // First, get the sql query when the table created
562         $res=sqlite_query($dbhandle,"SELECT sql FROM sqlite_master WHERE tbl_name = '$tname' ORDER BY type DESC");
563         $a=nucleus_mysql_fetch_assoc($res);
564         $tablesql=$a['sql'];
565         
566         // Check if each columns are unique
567         $notnull=array();
568         foreach(sqlite_splitByComma(substr($tablesql,strpos($tablesql,'(')+1)) as $value) {
569                 $name=str_replace("'",'',substr($value,0,strpos($value,' ')));
570                 if (strpos(strtoupper($value),'NOT NULL')!==false) $notnull[$name]='';
571                 else $notnull[$name]='YES';
572         }
573         
574         // Get the primary key (and check if it is unique???).
575         if (preg_match('/[^a-zA-Z_\']([\S]+)[^a-zA-Z_\']+INTEGER NOT NULL PRIMARY KEY/i',$tablesql,$matches)) {
576                 $pkey=str_replace("'",'',$matches[1]);
577                 $pkeynull='';
578         } else if (preg_match('/[^a-zA-Z_\']([\S]+)[^a-zA-Z_\']+INTEGER PRIMARY KEY/i',$tablesql,$matches)) {
579                 $pkey=str_replace("'",'',$matches[1]);
580                 $pkeynull='YES';
581         } else if (preg_match('/PRIMARY KEY[\s]*?\(([^\)]+)\)/i',$tablesql,$matches)) {
582                 $pkey=null;// PRIMARY KEY ('xxx'[,'xxx'])
583                 foreach(explode(',',$matches[1]) as $key=>$value) {
584                         $value=str_replace("'",'',trim($value));
585                         $key++;
586                         $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT '$value' FROM '$tname'"));
587                         sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
588                                 " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
589                                 " VALUES ('$tname', '0', 'PRIMARY', '$key',".
590                                 " '$value', 'A', '$cardinality', null, null, '', 'BTREE', '')"); 
591                 }
592         } else $pkey=null;
593         
594         // Check the index.
595         $res=sqlite_query($dbhandle,"SELECT sql,name FROM sqlite_master WHERE type = 'index' and tbl_name = '$tname' ORDER BY type DESC");
596         while ($a=nucleus_mysql_fetch_assoc($res)) {
597                 if (!($sql=$a['sql'])) {// Primary key
598                         if ($pkey && strpos(strtolower($a['name']),'autoindex')) {
599                                 $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT $pkey FROM '$tname'"));
600                                 sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
601                                         " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
602                                         " VALUES ('$tname', '0', 'PRIMARY', '1',".
603                                         " '$pkey', 'A', '$cardinality', null, null, '$pkeynull', 'BTREE', '')"); 
604                                 $pkey=null;
605                         }
606                 } else {// Non-primary key
607                         if (($name=str_replace("'",'',$a['name'])) && preg_match('/\(([\s\S]+)\)/',$sql,$matches)) {
608                                 foreach(explode(',',$matches[1]) as $key=>$value) {
609                                         $columnname=str_replace("'",'',$value);
610                                         if (strpos(strtoupper($sql),'CREATE UNIQUE ')===0) $nonunique='0';
611                                         else $nonunique='1';
612                                         $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT $columnname FROM '$tname'"));
613                                         sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
614                                                 " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
615                                                 " VALUES ('$tname', '$nonunique', '$name', '".(string)($key+1)."',".
616                                                 " '$columnname', 'A', '$cardinality', null, null, '$notnull[$columnname]', 'BTREE', '')"); 
617                                 }
618                         }
619                 }
620         }
621         if ($pkey) { // The case that the key (index) is not defined.
622                 $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT $pkey FROM '$tname'"));
623                 sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
624                         " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
625                         " VALUES ('$tname', '0', 'PRIMARY', '1',".
626                         " '$pkey', 'A', '$cardinality', null, null, '$pkeynull', 'BTREE', '')"); 
627                 $pkey=null;
628         }
629         
630         // return the final query to show the keys in MySQL style (using temporary table).
631         return "SELECT * FROM $tmpname";
632 }
633 function sqlite_showFieldsFrom($tname,$dbhandle){
634         // This function is for supporing 'SHOW FIELDS FROM' and 'SHOW COLUMNS FROM'.
635         // For making the same result as obtained by MySQL, temporary table is made.
636         $tname=str_replace("'",'',$tname);
637         
638         // First, get the sql query when the table created
639         $res=sqlite_query($dbhandle,"SELECT sql FROM sqlite_master WHERE tbl_name = '$tname' ORDER BY type DESC");
640         $a=nucleus_mysql_fetch_assoc($res);
641         $tablesql=trim($a['sql']);
642         if (preg_match('/^[^\(]+\(([\s\S]*?)\)$/',$tablesql,$matches)) $tablesql=$matches[1];
643         $tablearray=array();
644         foreach(sqlite_splitByComma($tablesql) as $value) {
645                 $value=trim($value);
646                 if ($i=strpos($value,' ')) {
647                         $name=str_replace("'",'',substr($value,0,$i));
648                         $value=trim(substr($value,$i));
649                         if (substr($value,-1)==',') $value=substr($value,strlen($value)-1);
650                         $tablearray[$name]=$value;
651                 }
652         }
653         
654         // Check if INDEX has been made for the parameter 'MUL' in 'KEY' column
655         $multi=array();
656         $res=sqlite_query($dbhandle,"SELECT name FROM sqlite_master WHERE type = 'index' and tbl_name = '$tname' ORDER BY type DESC");
657         while ($a=nucleus_mysql_fetch_assoc($res)) $multi[str_replace("'",'',$a['name'])]='MUL';
658         
659         // Create a temporary table for making result
660         if (function_exists('microtime')) $tmpname='t'.str_replace('.','',str_replace(' ','',microtime()));
661         else $tmpname = 't'.rand(0,999999).time();
662         sqlite_query($dbhandle,"CREATE TEMPORARY TABLE $tmpname ('Field', 'Type', 'Null', 'Key', 'Default', 'Extra')"); 
663         
664         // Check the table
665         foreach($tablearray as $field=>$value) {
666                 if (strtoupper($field)=='PRIMARY') continue;//PRIMARY KEY('xx'[,'xx'])
667                 $uvalue=strtoupper($value.' ');
668                 $key=(string)$multi[$field];
669                 if ($uvalue=='INTEGER NOT NULL PRIMARY KEY ' || $uvalue=='INTEGER PRIMARY KEY ') {
670                         $key='PRI';
671                         $extra='auto_increment';
672                 } else $extra='';
673                 if ($i=strpos($uvalue,' ')) {
674                         $type=substr($value,0,$i);
675                         if (strpos($type,'(') && ($i=strpos($value,')')))
676                                 $type=substr($value,0,$i+1);
677                 } else $type='';
678                 if (strtoupper($type)=='INTEGER') $type='int(11)';
679                 if (strpos($uvalue,'NOT NULL')===false) $null='YES';
680                 else {
681                         $null='';
682                         $value=preg_replace('/NOT NULL/i','',$value);
683                         $uvalue=strtoupper($value);
684                 }
685                 if ($i=strpos($uvalue,'DEFAULT')) {
686                         $default=trim(substr($value,$i+7));
687                         if (strtoupper($default)=='NULL') {
688                                 $default="";
689                                 $setdefault="";
690                         } else {
691                                 if (substr($default,0,1)=="'") $default=substr($default,1,strlen($default)-2);
692                                 $default="'".$default."',";
693                                 $setdefault="'Default',";
694                         }
695                 } else if ($null!='YES' && $extra!='auto_increment') {
696                         if (strpos(strtolower($type),'int')===false) $default="'',";
697                         else $default="'0',";
698                         $setdefault="'Default',";
699                 } else {
700                         $default="";
701                         $setdefault="";
702                 }
703                 sqlite_query($dbhandle,"INSERT INTO '$tmpname' ('Field', 'Type', 'Null', 'Key', $setdefault 'Extra')".
704                         " VALUES ('$field', '$type', '$null', '$key', $default '$extra')");
705         }
706         
707         // return the final query to show the keys in MySQL style (using temporary table).
708         return "SELECT * FROM $tmpname";
709 }
710 function sqlite_mysql_query_debug(&$query){
711         // The debug mode is so far used for checking query difference like "SELECT i.itime, ....".
712         // This must be chaged to "SELECT i.itime as itime,..." for SQLite.
713         // (This feature is not needed any more after the version 0.8.1 (see intialization query))
714         $uquery=strtoupper($query);
715         if (strpos($uquery,"SELECT ")!==0) return $query;
716         if (($i=strpos($uquery," FROM "))===false) return $query;
717         $select=sqlite_splitByComma(substr($query,7,$i-7));
718         $query=substr($query,$i);
719         $ret='';
720         foreach($select as $value){
721                 if (preg_match('/^([a-z_]+)\.([a-z_]+)$/i',$value,$matches)) {
722                         $value=$value." as ".$matches[2];
723                         $t=$matches[0]."=>$value\n";
724                         $a=debug_backtrace();
725                         foreach($a as $key=>$btrace) {
726                                 if (!($templine=$btrace['line'])) continue;
727                                 if (!($tempfile=$btrace['file'])) continue;
728                                 $tempfile=preg_replace('/[\s\S]*?[\/\\\\]([^\/\\\\]+)$/','$1',$tempfile);
729                                 $t.="$tempfile line:$templine\n";
730                         }
731                         sqlite_DebugMessage($t);
732                 }
733                 if ($ret) $ret.=', ';
734                 $ret.=$value;
735         }
736         return "SELECT $ret $query";
737 }
738
739 function nucleus_mysql_list_tables($p1=null,$p2=null) {
740         global $SQLITE_DBHANDLE,$MYSQL_DATABASE;
741         return sqlite_query($SQLITE_DBHANDLE,"SELECT name as Tables_in_$MYSQL_DATABASE FROM sqlite_master WHERE type='table'");
742 }
743 function nucleus_mysql_listtables($p1=null,$p2=null) { return nucleus_mysql_list_tables($p1,$p2);}
744
745 function nucleus_mysql_affected_rows($p1=null){
746         global $SQLITE_DBHANDLE;
747         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
748         return sqlite_changes($dbhandle);
749 }
750
751 function nucleus_mysql_error($p1=null){
752         global $SQLITE_DBHANDLE;
753         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
754         return sqlite_error_string ( sqlite_last_error ($dbhandle) );
755 }
756
757 function nucleus_mysql_fetch_array($p1,$p2=SQLITE_BOTH){
758         return sqlite_fetch_array ($p1,$p2);
759 }
760
761 function nucleus_mysql_fetch_assoc($p1){
762         return sqlite_fetch_array($p1,SQLITE_ASSOC);
763 }
764
765 function nucleus_mysql_fetch_object($p1,$p2=SQLITE_BOTH){
766         if (is_array($ret=sqlite_fetch_array ($p1,$p2))) {
767                 $o=new SQLITE_OBJECT;
768                 foreach ($ret as $key=>$value) {
769                         if (strstr($key,'.')) {// Remove table name.
770                                 $key=preg_replace('/^(.+)\."(.+)"$/','"$2"',$key);
771                                 $key=preg_replace('/^(.+)\.([^.^"]+)$/','$2',$key);
772                         }
773                         $o->$key=$value;
774                 }
775                 return $o;
776         } else return false;
777 }
778
779 function nucleus_mysql_fetch_row($p1){
780         return sqlite_fetch_array($p1,SQLITE_NUM);
781 }
782
783 function nucleus_mysql_field_name($p1,$p2){
784         return sqlite_field_name ($p1,$p2);
785 }
786
787 function nucleus_mysql_free_result($p1){
788         // ???? Cannot find corresponding function of SQLite.
789         // Maybe SQLite is NOT used for the high spec server
790         // that need mysql_free_result() function because of
791         // many SQL-queries in a script.
792         return true;
793 }
794
795 function nucleus_mysql_insert_id($p1=null){
796         global $SQLITE_DBHANDLE;
797         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
798         return sqlite_last_insert_rowid ($dbhandle);
799 }
800
801 function nucleus_mysql_num_fields($p1){
802         return sqlite_num_fields ($p1);
803 }
804
805 function nucleus_mysql_num_rows($p1){
806         return sqlite_num_rows ($p1);
807 }
808 function nucleus_mysql_numrows($p1){
809         return sqlite_num_rows ($p1);
810 }
811
812 function nucleus_mysql_result($p1,$p2,$p3=null){
813         if ($p3) return sqlite_ReturnWithError('nucleus_mysql_result');
814         if (!$p2) return sqlite_fetch_single ($p1);
815         $a=sqlite_fetch_array ($p1);
816         return $a[$p2];
817 }
818
819 function nucleus_mysql_unbuffered_query($p1,$p2=null){
820         return nucleus_mysql_query($p1,$p2,true);
821 }
822
823 function nucleus_mysql_client_encoding($p1=null){
824         return sqlite_libencoding();
825 }
826
827 function nucleus_mysql_data_seek($p1,$p2) {
828         return sqlite_seek($p1,$p2);
829 }
830
831 function nucleus_mysql_errno ($p1=null){
832         global $SQLITE_DBHANDLE;
833         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
834         return sqlite_last_error($dbhandle);
835 }
836
837 function nucleus_mysql_escape_string ($p1){
838         // The "'" will be changed to "''".
839         // This way works for both MySQL and SQLite when single quotes are used for string.
840         // Note that single quote is always used in this wrapper.
841         // If a plugin is made on SQLite-Nucleus and such plugin will be used for MySQL-Nucleus,
842         // nucleus_mysql_escape_string() will be changed to mysql_escape_string() and
843         // this routine won't be used, so this way won't be problem.
844         return sqlite_escape_string($p1);
845 }
846
847 function nucleus_mysql_real_escape_string ($p1,$p2=null){
848         //addslashes used here.
849         return addslashes($p1);
850 }
851
852 function nucleus_mysql_create_db ($p1,$p2=null){
853         // All prameters are ignored.
854         // Returns always true;
855         return true;
856 }
857
858 function nucleus_mysql_pconnect($p1=null,$p2=null,$p3=null,$p4=null,$p5=null){
859         global $SQLITE_DBHANDLE,$SQLITECONF;
860         sqlite_close ($SQLITE_DBHANDLE);
861         $SQLITE_DBHANDLE=sqlite_popen($SQLITECONF['DBFILENAME']);
862         return ($SQLITE['DBHANDLE']=$SQLITE_DBHANDLE);
863 }
864
865 function nucleus_mysql_fetch_field($p1,$p2=null){
866         if ($p2) return sqlite_ReturnWithError('nucleus_mysql_fetch_field');
867         // Only 'name' is supported.
868         $o=new SQLITE_OBJECT;
869         $o->name=array();
870         if(is_array($ret=sqlite_fetch_array ($p1,SQLITE_ASSOC )))
871                 foreach ($ret as $key=>$value) {
872                         if (is_string($key)) array_push($o->name,$key);
873                 }
874         return $o;
875
876 }
877
878 // This function is called instead of _execute_queries() in backp.php
879 function sqlite_restore_execute_queries(&$query){
880         global $DIR_NUCLEUS,$DIR_LIBS,$DIR_PLUGINS,$CONF;
881         
882         // Skip until the first "#" or "--"
883         if (($i=strpos($query,"\n#"))===false) $i=strlen($query);
884         if (($j=strpos($query,"\n--"))===false) $j=strlen($query);
885         if ($i<$j) $query=substr($query,$i+1);
886         else  $query=substr($query,$j+1);
887         
888         // Save the query to temporary file in sqlite directory.
889         if (function_exists('microtime')) {
890                 $prefix=preg_replace('/[^0-9]/','',microtime());
891         } else {
892                 srand(time());
893                 $prefix=(string)rand(0,999999);
894         }
895         $tmpname=tempnam($DIR_NUCLEUS.'sqlite/',"tmp$prefix");
896         if (!($handle=@fopen($tmpname,'w'))) return 'Cannot save temporary DB file.';
897         fwrite($handle,$query);
898         fclose($handle);
899         $tmpname=preg_replace('/[\s\S]*?[\/\\\\]([^\/\\\\]+)$/','$1',$tmpname);
900         
901         // Read the option from NP_SQLite
902         if (!class_exists('NucleusPlugin')) { include($DIR_LIBS.'PLUGIN.php');}
903         if (!class_exists('NP_SQLite')) { include($DIR_PLUGINS.'NP_SQLite.php'); }
904         $p=new NP_SQLite();
905         if (!($numatonce=@$p->getOption('numatonce'))) $numatonce=20;
906         if (!($refreshwait=@$p->getOption('refreshwait'))) $refreshwait=1;
907         
908         // Start process.
909         $url="plugins/sqlite/restore.php?dbfile=$tmpname&numatonce=$numatonce&refreshwait=$refreshwait";
910         header('HTTP/1.0 301 Moved Permanently');
911         header('Location: '.$url);
912         exit('<html><body>Moved Permanently</body></html>');
913 }
914
915 ?>