KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > gui > html > scanparser


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10
11 package org.mmbase.module.gui.html;
12
13 import java.util.*;
14 import java.io.*;
15 import java.util.zip.*;
16 import javax.servlet.*;
17
18 import org.mmbase.module.*;
19 import org.mmbase.util.*;
20 import org.mmbase.module.core.*;
21
22 import org.mmbase.util.logging.*;
23
24 /**
25  * scanpage is a container class it holds all objects needed per scan page
26  * it was introduced to make servscan threadsafe but will probably in the future
27  * hold all page related info instead of HttpServletR equest and HttpServletResponse
28  * because we want extend the model of offline page generation.
29  *
30  * @javadoc
31  * @application SCAN
32  * @rename SCANParser
33  * @author Daniel Ockeloen
34  * @version $Id: scanparser.java,v 1.73 2005/10/26 07:35:36 michiel Exp $
35  */

36 public class scanparser extends ProcessorModule {
37
38     public static scancacheInterface scancache=null;
39
40     private static Logger log = Logging.getLoggerInstance(scanparser.class.getName());
41     private static HTMLFormGenerator htmlgen=new HTMLFormGenerator();
42     private CounterInterface counter = null;
43     private static ProcessorModule grab=null;
44     private static sessionsInterface sessions=null;
45     private static idInterface id=null;
46     private static MMBase mmbase=null;
47     private static TransactionHandlerInterface transactionhandler;
48     private static Hashtable processors = new Hashtable();
49     private static boolean debug=false;
50     private static RandomPlus rnd;
51     private static int crcseed;
52
53     private Hashtable pagesprocessing=new Hashtable();
54
55     // needs fix !
56
private static String JavaDoc loadmode="no-cache";
57     private static String JavaDoc htmlroot;
58     Hashtable Roots;
59
60     public scanparser() {
61         htmlroot = MMBaseContext.getHtmlRoot();
62     }
63
64     /**
65      * Init the servscan, this is needed because it was created using
66      * a newInstanceOf().
67      */

68     public void init() {
69         Roots=getRoots();
70         // org.mmbase start();
71
sessions=(sessionsInterface)getModule("SESSION");
72         scancache=(scancacheInterface)getModule("SCANCACHE");
73         mmbase=(MMBase)getModule("MMBASEROOT");
74         transactionhandler=(TransactionHandlerInterface)getModule("TRANSACTIONHANDLER");
75         // org.mmbase stats=(StatisticsInterface)getModule("STATS");
76
rnd=new RandomPlus();
77         crcseed=rnd.nextInt();
78     }
79
80      /**
81       * getMimeType: Returns the mimetype using ServletContext.getServletContext which returns the servlet context
82       * which is set when servscan is loaded.
83       * Fixed on 22 December 1999 by daniel & davzev.
84       * @param ext A String containing the extension.
85       * @return The mimetype.
86       */

87      public String JavaDoc getMimeType(String JavaDoc ext) {
88          return getMimeTypeFile("dummy."+ext);
89      }
90  
91      public String JavaDoc getMimeTypeFile(String JavaDoc fileName) {
92          ServletContext sx = MMBaseContext.getServletContext();
93          String JavaDoc mimeType = sx.getMimeType(fileName);
94          if (mimeType == null) {
95              log.warn("getMimeType(" + fileName + "): Can't find mimetype retval=null -> setting mimetype to default text/html");
96              mimeType = "text/html";
97          }
98          return mimeType;
99      }
100
101
102     public String JavaDoc doPrePart(String JavaDoc template, int last, int rpos, int numitems,int epos) {
103         int precmd=0,postcmd=0,prepostcmd=0,index;
104         StringBuffer JavaDoc dst=new StringBuffer JavaDoc();
105         String JavaDoc cmd="$ITEM";
106         int endc='^';
107         if (template==null) return "No Template";
108         while ((precmd=template.indexOf(cmd,postcmd))!=-1) {
109             dst.append(template.substring(postcmd,precmd));
110             prepostcmd=precmd+cmd.length();
111             postcmd=precmd+6;
112             try {
113                 index=Integer.parseInt(template.substring(prepostcmd,postcmd));
114                 try {
115                     index=Integer.parseInt(template.substring(prepostcmd,postcmd+1));
116                     postcmd++;
117                 } catch (Exception JavaDoc g) {}
118                 index--;
119                 try {
120                     dst.append("DUMMY");
121                 } catch (ArrayIndexOutOfBoundsException JavaDoc e) {}
122             } catch (NumberFormatException JavaDoc e) {
123                 //index=1;
124
try {
125                     if (template.charAt(prepostcmd)=='L') {
126                         dst.append(""+last);
127                     } else if (template.charAt(prepostcmd)=='R') {
128                         dst.append(""+(rpos+1));
129                     } else if (template.charAt(prepostcmd)=='E') {
130                         dst.append(""+epos);
131                     } else if (template.charAt(prepostcmd)=='S') {
132                         dst.append(""+numitems);
133                     }
134                 } catch (ArrayIndexOutOfBoundsException JavaDoc f) {}
135             }
136         }
137         dst.append(template.substring(postcmd));
138         return dst.toString();
139     }
140
141     public String JavaDoc doEndPart(String JavaDoc template, int last, int rpos, int numitems,int epos) {
142         int precmd=0,postcmd=0,prepostcmd=0,index;
143         StringBuffer JavaDoc dst=new StringBuffer JavaDoc();
144         String JavaDoc cmd="$ITEM";
145         int endc='^';
146         if (template==null) return "No Template";
147         while ((precmd=template.indexOf(cmd,postcmd))!=-1) {
148             dst.append(template.substring(postcmd,precmd));
149             prepostcmd=precmd+cmd.length();
150             postcmd=precmd+6;
151             try {
152                 index=Integer.parseInt(template.substring(prepostcmd,postcmd));
153                 try {
154                     index=Integer.parseInt(template.substring(prepostcmd,postcmd+1));
155                     postcmd++;
156                 } catch (Exception JavaDoc g) {}
157                 index--;
158                 try {
159                     dst.append("DUMMY");
160                 } catch (ArrayIndexOutOfBoundsException JavaDoc e) {}
161             } catch (NumberFormatException JavaDoc e) {
162                 //index=1;
163
try {
164                     if (template.charAt(prepostcmd)=='L') {
165                         dst.append(""+last);
166                     } else if (template.charAt(prepostcmd)=='R') {
167                         dst.append(""+(rpos+1));
168                     } else if (template.charAt(prepostcmd)=='E') {
169                         dst.append(""+epos);
170                     } else if (template.charAt(prepostcmd)=='S') {
171                         dst.append(""+numitems);
172                     }
173                 } catch (ArrayIndexOutOfBoundsException JavaDoc f) {}
174             }
175         }
176         dst.append(template.substring(postcmd));
177         return dst.toString();
178     }
179
180     public Vector reverse(Vector input,int num) {
181         Vector results=new Vector();
182         for (Enumeration e=input.elements();e.hasMoreElements();) {
183             for (int i=0;i<num;i++) {
184                 String JavaDoc val=(String JavaDoc)e.nextElement();
185                 results.insertElementAt(val,i);
186             }
187         }
188         return results;
189     }
190
191     boolean do_vals(String JavaDoc cmd,sessionInfo session,scanpage sp) throws ParseException {
192         int il=-1;
193         int ir=-1;
194         int andpos=cmd.indexOf(" AND ");
195         int orpos=cmd.indexOf(" OR ");
196         if (andpos!=-1 || orpos!=-1) {
197             boolean result=false;
198             boolean done=false;
199             String JavaDoc part;
200             do {
201                 if (andpos!=-1) {
202                     part=cmd.substring(0,andpos);
203                     cmd=cmd.substring(andpos+5);
204                     result=do_val(part,session,sp);
205                     done=!result;
206                 } else if (orpos!=-1) {
207                     part=cmd.substring(0,orpos);
208                     cmd=cmd.substring(orpos+4);
209                     result=do_val(part,session,sp);
210                     done=result;
211                 } else if (andpos<orpos) {
212                     part=cmd.substring(0,andpos);
213                     cmd=cmd.substring(andpos+5);
214                     result=do_val(part,session,sp);
215                     done=!result;
216                 } else {
217                     part=cmd.substring(0,orpos);
218                     cmd=cmd.substring(orpos+4);
219                     result=do_val(part,session,sp);
220                     done=result;
221                 }
222                 andpos=cmd.indexOf(" AND ");
223                 orpos=cmd.indexOf(" OR ");
224             } while (!done && (andpos!=-1 || orpos!=-1));
225             if (done) return result;
226             result=do_val(cmd,session,sp);
227             return result;
228         } else {
229             return do_val(cmd,session,sp);
230         }
231     }
232
233     boolean do_val(String JavaDoc cmd,sessionInfo session,scanpage sp) throws ParseException {
234         int il=-1;
235         int ir=-1;
236         int pos=cmd.indexOf('=');
237         if (pos!=-1) {
238             String JavaDoc l=cmd.substring(0,cmd.indexOf("="));
239             String JavaDoc r=cmd.substring(cmd.indexOf("=")+2);
240             char e=cmd.charAt(pos+1);
241             l=handle_line(l,session,sp);
242             r=handle_line(r,session,sp);
243             try {
244                 il=Integer.parseInt(l);
245                 ir=Integer.parseInt(r);
246             } catch (Exception JavaDoc f){ }
247             if (il!=-1) {
248                 if ((e=='=' || e=='E') && (il==ir)) return true;
249                 if (e=='N' && (il!=ir)) return true;
250                 if (e=='H' && (il>ir)) return true;
251                 if (e=='L' && (il<ir)) return true;
252                 if (e=='M' && (il<=ir)) return true;
253                 if (e=='A' && (il>=ir)) return true;
254                 return false;
255             } else {
256                 if ((e=='=' || e=='E') && (l.equals(r))) return true;
257                 if (e=='N' && (!l.equals(r))) return true;
258                 if (e=='C' && (l.equalsIgnoreCase(r))) return true;
259                 return false;
260             }
261         } else {
262             return false;
263         }
264     }
265
266     /**
267      * Process the HTML for our own extensions
268      *
269      */

270     public final String JavaDoc handle_line(String JavaDoc body,sessionInfo session,scanpage sp) throws ParseException {
271
272         String JavaDoc part=null;
273         int qw_pos,qw_pos2,end_pos,end_pos2;
274         int precmd=0,postcmd=-1,prepostcmd=0;
275         StringBuffer JavaDoc newbody=new StringBuffer JavaDoc();
276
277         // old pos for IFs moved to past LIST
278
if (body.indexOf("<IF")!=-1) {
279             body=do_conditions(body,session,sp);
280         }
281
282         // First find the processor (for the MACRO commands)
283
part=finddocmd(body,"<PROCESSOR ",'>',8,session,sp);
284         body=part;
285
286         // Include other HTML
287
part=finddocmd(body,"<INCLUDE ",'>',5,session,sp);
288         body=part;
289
290
291         // <LIST text1> text2 </LIST>
292
// The code below will hand text1 and text2 to the method do_list(text1, text2, session, sp)
293
while ((precmd=body.indexOf("<LIST ",postcmd))!=-1) {
294             newbody.append(body.substring(postcmd+1,precmd));
295             prepostcmd=precmd+6;
296             if ((postcmd=body.indexOf('>',precmd))!=-1) {
297                 end_pos2=body.indexOf("</LIST>",prepostcmd);
298                 if (end_pos2!=-1) {
299                     try {
300                         newbody.append(do_list(body.substring(prepostcmd,postcmd),body.substring(postcmd+1,end_pos2),session,sp));
301                     } catch(Exception JavaDoc e) {
302                         String JavaDoc errorMsg = "Error in list: "+e.getMessage()+" in page "+sp.getUrl();
303                         newbody.append(errorMsg);
304                         log.debug("handle_line(): ERROR: do_list(): "+prepostcmd+","+postcmd+","+end_pos2+" in page("+sp.getUrl()+") : "+e);
305                         e.printStackTrace();
306                     }
307                     postcmd=end_pos2+7;
308                 }
309             } else {
310                 postcmd=prepostcmd;
311             }
312         }
313         if (postcmd < body.length()) {
314             newbody.append(body.substring(postcmd+1));
315         }
316         body=newbody.toString();
317
318         // detect a <IF> page (daniel)
319

320         // Unmap (special commands)
321
part=finddocmd(body,"<UNMAP ",'>',7,session,sp);
322         body=part;
323
324         // Macro's (special commands)
325
part=finddocmd(body,"<MACRO ",'>',1,session,sp);
326         body=part;
327
328         // Include other HTML
329
part=finddocmd(body,"<INCLUDE ",'>',5,session,sp);
330         body=part;
331
332         // Include other HTML in the LIST command
333
part=finddocmd(body,"<LISTINCLUDE ",'>',5,session,sp);
334         body=part;
335
336         // Unmap (special commands)
337
part=finddocmd(body,"<UNMAP ",'>',7,session,sp);
338         body=part;
339
340         // Macro's (special commands)
341
part=finddocmd(body,"<MACRO ",'>',1,session,sp);
342         body=part;
343         // Do the dollar commands
344
body=dodollar(body,session,sp);
345
346         // TESTING 1 2 3 of the ifs after the include RICO
347
if (body.indexOf("<IF")!=-1) {
348             body=do_conditions(body,session,sp);
349         }
350
351         // TESTING 1 2 3 of the ifs after the _ONLY_ after the list Daniel
352
if (body.indexOf("<LIF")!=-1) {
353             // debug("handle_line(): LIF detected on servscan");
354
body=do_conditions_lif(body,session,sp);
355         }
356
357         // <NORELOAD>, make it possible to jump pages
358
part=finddocmd(body,"<NORELOAD ",'>',13,session,sp);
359         body=part;
360
361         // DO set variables
362
part=finddocmd(body,"<DO ",'>',6,session,sp);
363         body=part;
364
365         // <SAVE, make it possible to save
366
part=finddocmd(body,"<SAVE ",'>',19,session,sp);
367         body=part;
368
369         // <CRC HREF=", make it possible to save
370
part=finddocmd(body,"<CRC HREF=",'>',24,session,sp);
371         body=part;
372
373         // <TRANSACTION text1> text2 </TRANSACTION>
374
// The code below will hand text1 and text2 to the method do_transaction(text1, text2, session, sp)
375
newbody=new StringBuffer JavaDoc();
376         postcmd=0;
377
378         while ((precmd=body.indexOf("<transactions",postcmd))!=-1) {
379             newbody.append(body.substring(postcmd,precmd));
380             prepostcmd=precmd+13;
381             if ((postcmd=body.indexOf('>',precmd))!=-1) {
382                 end_pos2=body.indexOf("</transactions>",prepostcmd);
383                 if (end_pos2!=-1) {
384                     postcmd=end_pos2+15;
385                     try {
386                         newbody.append(do_transaction(body.substring(precmd,postcmd),session,sp));
387                     } catch(Exception JavaDoc e) {
388                         log.error("handle_line(): ERROR: do_transaction(): "+prepostcmd+","+postcmd+","+end_pos2+" in page("+sp.getUrl()+") : "+e);
389                         e.printStackTrace();
390                     }
391                 }
392             } else {
393                 postcmd=prepostcmd;
394             }
395         }
396
397         newbody.append(body.substring(postcmd));
398         body=newbody.toString();
399
400         // <GOTO, make it possible to jump pages
401
part=finddocmd(body,"<GOTO ",'>',10,session,sp);
402         body=part;
403
404         // <HOST, demand a host for this page
405
part=finddocmd(body,"<HOST ",'>',11,session,sp);
406         body=part;
407
408         // <NEWPAGE, make it possible to 'jump' by loading new pages
409
part=finddocmd(body,"<NEWPAGE ",'>',12,session,sp);
410         body=part;
411
412         // <GRAB, make it possible to get information of other html-pages
413
part=finddocmd(body,"<GRAB ",'>',14,session,sp);
414         body=part;
415
416         // <PART, make it possible to include other parsed ! and cached pages
417
part=finddocmd(body,"<PART ",'>',20,session,sp);
418         body=part;
419
420         // Counter tag
421
part=finddocmd(body,"<COUNTER",'>',21,session,sp);
422         body=part;
423
424         // <TREEPART, TREEFILE
425
part=finddocmd(body,"<TREE",'>',22,session,sp);
426         body=part;
427
428         // <LEAFPART, LEAFFILE
429
part=finddocmd(body,"<LEAF",'>',23,session,sp);
430         body=part;
431
432         // Last one always
433
part=finddocmd(body,"$LBJ-",'^',4,session,sp);
434         body=part;
435
436         return body;
437     }
438
439     /**
440      * Main function, calls the several handlers for the diffenrent TAGS
441      */

442     private final String JavaDoc finddocmd(String JavaDoc body,String JavaDoc cmd,int endc,int docmd,sessionInfo session,scanpage sp) throws ParseException {
443         return finddocmd(body,cmd,""+(char)endc,docmd,session,sp);
444     }
445
446     /**
447      * Main function, calls the several handlers for the diffenrent TAGS
448      */

449     private final String JavaDoc finddocmd(String JavaDoc body,String JavaDoc cmd,String JavaDoc endc,int docmd,sessionInfo session,scanpage sp) throws ParseException {
450         int precmd=0,postcmd=0,prepostcmd=0;
451         StringBuffer JavaDoc newbody=new StringBuffer JavaDoc();
452         int pos,pos2;
453         boolean removeToken=false;
454
455         while ((precmd=body.indexOf(cmd,postcmd))!=-1) {
456             if (removeToken) {
457                 newbody.append(body.substring(postcmd+1,precmd));
458             } else {
459                 newbody.append(body.substring(postcmd,precmd));
460             }
461
462             removeToken=false;
463             prepostcmd=precmd+cmd.length();
464
465             //if ((postcmd=body.indexOf(endc,precmd))!=-1) {
466
pos=-1;
467             for (int i=0;i<endc.length();i++) {
468                 pos2=body.indexOf(endc.charAt(i),precmd);
469                 if (pos2!=-1 && (pos==-1 || pos2<pos)) {
470                     pos=pos2;
471                     if (i==0) {
472                         removeToken=true;
473                     } else {
474                         removeToken=false;
475                     }
476                 }
477             }
478
479             if (pos!=-1) {
480                 postcmd=pos;
481
482                 //debug("newpart "+newpart);
483

484                 String JavaDoc partbody;
485                 switch(docmd) {
486                     case 1: // '<MACRO '
487
newbody.append(do_macro(body.substring(prepostcmd,postcmd),session,sp));
488                         break;
489                     case 2: // '$SQL-'
490
//org.mmbase newbody.append(do_sql(body.substring(prepostcmd,postcmd)));
491
break;
492                     case 3: // '$ID-'
493
newbody.append(do_id(body.substring(prepostcmd,postcmd),sp));
494                         break;
495                     case 4: // '$OBJ-' , '$VAR-' , '$COLOR-' '$TEXT-' and '$LBJ-'
496
newbody.append(body.substring(prepostcmd,postcmd));
497                         break;
498                     case 5: // '<INCLUDE '
499
newbody.append(do_include(body.substring(prepostcmd,postcmd),session,sp));
500                         break;
501                     case 6: // '<DO '
502
newbody.append(do_do(body.substring(prepostcmd,postcmd),session,sp));
503                         break;
504                     case 7: // '<UNMAP '
505
newbody.append(do_unmap(body.substring(prepostcmd,postcmd),session,sp));
506                         break;
507                     case 8: // '<PROCESSOR '
508
sp.processor=getProcessor(body.substring(prepostcmd,postcmd));
509                         break;
510                     //case 9: // '$DOC- '
511
// newbody.append(do_doc(body.substring(prepostcmd,postcmd)));
512
// break;
513
case 9: // '$MOD-'
514
newbody.append(do_mod(sp,body.substring(prepostcmd,postcmd)));
515                         break;
516                     case 10: // '<GOTO'
517
// newbody=new StringBuffer();
518
// newbody.append(do_goto(sp,body.substring(prepostcmd,postcmd)));
519
return do_goto(sp,body.substring(prepostcmd,postcmd));
520 // break;
521
case 11: // '<HOST'
522
String JavaDoc url = do_host(sp, body.substring(prepostcmd,postcmd));
523                         if (sp.rstatus==1) // if redir return url else eat the tag
524
return url;
525                         break;
526                     case 12: // '<NEWPAGE'
527
newbody=new StringBuffer JavaDoc();
528                         newbody.append(do_newpage(sp,body.substring(prepostcmd,postcmd)));
529                         break;
530                     case 13: // '<RELOAD'
531
// org.mmbase newbody.append(do_reload(body.substring(prepostcmd,postcmd)));
532
break;
533                     case 14: // '<GRAB'
534
// org.mmbase newbody.append(do_grab(body.substring(prepostcmd,postcmd)));
535
break;
536                     case 15: // '$PAGE-'
537
// newbody.append(do_page(body.substring(prepostcmd,postcmd)));
538
break;
539                     case 16: // '$AREA-'
540
newbody.append(body.substring(prepostcmd,postcmd));
541                         break;
542                     case 17: // '$SESSION-'
543
newbody.append(do_session(body.substring(prepostcmd,postcmd),session));
544                         break;
545                     case 18: // '$LASTLIST'
546
// org.mmbase newbody.append(""+lastlistitem);
547
break;
548                     case 19: // '<SAVE'
549
newbody.append(do_save(session,body.substring(prepostcmd,postcmd)));
550                         break;
551                     case 20: // '<PART '
552
partbody=do_part(body.substring(prepostcmd,postcmd),session,sp,0);
553                         if ((sp.rstatus==1) || (sp.rstatus==2)) {
554                             return partbody;
555                         };
556                         newbody.append(partbody);
557                         break;
558                     case 21: // '<COUNTER'
559
newbody.append(do_counter(body.substring(prepostcmd,postcmd),session,sp));
560                         break;
561                     case 22: // '<TREEPART, TREEFILE'
562
case 23: // '<LEAFPART, LEAFFILE'
563
partbody=do_smart(body.substring(prepostcmd,postcmd),session,sp, docmd==23);
564                         if ((sp.rstatus==1) || (sp.rstatus==2)) {
565                             return partbody;
566                         };
567                         newbody.append(partbody);
568                         break;
569                     case 24: // '<CRC CHECK'
570
newbody.append(do_crc(session,body.substring(prepostcmd,postcmd)));
571                         break;
572                     default:
573                         log.fatal("Woops broken case in method finddocmd");
574                         break;
575                 }
576             } else {
577                 postcmd=prepostcmd;
578             }
579         }
580         if (removeToken) {
581             newbody.append(body.substring(postcmd+1));
582         } else {
583             newbody.append(body.substring(postcmd));
584         }
585         return newbody.toString();
586     }
587
588     /**
589      * The &lt;COUNTER x y&gt; tag is only used by the VPRO, it returns information in regard to nedstat.
590      *
591      * @param part A string containing the remaining COUNTER part.
592      * @param session The sessionInfo object.
593      * @param sp The current scanpage object.
594      * @return A String containing the counter value.
595      */

596     private String JavaDoc do_counter( String JavaDoc part, sessionInfo session, scanpage sp ) throws ParseException {
597         String JavaDoc result = null;
598
599         if(counter==null) {
600             counter=(CounterInterface)getModule("COUNTER");
601             if(counter==null) {
602                 log.error("<COUNTER tag is used but counter module is not loaded.");
603                 return "";
604             }
605         }
606
607         // Scan & Parse all $ attributes used in the tag.
608
part = dodollar(part,session,sp);
609
610         long time = System.currentTimeMillis();
611         part = part.trim();
612         log.debug("Using part ["+part+"]");
613         int i=part.indexOf(' ');
614         String JavaDoc params="";
615         if (i!=-1) {
616             params=part.substring(i+1);
617         } else {
618             log.debug("["+part +"] no arguments are given.");
619         }
620
621         result = counter.getTag(params, session, sp);
622
623         log.debug("processing counter took "+ (System.currentTimeMillis() - time ) + " ms.");
624         return result;
625     }
626
627     private final String JavaDoc do_part(String JavaDoc part2,sessionInfo session,scanpage sp,int markPart) throws ParseException {
628
629         String JavaDoc part="",filename,paramline=null;;
630         Vector oldparams=sp.getParamsVector();
631         String JavaDoc oldQueryString = sp.querystring;
632
633         sp.partlevel++;
634
635         part2=dodollar(part2,session,sp);
636         // we now may have a a param setup like part.shtml?1212+1212+1212
637
// split it so we can load the file and get the params
638
int pos=part2.indexOf('?');
639         if (pos!=-1) {
640             filename=part2.substring(0,pos);
641             paramline=part2.substring(pos+1);
642             if (sp.req_line==null) sp.req_line=filename;
643         } else {
644             filename = part2;
645             paramline = "";
646         }
647
648         if (filename.indexOf("..")>=0) {
649             sp.partlevel--;
650             log.error("do_part: Usage of '..' in filepath not allowed!");
651             return "Usage of '..' in filepath not allowed!";
652         }
653
654         // Set new params for part
655
sp.querystring = paramline;
656         sp.setParamsLine(paramline);
657
658         if ((filename.length()>0) && (filename.charAt(0)!='/')) {
659             String JavaDoc servletPath = sp.req_line;
660             if (sp.req!=null) {
661                 servletPath=sp.req.getServletPath();
662             }
663             filename = servletPath.substring(0,servletPath.lastIndexOf("/")+1)+filename;
664             if (log.isDebugEnabled()) log.debug("do_part: filename:"+filename);
665         }
666
667         // Test if we are going circular
668
if (sp.partlevel>8) {
669             log.warn("Warning more then "+sp.partlevel+" nested parts "+sp.req_line);
670             if (sp.partlevel>14) throw new CircularParseException("Too many parts, level="+sp.partlevel+" URI "+sp.getUrl());
671         }
672
673         // debug("do_part(): filename="+filename);
674
// debug("do_part(): paramline="+paramline);
675
part=getfile(filename);
676         if (part!=null) {
677
678             // unlike include we need to map this ourselfs before including it
679
// in this page !!
680
try {
681                 String JavaDoc cachedPart = handlePartCache(filename + "?" + paramline, part, session, sp);
682                 if (cachedPart == null) part = handle_line(part,session,sp); else part = cachedPart;
683             } catch (Exception JavaDoc e) {
684                 String JavaDoc errorMsg = "Error in part "+filename;
685                 if (paramline!=null) errorMsg += "?" + paramline;
686                 errorMsg += "\n" + e.getMessage() + "\n Parted by "+sp.getUrl();
687                 part = errorMsg;
688                 log.error("do_part(): "+errorMsg);
689                 e.printStackTrace();
690             }
691
692             if (markPart>0) {
693                 // Add start and end comments to part
694
String JavaDoc marker = "part "+filename;
695                 if (paramline!=null) marker += "?"+paramline;
696                 String JavaDoc startComment, endComment;
697                 if (markPart==1) { startComment = "<!--"; endComment = "-->"; }
698                 else { startComment = "/*"; endComment = "*/"; }
699                 marker += "\n"+endComment;
700                 part = startComment+"\nStart "+ marker + part + startComment+"\nEnd of " + marker;
701             }
702
703             sp.setParamsVector(oldparams);
704             sp.querystring = oldQueryString;
705             sp.partlevel--;
706             return part;
707         } else {
708             sp.setParamsVector(oldparams);
709             sp.querystring = oldQueryString;
710             sp.partlevel--;
711             return "";
712         }
713     }
714
715     /**
716      * Returns the cached part when the part contains the tag <CACHE HENK> and the page is not exprired and reload is off
717      * else a null wil be returned.
718      */

719     private String JavaDoc handlePartCache(String JavaDoc filename, String JavaDoc part, sessionInfo session, scanpage sp) throws ParseException {
720         if (part == null)
721             return null;
722
723         /* Test if cache HENK is used in this page or not.
724          */

725         int start = part.indexOf("<CACHE HENK");
726         int end;
727         if (start>=0) {
728             start+=11;
729             end = part.indexOf(">", start);
730         } else
731             return null;
732
733         /* Ok it's used. Now look for the specified filename in the cache by (poolname, key, <CACHE HENK expire_time>).
734          */

735         // if (debug) debug("handlePartCache(): lookup " + filename);
736

737         String JavaDoc result = null;
738         if (!sp.reload) {
739             result = scancache.get("HENK", filename, part.substring(start,end+1),sp);
740             if (result != null) {
741                 if(log.isDebugEnabled())
742                     log.debug("Got " + filename + "out of cache HENK.");
743                 return result;
744             }
745         }
746
747         /* The page couldn't be retrieved out of the cache.
748          * Parse it and put it in the cache.
749          */

750         try {
751             // Parse everything before the cache henk tag
752
result = "";
753             if (start>11) {
754                 result = handle_line(part.substring(0,start-11),session,sp);
755             }
756             // Parse everything after the cache henk tag
757
result += handle_line(part.substring(end + 1),session,sp);
758         } catch (Exception JavaDoc e) {
759             String JavaDoc errorMsg = "Error in part "+filename;
760             errorMsg += "\n" + e.getMessage() + "\n Parted by "+sp.getUrl();
761             part = errorMsg;
762             log.error("handlePartCache(): "+errorMsg);
763             log.error(e.getMessage());
764             log.error(Logging.stackTrace(e));
765         }
766         scancache.put("HENK", filename, result);
767         return result;
768     }
769
770     /**
771      * Support method for do_smart
772      * Add version to path if version defined
773      */

774     private static String JavaDoc getVersion(String JavaDoc name, sessionInfo session) {
775         String JavaDoc version = session.getValue(name+"version");
776         if (version!=null) {
777             version=version.trim();
778             if (version.equals("")) version = null;
779         }
780         return version;
781     }
782
783     /**
784      * Support method for do_smart
785      * Return the path for the file to part
786      */

787     private String JavaDoc getSmartFileName( String JavaDoc path, // Path currently investigated
788
String JavaDoc builderPath, // path to add between path and filename for LEAVE version
789
String JavaDoc fileName, // File name of part we are looking for
790
String JavaDoc bestFile, // Last found file which is ok
791
Enumeration nodes, // The passed object nodes
792
sessionInfo session, // The session for version control
793
boolean leaf, // TREE or LEAF version
794
boolean byALias // NAME version
795
) throws ParseException {
796         // Get node from args
797
MMObjectNode node = (MMObjectNode)nodes.nextElement();
798         String JavaDoc nodeNumber;
799         if (byALias) {
800             nodeNumber = ""+mmbase.getOAlias().getAlias(node.getIntValue("number"));
801         } else {
802             nodeNumber = ""+node.getValue("number");
803         }
804
805         // Ask the builder of the node to create the path to search for the part
806
// If null returned we're done and return bestFile
807
path = node.getBuilder().getSmartPath(htmlroot, path, nodeNumber, getVersion(node.getName(), session));
808         if (path==null) {
809             if (log.isDebugEnabled()) log.debug("getSmartFile: no dir found for node "+nodeNumber+". Returning "+bestFile);
810             return bestFile;
811         }
812
813         String JavaDoc newFileName;
814         if (leaf) {
815             // Remove one builder name from the builder path
816
int i = builderPath.indexOf(File.separatorChar);
817             if (i<0) newFileName = path+fileName;
818             else {
819                 builderPath = builderPath.substring(i+1);
820                 newFileName = path + builderPath + File.separator + fileName;
821             }
822         } else newFileName = path + fileName;
823
824         // Check if file present if so, select it as the new bestFile to use
825
String JavaDoc fileToCheck = htmlroot+newFileName;
826         File f = new File(fileToCheck);
827         if (f.exists()) {
828             bestFile = newFileName;
829             if (log.isDebugEnabled()) log.debug("Found and selecting " + newFileName + " as new best file");
830         } else if (log.isDebugEnabled()) log.debug(fileToCheck + " not found, continuing search");
831
832         // If no more object numbers then return the bestFile so far else continue the travel
833
if (!nodes.hasMoreElements())
834             return bestFile;
835
836         return getSmartFileName( path, builderPath, fileName, bestFile, nodes, session, leaf, byALias);
837     }
838
839     /**
840      * TREEPART, TREEFILE, LEAFPART or LEAFFILE
841      * @param args action+objectnumbers+filepath
842      * action: PATH or FILE
843      * objectnumbers: + seperated list of objectnumbers, a ( will start skipping args, a ) will stop skipping args
844      * filepath: (optional) file to part
845      * @param leaf false for TREE and true for LEAF version
846      */

847     private String JavaDoc do_smart(String JavaDoc args, sessionInfo session, scanpage sp, boolean leaf) throws ParseException {
848         // Get action: PART or FILE
849
String JavaDoc cmdName;
850         if (leaf) cmdName = "LEAF"; else cmdName = "TREE";
851         int pos = args.indexOf(" ");
852         if (pos<0) throw new ParseException("Blank expected after <"+cmdName+"PART or FILE");
853         String JavaDoc action = args.substring(0, pos);
854         if (!(action.equals("PART") || action.equals("FILE")))
855             throw new ParseException("PART or FILE expected after <"+cmdName);
856         args = args.substring(pos+1);
857         args = dodollar(args, session, sp);
858         if (log.isDebugEnabled()) log.debug(cmdName+action+" "+args);
859
860         boolean byALias=false;
861         if ((args.length()>=6) && args.substring(0,6).equals("ALIAS ")) {
862             byALias=true;
863             args = args.substring(6); // Returns empty if length 6, no exception
864
}
865
866         int addMarkers = 0;
867         if ((args.length()>=6) && args.substring(0,6).equals("DEBUG ")) {
868             addMarkers = 1;
869             args = args.substring(6); // Returns empty if length 6, no exception
870
}
871         if ((args.length()>=12) && args.substring(0,12).equals("DEBUGCSTYLE ")) {
872             addMarkers = 2;
873             args = args.substring(12); // Returns empty if length 12, no exception
874
}
875
876         // Set root path
877
String JavaDoc path = File.separator;
878
879         // Use the last argument or the builder name of last arg to compose the filename to find
880
// Add the buildernames of the passed nodes to builderPath for leafpart and leaffile
881
String JavaDoc filename = "";
882         String JavaDoc builderPath = "";
883         Vector nodes = new Vector();
884         String JavaDoc arg = "";
885         boolean skip = false;
886         StringTokenizer tokens = new StringTokenizer(args, "+");
887         while (tokens.hasMoreTokens()) {
888             arg = tokens.nextToken().trim();
889             if ((arg==null) || arg.equals(""))
890                 throw new ParseException(cmdName+action+" "+args+": no or empty object number specified");
891             if (skip) { // Skip all args until closing ) found
892
if (arg.equals(")")) skip = false;
893             }
894             else if (arg.equals("(")) skip = true;
895             else {
896                 boolean isNumber = true;
897                 try { Integer.parseInt(arg); } catch (NumberFormatException JavaDoc n) { isNumber = false; }
898                 if (isNumber) {
899                     MMObjectNode node = mmbase.getTypeDef().getNode(arg);
900                     if (node==null) throw new ParseException(cmdName+action+" node "+arg+" not found");
901                     nodes.addElement(node);
902                     if (leaf) builderPath += File.separator + node.getName();
903                 }
904                 else {
905                     // Select the non number as filename to part, first add the remaining tokens
906
while (tokens.hasMoreTokens()) arg+="+"+tokens.nextToken();
907                     filename = arg; // Use it as filename
908
args = ""; // Clear args to pass to part and split filename on ? for new args
909
pos = filename.indexOf('?');
910                     if (pos>=0) {
911                         if (pos<filename.length()-1) args = filename.substring(pos+1);
912                         filename = filename.substring(0, pos);
913                     }
914                     break; // Save one test, we're done
915
}//else
916
}//else
917
}//while
918

919         // If no part name passed as arg, use parts/buildername.shtml?args
920
if (filename.equals("")) {
921             MMObjectNode node = mmbase.getTypeDef().getNode(arg);
922             if (node==null) throw new ParseException(cmdName+action + " node " + arg + " not found");
923             filename = "parts"+File.separator+node.getName()+".shtml";
924         }
925
926         String JavaDoc bestFile;
927         if (leaf) {
928             // Remove leading slash from builderPath
929
if (builderPath.length()>0) builderPath = builderPath.substring(1);
930             // If nothing better found part bestFile
931
bestFile = path + builderPath + File.separator +filename;
932         } else bestFile = path + filename; // If nothing better found part bestFile
933

934         // Travel the smart object tree to find an override of the default part
935
Enumeration e = nodes.elements();
936         if (e.hasMoreElements())
937             bestFile = getSmartFileName( path, builderPath, filename, bestFile, e, session, leaf, byALias);
938
939         if (!args.equals("")) bestFile += "?"+args;
940         if (log.isDebugEnabled()) log.debug(cmdName+action+" using "+bestFile);
941
942         if (action.equals("FILE"))
943             return bestFile;
944
945         return do_part(bestFile, session, sp, addMarkers);
946     }
947
948     /**
949      * @param where A string with the location of the to be parsed file
950      * @return A html-page
951      */

952     public final String JavaDoc getfile(String JavaDoc where) {
953         File scanfile=null;
954         int filesize,len=-1;
955         cacheline cline=null;
956         FileInputStream scan=null;
957         Date lastmod;
958         String JavaDoc rtn=null;
959
960         String JavaDoc filename=htmlroot.trim()+where.trim();
961
962         filename=filename.replace('/',(System.getProperty("file.separator")).charAt(0));
963         filename=filename.replace('\\',(System.getProperty("file.separator")).charAt(0));
964         scanfile = new File(filename);
965         filesize = (int)scanfile.length();
966         lastmod=new Date(scanfile.lastModified());
967         cline=new cacheline(filesize);
968         cline.lastmod=lastmod;
969         try {
970             scan = new FileInputStream(scanfile);
971             len=scan.read(cline.buffer,0,filesize);
972             scan.close();
973         } catch(FileNotFoundException e) {
974             // give_404_error("getfile"); // does not seem to exist.
975
// not nice but, at least it does _something_ now:
976
rtn = "File " + where + " not found";
977             // perhaps better do not show, since it looks ugly in the editors, of which the help files normally are missing...
978
// but at least log:
979
log.error("file not found: "+where);
980         } catch(IOException e) {
981             log.error("IOException: " + Logging.stackTrace(e));
982         }
983         if (len!=-1) {
984             rtn=new String JavaDoc(cline.buffer,0);
985         }
986         log.trace(rtn); // perhaps a little overkill
987
return rtn;
988     }
989
990
991     /**
992      * Main function, replaces most of the $ commands
993      */

994     private final String JavaDoc dodollar(String JavaDoc newbody,sessionInfo session,scanpage sp) throws ParseException {
995
996         if ( newbody.indexOf('$') == -1) {
997             return newbody;
998         }
999
1000        long oldtime = System.currentTimeMillis();
1001
1002        String JavaDoc part,part2;
1003        int qw_pos,qw_pos2,end_pos,end_pos2;
1004
1005        // Parameter fill in
1006
while (newbody.indexOf("$PARAM")!=-1) {
1007            qw_pos=newbody.indexOf("$PARAM");
1008            qw_pos2=qw_pos+7;
1009            part=newbody.substring(0,qw_pos);
1010            part+=do_param(sp,newbody.substring(qw_pos+6,qw_pos2));
1011            part+=newbody.substring(qw_pos2);
1012            newbody=part;
1013        }
1014
1015        // locals fill in
1016
while (newbody.indexOf("$LOCAL")!=-1) {
1017            qw_pos=newbody.indexOf("$LOCAL");
1018            qw_pos2=qw_pos+7;
1019            part=newbody.substring(0,qw_pos);
1020            part+=do_local(newbody.substring(qw_pos+6,qw_pos2));
1021            part+=newbody.substring(qw_pos2);
1022            newbody=part;
1023        }
1024
1025        //debug("dodollar(): 2 " + (System.currentTimeMillis() - oldtime) + " ms." + cookie);
1026

1027        // Personal obj's
1028
part=finddocmd(newbody,"$ID-","^\n\r\"=<> ,",3,session,sp);
1029        newbody=part;
1030
1031        part=finddocmd(newbody,"$LASTLIST","^\n\r\"=<> ,",18,session,sp);
1032        newbody=part;
1033
1034        // OBJects new VERSION
1035
part=finddocmd(newbody,"$AREA-","^\n\r\"=<> ,",16,session,sp);
1036        newbody=part;
1037
1038        // find pages
1039
part=finddocmd(newbody,"$PAGE-","^\n\r\"=<> ,",15,session,sp);
1040        newbody=part;
1041
1042        // find sessions
1043
part=finddocmd(newbody,"$SESSION-","^\n\r\"=<> ,",17,session,sp);
1044        newbody=part;
1045
1046        // OBJects
1047
part=finddocmd(newbody,"$OBJ-",'^',4,session,sp);
1048        newbody=part;
1049        // clone of OBJ
1050
part=finddocmd(newbody,"$VAR-",'^',4,session,sp);
1051        newbody=part;
1052        // clone of OBJ
1053
part=finddocmd(newbody,"$COLOR-",'^',4,session,sp);
1054        newbody=part;
1055        // clone of OBJ
1056
part=finddocmd(newbody,"$TEXT-",'^',4,session,sp);
1057        newbody=part;
1058        // SQL queries
1059
part=finddocmd(newbody,"$SQL-",'^',2,session,sp);
1060        newbody=part;
1061        // CONST , not recognized in finddocmd , so must be build and added there
1062
// part=finddocmd(newbody,"$CONST-",'^',7,session,sp);
1063
// newbody=part;
1064
// Cineserv
1065
// part=finddocmd(newbody,"$DOC-",'^',9,);
1066
// newbody=part;
1067

1068        // Modules
1069
part=finddocmd(newbody,"$MOD-","^\n\r\"=< ,",9,session,sp);
1070        newbody=part;
1071
1072        //debug("dodollar(): 3 " + (System.currentTimeMillis() - oldtime) + " ms." + cookie);
1073

1074        return newbody;
1075    }
1076
1077    // local fill in routine
1078
//private final String do_local(HttpPost poster,String part2) {
1079
private final String JavaDoc do_local(String JavaDoc part2) {
1080        // daniel
1081
String JavaDoc rtn=null;
1082
1083        //rtn=poster.getPostParameter("LOCAL"+part2);
1084
rtn=null;
1085        if (rtn==null) {
1086            rtn="";
1087        }
1088        return rtn;
1089    }
1090
1091    // Parameter fill in routine
1092
private final String JavaDoc do_param(scanpage sp,String JavaDoc part2) {
1093        // rico
1094
int i;
1095        String JavaDoc rtn=null;
1096
1097        if (part2!=null) {
1098            if (part2.equals("L")) {
1099                // Eval $PARAML: the number of params
1100
if (sp.params==null) {
1101                    sp.getParam(0); // Force build of params
1102
if (sp.params==null) // No params
1103
return "0";
1104                }
1105                return ""+sp.params.size();
1106            }
1107            if (part2.equals("A")) {
1108                // Eval $PARAMA
1109
if (sp.querystring == null)
1110                    return "";
1111                return sp.querystring;
1112            }
1113            if (part2.equals("T")) {
1114                // Eval $PARAMT: Returns value of the tail parameter.
1115
if (sp.params==null) {
1116                    sp.getParam(0); // Force build of params
1117
if (sp.params==null) // No params
1118
return "";
1119                }
1120                return sp.getParam(sp.params.size()-1);
1121            }
1122            if (part2.equals("Y")) {
1123                // Eval $PARAMY: Returns value of the tail-1 parameter.
1124
if (sp.params==null) {
1125                    sp.getParam(0); // Force build of params
1126
if (sp.params==null) // No params
1127
return "";
1128                }
1129                if (sp.params.size()<2)
1130                    return "";
1131                return sp.getParam(sp.params.size()-2);
1132            }
1133
1134        }
1135        // Handle $PARAMn
1136
i=Integer.parseInt(part2);
1137        rtn=sp.getParam(i-1);
1138        if (rtn==null) rtn="";
1139        return rtn;
1140    }
1141
1142    /**
1143     * Special commands, this will grow
1144     */

1145    private final String JavaDoc do_save(sessionInfo session,String JavaDoc part) {
1146        StringTokenizer tok= new StringTokenizer(part," -",true);
1147        if (tok.hasMoreTokens()) {
1148            String JavaDoc type=tok.nextToken();
1149            if (type.equals("SESSION")) {
1150                sessions.saveValue(session,part.substring(8));
1151            }
1152        }
1153        return "";
1154    }
1155
1156    private final String JavaDoc do_crc(sessionInfo session,String JavaDoc part) {
1157        part=part.substring(1,part.length()-2);
1158
1159        int crckey=calccrc32(part);
1160        return "<A HREF=\""+part+"+CRC"+crckey+"\">";
1161    }
1162
1163    private final String JavaDoc do_session(String JavaDoc part2,sessionInfo session) {
1164        if (sessions!=null) {
1165            String JavaDoc value=sessions.getValue(session,part2);
1166            if (value!=null) {
1167                return value;
1168            } else {
1169                return "";
1170            }
1171        } else {
1172            return "";
1173        }
1174    }
1175
1176    private final String JavaDoc do_newpage(scanpage sp,String JavaDoc part) {
1177        //debug( "do_newpage("+sp.getUrl()+")");
1178
sp.rstatus=2;
1179        return part;
1180    }
1181
1182    private final String JavaDoc do_goto(scanpage sp,String JavaDoc part) {
1183        sp.rstatus=1;
1184        return part;
1185    }
1186
1187    /**
1188     * Check request host against wanted host and optional backend host
1189     * Handles &lt;HOST [host[,backendhost]]&gt; tag
1190     * @return null and sp.rstatus unchanged if hosts match or in case of an unspecified host
1191     * returns url and sp.rstatus 1, if redir to wantedhost requested
1192     */

1193    private final String JavaDoc do_host(scanpage sp, String JavaDoc hosts) {
1194        String JavaDoc hostDelimiters = ",";
1195        if (hosts==null) return null;
1196
1197        //Get the requested host from the request
1198
if (sp.req==null) return null;
1199        String JavaDoc requestHost = sp.req.getHeader("Host");
1200        if (requestHost==null) return null; // No such header
1201
requestHost = requestHost.trim();
1202        if (requestHost.length() < 1) return null;
1203
1204        // remove port
1205
int i = requestHost.indexOf(':');
1206        if (i==0) return null; // First char :, no host only port....
1207
if (i>0) requestHost = requestHost.substring(0, i);
1208
1209        //try to match requested host with allowed host
1210
StringTokenizer allowedHosts = new StringTokenizer(hosts.trim(),hostDelimiters);
1211
1212        //allowed to use this server? Take the first if no
1213
while (allowedHosts.hasMoreTokens()) {
1214            String JavaDoc aHost = allowedHosts.nextToken().trim();
1215            if (aHost.equalsIgnoreCase(requestHost)) {
1216                log.debug("requested host " + requestHost + " found in allowed host list");
1217                return null;
1218            }
1219        }
1220        String JavaDoc firstHost = null;
1221        int delimitIndex = hosts.indexOf(hostDelimiters);
1222        if (delimitIndex > -1) {
1223            firstHost = hosts.substring(0,delimitIndex).trim();
1224        } else {
1225            firstHost = hosts.trim();
1226        }
1227
1228        if (log.isDebugEnabled()) log.debug("Request host: " + requestHost + "not found, first host: " + firstHost);
1229
1230        // Redirect the request to the wanted host
1231
sp.rstatus = 1;
1232        String JavaDoc url = "http://" + firstHost + sp.getUrl();
1233        if (log.isDebugEnabled()) log.debug("Redirecting to "+url);
1234        return url;
1235    }
1236
1237    /**
1238     * try to acces a module (Must be a ProcessorInterface)
1239     * and replace "part" by whatever the processor returns.
1240     */

1241    private final String JavaDoc do_mod(scanpage sp,String JavaDoc part) {
1242        int index = part.indexOf('-');
1243        if (index == -1) {
1244            log.error("do_mod(): part (no '-'): '" + part+"' ("+sp.getUrl()+")");
1245            return "";
1246        } else {
1247            String JavaDoc moduleName = part.substring(0,index);
1248            String JavaDoc moduleCommand = part.substring(index+1,part.length());
1249
1250            ProcessorInterface proc = getProcessor(moduleName);
1251            if (proc == null) {
1252                log.error("do_mod(): no Processor(" + moduleName +") found for page("+sp.getUrl()+")");
1253                return "";
1254            } else {
1255                return proc.replace(sp, moduleCommand);
1256            }
1257        }
1258    }
1259
1260    /**
1261     * give a name an you get the processor (Interface), if procName does not exists then null is returned.
1262     */

1263    private final ProcessorInterface getProcessor(String JavaDoc procName) {
1264        if (processors.containsKey(procName)) {
1265            return (ProcessorInterface) processors.get(procName);
1266        } else {
1267            Object JavaDoc obj = getModule (procName);
1268            if (obj == null) {
1269                log.error("getProcessor(): Not authorized or not a valid class name: " + procName);
1270                return null;
1271            } else {
1272                // debug(obj);
1273
}
1274
1275            if (obj instanceof ProcessorInterface) {
1276                //debug("servscan.getProcessor: we have a new Processor("+procName+")");
1277
ProcessorInterface pr = (ProcessorInterface) obj;
1278                processors.put(procName,pr);
1279                return pr;
1280            } else {
1281                log.error("getProcessor(): not a valid Processor("+ procName+")");
1282                return null;
1283            }
1284        }
1285    }
1286
1287     private final String JavaDoc do_unmap(String JavaDoc part,sessionInfo session,scanpage sp) throws ParseException {
1288        String JavaDoc part1,part2;
1289        int pnt;
1290
1291        part=dodollar(part,session,sp);
1292        return "";
1293    }
1294
1295    private final String JavaDoc do_do(String JavaDoc part,sessionInfo session,scanpage sp) throws ParseException {
1296        String JavaDoc part1,part2;
1297        int pnt;
1298        part=dodollar(part,session,sp);
1299
1300        // Chop
1301
pnt=part.indexOf('=');
1302        part2=part.substring(pnt+1);
1303        part1=part.substring(0,pnt);
1304        if (part1.indexOf("SESSION-")==0) {
1305            if (sessions!=null) {
1306                // do some sec. checks
1307
sessions.setValue(session,part1.substring(8),part2);
1308            }
1309        } else if (part1.indexOf("ID-")==0) {
1310            String JavaDoc name=HttpAuth.getRemoteUser(sp);
1311            if (name!=null && name.length()>1) {
1312                //setUserServletProperty(part1.substring(3),part2,0);
1313
id.setValue(name,part1.substring(3),part2);
1314            }
1315        }
1316        return "";
1317    }
1318
1319    private final String JavaDoc do_include(String JavaDoc part2,sessionInfo session,scanpage sp) throws ParseException {
1320        String JavaDoc part="";
1321        part2=dodollar(part2,session,sp);
1322        //time(" - cookie = " + cookie + ", doinclude - dodollar", false);
1323
part=getfile(part2);
1324        //time(" - cookie = " + cookie + ", doinclude - doinclude", false);
1325
if (part!=null) {
1326            return part;
1327        } else {
1328            return "";
1329        }
1330    }
1331
1332    private final String JavaDoc do_id(String JavaDoc part2,scanpage sp) {
1333        String JavaDoc name=HttpAuth.getRemoteUser(sp);
1334        String JavaDoc part="";
1335        if (name!=null && name.length()>1) {
1336            //part=getUserServletProperty(part2,0);
1337
part=id.getValue(name,part2);
1338            if (part==null) return "";
1339        } else {
1340            part="Unknown";
1341        }
1342        return part;
1343    }
1344
1345    /**
1346     * This is the generic macro processor.
1347     * It processes the tokens after the &lt;MACRO&gt; tag and gives them in a
1348     * Vector to the processor specified in the page
1349     * Tokens supported of the form :
1350     * tokje=blah
1351     * tokje="blah"
1352     * tokje
1353     * "tokje"
1354     * All seperated by spaces
1355     * To hook into to this create a Processor (@see vpro.james.coreserver.Module
1356     * and @see vpro.james.modules.Processor)
1357     * load it in the server, give servscan permission and put the tag with
1358     * the module name in the html page (&lt;PROCESSOR YourProcessor&gt;, and
1359     * for forms &lt;INPUT TYPE="HIDDEN" NAME="PRC-VAR-PROCESSOR" VALUE="YourProcessor"&gt;)
1360     */

1361    private final String JavaDoc do_macro(String JavaDoc part,sessionInfo session,scanpage sp) throws ParseException {
1362        String JavaDoc tokje;
1363
1364        Vector cmds;
1365        ProcessorInterface tmpprocessor=null;
1366
1367        part=dodollar(part,session,sp);
1368
1369        int pos=part.indexOf("PROCESSOR=");
1370        if (pos!=-1) {
1371            String JavaDoc str=part.substring(pos+10);
1372            if (str.indexOf(' ')!=-1) str=str.substring(0,str.indexOf(' '));
1373            if (str!=null) {
1374                if (str.charAt(0)=='"') str=str.substring(1,str.length()-1);
1375                tmpprocessor=getProcessor(str);
1376
1377                if( tmpprocessor==null ) {
1378                    if (sp.processor!=null)
1379                        log.warn("do_macro(): No processor("+str+") found for page("+sp.getUrl()+"), but scanpage has one.");
1380                    else
1381                        log.error("do_macro(): No processor("+str+") found for page("+sp.getUrl()+")");
1382                }
1383            }
1384        }
1385
1386        cmds=tokenizestring(part);
1387
1388        if (tmpprocessor!=null) {
1389            tokje=htmlgen.getHTMLElement(sp, tmpprocessor,cmds);
1390        } else if (sp.processor!=null) {
1391            tokje=htmlgen.getHTMLElement(sp, sp.processor,cmds);
1392        } else {
1393            log.error("do_macro(): No processor() specified in page("+sp.getUrl()+")");
1394            tokje="<b> No Processor specified in page </b><br />";
1395        }
1396        return tokje;
1397    }
1398
1399    /**
1400     * Method that tokenizes a string into pieces
1401     * Tokens supported of the form :
1402     * tokje=blah
1403     * tokje="blah"
1404     * tokje
1405     * "tokje"
1406     * All seperated by spaces
1407     */

1408    private Vector tokenizestring(String JavaDoc part) {
1409        String JavaDoc current="",tokje;
1410        boolean inDQuote=false;
1411        int pos;
1412        Vector cmds=new Vector();
1413        StringTokenizer tok;
1414
1415        // OK lets chop the parts
1416
tok= new StringTokenizer(part," \"=",true);
1417        while(tok.hasMoreTokens()) {
1418            tokje=tok.nextToken();
1419            if (inDQuote) {
1420                if (tokje.equals("\"")) {
1421                    inDQuote=false;
1422                    current+=tokje;
1423                } else {
1424                    current+=tokje;
1425                }
1426            } else {
1427                if (tokje.equals("\"")) {
1428                    inDQuote=true;
1429                    current+=tokje;
1430                } else if (tokje.equals(" ")) {
1431                    cmds.addElement(current);
1432                    current="";
1433                } else if (tokje.equals("=")) {
1434                    current+=tokje;
1435                } else {
1436                    current+=tokje;
1437                }
1438            }
1439        }
1440        if (!current.equals("")) {
1441            cmds.addElement(current);
1442        }
1443        return cmds;
1444    }
1445
1446    /**
1447     * handle if/then/elseif/\/if
1448     */

1449    String JavaDoc do_conditions_lif(String JavaDoc body,sessionInfo session,scanpage sp) throws ParseException {
1450        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
1451
1452        int depth=0;
1453        int ifpos=0;
1454        int newifpos=0;
1455        int elsepos=0;
1456        int elseifpos=0;
1457        int endifpos=0;
1458
1459        // counters for occurrence
1460
int ifcount=0;
1461        int elsecount=0;
1462        int elseifcount=0;
1463        int endifcount=0;
1464
1465        // boolean if a token was found
1466
boolean found=true;
1467
1468        buffer = new StringBuffer JavaDoc();
1469        ifpos=body.indexOf("<LIF",ifpos);
1470        while (ifpos!=-1) {
1471            // append the part before the <IF
1472
buffer.append(body.substring(0,ifpos));
1473
1474            // unmap this one IF, result will be the correct part+rest
1475
buffer.append(do_if(body.substring(ifpos+4),session,sp));
1476
1477            // convert buffer back to body and clear buffer
1478
body=buffer.toString();
1479            buffer=new StringBuffer JavaDoc();
1480
1481            // try to get a new </IF pos
1482
ifpos=body.indexOf("<LIF");
1483        }
1484        return body;
1485    }
1486
1487    String JavaDoc do_if(String JavaDoc body,sessionInfo session,scanpage sp) throws ParseException {
1488        int endpos=-1;
1489        // first hunt down the command
1490
int pos = body.indexOf('>');
1491        if (pos!=-1) {
1492            String JavaDoc cmd=body.substring(1,pos);
1493            boolean state=do_vals(cmd,session,sp);
1494            body=body.substring(pos+1);
1495
1496            boolean found=false;
1497            int depth=0;
1498            pos=0;
1499            int beg=0;
1500            int end=0;
1501            int els=-1;
1502            while (!found) {
1503                beg=body.indexOf("<IF",pos);
1504                end=body.indexOf("</IF>",pos);
1505                if (beg==-1 || beg>end) {
1506                    if (depth==0) {
1507                        found=true;
1508                        if (els==-1) {
1509                            els=body.indexOf("<ELSE>",pos);
1510                            if (els>end) els=-1;
1511                        }
1512                    } else {
1513                        depth--;
1514                        pos=end+2;
1515                    }
1516                } else {
1517                    if (depth==0 && els==-1) {
1518                        els=body.indexOf("<ELSE>",pos);
1519                        if (els>end && els<beg) els=-1;
1520                    }
1521                    pos=beg+2;
1522                    depth++;
1523                }
1524            }
1525            if (els==-1) {
1526                if (state) {
1527                    body=body.substring(0,end)+body.substring(end+5);
1528                } else {
1529                    body=body.substring(end+5);
1530                }
1531            } else {
1532                if (state) {
1533                    body=body.substring(0,els)+body.substring(end+5);
1534                } else {
1535                    body=body.substring(els+6,end)+body.substring(end+5);
1536                }
1537            }
1538        } else {
1539            log.error("do_if(): no end on if command");
1540        }
1541        return body;
1542    }
1543
1544
1545    /**
1546     * handle if/then/elseif/\/if
1547     */

1548    String JavaDoc do_conditions(String JavaDoc body,sessionInfo session,scanpage sp) throws ParseException {
1549        StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
1550
1551        int depth=0;
1552        int ifpos=0;
1553        int newifpos=0;
1554        int elsepos=0;
1555        int elseifpos=0;
1556        int endifpos=0;
1557
1558        // counters for occurrence
1559
int ifcount=0;
1560        int elsecount=0;
1561        int elseifcount=0;
1562        int endifcount=0;
1563
1564        // boolean if a tken was found
1565
boolean found=true;
1566
1567        buffer = new StringBuffer JavaDoc();
1568        ifpos=body.indexOf("<IF",ifpos);
1569        while (ifpos!=-1) {
1570            // append the part before the <IF
1571
buffer.append(body.substring(0,ifpos));
1572
1573            // unmap this one IF, result will be the correct part+rest
1574
buffer.append(do_if(body.substring(ifpos+3),session,sp));
1575
1576            // convert buffer back to body and clear buffer
1577
body=buffer.toString();
1578            buffer=new StringBuffer JavaDoc();
1579
1580            // try to get a new </IF pos
1581
ifpos=body.indexOf("<IF");
1582        }
1583        return body;
1584    }
1585
1586    private String JavaDoc do_list(String JavaDoc cmd,String JavaDoc template, sessionInfo session,scanpage sp) throws ParseException {
1587        long ll1,ll2;
1588        StringBuffer JavaDoc rtn=new StringBuffer JavaDoc();
1589        ProcessorInterface tmpprocessor=null;
1590        String JavaDoc command=null;
1591        String JavaDoc sorted=null;
1592        String JavaDoc sortedpos=null;
1593        String JavaDoc str,key=null;
1594        StringTagger tagger=null;
1595        Object JavaDoc obj;
1596        Vector t,cmds,result;
1597        int numitems=1,maxitems=-1,curitem=0,offset=0;
1598        int maxtotal=-1;
1599
1600        ll1=System.currentTimeMillis();
1601        cmd=dodollar(cmd,session,sp);
1602        cmd=Strip.Whitespace(cmd,Strip.BOTH);
1603        String JavaDoc oldcmd=cmd;
1604
1605        String JavaDoc wantCache="HENK";
1606        if (sp.reload) {
1607            if (cmd.indexOf(" CACHE=")!=-1) {
1608                String JavaDoc rst=scancache.get("HENK","/LISTS/"+cmd+template,sp);
1609                if (rst!=null) {
1610                    return rst;
1611                }
1612            }
1613        }
1614
1615        cmds=tokenizestring(cmd);
1616
1617        t=new Vector();
1618        int pos=cmd.indexOf('"');
1619        if (pos==0) {
1620            pos=cmd.indexOf('"',pos+1);
1621            if (pos!=-1) {
1622                command=cmd.substring(0,pos+1);
1623                if ((pos+1)!=cmd.length()) {
1624                    cmd=cmd.substring(pos+2);
1625                } else {
1626                    cmd="";
1627                }
1628            }
1629        } else {
1630            pos=cmd.indexOf(' ');
1631            if (pos!=-1) {
1632                command=cmd.substring(0,pos);
1633                cmd=cmd.substring(pos+1);
1634            }
1635        }
1636
1637        // Process commands to list if any parse them but they can be overiden
1638
// by the processor
1639
if (cmds.size()>1) {
1640            tagger=new StringTagger(cmd,' ','=',',','"');
1641
1642            /*
1643            str=tagger.Value("ITEMS");
1644            try {
1645                numitems=Integer.parseInt(str);
1646            } catch (NumberFormatException x) {
1647                numitems=1;
1648            }
1649            */

1650
1651            str=tagger.Value("MAX");
1652            try {
1653                maxitems=Integer.parseInt(str);
1654            } catch (NumberFormatException JavaDoc x) {
1655                maxitems=-1;
1656            }
1657            maxtotal=maxitems;
1658
1659            str=tagger.Value("OFFSET");
1660            try {
1661                offset=Integer.parseInt(str);
1662            } catch (NumberFormatException JavaDoc x) {
1663                offset=0;
1664            }
1665
1666            str=tagger.Value("AUTORANGE");
1667            if (str!=null && maxitems!=-1) {
1668                int u=str.indexOf('/');
1669                if (u!=-1) {
1670                    key=str.substring(0,u);
1671                    String JavaDoc acmd=str.substring(u+1);
1672                    String JavaDoc value=sessions.getValue(session,key);
1673                    try {
1674                        offset=Integer.parseInt(value);
1675                    } catch (NumberFormatException JavaDoc x) {
1676                        offset=0;
1677                    }
1678                    if (acmd.equals("NEXT")) {
1679                        //sessions.setValue(session,key,""+(offset+maxitems));
1680
offset=offset+maxitems;
1681                    } else
1682                    if (acmd.equals("PREV")) {
1683                        //sessions.setValue(session,key,""+(offset-maxitems));
1684
offset=offset-maxitems;
1685                    } else {
1686                        offset=0;
1687                        sessions.setValue(session,key,"0");
1688                    }
1689                }
1690            }
1691
1692            sorted=tagger.Value("SORTED");
1693            sortedpos=tagger.Value("SORTPOS");
1694
1695            str=tagger.Value("PROCESSOR");
1696            if (str!=null) {
1697                if (str.charAt(0)=='"') str=str.substring(1,str.length()-1);
1698                tmpprocessor=getProcessor(str);
1699            }
1700
1701        } else {
1702            tagger=new StringTagger("",' ','=',',','"');
1703        }
1704
1705        if (sessions!=null && session!=null && key!=null) {
1706            sessions.setValue(session,key,""+offset);
1707        }
1708
1709        String JavaDoc version=tagger.Value("VERSION");
1710        if (version==null || version.equals("1.0")) {
1711            // is there a proccesor defined ?
1712
if (sp.processor!=null || tmpprocessor!=null) {
1713                // Call the processor to get the real info this might override
1714
// some of the layout calls like numitems and sort etc etc
1715
if (tmpprocessor==null) {
1716                    result=sp.processor.getList(sp,tagger,command);
1717                } else {
1718                    result=tmpprocessor.getList(sp,tagger,command);
1719                }
1720                // do we have a result ifso do the layout stuff
1721
if (result!=null) {
1722                    // added reverse, should be changed soon
1723
if (sorted!=null && sorted.equals("ALPHA")) result=SortedVector.SortVector(result);
1724
1725                    // get the number of items set by the user or by the processor
1726
str=tagger.Value("ITEMS");
1727                    if (str!=null) {
1728                        try {
1729                            numitems=Integer.parseInt(str);
1730                        } catch (NumberFormatException JavaDoc x) {
1731                            numitems=1;
1732                        }
1733                    } else {
1734                        numitems=1;
1735                    }
1736
1737                    if (sorted!=null && sorted.equals("MALPHA")) {
1738                        if (sortedpos!=null) {
1739                            result=doMAlphaSort(result,sortedpos,numitems);
1740                        } else {
1741                            result=doMAlphaSort(result,"1",numitems);
1742                        }
1743                    }
1744
1745                    if (sorted!=null && sorted.equals("REVERSE")) result=reverse(result,numitems);
1746
1747                    curitem=1;
1748                    int jsize=result.size();
1749                    if (maxtotal==-1 || maxtotal>(jsize/numitems)) maxtotal=jsize/numitems;
1750                    if (maxitems==-1) {
1751                        maxitems=jsize;
1752                    } else {
1753                        maxitems=(maxitems*numitems)+(offset*numitems);
1754                        if (maxitems>jsize) {
1755                            maxitems=jsize;
1756                            if (key!=null) {
1757                                //sessions.setValue(session,key,"-1");
1758
}
1759                        }
1760                    }
1761                    offset*=numitems;
1762                    for (int j=offset;j<maxitems;j+=numitems) {
1763                        t.removeAllElements();
1764                        for (int i=0;i<numitems;i++) {
1765                            try {
1766                                obj=result.elementAt(j+i);
1767                                if (obj==null) obj="NULL";
1768                            } catch (ArrayIndexOutOfBoundsException JavaDoc r) {
1769                                obj="No Such Element";
1770                            }
1771                            t.addElement(obj);
1772                        }
1773                        rtn.append(processtemplate(t,template,curitem+(offset/numitems),jsize/numitems,curitem,numitems));
1774                        //rtn.append(processtemplate(t,template,curitem+(offset/numitems),maxtotal,curitem));
1775
curitem++;
1776                    }
1777                    // org.mmbase lastlistitem=curitem;
1778
} else {
1779                    rtn.append(" Processor failed to process command <br />");
1780                    log.error("do_list(): Processor failed to process command : "+cmd+" ("+sp.processor+") ("+tmpprocessor+")");
1781                }
1782            } else {
1783                rtn.append(" No Processor specified in page <br />");
1784            }
1785        } else if (version.equals("2.0")) {
1786            // is there a proccesor defined ?
1787
//debug("do_list(): LIST 2.0 -> Start");
1788
long ltime1=System.currentTimeMillis();
1789            if (sp.processor!=null || tmpprocessor!=null) {
1790                // Call the processor to get the real info this might override
1791
// some of the layout calls like numitems and sort etc etc
1792
if (tmpprocessor==null) {
1793                    result=sp.processor.getList(sp,tagger,command);
1794                } else {
1795                    result=tmpprocessor.getList(sp,tagger,command);
1796                }
1797                long ltime2=System.currentTimeMillis();
1798                //debug("do_list(): LIST 2.0 -> GETLIST="+(ltime2-ltime1));
1799
ltime1=ltime2;
1800
1801                // do we have a result ifso do the layout stuff
1802
if (result!=null) {
1803                    // added reverse, should be changed soon
1804
if (sorted!=null && sorted.equals("ALPHA")) result=SortedVector.SortVector(result);
1805
1806                    // get the number of items set by the user or by the processor
1807
str=tagger.Value("ITEMS");
1808                    if (str!=null) {
1809                        try {
1810                            numitems=Integer.parseInt(str);
1811                        } catch (NumberFormatException JavaDoc x) {
1812                            numitems=1;
1813                        }
1814                    } else {
1815                        numitems=1;
1816                    }
1817
1818                    if (sorted!=null && sorted.equals("REVERSE")) result=reverse(result,numitems);
1819
1820                    //debug("PART="+template);
1821

1822                    String JavaDoc listprepart=null;
1823                    String JavaDoc listendpart=null;
1824                    // if there is a LISTLOOP split it in 3 parts
1825
int listprepos=template.indexOf("<LISTLOOP>");
1826                    int listendpos=template.indexOf("</LISTLOOP>");
1827                    if (listprepos!=-1) {
1828                        // oke found a listloop
1829
listprepart=template.substring(0,listprepos);
1830                        listendpart=template.substring(listendpos+11);
1831                        template=template.substring(listprepos+10,listendpos);
1832                    }
1833
1834                    //debug("do_list(): PRE="+listprepart+"*");
1835
//debug("do_list(): PART="+template+"*");
1836
//debug("do_list(): END="+listendpart+"*");
1837

1838                    // new part handles the 'prepart' of LISTLOOP
1839
// ends new part handles the 'prepart' of LISTLOOP
1840

1841                    curitem=1;
1842                    int jsize=result.size();
1843                    if (maxtotal==-1 || maxtotal>(jsize/numitems)) maxtotal=jsize/numitems;
1844                    if (maxitems==-1) {
1845                        maxitems=jsize;
1846                    } else {
1847                        maxitems=(maxitems*numitems)+(offset*numitems);
1848                        if (maxitems>jsize) {
1849                            maxitems=jsize;
1850                            if (key!=null) {
1851                                //sessions.setValue(session,key,"-1");
1852
}
1853                        }
1854                    }
1855                    offset*=numitems;
1856
1857                    // added for prelist/endlist
1858
if (listprepart!=null && !listprepart.equals("")) {
1859                        rtn.append(doPrePart(listprepart,jsize/numitems,offset/numitems,maxitems/numitems,numitems));
1860                    }
1861
1862                    for (int j=offset;j<maxitems;j+=numitems) {
1863                        t.removeAllElements();
1864                        for (int i=0;i<numitems;i++) {
1865                            try {
1866                                obj=result.elementAt(j+i);
1867                                if (obj==null) obj="NULL";
1868                            } catch (ArrayIndexOutOfBoundsException JavaDoc r) {
1869                                obj="No Such Element";
1870                            }
1871                            t.addElement(obj);
1872                        }
1873                        rtn.append(processtemplate(t,template,curitem+(offset/numitems),jsize/numitems,curitem,numitems));
1874                        //rtn.append(processtemplate(t,template,curitem+(offset/numitems),maxtotal,curitem));
1875
curitem++;
1876                    }
1877                    // org.mmbase lastlistitem=curitem;
1878

1879                    // added for prelist/endlist
1880
if (listendpart!=null && !listendpart.equals("")) {
1881                        rtn.append(doEndPart(listendpart,jsize/numitems,offset/numitems,maxitems/numitems,numitems));
1882                    }
1883
1884                    ltime2=System.currentTimeMillis();
1885                    //debug("do_list(): LIST 2.0 -> PROCESSTEMPLATE="+(ltime2-ltime1));
1886
ltime1=ltime2;
1887                } else {
1888                    rtn.append(" Processor failed to process command <br />");
1889                    log.error("do_list(): Processor failed to process command : "+cmd+" ("+sp.processor+") ("+tmpprocessor+")");
1890                }
1891            } else {
1892                rtn.append(" No Processor specified in page <br />");
1893            }
1894            //debug("do_list(): LIST 2.0 -> End");
1895
}
1896
1897        // -----------------------------------
1898

1899        if (cmd.indexOf(" CACHE=")!=-1) {
1900            scancache.put("HENK","/LISTS/"+oldcmd+template,rtn.toString());
1901        }
1902        ll2=System.currentTimeMillis();
1903        if (log.isDebugEnabled() && (ll2-ll1)>300) {
1904            log.debug("do_list(): time("+(ll2-ll1)+" ms)");
1905        }
1906        return rtn.toString();
1907    }
1908
1909    private String JavaDoc processtemplate(Vector v,String JavaDoc template, int pos, int last, int rpos, int numitems) {
1910        int precmd=0,postcmd=0,prepostcmd=0,index;
1911        StringBuffer JavaDoc dst=new StringBuffer JavaDoc();
1912        String JavaDoc cmd="$ITEM";
1913        int endc='^';
1914        if (template==null) return "No Template";
1915        if (v==null) return "Vector is null";
1916        while ((precmd=template.indexOf(cmd,postcmd))!=-1) {
1917            dst.append(template.substring(postcmd,precmd));
1918            prepostcmd=precmd+cmd.length();
1919            postcmd=precmd+6;
1920            try {
1921                index=Integer.parseInt(template.substring(prepostcmd,postcmd));
1922                try {
1923                    index=Integer.parseInt(template.substring(prepostcmd,postcmd+1));
1924                    postcmd++;
1925                } catch (Exception JavaDoc g) {}
1926                index--;
1927                try {
1928                    dst.append((v.elementAt(index)).toString());
1929                } catch (ArrayIndexOutOfBoundsException JavaDoc e) {}
1930            } catch (NumberFormatException JavaDoc e) {
1931                //index=1;
1932
try {
1933                    if (template.charAt(prepostcmd)=='P') {
1934                        dst.append(""+pos);
1935                    } else if (template.charAt(prepostcmd)=='L') {
1936                        dst.append(""+last);
1937                    } else if (template.charAt(prepostcmd)=='R') {
1938                        dst.append(""+rpos);
1939                    } else if (template.charAt(prepostcmd)=='S') {
1940                        dst.append(""+numitems);
1941                    } else if (template.charAt(prepostcmd)=='F') {
1942                        if (pos==last) {
1943                            dst.append("YES");
1944                        } else {
1945                            dst.append("NO");
1946                        }
1947                    }
1948                } catch (ArrayIndexOutOfBoundsException JavaDoc f) {}
1949            }
1950        }
1951        dst.append(template.substring(postcmd));
1952        return dst.toString();
1953    }
1954
1955    // how do we handle multihosts in servlet API now ?
1956
Hashtable getRoots() {
1957        /*
1958        int pos;
1959        String tmp,tmp2;
1960        Hashtable result=new Hashtable();
1961        result.put("www",DocumentRoot);
1962
1963        for (Enumeration e=getInitParameters().keys();e.hasMoreElements();) {
1964            tmp=(String)e.nextElement();
1965            tmp2=(String)getInitParameter(tmp);
1966            pos=tmp.indexOf("Root.");
1967            if (pos==0) {
1968                result.put(tmp.substring(5),tmp2);
1969            }
1970        }
1971        */

1972        Hashtable result=new Hashtable();
1973        return result;
1974    }
1975
1976    /**
1977     * This does the handling of the Form inputs.
1978     * It calls the processor to handle the PRC-CMD's it finds after
1979     * it has done the PRC-VAR's fill in.
1980     */

1981    public final void do_proc_input(String JavaDoc rq_line,HttpPost poster,Hashtable proc_var,Hashtable proc_cmd,scanpage sp) {
1982        String JavaDoc part,part2,sqlstatement;
1983        Object JavaDoc obj;
1984        int qw_pos,qw_pos2;
1985        Vector results;
1986
1987        // First find the processor of this page
1988
if ((part=(String JavaDoc)proc_var.get("PROCESSOR"))!=null) {
1989            //processor=(Processor)getModule(part);
1990
sp.processor=getProcessor(part);
1991            if (sp.processor!=null) {
1992                sp.processor.process(sp,proc_cmd,proc_var);
1993            } else {
1994                log.error("do_proc_input(): Processor("+part+") is not loaded in server for page("+sp.getUrl()+")");
1995            }
1996        } else {
1997            log.warn("do_proc_input(): No Processor specified : "+rq_line);
1998            log.info("do_proc_input(): proc_var="+proc_var);
1999            log.info("do_proc_input(): proc_cmd="+proc_cmd);
2000            return;
2001        }
2002        return;
2003    }
2004
2005    public String JavaDoc calcPage(String JavaDoc part2,scanpage sp,int cachetype) {
2006
2007        if (log.isDebugEnabled()) log.debug("calcPage("+part2+","+sp.getUrl()+","+cachetype+")");
2008
2009        try {
2010            String JavaDoc filename,paramline=null;
2011
2012            // we now may have a a param setup like part.shtml?1212+1212+1212
2013
// split it so we can load the file and get the params
2014
int pos=part2.indexOf('?');
2015            if (pos!=-1) {
2016                filename=part2.substring(0,pos);
2017                paramline=part2.substring(pos+1);
2018                //((worker)req).setParamLine(paramline);
2019
sp.setParamsLine(paramline);
2020                if (sp.req_line==null) sp.req_line=filename;
2021                if (log.isDebugEnabled()) log.debug("calcPage(): setting paramline="+paramline);
2022            } else {
2023                filename=part2;
2024            }
2025            if ((sp.mimetype==null) || sp.mimetype.equals("")) {
2026                sp.mimetype=getMimeTypeFile(filename);
2027            }
2028
2029            if (log.isDebugEnabled()) {
2030                log.debug("calcPage(): filename="+filename);
2031                log.debug("calcPage(): paramline="+paramline);
2032                log.debug("calcPage(): mimetype="+sp.mimetype);
2033            }
2034            sp.body=getfile(filename);
2035
2036            if (sp.body!=null) {
2037
2038                String JavaDoc wantCache=null;
2039
2040                if (sp.body.indexOf("<CACHE PAGE")!=-1) {
2041                    wantCache="PAGE";
2042                }
2043                if (sp.body.indexOf("<CACHE HENK")!=-1) {
2044                    wantCache="HENK";
2045                }
2046                sp.wantCache=wantCache;
2047                // end cache
2048
// unlike include we need to map this ourselfs before including it
2049
// in this page !!
2050
//part=handle_line(part,req);
2051
sp.body=handle_line(sp.body,sp.session,sp);
2052                if (wantCache!=null) {
2053                    scancache.newput2(wantCache,part2,sp.body,cachetype, sp.mimetype);
2054                }
2055
2056                return sp.body;
2057            } else {
2058                return "";
2059            }
2060        } catch (Exception JavaDoc r) {
2061            log.error("calcPage("+part2+","+sp.getUrl()+","+cachetype+"): "+r);
2062            r.printStackTrace();
2063            return "";
2064        }
2065    }
2066
2067    /**
2068     * Start a process to calculate a page in the background
2069     * used by scancache to generate new pages for expired ones
2070     * @param sp The request of the page (duplicated from the original)
2071     * @param uri The uri of the request
2072     */

2073    public synchronized void processPage(scanpage sp,String JavaDoc uri) {
2074        if (!pagesprocessing.containsKey(uri)) {
2075            log.debug("processPage : creating process for: "+uri);
2076            PageProcess pp=new PageProcess(this,sp,uri);
2077            pagesprocessing.put(uri,pp);
2078            log.debug("processPage : currently running "+pagesprocessing);
2079        } else {
2080            log.debug("processPage : page already in progress: "+uri);
2081        }
2082    }
2083
2084    /**
2085     * Remove a PageProcess from the list of pages currently being calculated
2086     * @param uri Uri of the request being calculated
2087     */

2088    public void removeProcess(String JavaDoc uri) {
2089        pagesprocessing.remove(uri);
2090    }
2091
2092    /**
2093     * davzev changed method syntax from int sortonnumber to String sortonnumbers.
2094     * Sort the lines in the vector, to do this we need to first group
2095     * them and then sort them by item number defined
2096     * @param input - the result Vector unsorted.
2097     * @param sortonnumbers - a String with colpositions eg. "6:4" denoting the
2098     * order and colpositions for the sort.
2099     * @param numberofitems - integer with the amount of items.
2100     * @return a Vector with sorted items.
2101     */

2102    Vector doMAlphaSort(Vector input,String JavaDoc sortonnumbers,int numberofitems) {
2103
2104        //SortedVector output = new SortedVector(new RowVectorCompare(sortonnumber));
2105
if (log.isDebugEnabled()) log.debug("doMAlphaSort: Sorting using MultiColCompare("+sortonnumbers+ ")");
2106        SortedVector output = new SortedVector(new MultiColCompare(sortonnumbers));
2107        // first create vectors with numberofitems per vector
2108
Enumeration einput=input.elements();
2109        while (einput.hasMoreElements()) {
2110            Vector row=new Vector();
2111            for (int i=0;i<numberofitems;i++) {
2112                row.addElement((String JavaDoc)einput.nextElement());
2113            }
2114            output.addSorted(row);
2115        }
2116        Vector result=new Vector();
2117        Enumeration eoutput=output.elements();
2118        while (eoutput.hasMoreElements()) {
2119            Vector row=(Vector)eoutput.nextElement();
2120            Enumeration erow=row.elements();
2121            while (erow.hasMoreElements()) {
2122                result.addElement(erow.nextElement());
2123            }
2124        }
2125        return result;
2126    }
2127
2128    private String JavaDoc printURI(scanpage sp) {
2129        String JavaDoc rtn="";
2130        if (sp!=null) {
2131            if (sp.req_line!=null) {
2132                rtn=sp.req_line;
2133            } else {
2134                rtn="req_line==NULL";
2135            }
2136        } else {
2137            rtn="scanpage==NULL";
2138        }
2139        return rtn;
2140    }
2141
2142    private String JavaDoc do_transaction(String JavaDoc template, sessionInfo session,scanpage sp) throws ParseException {
2143        transactionhandler.handleTransaction(template,session,sp);
2144        return "";
2145    }
2146
2147
2148    public static int calccrc32(String JavaDoc str) {
2149        CRC32 crc=new CRC32();
2150        str=""+crcseed+str+crcseed;
2151        byte dst[]=new byte[str.length()];
2152
2153        str.getBytes(0,str.length(),dst,0);
2154        crc.update(dst);
2155        return (int)crc.getValue();
2156    }
2157}
2158
Popular Tags