2 * Copyright (C) 2001, 2002 The Mir-coders group
4 * This file is part of Mir.
6 * Mir is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * Mir is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with Mir; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 * In addition, as a special exception, The Mir-coders gives permission to link
21 * the code of this program with the com.oreilly.servlet library, any library
22 * licensed under the Apache Software License, The Sun (tm) Java Advanced
23 * Imaging library (JAI), The Sun JIMI library (or with modified versions of
24 * the above that use the same license as the above), and distribute linked
25 * combinations including the two. You must obey the GNU General Public
26 * License in all respects for all of the code used other than the above
27 * mentioned libraries. If you modify this file, you may extend this exception
28 * to your version of the file, but you are not obligated to do so. If you do
29 * not wish to do so, delete this exception statement from your version.
37 import java.text.NumberFormat;
41 * Statische Hilfsmethoden zur Stringbehandlung
43 * @version $Revision: 1.25 $ $Date: 2002/09/14 03:32:12 $
44 * @author $Author: zapata $
46 * $Log: StringUtil.java,v $
47 * Revision 1.25 2002/09/14 03:32:12 zapata
48 * fixed a small email address filtering bug
50 * Revision 1.24 2002/09/01 22:05:50 mh
53 * Revision 1.23.2.1 2002/09/01 21:31:40 mh
56 * Revision 1.23 2002/06/28 20:39:37 mh
57 * added numberformat helper. make webdbDate2readableDate use webdb_create instead. make the order and appearance of it more consistent. cvs macros. and finally code tidying
61 public final class StringUtil {
63 private static RE re_newline2br, re_brbr2p, re_mail, re_url, re_tags;
65 private StringUtil() { } // this avoids contruction
70 re_newline2br = new RE("(\r?\n){1}");
71 re_brbr2p = new RE("(<br>\r?\n<br>){1,}");
72 re_mail = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)");
73 re_url = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
74 re_tags = new RE("<[^>]*>",RE.REG_ICASE);
76 catch (REException e){
77 System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
82 * Formats a number with the specified minimum and maximum number of digits.
84 public static synchronized String zeroPaddingNumber(long value, int minDigits,
87 NumberFormat numberFormat = NumberFormat.getInstance();
88 numberFormat.setMinimumIntegerDigits(minDigits);
89 numberFormat.setMaximumIntegerDigits(maxDigits);
90 return numberFormat.format(value);
94 * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
96 * @return 8-ziffriger String (yyyymmdd)
99 public static final String date2webdbDate (GregorianCalendar theDate) {
100 StringBuffer webdbDate = new StringBuffer();
101 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
102 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
103 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
104 return webdbDate.toString();
108 * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
110 * @return 12-ziffriger String (yyyymmdd)
113 public static final String date2webdbDateTime (GregorianCalendar theDate) {
114 StringBuffer webdbDate = new StringBuffer();
115 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
116 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
117 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
118 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
119 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
120 return webdbDate.toString();
124 * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)
126 * @return w3approved datetime
129 public static final String date2w3DateTime (GregorianCalendar theDate) {
130 StringBuffer webdbDate = new StringBuffer();
131 webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
132 webdbDate.append("-");
133 webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
134 webdbDate.append("-");
135 webdbDate.append(pad2(theDate.get(Calendar.DATE)));
136 webdbDate.append("T");
137 webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
138 webdbDate.append(":");
139 webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
140 webdbDate.append(":");
141 webdbDate.append(pad2(theDate.get(Calendar.SECOND)));
142 //assumes you are an hour-multiple away from UTC....
143 int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));
145 webdbDate.append("-");
148 webdbDate.append("+");
150 webdbDate.append(pad2(Math.abs(offset)));
151 webdbDate.append(":00");
152 return webdbDate.toString();
156 * wandelt Calendar in dd.mm.yyyy / hh.mm um
158 * @return String mit (dd.mm.yyyy / hh.mm um)
160 public static String date2readableDateTime (GregorianCalendar theDate) {
161 String readable = "";
163 readable += pad2(theDate.get(Calendar.DATE));
164 readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
165 readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
166 hour = theDate.get(Calendar.HOUR);
167 if (theDate.get(Calendar.AM_PM) == Calendar.PM)
169 readable += " / " + pad2(hour);
170 readable += ":" + pad2(theDate.get(Calendar.MINUTE));
175 * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
179 * @return String mit <code>/yyyy/mm/dd</code>
181 public static final String webdbDate2path (String webdbDate) {
182 StringBuffer path = new StringBuffer();
183 path.append("/").append(webdbDate.substring(0, 4));
184 path.append("/").append(webdbDate.substring(4, 6));
187 //path.append("/").append(webdbDate.substring(6, 8));
188 return path.toString();
192 * wandelt Calendar in dd.mm.yyyy um
195 * @return String mit <code>yyyy.mm.dd</code>
197 public static final String webdbDate2readableDate (String webdbDate) {
199 date += webdbDate.substring(0, 4);
200 date += "-" + webdbDate.substring(5, 7);
201 date += "-"+webdbDate.substring(8, 10);
207 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
208 * to dd.mm.yyyy hh:mm
210 public static String dateToReadableDate(String date) {
211 StringBuffer returnDate = new StringBuffer();
214 returnDate.append(date.substring(8,10)).append('.');
215 returnDate.append(date.substring(5,7)).append('.');
216 returnDate.append(date.substring(0,4)).append(' ');
217 returnDate.append(date.substring(11,16));
219 return returnDate.toString();
223 * converts string from format: yyyy-mm-dd__hh:mm:ss.dddddd+TZ
224 * to yyyy-mm-ddThh:mm:ss+TZ:00 (w3 format for Dublin Core)
226 public static String webdbdateToDCDate(String date) {
227 StringBuffer returnDate = new StringBuffer();
229 returnDate.append(date.substring(0,10));
230 returnDate.append("T");
231 returnDate.append(date.substring(11,19));
232 //String tzInfo=date.substring(26,29);
233 //if (tzInfo.equals("+00")){
234 //UTC gets a special code in w3 dates
235 // returnDate.append("Z");
238 //need to see what a newfoundland postgres
239 //timestamp looks like before making this robust
240 // returnDate.append(tzInfo);
241 // returnDate.append(":00");
245 return returnDate.toString();
250 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
253 public static String dateToYear (String date) {
254 StringBuffer returnDate = new StringBuffer();
257 returnDate.append(date.substring(0,4));
259 return returnDate.toString();
263 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
266 public static String dateToMonth (String date) {
267 StringBuffer returnDate = new StringBuffer();
269 if (!date.substring(5,6).equalsIgnoreCase("0")) returnDate.append(date.substring(5,7));
270 else returnDate.append(date.substring(6,7));
272 return returnDate.toString();
276 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
279 public static String dateToDayOfMonth (String date) {
280 StringBuffer returnDate = new StringBuffer();
282 if (!date.substring(8,9).equalsIgnoreCase("0")) returnDate.append(date.substring(8,10));
283 else returnDate.append(date.substring(9,10));
285 return returnDate.toString();
289 * converts string from format: yyyy-mm-dd__hh:mm:ss.d
292 public static String dateToTime (String date) {
293 StringBuffer returnDate = new StringBuffer();
295 returnDate.append(date.substring(11,16));
297 return returnDate.toString();
301 * Splits the provided CSV text into a list. stolen wholesale from
302 * from Jakarta Turbine StrinUtils.java -mh
304 * @param text The CSV list of values to split apart.
305 * @param separator The separator character.
306 * @return The list of values.
308 public static String[] split(String text, String separator)
310 StringTokenizer st = new StringTokenizer(text, separator);
311 String[] values = new String[st.countTokens()];
313 while (st.hasMoreTokens())
315 values[pos++] = st.nextToken();
321 * Joins the elements of the provided array into a single string
322 * containing a list of CSV elements. Stolen wholesale from Jakarta
323 * Turbine StringUtils.java. -mh
325 * @param list The list of values to join together.
326 * @param separator The separator character.
327 * @return The CSV text.
329 public static String join(String[] list, String separator)
331 StringBuffer csv = new StringBuffer();
332 for (int i = 0; i < list.length; i++)
336 csv.append(separator);
340 return csv.toString();
345 * schließt einen String in Anführungsszeichen ein, falls er Leerzeichen o.ä. enthält
347 * @return gequoteter String
349 public static String quoteIfNecessary(String s) {
350 for (int i = 0; i < s.length(); i++)
351 if (!(Character.isLetterOrDigit(s.charAt(i)) || s.charAt(i) == '.'))
352 return quote(s, '"');
357 * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
358 * "gefährliche" Zeichen innerhalb des Strings
359 * Quotes special SQL-characters in <code>s</code>
361 * @return geqoteter String
363 public static String quote(String s)
365 //String s2 = quote(s, '\'');
366 //Quickhack ÊÊ Ê Ê Ê Ê Ê Ê
367 //Because of '?-Bug in Postgresql-JDBC-Driver
368 StringBuffer temp = new StringBuffer();
369 for(int i=0;i<s.length();i++){
370 if(s.charAt(i)=='\''){
371 temp.append("'");
373 temp.append(s.charAt(i));
376 String s2 = temp.toString();
379 s2 = quote(s2, '\"');
384 * schließt <code>s</code> in <code>'</code> ein und setzt Backslashes vor
385 * "gefährliche" Zeichen innerhalb des Strings
387 * @param s String, der gequoted werden soll
388 * @param quoteChar zu quotendes Zeichen
389 * @return gequoteter String
391 public static String quote(String s, char quoteChar)
393 StringBuffer buf = new StringBuffer(s.length());
395 while (pos < s.length()) {
396 int i = s.indexOf(quoteChar, pos);
397 if (i < 0) i = s.length();
398 buf.append(s.substring(pos, i));
400 if (pos < s.length()) {
402 buf.append(quoteChar);
406 return buf.toString();
410 * replaces dangerous characters in <code>s</code>
414 public static String unquote(String s)
417 StringBuffer buf = new StringBuffer(s.length());
419 String searchString = "\\"+quoteChar;
420 while (pos < s.length()) {
421 int i = s.indexOf(searchString, pos);
422 if (i < 0) i = s.length();
423 buf.append(s.substring(pos, i));
426 return buf.toString();
430 * Wandelet String in byte[] um.
432 * @return byte[] des String
435 public static byte[] stringToBytes(String s) {
436 String crlf = System.getProperty("line.separator");
437 if (!crlf.equals("\n"))
438 s = replace(s, "\n", crlf);
439 // byte[] buf = new byte[s.length()];
440 byte[] buf = s.getBytes();
445 * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
449 * @return String mit den Ersetzungen
451 public static String replace(String s, String pattern, String substitute) {
452 int i = 0, pLen = pattern.length(), sLen = substitute.length();
453 StringBuffer buf = new StringBuffer(s.length());
455 int j = s.indexOf(pattern, i);
457 buf.append(s.substring(i));
460 buf.append(s.substring(i, j));
461 buf.append(substitute);
465 return buf.toString();
469 * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
473 * @return String mit den Ersetzungen
475 public static String regexpReplace(String haystack, String pattern, String substitute) {
477 RE regex = new RE(pattern);
478 return regex.substituteAll(haystack,substitute);
479 } catch(REException ex){
488 * Fügt einen Separator an den Pfad an
490 * @return Pfad mit Separator am Ende
492 public static final String addSeparator (String path) {
493 return path.length() == 0 || path.endsWith(File.separator) ? path : path
494 + File.separatorChar;
498 * Fügt ein <code>/</code> ans ende des Strings and
500 * @return Pfad mit <code>/</code> am Ende
502 public static final String addSlash (String path) {
503 return path.length() == 0 || path.endsWith("/") ? path : path + '/';
507 * Löscht <code>/</code> am Ende des Strings, falls vorhanden
509 * @return String ohne <code>/</code> am Ende
511 public static final String removeSlash (String path) {
512 return path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
517 * Checks to see if the path is absolute by looking for a leading file
522 public static boolean isAbsolutePath (String path) {
523 return path.startsWith(File.separator);
527 * Löscht Slash am Anfang des Strings
531 public static String removeFirstSlash (String path) {
532 return path.startsWith("/") ? path.substring(1) : path;
536 * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
537 * @return zwistellige Zahl
539 public static String pad2 (int number) {
540 return number < 10 ? "0" + number : String.valueOf(number);
544 * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
546 * @return 3-stellige Zahl
548 public static String pad3 (int number) {
549 return number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
553 * Konvertiert Unix-Linefeeds in Win-Linefeeds
555 * @return Konvertierter String
557 public static String unixLineFeedsToWin(String s) {
560 i = s.indexOf('\n', i+1);
562 if ((i == 0 || s.charAt(i-1) != '\r') &&
563 (i == s.length()-1 || s.charAt(i+1) != '\r')) {
564 s = s.substring(0, i)+'\r'+s.substring(i);
573 * verwandelt einen String in eine gültige Url, konvertiert Sonderzeichen
574 * und Spaces werden zu Underscores
576 * @return gültige Url
578 public static String convert2url(String s) {
580 StringBuffer buf = new StringBuffer();
581 for(int i = 0; i < s.length(); i++ ) {
582 switch( s.charAt( i ) ) {
584 buf.append( "oe" ); break;
586 buf.append( "ae" ); break;
588 buf.append( "ue" ); break;
590 buf.append( "a" ); break;
593 buf.append( "_" ); break;
595 if( buf.charAt( buf.length() - 1 ) != '_' ) {
600 buf.append( s.charAt( i ) );
603 return buf.toString();
607 public static String decodeHTMLinTags(String s){
608 StringBuffer buffer = new StringBuffer();
609 boolean start = false;
610 boolean stop = false;
615 for(int i=0;i<s.length();i++){
616 if(s.charAt(i)=='<'){
619 } else if(s.charAt(i)=='>'){
624 buffer.append(s.substring(temp,startIndex));
625 buffer.append(replaceQuot(s.substring(startIndex,stopIndex+1)));
626 i= temp= stopIndex+1;
632 buffer.append(s.substring(stopIndex+1));
633 return buffer.toString();
639 public static String replaceQuot(String s) {
640 StringBuffer buffer = new StringBuffer();
641 for(int j = 0; j < s.length();j++){
642 if(s.charAt(j)=='&'){
643 if(s.indexOf( """,j) == j) {
644 buffer.append( "\"" );
648 buffer.append(s.charAt(j));
651 return buffer.toString();
654 /** wandelt Quotes in Sonderzeichen um
657 public static String decodeHtml(String s) {
658 StringBuffer buf = new StringBuffer();
659 for(int i=0;i < s.length(); i++ ) {
660 if( s.indexOf( "ö", i ) == i ) {
661 buf.append( "ö" ); i += 5;
664 if( s.indexOf( "ä", i ) == i ) {
665 buf.append( "ä" ); i += 5;
668 if( s.indexOf( "ü", i ) == i ) {
669 buf.append( "ü" ); i += 5;
672 if( s.indexOf( "Ö", i ) == i ) {
673 buf.append( "Ö" ); i += 5;
676 if( s.indexOf( "Ä", i ) == i ) {
677 buf.append( "Ä" ); i += 5;
680 if( s.indexOf( "Ü", i ) == i ) {
681 buf.append( "Ü" ); i += 5;
684 if( s.indexOf( "ß", i ) == i ) {
685 buf.append( "ß" ); i += 6;
688 if( s.indexOf( """, i ) == i ) {
689 buf.append( "\"" ); i += 5;
692 buf.append( s.charAt(i) );
694 return buf.toString();
699 * schnellere Variante der String.toLowerCase()-Routine
701 * @return String in Kleinbuchsten
703 public static String toLowerCase(String s) {
705 char[] a = new char[l];
706 for (int i = 0; i < l; i++)
707 a[i] = Character.toLowerCase(s.charAt(i));
708 return new String(a);
712 * Findet <code>element</code> im String-Array <code>array</code>
715 * @return Fundstelle als int oder -1
717 public static int indexOf(String[] array, String element) {
719 for (int i = 0; i < array.length; i++)
720 if (array[i].equals(element))
726 * Testet auf Vorkommen von <code>element</code> in <code>array</code>
727 * @param array String-Array
729 * @return true wenn <code>element</code> vorkommt, sonst false
731 public static boolean contains(String[] array, String element) {
732 return indexOf(array, element) >= 0;
736 * Ermittelt CRC-Prüfsumme von String <code>s</code>
738 * @return CRC-Prüfsumme
740 public static int getCRC(String s) {
742 char val[] = s.toCharArray();
743 int len = val.length;
745 for (int i = 0 ; i < len; i++) {
747 h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
750 return (h << 8) | (len & 0xff);
754 * Liefert Default-Wert def zurück, wenn String <code>s</code>
759 * @return geparster int aus s oder def
761 public static int parseInt(String s, int def) {
762 if (s == null) return def;
764 return Integer.parseInt(s);
765 } catch (NumberFormatException e) {
771 * Liefert Defaultwert def zurück, wenn s nicht zu einem float geparsed werden kann.
774 * @return geparster float oder def
776 public static float parseFloat(String s, float def) {
777 if (s == null) return def;
779 return new Float(s).floatValue();
780 } catch (NumberFormatException e) {
786 * Findet Ende eines Satzes in String <code>text</code>
789 * @return index des Satzendes, oder -1
791 public static int findEndOfSentence(String text, int startIndex) {
793 int i = text.indexOf('.', startIndex);
794 if (i < 0) return -1;
795 if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
796 (i+1 >= text.length()
797 || text.charAt(i+1) == ' '
798 || text.charAt(i+1) == '\n'
799 || text.charAt(i+1) == '\t'))
806 * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
809 * @return Index des Wortendes, oder -1
811 public static int findEndOfWord(String text, int startIndex) {
812 int i = text.indexOf(' ', startIndex),
813 j = text.indexOf('\n', startIndex);
814 if (i < 0) i = text.length();
815 if (j < 0) j = text.length();
816 return Math.min(i, j);
821 * convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
822 * in den html-tag <p>
823 * nur sinnvoll, wenn text nicht im html-format eingegeben
825 public static String convertNewline2P(String haystack) {
826 return re_brbr2p.substituteAll(haystack,"\n</p><p>");
830 * convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
831 * in den html-tag <br>
832 * nur sinnvoll, wenn text nicht im html-format eingegeben
834 public static String convertNewline2Break(String haystack) {
835 return re_newline2br.substituteAll(haystack,"$0<br />");
839 * createMailLinks wandelt text im email-adressenformat
840 * in einen klickbaren link um
841 * nur sinnvoll, wenn text nicht im html-format eingegeben
843 public static String createMailLinks(String haystack) {
844 return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
849 * createMailLinks wandelt text im email-adressenformat
850 * in einen klickbaren link um
851 * nur sinnvoll, wenn text nicht im html-format eingegeben
853 public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
854 return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/> <a href=\"mailto:$0\">$0</a>");
859 * createURLLinks wandelt text im url-format
860 * in einen klickbaren link um
861 * nur sinnvoll, wenn text nicht im html-format eingegeben
863 public static String createURLLinks(String haystack) {
864 return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
868 * this routine takes text in url format and makes
869 * a clickaeble "<href>" link removing any "illegal" html tags
870 * @param haystack, the url
871 * @param title, the href link text
872 * @param imagRoot, the place to find icons
873 * @param extImage, the url of the icon to show next to the link
874 * @return a String containing the url
876 public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
878 return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">$0</a>");
880 title = removeHTMLTags(title);
881 return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/> <a href=\"$0\">"+title+"</a>");
886 * this routine takes text in url format and makes
887 * a clickaeble "<href>" link removing any "illegal" html tags
888 * @param haystack, the url
889 * @param imageRoot, the place to find icons
890 * @param extImage, the url of the icon to show next to the link
891 * @param intImage, unused
892 * @return a String containing the url
894 public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
895 return createURLLinks(haystack, title, imageRoot, extImage);
899 * deleteForbiddenTags
900 * this method deletes all <script>, <body> and <head>-tags
902 public static final String deleteForbiddenTags(String haystack) {
904 RE regex = new RE("<[ \t\r\n](.*?)script(.*?)/script(.*?)>",RE.REG_ICASE);
905 haystack = regex.substituteAll(haystack,"");
906 regex = new RE("<head>(.*?)</head>");
907 haystack = regex.substituteAll(haystack,"");
908 regex = new RE("<[ \t\r\n/]*body(.*?)>");
909 haystack = regex.substituteAll(haystack,"");
911 } catch(REException ex){
917 * this method deletes all html tags
919 public static final String removeHTMLTags(String haystack){
920 return re_tags.substituteAll(haystack,"");
925 * this method deletes all but the approved tags html tags
926 * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
928 public static String approveHTMLTags(String haystack){
930 String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
931 String badAttributes="onAbort|onBlur|onChange|onClick|onDblClick|onDragDrop|onError|onFocus|onKeyDown|onKeyPress|onKeyUp|onLoad|onMouseDown|onMouseMove|onMouseOut|onMouseOver|onMouseUp|onMove|onReset|onResize|onSelect|onSubmit|onUnload";
932 String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
934 // kill all the bad tags that have attributes
935 String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
936 RE regex = new RE(s,RE.REG_ICASE);
937 haystack = regex.substituteAll(haystack,"");
939 // kill all the bad tags that are attributeless
940 regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
941 haystack = regex.substituteAll(haystack,"");
943 // kill all the tags which have a javascript attribute like onLoad
944 regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
945 haystack = regex.substituteAll(haystack,"");
947 // kill all the tags which include a url to an unacceptable protocol
948 regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
949 haystack = regex.substituteAll(haystack,"");
952 } catch(REException ex){
953 ex.printStackTrace();
960 * createHTML ruft alle regex-methoden zum unwandeln eines nicht
961 * htmlcodierten string auf und returnt einen htmlcodierten String
963 public static String createHTML(String content){
964 content=convertNewline2Break(content);
965 content=convertNewline2P(content);
966 content=createMailLinks(content);
967 content=createURLLinks(content);
973 * createHTML ruft alle regex-methoden zum unwandeln eines nicht
974 * htmlcodierten string auf und returnt einen htmlcodierten String
976 public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
977 content=convertNewline2Break(content);
978 content=convertNewline2P(content);
979 content=createMailLinks(content,producerDocRoot,mailImage);
980 content=createURLLinks(content,null,producerDocRoot,extImage,intImage);