OSDN Git Service

Ver 0.8.5
[nucleus-jp/nucleus-plugins.git] / trunk / sqlite / nucleus / sqlite / sqlite.php
1 <?php
2     /***************************************
3     * SQLite-MySQL wrapper for Nucleus     *
4     *                           ver 0.8.5  *
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         $i = 0;
438         $defs = preg_split("/[,]+/",$alterdefs,-1,PREG_SPLIT_NO_EMPTY);
439         $prevword = $table;
440         $oldcols = preg_split("/[,]+/",substr(trim($createtemptableSQL),strpos(trim($createtemptableSQL),'(')+1),-1,PREG_SPLIT_NO_EMPTY);
441         $newcols = array();
442         for($i=0;$i<sizeof($oldcols);$i++){
443                 $colparts = preg_split("/[\s]+/",$oldcols[$i],-1,PREG_SPLIT_NO_EMPTY);
444                 $oldcols[$i] = $colparts[0];
445                 $newcols[$colparts[0]] = $colparts[0];
446         }
447         $newcolumns = '';
448         $oldcolumns = '';
449         reset($newcols);
450         while(list($key,$val) = each($newcols)){
451                 if (strtoupper($val)!='PRIMARY' && strtoupper($key)!='PRIMARY' &&
452                     strtoupper($val)!='UNIQUE'  && strtoupper($key)!='UNIQUE'){
453                         $newcolumns .= ($newcolumns?', ':'').$val;
454                         $oldcolumns .= ($oldcolumns?', ':'').$key;
455                 }
456         }
457         $copytotempsql = 'INSERT INTO '.$tmpname.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$table;
458         $dropoldsql = 'DROP TABLE '.$table;
459         $createtesttableSQL = $createtemptableSQL;
460         foreach($defs as $def){
461                 $defparts = preg_split("/[\s]+/",$def,-1,PREG_SPLIT_NO_EMPTY);
462                 $action = strtolower($defparts[0]);
463                 switch($action){
464                 case 'modify':
465                         // Modification does not mean anything for SQLite, so just return true.
466                         // But this command will be supported in future???
467                         break;
468                 case 'add':
469                         if(($i=sizeof($defparts)) <= 2) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error');
470                         
471                         // ignore if there is already such table
472                         $exists=false;
473                         foreach($oldcols as $value) if (str_replace("'",'',$defparts[1])==str_replace("'",'',$value)) $exists=true;
474                         if ($exists) break;
475                         
476                         // Ignore 'AFTER xxxx' statement.
477                         // Maybe this feature will be supprted later.
478                         if (4<=$i && strtoupper($defparts[$i-2])=='AFTER') 
479                                 unset($defparts[$i-1],$defparts[$i-2]);
480                         
481                         $createtesttableSQL = substr($createtesttableSQL,0,strlen($createtesttableSQL)-1).',';
482                         for($i=1;$i<sizeof($defparts);$i++) $createtesttableSQL.=' '.$defparts[$i];
483                         $createtesttableSQL.=')';
484                         break;
485                 case 'change':
486                         if(sizeof($defparts) <= 3) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').($defparts[2]?' '.$defparts[2]:'').'": syntax error');
487                         if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
488                                 if($newcols[$defparts[1]] != $defparts[1]){
489                                         sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
490                                         return false;
491                                 }
492                                 $newcols[$defparts[1]] = $defparts[2];
493                                 $nextcommapos = strpos($createtesttableSQL,',',$severpos);
494                                 $insertval = '';
495                                 for($i=2;$i<sizeof($defparts);$i++) $insertval.=' '.$defparts[$i];
496                                 if($nextcommapos) $createtesttableSQL = substr($createtesttableSQL,0,$severpos).$insertval.substr($createtesttableSQL,$nextcommapos);
497                                 else $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1)).$insertval.')';
498                         } else  return sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
499                         break;
500                 case 'drop':
501                         if(sizeof($defparts) < 2) return sqlite_ReturnWithError('near "'.$defparts[0].($defparts[1]?' '.$defparts[1]:'').'": syntax error');
502                         if($severpos = strpos($createtesttableSQL,' '.$defparts[1].' ')){
503                                 $nextcommapos = strpos($createtesttableSQL,',',$severpos);
504                                 if($nextcommapos) $createtesttableSQL = substr($createtesttableSQL,0,$severpos).substr($createtesttableSQL,$nextcommapos + 1);
505                                 else $createtesttableSQL = substr($createtesttableSQL,0,$severpos-(strpos($createtesttableSQL,',')?0:1) - 1).')';
506                                 unset($newcols[$defparts[1]]);
507                         } else  return sqlite_ReturnWithError('unknown column "'.$defparts[1].'" in "'.$table.'"');
508                         break;
509                 default:
510                         return sqlite_ReturnWithError('near "'.$prevword.'": syntax error');
511                         break;
512                 }
513                 $prevword = $defparts[sizeof($defparts)-1];
514         }
515
516         //this block of code generates a test table simply to verify that the columns specifed are valid in an sql statement
517         //this ensures that no reserved words are used as columns, for example
518         if (!sqlite_query($dbhandle,$createtesttableSQL)) return false;
519         $droptempsql = 'DROP TABLE '.$tmpname;
520         sqlite_query($dbhandle,$droptempsql);
521         //end block
522
523         $createnewtableSQL = 'CREATE '.substr(trim(preg_replace("'".$tmpname."'",$table,$createtesttableSQL,1)),17);
524         $newcolumns = '';
525         $oldcolumns = '';
526         reset($newcols);
527         while(list($key,$val) = each($newcols)) {
528                 if (strtoupper($val)!='PRIMARY' && strtoupper($key)!='PRIMARY' &&
529                     strtoupper($val)!='UNIQUE'  && strtoupper($key)!='UNIQUE'){
530                         $newcolumns .= ($newcolumns?', ':'').$val;
531                         $oldcolumns .= ($oldcolumns?', ':'').$key;
532                 }
533         }
534         $copytonewsql = 'INSERT INTO '.$table.'('.$newcolumns.') SELECT '.$oldcolumns.' FROM '.$tmpname;
535
536         sqlite_query($dbhandle,$createtemptableSQL); //create temp table
537         sqlite_query($dbhandle,$copytotempsql); //copy to table
538         sqlite_query($dbhandle,$dropoldsql); //drop old table
539
540         sqlite_query($dbhandle,$createnewtableSQL); //recreate original table
541         sqlite_query($dbhandle,$copytonewsql); //copy back to original table
542         sqlite_query($dbhandle,$droptempsql); //drop temp table
543         return true;
544 }
545 function sqlite_showKeysFrom($tname,$dbhandle) {
546         // This function is for supporing 'SHOW KEYS FROM' and 'SHOW INDEX FROM'.
547         // For making the same result as obtained by MySQL, temporary table is made.
548         $tname=str_replace("'",'',$tname);
549         
550         // Create a temporary table for making result
551         if (function_exists('microtime')) $tmpname='t'.str_replace('.','',str_replace(' ','',microtime()));
552         else $tmpname = 't'.rand(0,999999).time();
553         sqlite_query($dbhandle,"CREATE TEMPORARY TABLE $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
554                 " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')"); 
555         
556         // First, get the sql query when the table created
557         $res=sqlite_query($dbhandle,"SELECT sql FROM sqlite_master WHERE tbl_name = '$tname' ORDER BY type DESC");
558         $a=nucleus_mysql_fetch_assoc($res);
559         $tablesql=$a['sql'];
560         
561         // Check if each columns are unique
562         $notnull=array();
563         foreach(sqlite_splitByComma(substr($tablesql,strpos($tablesql,'(')+1)) as $value) {
564                 $name=str_replace("'",'',substr($value,0,strpos($value,' ')));
565                 if (strpos(strtoupper($value),'NOT NULL')!==false) $notnull[$name]='';
566                 else $notnull[$name]='YES';
567         }
568         
569         // Get the primary key (and check if it is unique???).
570         if (preg_match('/[^a-zA-Z_\']([\S]+)[^a-zA-Z_\']+INTEGER NOT NULL PRIMARY KEY/i',$tablesql,$matches)) {
571                 $pkey=str_replace("'",'',$matches[1]);
572                 $pkeynull='';
573         } else if (preg_match('/[^a-zA-Z_\']([\S]+)[^a-zA-Z_\']+INTEGER PRIMARY KEY/i',$tablesql,$matches)) {
574                 $pkey=str_replace("'",'',$matches[1]);
575                 $pkeynull='YES';
576         } else if (preg_match('/PRIMARY KEY[\s]*?\(([^\)]+)\)/i',$tablesql,$matches)) {
577                 $pkey=null;// PRIMARY KEY ('xxx'[,'xxx'])
578                 foreach(explode(',',$matches[1]) as $key=>$value) {
579                         $value=str_replace("'",'',trim($value));
580                         $key++;
581                         $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT '$value' FROM '$tname'"));
582                         sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
583                                 " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
584                                 " VALUES ('$tname', '0', 'PRIMARY', '$key',".
585                                 " '$value', 'A', '$cardinality', null, null, '', 'BTREE', '')"); 
586                 }
587         } else $pkey=null;
588         
589         // Check the index.
590         $res=sqlite_query($dbhandle,"SELECT sql,name FROM sqlite_master WHERE type = 'index' and tbl_name = '$tname' ORDER BY type DESC");
591         while ($a=nucleus_mysql_fetch_assoc($res)) {
592                 if (!($sql=$a['sql'])) {// Primary key
593                         if ($pkey && strpos(strtolower($a['name']),'autoindex')) {
594                                 $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT $pkey FROM '$tname'"));
595                                 sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
596                                         " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
597                                         " VALUES ('$tname', '0', 'PRIMARY', '1',".
598                                         " '$pkey', 'A', '$cardinality', null, null, '$pkeynull', 'BTREE', '')"); 
599                                 $pkey=null;
600                         }
601                 } else {// Non-primary key
602                         if (($name=str_replace("'",'',$a['name'])) && preg_match('/\(([\s\S]+)\)/',$sql,$matches)) {
603                                 foreach(explode(',',$matches[1]) as $key=>$value) {
604                                         $columnname=str_replace("'",'',$value);
605                                         if (strpos(strtoupper($sql),'CREATE UNIQUE ')===0) $nonunique='0';
606                                         else $nonunique='1';
607                                         $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT $columnname FROM '$tname'"));
608                                         sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
609                                                 " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
610                                                 " VALUES ('$tname', '$nonunique', '$name', '".(string)($key+1)."',".
611                                                 " '$columnname', 'A', '$cardinality', null, null, '$notnull[$columnname]', 'BTREE', '')"); 
612                                 }
613                         }
614                 }
615         }
616         if ($pkey) { // The case that the key (index) is not defined.
617                 $cardinality=nucleus_mysql_num_rows(sqlite_query($dbhandle,"SELECT $pkey FROM '$tname'"));
618                 sqlite_query($dbhandle,"INSERT INTO $tmpname ('Table', 'Non_unique', 'Key_name', 'Seq_in_index',".
619                         " 'Column_name', 'Collation', 'Cardinality', 'Sub_part', 'Packed', 'Null', 'Index_type', 'Comment')".
620                         " VALUES ('$tname', '0', 'PRIMARY', '1',".
621                         " '$pkey', 'A', '$cardinality', null, null, '$pkeynull', 'BTREE', '')"); 
622                 $pkey=null;
623         }
624         
625         // return the final query to show the keys in MySQL style (using temporary table).
626         return "SELECT * FROM $tmpname";
627 }
628 function sqlite_showFieldsFrom($tname,$dbhandle){
629         // This function is for supporing 'SHOW FIELDS FROM' and 'SHOW COLUMNS FROM'.
630         // For making the same result as obtained by MySQL, temporary table is made.
631         $tname=str_replace("'",'',$tname);
632         
633         // First, get the sql query when the table created
634         $res=sqlite_query($dbhandle,"SELECT sql FROM sqlite_master WHERE tbl_name = '$tname' ORDER BY type DESC");
635         $a=nucleus_mysql_fetch_assoc($res);
636         $tablesql=trim($a['sql']);
637         if (preg_match('/^[^\(]+\(([\s\S]*?)\)$/',$tablesql,$matches)) $tablesql=$matches[1];
638         $tablearray=array();
639         foreach(sqlite_splitByComma($tablesql) as $value) {
640                 $value=trim($value);
641                 if ($i=strpos($value,' ')) {
642                         $name=str_replace("'",'',substr($value,0,$i));
643                         $value=trim(substr($value,$i));
644                         if (substr($value,-1)==',') $value=substr($value,strlen($value)-1);
645                         $tablearray[$name]=$value;
646                 }
647         }
648         
649         // Check if INDEX has been made for the parameter 'MUL' in 'KEY' column
650         $multi=array();
651         $res=sqlite_query($dbhandle,"SELECT name FROM sqlite_master WHERE type = 'index' and tbl_name = '$tname' ORDER BY type DESC");
652         while ($a=nucleus_mysql_fetch_assoc($res)) $multi[str_replace("'",'',$a['name'])]='MUL';
653         
654         // Create a temporary table for making result
655         if (function_exists('microtime')) $tmpname='t'.str_replace('.','',str_replace(' ','',microtime()));
656         else $tmpname = 't'.rand(0,999999).time();
657         sqlite_query($dbhandle,"CREATE TEMPORARY TABLE $tmpname ('Field', 'Type', 'Null', 'Key', 'Default', 'Extra')"); 
658         
659         // Check the table
660         foreach($tablearray as $field=>$value) {
661                 if (strtoupper($field)=='PRIMARY') continue;//PRIMARY KEY('xx'[,'xx'])
662                 $uvalue=strtoupper($value.' ');
663                 $key=(string)$multi[$field];
664                 if ($uvalue=='INTEGER NOT NULL PRIMARY KEY ' || $uvalue=='INTEGER PRIMARY KEY ') {
665                         $key='PRI';
666                         $extra='auto_increment';
667                 } else $extra='';
668                 if ($i=strpos($uvalue,' ')) {
669                         $type=substr($value,0,$i);
670                         if (strpos($type,'(') && ($i=strpos($value,')')))
671                                 $type=substr($value,0,$i+1);
672                 } else $type='';
673                 if (strtoupper($type)=='INTEGER') $type='int(11)';
674                 if (strpos($uvalue,'NOT NULL')===false) $null='YES';
675                 else {
676                         $null='';
677                         $value=preg_replace('/NOT NULL/i','',$value);
678                         $uvalue=strtoupper($value);
679                 }
680                 if ($i=strpos($uvalue,'DEFAULT')) {
681                         $default=trim(substr($value,$i+7));
682                         if (strtoupper($default)=='NULL') {
683                                 $default="";
684                                 $setdefault="";
685                         } else {
686                                 if (substr($default,0,1)=="'") $default=substr($default,1,strlen($default)-2);
687                                 $default="'".$default."',";
688                                 $setdefault="'Default',";
689                         }
690                 } else if ($null!='YES' && $extra!='auto_increment') {
691                         if (strpos(strtolower($type),'int')===false) $default="'',";
692                         else $default="'0',";
693                         $setdefault="'Default',";
694                 } else {
695                         $default="";
696                         $setdefault="";
697                 }
698                 sqlite_query($dbhandle,"INSERT INTO '$tmpname' ('Field', 'Type', 'Null', 'Key', $setdefault 'Extra')".
699                         " VALUES ('$field', '$type', '$null', '$key', $default '$extra')");
700         }
701         
702         // return the final query to show the keys in MySQL style (using temporary table).
703         return "SELECT * FROM $tmpname";
704 }
705 function sqlite_mysql_query_debug(&$query){
706         // The debug mode is so far used for checking query difference like "SELECT i.itime, ....".
707         // This must be chaged to "SELECT i.itime as itime,..." for SQLite.
708         // (This feature is not needed any more after the version 0.8.1 (see intialization query))
709         $uquery=strtoupper($query);
710         if (strpos($uquery,"SELECT ")!==0) return $query;
711         if (($i=strpos($uquery," FROM "))===false) return $query;
712         $select=sqlite_splitByComma(substr($query,7,$i-7));
713         $query=substr($query,$i);
714         $ret='';
715         foreach($select as $value){
716                 if (preg_match('/^([a-z_]+)\.([a-z_]+)$/i',$value,$matches)) {
717                         $value=$value." as ".$matches[2];
718                         $t=$matches[0]."=>$value\n";
719                         $a=debug_backtrace();
720                         foreach($a as $key=>$btrace) {
721                                 if (!($templine=$btrace['line'])) continue;
722                                 if (!($tempfile=$btrace['file'])) continue;
723                                 $tempfile=preg_replace('/[\s\S]*?[\/\\\\]([^\/\\\\]+)$/','$1',$tempfile);
724                                 $t.="$tempfile line:$templine\n";
725                         }
726                         sqlite_DebugMessage($t);
727                 }
728                 if ($ret) $ret.=', ';
729                 $ret.=$value;
730         }
731         return "SELECT $ret $query";
732 }
733
734 function nucleus_mysql_list_tables($p1=null,$p2=null) {
735         global $SQLITE_DBHANDLE,$MYSQL_DATABASE;
736         return sqlite_query($SQLITE_DBHANDLE,"SELECT name as Tables_in_$MYSQL_DATABASE FROM sqlite_master WHERE type='table'");
737 }
738 function nucleus_mysql_listtables($p1=null,$p2=null) { return nucleus_mysql_list_tables($p1,$p2);}
739
740 function nucleus_mysql_affected_rows($p1=null){
741         global $SQLITE_DBHANDLE;
742         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
743         return sqlite_changes($dbhandle);
744 }
745
746 function nucleus_mysql_error($p1=null){
747         global $SQLITE_DBHANDLE;
748         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
749         return sqlite_error_string ( sqlite_last_error ($dbhandle) );
750 }
751
752 function nucleus_mysql_fetch_array($p1,$p2=SQLITE_BOTH){
753         return sqlite_fetch_array ($p1,$p2);
754 }
755
756 function nucleus_mysql_fetch_assoc($p1){
757         return sqlite_fetch_array($p1,SQLITE_ASSOC);
758 }
759
760 function nucleus_mysql_fetch_object($p1,$p2=SQLITE_BOTH){
761         if (is_array($ret=sqlite_fetch_array ($p1,$p2))) {
762                 $o=new SQLITE_OBJECT;
763                 foreach ($ret as $key=>$value) {
764                         if (strstr($key,'.')) {// Remove table name.
765                                 $key=preg_replace('/^(.+)\."(.+)"$/','"$2"',$key);
766                                 $key=preg_replace('/^(.+)\.([^.^"]+)$/','$2',$key);
767                         }
768                         $o->$key=$value;
769                 }
770                 return $o;
771         } else return false;
772 }
773
774 function nucleus_mysql_fetch_row($p1){
775         return sqlite_fetch_array($p1,SQLITE_NUM);
776 }
777
778 function nucleus_mysql_field_name($p1,$p2){
779         return sqlite_field_name ($p1,$p2);
780 }
781
782 function nucleus_mysql_free_result($p1){
783         // ???? Cannot find corresponding function of SQLite.
784         // Maybe SQLite is NOT used for the high spec server
785         // that need mysql_free_result() function because of
786         // many SQL-queries in a script.
787         return true;
788 }
789
790 function nucleus_mysql_insert_id($p1=null){
791         global $SQLITE_DBHANDLE;
792         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
793         return sqlite_last_insert_rowid ($dbhandle);
794 }
795
796 function nucleus_mysql_num_fields($p1){
797         return sqlite_num_fields ($p1);
798 }
799
800 function nucleus_mysql_num_rows($p1){
801         return sqlite_num_rows ($p1);
802 }
803 function nucleus_mysql_numrows($p1){
804         return sqlite_num_rows ($p1);
805 }
806
807 function nucleus_mysql_result($p1,$p2,$p3=null){
808         if ($p3) return sqlite_ReturnWithError('nucleus_mysql_result');
809         if (!$p2) return sqlite_fetch_single ($p1);
810         $a=sqlite_fetch_array ($p1);
811         return $a[$p2];
812 }
813
814 function nucleus_mysql_unbuffered_query($p1,$p2=null){
815         return nucleus_mysql_query($p1,$p2,true);
816 }
817
818 function nucleus_mysql_client_encoding($p1=null){
819         return sqlite_libencoding();
820 }
821
822 function nucleus_mysql_data_seek($p1,$p2) {
823         return sqlite_seek($p1,$p2);
824 }
825
826 function nucleus_mysql_errno ($p1=null){
827         global $SQLITE_DBHANDLE;
828         if (!($dbhandle=$p1)) $dbhandle=$SQLITE_DBHANDLE;
829         return sqlite_last_error($dbhandle);
830 }
831
832 function nucleus_mysql_escape_string ($p1){
833         // The "'" will be changed to "''".
834         // This way works for both MySQL and SQLite when single quotes are used for string.
835         // Note that single quote is always used in this wrapper.
836         // If a plugin is made on SQLite-Nucleus and such plugin will be used for MySQL-Nucleus,
837         // nucleus_mysql_escape_string() will be changed to mysql_escape_string() and
838         // this routine won't be used, so this way won't be problem.
839         return sqlite_escape_string($p1);
840 }
841
842 function nucleus_mysql_real_escape_string ($p1,$p2=null){
843         //addslashes used here.
844         return addslashes($p1);
845 }
846
847 function nucleus_mysql_create_db ($p1,$p2=null){
848         // All prameters are ignored.
849         // Returns always true;
850         return true;
851 }
852
853 function nucleus_mysql_pconnect($p1=null,$p2=null,$p3=null,$p4=null,$p5=null){
854         global $SQLITE_DBHANDLE,$SQLITECONF;
855         sqlite_close ($SQLITE_DBHANDLE);
856         $SQLITE_DBHANDLE=sqlite_popen($SQLITECONF['DBFILENAME']);
857         return ($SQLITE['DBHANDLE']=$SQLITE_DBHANDLE);
858 }
859
860 function nucleus_mysql_fetch_field($p1,$p2=null){
861         if ($p2) return sqlite_ReturnWithError('nucleus_mysql_fetch_field');
862         // Only 'name' is supported.
863         $o=new SQLITE_OBJECT;
864         $o->name=array();
865         if(is_array($ret=sqlite_fetch_array ($p1,SQLITE_ASSOC )))
866                 foreach ($ret as $key=>$value) {
867                         if (is_string($key)) array_push($o->name,$key);
868                 }
869         return $o;
870
871 }
872
873 // This function is called instead of _execute_queries() in backp.php
874 function sqlite_restore_execute_queries(&$query){
875         global $DIR_NUCLEUS,$DIR_LIBS,$DIR_PLUGINS,$CONF;
876         
877         // Skip until the first "#" or "--"
878         if (($i=strpos($query,"\n#"))===false) $i=strlen($query);
879         if (($j=strpos($query,"\n--"))===false) $j=strlen($query);
880         if ($i<$j) $query=substr($query,$i+1);
881         else  $query=substr($query,$j+1);
882         
883         // Save the query to temporary file in sqlite directory.
884         if (function_exists('microtime')) {
885                 $prefix=preg_replace('/[^0-9]/','',microtime());
886         } else {
887                 srand(time());
888                 $prefix=(string)rand(0,999999);
889         }
890         $tmpname=tempnam($DIR_NUCLEUS.'sqlite/',"tmp$prefix");
891         if (!($handle=@fopen($tmpname,'w'))) return 'Cannot save temporary DB file.';
892         fwrite($handle,$query);
893         fclose($handle);
894         $tmpname=preg_replace('/[\s\S]*?[\/\\\\]([^\/\\\\]+)$/','$1',$tmpname);
895         
896         // Read the option from NP_SQLite
897         if (!class_exists('NucleusPlugin')) { include($DIR_LIBS.'PLUGIN.php');}
898         if (!class_exists('NP_SQLite')) { include($DIR_PLUGINS.'NP_SQLite.php'); }
899         $p=new NP_SQLite();
900         if (!($numatonce=@$p->getOption('numatonce'))) $numatonce=20;
901         if (!($refreshwait=@$p->getOption('refreshwait'))) $refreshwait=1;
902         
903         // Start process.
904         $url="plugins/sqlite/restore.php?dbfile=$tmpname&numatonce=$numatonce&refreshwait=$refreshwait";
905         header('HTTP/1.0 301 Moved Permanently');
906         header('Location: '.$url);
907         exit('<html><body>Moved Permanently</body></html>');
908 }
909
910 ?>