merged with 1.1
authorzapata <zapata>
Wed, 3 Sep 2003 18:29:00 +0000 (18:29 +0000)
committerzapata <zapata>
Wed, 3 Sep 2003 18:29:00 +0000 (18:29 +0000)
235 files changed:
NEWS
build.xml
bundles/admin_de.properties
bundles/admin_en.properties
bundles/admin_es.properties
bundles/admin_eu.properties
bundles/admin_gz.properties
bundles/admin_it.properties
bundles/admin_nl.properties
bundles/admin_pt.properties
bundles/admin_sv.properties
dbscripts/create_pg.sql
dbscripts/extra/hashpasswords.sh [new file with mode: 0755]
dbscripts/populate_mediafolder.sql
dbscripts/updates/update20030704.sql [new file with mode: 0755]
doc/INSTALL.mir
doc/INSTALL.postgresql [deleted file]
doc/KNOWN_BUGS
doc/MAINTENANCE.postgresql
doc/mission.html
etc/bundles/open_en.properties
etc/config.properties-dist
etc/open/comment.template
etc/open/editarticle.template
etc/open/editcomment.template
etc/open/posting.template
etc/producer/article.template
etc/producer/featurearchive.template
etc/producer/newswirearchive.template
etc/producer/startpage.template
etc/producer/topicpage.template
lib/README.txt
source/Mir.java
source/OpenMir.java
source/default.properties
source/mir/entity/Entity.java
source/mir/entity/EntityList.java
source/mir/entity/EntityRelation.java [deleted file]
source/mir/entity/adapter/EntityAdapterDefinition.java
source/mir/entity/adapter/EntityAdapterEngine.java [new file with mode: 0755]
source/mir/entity/adapter/EntityAdapterFailure.java [new file with mode: 0755]
source/mir/entity/adapter/EntityAdapterModel.java
source/mir/entity/adapter/EntityListAdapter.java
source/mir/generator/FreemarkerGenerator.java
source/mir/generator/Generator.java
source/mir/media/MirMedia.java
source/mir/misc/HTMLTemplateProcessor.java [deleted file]
source/mir/misc/StringUtil.java
source/mir/module/AbstractModule.java
source/mir/producer/EntityBatchingProducerNode.java
source/mir/producer/EntityDeletingProducerNode.java [new file with mode: 0755]
source/mir/producer/EntityModifyingProducerNode.java
source/mir/producer/FreeQueryProducerNode.java
source/mir/producer/ListEnumeratingProducerNode.java [new file with mode: 0755]
source/mir/producer/NodedProducer.java
source/mir/producer/Producer.java
source/mir/producer/RSSProducerNode.java
source/mir/producer/reader/DefaultProducerNodeBuilders.java
source/mir/producer/reader/ProducerConfigReader.java
source/mir/rss/RDFResource.java
source/mir/rss/RSS091Reader.java [new file with mode: 0755]
source/mir/rss/RSSAggregator.java
source/mir/rss/RSSBasicModule.java
source/mir/rss/RSSModule.java
source/mir/rss/RSSReader.java
source/mir/rss/RSSTest.java
source/mir/servlet/AbstractServlet.java
source/mir/servlet/ServletModule.java
source/mir/servlet/ServletModuleDispatch.java
source/mir/servlet/ServletModuleShow.java [deleted file]
source/mir/session/HTTPAdapters.java
source/mir/session/Session.java
source/mir/session/ValidationError.java [new file with mode: 0755]
source/mir/session/ValidationHelper.java [new file with mode: 0755]
source/mir/storage/Database.java
source/mir/storage/DatabaseAdaptor.java [deleted file]
source/mir/storage/DatabaseAdaptorMySQL.java [deleted file]
source/mir/storage/DatabaseAdaptorOracle.java [deleted file]
source/mir/storage/DatabaseAdaptorPostgresql.java [deleted file]
source/mir/storage/DatabaseAdaptorSybase.java [deleted file]
source/mir/storage/StorageObject.java
source/mir/util/DateTimeFunctions.java [new file with mode: 0755]
source/mir/util/DateToMapAdapter.java [deleted file]
source/mir/util/GeneratorDateTimeFunctions.java [new file with mode: 0755]
source/mir/util/GeneratorFormatAdapters.java [new file with mode: 0755]
source/mir/util/GeneratorHTMLFunctions.java
source/mir/util/GeneratorStringFunctions.java
source/mir/util/HTMLRoutines.java
source/mir/util/HTTPParsedRequest.java
source/mir/util/HTTPRequestParser.java
source/mir/util/JDBCStringRoutines.java
source/mir/util/ParameterExpander.java
source/mir/util/PropertiesManipulator.java
source/mir/util/StringRoutines.java
source/mir/util/StructuredContentParser.java [new file with mode: 0755]
source/mir/util/Translate.java [new file with mode: 0755]
source/mir/util/XMLReader.java
source/mircoders/accesscontrol/AccessControl.java [new file with mode: 0755]
source/mircoders/accesscontrol/AuthorizationExc.java [new file with mode: 0755]
source/mircoders/accesscontrol/AuthorizationFailure.java [new file with mode: 0755]
source/mircoders/entity/EntityComment.java
source/mircoders/entity/EntityContent.java
source/mircoders/entity/EntityMedia.java [deleted file]
source/mircoders/entity/EntityUploadedMedia.java
source/mircoders/global/Abuse.java
source/mircoders/global/JobQueue.java
source/mircoders/global/MirGlobal.java
source/mircoders/global/ProducerEngine.java
source/mircoders/localizer/MirAdminInterfaceLocalizer.java
source/mircoders/localizer/MirAntiAbuseFilterType.java [new file with mode: 0755]
source/mircoders/localizer/MirOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicAdminInterfaceLocalizer.java
source/mircoders/localizer/basic/MirBasicAntiAbuseFilterTypes.java [new file with mode: 0755]
source/mircoders/localizer/basic/MirBasicArticlePostingHandler.java
source/mircoders/localizer/basic/MirBasicChildArticlePostingHandler.java
source/mircoders/localizer/basic/MirBasicCommentPostingHandler.java
source/mircoders/localizer/basic/MirBasicDataModelLocalizer.java
source/mircoders/localizer/basic/MirBasicLocalizer.java
source/mircoders/localizer/basic/MirBasicOpenPostingLocalizer.java
source/mircoders/localizer/basic/MirBasicPostingSessionHandler.java
source/mircoders/localizer/basic/MirBasicProducerAssistantLocalizer.java
source/mircoders/media/MediaHandlerAudio.java
source/mircoders/media/MediaHandlerGeneric.java
source/mircoders/media/MediaHandlerImages.java
source/mircoders/media/MediaHandlerImagesExtern.java
source/mircoders/media/MediaHandlerMp3.java
source/mircoders/media/MediaHandlerRealAudio.java
source/mircoders/media/MediaHandlerRealVideo.java
source/mircoders/module/ModuleArticleType.java
source/mircoders/module/ModuleComment.java
source/mircoders/module/ModuleMediaType.java
source/mircoders/module/ModuleMediafolder.java
source/mircoders/module/ModuleTopics.java
source/mircoders/module/ModuleUsers.java
source/mircoders/pdf/PDFGenerator.java
source/mircoders/producer/ContentModifyingProducerNode.java
source/mircoders/producer/IndexingProducerNode.java
source/mircoders/producer/PDFPreFormattingProducerNode.java
source/mircoders/search/TopicMatrixSearchTerm.java [new file with mode: 0755]
source/mircoders/servlet/ServletHelper.java
source/mircoders/servlet/ServletModuleAbuse.java
source/mircoders/servlet/ServletModuleAdmin.java
source/mircoders/servlet/ServletModuleArticleType.java
source/mircoders/servlet/ServletModuleAudio.java
source/mircoders/servlet/ServletModuleBreaking.java
source/mircoders/servlet/ServletModuleComment.java
source/mircoders/servlet/ServletModuleCommentStatus.java
source/mircoders/servlet/ServletModuleContent.java
source/mircoders/servlet/ServletModuleFileEdit.java
source/mircoders/servlet/ServletModuleHidden.java
source/mircoders/servlet/ServletModuleImages.java
source/mircoders/servlet/ServletModuleLanguage.java
source/mircoders/servlet/ServletModuleLocalizer.java
source/mircoders/servlet/ServletModuleMediafolder.java
source/mircoders/servlet/ServletModuleMessage.java
source/mircoders/servlet/ServletModuleOpenIndy.java
source/mircoders/servlet/ServletModuleOtherMedia.java
source/mircoders/servlet/ServletModuleProducer.java
source/mircoders/servlet/ServletModuleTopics.java
source/mircoders/servlet/ServletModuleUploadedMedia.java
source/mircoders/servlet/ServletModuleUsers.java
source/mircoders/servlet/ServletModuleVideo.java
source/mircoders/storage/DatabaseArticleType.java
source/mircoders/storage/DatabaseAudio.java
source/mircoders/storage/DatabaseComment.java
source/mircoders/storage/DatabaseCommentStatus.java
source/mircoders/storage/DatabaseCommentToMedia.java
source/mircoders/storage/DatabaseContent.java
source/mircoders/storage/DatabaseContentToMedia.java
source/mircoders/storage/DatabaseContentToTopics.java
source/mircoders/storage/DatabaseImageColor.java
source/mircoders/storage/DatabaseImageFormat.java
source/mircoders/storage/DatabaseImageLayout.java
source/mircoders/storage/DatabaseImageType.java
source/mircoders/storage/DatabaseImages.java
source/mircoders/storage/DatabaseLanguage.java
source/mircoders/storage/DatabaseMedia.java [deleted file]
source/mircoders/storage/DatabaseMediaType.java
source/mircoders/storage/DatabaseMediafolder.java
source/mircoders/storage/DatabaseOther.java
source/mircoders/storage/DatabaseRights.java
source/mircoders/storage/DatabaseTopics.java
source/mircoders/storage/DatabaseUploadedMedia.java
source/mircoders/storage/DatabaseUsers.java
source/mircoders/storage/DatabaseVideo.java
source/tool/ConfigTool.java [new file with mode: 0755]
templates/admin/EDITFUNCTIONS.template [new file with mode: 0755]
templates/admin/FUNCTIONS.template
templates/admin/FUNCTIONS_media.template
templates/admin/LISTFUNCTIONS.template [new file with mode: 0755]
templates/admin/SETTINGS.template [new file with mode: 0755]
templates/admin/abuse.filter.template [new file with mode: 0755]
templates/admin/abuse.filters.template
templates/admin/abuse.log.template
templates/admin/abuse.template
templates/admin/articletype.template
templates/admin/articletypelist.template
templates/admin/audio.template
templates/admin/breaking.template
templates/admin/breakinglist.template
templates/admin/comment.template
templates/admin/commentlist.template
templates/admin/commentstatus.template
templates/admin/commentstatuslist.template
templates/admin/confirm.template
templates/admin/content.template
templates/admin/contentlist.template
templates/admin/error.template
templates/admin/foot.template
templates/admin/head.template
templates/admin/head_nonavi.template
templates/admin/hiddenlist.template
templates/admin/image.template
templates/admin/imagelist.template
templates/admin/language.template
templates/admin/languagelist.template
templates/admin/linksimcs.template [deleted file]
templates/admin/login.template
templates/admin/media.template [deleted file]
templates/admin/mediafolder.template
templates/admin/mediafolderlist.template
templates/admin/message.template
templates/admin/messagelist.template
templates/admin/other.template [new file with mode: 0755]
templates/admin/producerqueue.template
templates/admin/start_admin.template
templates/admin/topic.template
templates/admin/topiclist.template
templates/admin/uploadedmedia.template [new file with mode: 0755]
templates/admin/user.template
templates/admin/userlist.template
templates/admin/video.template
templates/admin/videolist.template
web/img/pdfbanner.png [new file with mode: 0755]
web/style/admin.css

diff --git a/NEWS b/NEWS
index dfcd453..0345c0e 100755 (executable)
--- a/NEWS
+++ b/NEWS
@@ -1,8 +1,8 @@
-[last changed: $Date: 2002/12/24 01:52:41 $]  2002 mir-coders group
+[last changed: $Date: 2003/09/03 18:29:00 $]  2002 mir-coders group
 -------------------------------------------------------------------------------
 
 ================================
-1.1(HEAD) (as of yet unreleased)
+1.1 (as of yet unreleased)
 ================================
 
 [New features/Improvements]
index 1a0ef69..cf424b1 100755 (executable)
--- a/build.xml
+++ b/build.xml
 
   <target name="javadoc" depends="prepare">
     <javadoc packagenames="mir.*, mircoders.*"
-            sourcefiles="source/${app.name}.java,source/Open${app.name}.java"
+            sourcefiles="source/Mir.java,source/OpenMir.java"
             sourcepath="source"
              destdir="${javadoc.home}">
          <classpath refid="project.class.path"/>
index b92a927..5bb635c 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########
 # language: deutsch / german
-# $Id: admin_de.properties,v 1.29 2003/04/28 00:44:05 zapata Exp $
+# $Id: admin_de.properties,v 1.30 2003/09/03 18:29:00 zapata Exp $
 
 languagename=Deutsch
 
@@ -111,7 +111,7 @@ comment.phone=Telefon
 comment.email=Email
 comment.url=Url
 comment.creator=Uhrheber
-comment.article=zu Artikel
+comment.article=Artikel
 comment.html=HTML?
 comment.status=Status 
 comment.language=Sprache
@@ -127,13 +127,13 @@ commentlist.hidden=versteckt
 commentlist.search=go!
 commentlist.activate = &Auml;nderungen aktivieren
 commentlist.order = Reihenfolge
-commentlist.order.datedesc= Datum (abst.)
-commentlist.order.dateasc= Datum (aufst.)
+commentlist.order.datedesc= Alte zuerst
+commentlist.order.dateasc= Neue zuerst
 commentlist.order.articletitle= Artikel Titel
 
-commentsearch.field = Suchen 
+commentsearch.field = Suchen
 commentsearch.field.title = Title
-commentsearch.field.creator = Author
+commentsearch.field.creator = Autor
 commentsearch.field.description = Beschreibung
 commentsearch.value = Feld
 
@@ -144,8 +144,8 @@ commentsearch.publishedstate.published = sichtbar
 commentsearch.status = Status
 
 commentsearch.order = Reihenfolge
-commentsearch.order.datedesc= Datum (abst.)
-commentsearch.order.dateasc= Datum (aufst.)
+commentsearch.order.datedesc= Alte zuerst
+commentsearch.order.dateasc= Neue zuerst
 commentsearch.order.articletitle= Artikeltitel
 
 commentsearch.searchbutton = suchen
@@ -197,9 +197,9 @@ content.creationdate=Datum
 content.modificationdate=letzte &Auml;nderung
 content.status=Status
 content.type=Artikeltyp
-content.import_date=Einf&uuml;gedatum 
+content.import_date=Einf&uuml;gedatum
 content.lastchange_date=letzte &Auml;nderung
-content.create_date=Datum 
+content.create_date=Datum
 content.published=ver&ouml;ffentlicht
 content.comments=Erg&auml;nzungen
 
@@ -228,8 +228,8 @@ contentsearch.publishedstate.published=sichtbar
 contentsearch.articletype = Artikeltyp
 
 contentsearch.order = sortieren nach
-contentsearch.order.datedesc=Neue zuerst
-contentsearch.order.dateasc=Alte zuerst
+contentsearch.order.datedesc=Alte zuerst
+contentsearch.order.dateasc=Neue zuerst
 contentsearch.order.title=nach Titel
 contentsearch.order.creator=nach Autor
 contentsearch.searchbutton=suchen
index 72b647c..bbd3fb2 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########
 # language: english
-# $Id: admin_en.properties,v 1.48 2003/05/03 23:30:49 zapata Exp $
+# $Id: admin_en.properties,v 1.49 2003/09/03 18:29:00 zapata Exp $
 
 languagename=English
 
@@ -94,6 +94,7 @@ other_medialist.htmltitle=Other media overview
 # breaking
 breaking.htmltitle=Breaking news
 breaking.textinfo=(max. 5 lines / 250 characters)
+breaking.id = id
 breaking.text=text
 breaking.date=date
 
@@ -111,10 +112,11 @@ comment.phone=Phone
 comment.email=Email
 comment.url=Url
 comment.creator=Author
-comment.article=For article
+comment.article=Article
 comment.html=HTML
 comment.status=Status 
 comment.language=Language
+comment.allcomments=All comments
 
 comment.operation.hide=hide
 comment.operation.unhide=unhide
@@ -135,6 +137,8 @@ commentlist.order.articletitle= article title
 commentsearch.field = Search
 commentsearch.field.title = Title
 commentsearch.field.creator = Author
+commentsearch.field.main_url = Url
+commentsearch.field.email = Email
 commentsearch.field.description = Description
 commentsearch.value = Value
 
@@ -221,6 +225,8 @@ contentsearch.field = field
 contentsearch.field.title = Title
 contentsearch.field.creator = Author
 contentsearch.field.contents=Contents
+contentsearch.field.creator_email = Email
+contentsearch.field.creator_main_url = Web address
 
 contentsearch.publishedstate = publication state
 contentsearch.publishedstate.hidden=hidden
@@ -244,6 +250,7 @@ contentlist.select=Select
 
 # language
 language.htmltitle=Language
+language.id=Id
 language.name=Language
 language.code=Language code
 
@@ -261,6 +268,7 @@ login.submit=  OK
 
 # mediafolder
 mediafolder.htmltitle=mediafolder
+mediafolder.id=id
 mediafolder.date=date
 mediafolder.name=name
 mediafolder.location=location
@@ -272,6 +280,7 @@ mediafolderlist.htmltitle=media folder list
 
 # message
 message.htmltitle=messages
+message.id=id
 message.date=date
 message.title=title
 message.creator=author
@@ -285,7 +294,8 @@ start.htmltitle=admin
 
 start.content.new=new article
 start.show=show
-start.open_by_id=open id
+start.comment.open_by_id=open comment #
+start.content.open_by_id=open article #
 
 start.content.hidden=produce all hidden articles
 start.content.not_published=not (yet) published articles
@@ -296,6 +306,7 @@ start.content.all=all articles
 start.content.search=search
 
 start.allarticlesoftype={0}
+start.allcommentswithstatus={0}
 
 start.producers.title=GENERATE MANUALLY
 start.producers.produceAllNew=generate all new
@@ -304,8 +315,10 @@ start.producers.advanced=advanced page (use with care!)
 start.administer.title=ADMINISTER
 start.administer.comments=comments
 
+start.comments.title=COMMENTS
+
 start.breaking.title=breaking news
-start.list.title=LIST
+start.articles.title=ARTICLES
 start.fileedit.includes.title=edit include files
 start.addandedit.title=ADD / EDIT
 start.extra.title=EXTRA
@@ -325,7 +338,10 @@ start.superusermenu=super-user functions (use with care!)
 
 
 # topic
+
 topic.htmltitle=topic
+
+topic.id=id
 topic.title=name
 topic.description=description
 topic.filename=filename
@@ -338,6 +354,8 @@ topiclist.htmltitle=topiclist
 # users
 user.htmltitle=User
 user.login=Login
+user.ownpassword=Your own password
+user.oldpassword=Old password
 user.password=Password
 user.password2=Password (confirmation)
 user.admin=Admin
@@ -385,7 +403,9 @@ producer.job.date = Last change
 producer.job.cancel = cancel
 producer.job.abort = abort
 producer.job.empty = Queue is empty
+producer.job.runningtime = Running time
 
+producer.jobqueue.canceljobs = Cancel selected jobs
 producer.jobqueue.title = Current jobs
 producer.jobqueue.refresh = refresh
 producer.producerlist.title = Add a new job
@@ -429,14 +449,27 @@ abuse.log.browser=Browser
 
 abuse.filters = Filters
 abuse.filter.type = Type
+abuse.filter.expression = Expression
+abuse.filter.articleaction = Article 
+abuse.filter.commentaction = Comment 
+abuse.filter.comments = Comments (internal usage)
+abuse.filter.lasthit = Last hit
+abuse.filter.htmltitle = Edit filter
+
 abuse.filtertype.ip = IP Number
 abuse.filtertype.regexp = Regular expression
-abuse.filter.expression = Expression
 
+abuse.filtererror.title = Error:
+abuse.filtererror.invalidtype = Invalid filter type
+abuse.filtererror.invalidexpression = Invalid expression for this type
+
+abuse.filters.htmltitle = Anti-abuse filter rules
+abuse.log.htmltitle = Anti-abuse open posting log
 
 # head
 head.start=start
 head.logout=logout
+head.changepassword=password
 head.help=help
 head.search=search
 head.logged_in=logged in
@@ -460,8 +493,6 @@ articletypes.startspecial=Startpage-special
 
 # Comment status values
 commentstatus.normal=normal
-commentstatus.good=good
-commentstatus.bad=bad
 
 
 
@@ -471,8 +502,8 @@ error.title=The system caused an error
 error.text=This can happen. Even if the following error message is not be comprehensible for you, <br>it might be helpful to <a href="mailto:{0}">{1}</a>:
 error.text2=So please send an e-mail with the <font color="Red">red text</font> and detailed information regarding the events that led to this error to <a href="mailto:{0}">{1}</a>. Thanks!
 
-usererror.htmltitle=validation error
-usererror.title=Validation error
+usererror.htmltitle=Input error
+usererror.title=Input error
 usererror.text=Your input caused the following error:
 usererror.what_to_do=Please press the back button and try it again
 
@@ -480,6 +511,9 @@ media.error.unsupportedformat=The format of the media you uploaded is not suppor
 user.error.missingpasswords=The new password must be entered twice
 user.error.passwordmismatch=The passwords are not equal
 user.error.missingpassword=A password must be entered
+user.error.incorrectpassword= Incorrect password
+
+
 
 
 ########## infomessages ##########
index 07009f2..3c6e48d 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########
 # language: spanish
-# $Id: admin_es.properties,v 1.29 2003/05/03 23:30:49 zapata Exp $
+# $Id: admin_es.properties,v 1.30 2003/09/03 18:29:00 zapata Exp $
 
 languagename = Castellano
 
@@ -111,7 +111,7 @@ comment.phone = Tel\u00e9fono
 comment.email = Correo electr\u00f3nico
 comment.url = URL
 comment.creator = Autor
-comment.article = del art\u00edculo
+comment.article = Art\u00edculo
 comment.html = HTML
 comment.status = Estado
 comment.language = Idioma
index 411323f..ab37002 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########
 # language: euskera / basque
-# $Id: admin_eu.properties,v 1.12 2003/04/28 01:57:14 zapata Exp $
+# $Id: admin_eu.properties,v 1.13 2003/09/03 18:29:00 zapata Exp $
 
 languagename = Euskera
 
@@ -121,7 +121,7 @@ comment.phone = telefonoa
 comment.email = posta elektronikoa
 comment.url = URL
 comment.creator = egilea
-comment.article = hurrengo artikuluarena
+comment.article = Artikuluarena
 comment.html = HTML da?
 comment.status = Egoera
 comment.language = Hizkuntza
index ecfceaf..5d8a72c 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########\r
 # language: galician\r
-# $Id: admin_gz.properties,v 1.2 2003/05/03 23:30:49 zapata Exp $\r
+# $Id: admin_gz.properties,v 1.3 2003/09/03 18:29:00 zapata Exp $\r
 \r
 languagename = Galego\r
 \r
@@ -111,7 +111,7 @@ comment.phone = Tel\u00e9fono
 comment.email = Correo electr\u00f3nico\r
 comment.url = URL\r
 comment.creator = Autor\r
-comment.article = do art\u00edculo\r
+comment.article = Art\u00edculo\r
 comment.html = HTML\r
 comment.status = Estado\r
 comment.language = Idioma\r
index 089a12b..427b01c 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin #######
 # language: italiano
-# $Id: admin_it.properties,v 1.1 2003/05/15 17:14:59 zapata Exp $
+# $Id: admin_it.properties,v 1.2 2003/09/03 18:29:00 zapata Exp $
 
 # missing (master value = "English")
 languagename = italiano
@@ -122,7 +122,7 @@ comment.phone = telefono
 comment.email = email
 comment.url = url
 comment.creator = autore
-comment.article = dell'articolo
+comment.article = Articolo
 comment.html = HTML
 comment.status = stato
 comment.language = lingua
index ce9aea8..8a33f38 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########
 # language: dutch
-# $Id: admin_nl.properties,v 1.8 2003/04/28 01:57:14 zapata Exp $
+# $Id: admin_nl.properties,v 1.9 2003/09/03 18:29:00 zapata Exp $
 
 languagename = Nederlands
 
@@ -111,7 +111,7 @@ comment.phone = Telefoon
 comment.email = E-mail
 comment.url = Homepage
 comment.creator = Auteur
-comment.article = Voor artikel
+comment.article = Artikel
 comment.html = HTML?
 comment.status = Status 
 comment.language = Taal
index 7f49e29..215ad10 100755 (executable)
 ########## admin ##########
 # language: portuguese
-# $Id: admin_pt.properties,v 1.5 2003/04/26 23:20:24 zapata Exp $
+# $Id: admin_pt.properties,v 1.6 2003/09/03 18:29:00 zapata Exp $
 
-languagename=Português
+languagename = Portugu\u00eas
 
 # general
-yes=sim
-no=não
-dontcare=não ligo
-all=tudo
-month=mês
-year=ano
-file=arquivo
+yes = sim
+no = n\u00e3o
+dontcare = n\u00e3o ligo
+all = tudo
+month = m\u00eas
+year = ano
+file = arquivo
+new = novo
+by = por
+help = ajuda
+
 
 # actions
-insert=inserir
-save=salve
-edit=editar
-delete=delete
-add=adicionar
-filter=filtro
-attach=atribuir
-list=navegador
-back=voltar
-cancel=cancelar
-preview=preview
-reset=reset
+insert = inserir
+save = salvar
+edit = editar
+delete = delete
+add = adicionar
+filter = filtro
+attach = anexar
+list = navegador
+back = voltar
+cancel = cancelar
+preview = preview
+reset = reset
+administer = administrar
+search = busca
+
 
 # special
-fileedit=Editar um arquivo
+fileedit = Editar um arquivo
+
 
 # records
-records=entrada
-show_from_to=exibindo desde {0} à {1}
-no_matches_found=Sem ocorrências de $string
-list.next=próximo
-list.previous=anterior
+records = entrada
+show_from_to = exibindo desde {0} \u00e0 {1}
+no_matches_found = Sem ocorr\u00eancias de $string
+list.next = pr\u00f3ximo
+list.previous = anterior
+
 
 # media - used by image, audio, video and other media
-media.created=criado
-media.changed=última modificação
-media.published=publicado
-media.format=formato
-media.rights=Status do copyright 
-media.type=tipo
-media.mediafolder=Arquivo de mídia
-media.title=título
-media.size=tamanho
-media.description=descrição
-media.date=data
-media.location=endereço
-media.creator=autor(a)
-media.keywords=palavras-chaves
-media.comment=reparos (somente para uso interno)
-media.source=fonte
-media.is_published=publicado
-media.icon=ícone
-media.nr_of_media=Número de Ítens de Mídia(máx 20)
-media.nr_of_media.submit=define número
-
-medialist.search_text_in=Procure pelo texto em
+media.created = criado
+media.changed = \u00faltima modifica\u00e7\u00e3o
+media.published = publicado
+media.format = formato
+media.rights = Status do copyright 
+media.type = tipo
+media.mediafolder = Arquivo de m\u00eddia
+media.title = t\u00edtulo
+media.size = tamanho
+media.description = descri\u00e7\u00e3o
+media.date = data
+media.location = endere\u00e7o
+media.creator = autor(a)
+media.keywords = palavras-chaves
+media.comment = reparos (somente para uso interno)
+media.source = fonte
+media.is_published = publicado
+media.icon = \u00edcone
+media.nr_of_media = N\u00famero de \u00cdtens de M\u00eddia(m\u00e1x 20)
+media.nr_of_media.submit = define n\u00famero
+
+medialist.search_text_in = Procure pelo texto em
+
 
 # image
-image.htmltitle=Imagem
-imagelist.htmltitle=Imagens
+image.htmltitle = Imagem
+imagelist.htmltitle = Imagens
+
 
 # audio
-audio.htmltitle=Áudio
-audiolist.htmltitle=Audio overview
+audio.htmltitle = \u00c1udio
+audiolist.htmltitle = Audio overview
+
 
 # video
-video.htmltitle=Vídeo
-videolist.htmltitle=Video overview
+video.htmltitle = V\u00eddeo
+videolist.htmltitle = Video overview
+
 
 # other
-other_media.htmltitle=Outra mídia
-other_medialist.htmltitle=Other media overview
+other_media.htmltitle = Outra m\u00eddia
+other_medialist.htmltitle = Other media overview
+
 
 # breaking
-breaking.htmltitle=Últimas notícias
-breaking.textinfo=(máx. 5 linhas / 250 characters)
-breaking.text=texto
-breaking.date=data
+breaking.htmltitle = \u00daltimas not\u00edcias
+breaking.textinfo = (m\u00e1x. 5 linhas / 250 characters)
+breaking.text = texto
+breaking.date = data
+
+breakinglist.htmltitle = Breaking news overview
 
-breakinglist.htmltitle=Breaking news overview
 
 # comment
-comment.htmltitle=Comentário
-comment.date=Data
-comment.title=Título
-comment.published=Publicado
-comment.text=Texto do comentário
-comment.address=Endereço
-comment.phone=Telefone
-comment.email=Email
-comment.url=Url
-comment.creator=Autor(a)
-comment.article=Para o artigo
-comment.html=HTML?
-comment.status=Status 
-comment.language=Língua
-
-commentlist.htmltitle=Comentários
-commentlist.published=publicado
-commentlist.hidden=escondido
-commentlist.search=Vá!
-
-commentsearch.order.datedesc= date (desc.)
-commentsearch.order.dateasc= date (asc.)
-commentsearch.order.articletitle= título do artigo
+comment.htmltitle = Coment\u00e1rio
+comment.date = Data
+comment.title = T\u00edtulo
+comment.published = Publicado
+comment.text = Texto do coment\u00e1rio
+comment.address = Endere\u00e7o
+comment.phone = Telefone
+comment.email = Email
+comment.url = URL
+comment.creator = Autor(a)
+comment.article = Artigo
+comment.html = HTML?
+comment.status = Status 
+comment.language = L\u00edngua
+
+comment.operation.hide = esconder
+comment.operation.unhide = des-esconder
+
+
+#commentlist
+commentlist.htmltitle = Coment\u00e1rios
+commentlist.published = publicado
+commentlist.hidden = escondido
+commentlist.allcomments = Todos os coment\u00e1rios deste artigo
+commentlist.search = V\u00e1!
+commentlist.activate = ativar mudan\u00e7as
+commentlist.order = ordem
+commentlist.order.datedesc = data (descendente)
+commentlist.order.dateasc = data (ascendente)
+commentlist.order.articletitle = t\u00edtulo do artigo
+
+commentsearch.field = Busca
+commentsearch.field.title = T\u00edtulo
+commentsearch.field.creator = Autor
+commentsearch.field.description = Descri\u00e7\u00e3o
+commentsearch.value = Valor
+
+commentsearch.publishedstate = Data de publica\u00e7\u00e3o
+commentsearch.publishedstate.hidden = Escondido
+commentsearch.publishedstate.published = Publicado
+
+commentsearch.status = Status
+
+commentsearch.order = Ordem
+commentsearch.order.datedesc = data (descendente)
+commentsearch.order.dateasc = data (ascemdente)
+commentsearch.order.articletitle = t\u00edtulo do artigo
+
+commentsearch.searchbutton = Buscar
 
 
 # confirm
-confirm.htmltitle=delete confirmado
-confirm.really_delete=Tem certeza que quer deletar esta porta de entrada?
+confirm.htmltitle = delete confirmado
+confirm.really_delete = Tem certeza que quer deletar esta entrada?
+confirm.text = Isto ir\u00e1 apagar esta entrada do banco de dados para sempre
 
-# content
-content.htmltitle=Artigo
-content.owner=Dono
-content.topic=Assunto
-content.title=Título longo
-content.subtitle=Sub-título 
-content.edittitle = Conteúdo do título
-content.location=Localização
-content.creator=Autor(a)
-content.creator.email=E-mail
-content.creator.url=Endereço na web
-content.creator.address=Endereço
-content.creator.telephone=Telefone
-content.abstract=Abstract
-content.content=Conteúdo
-content.html=HTML?
-content.comment=Comentário Interno
-content.internal=(interno)
-content.attachments=Arquivos atribuidos
-content.images=Imagens
-content.audio=Áudio
-content.video=Vídeo
-content.other=Outra mídia
-content.media=Mídia
-content.addimage=adicionar imagem
-content.addaudio=adicionar áudio
-content.addvideo=adicionar vídeo
-content.addother=adicionar outra mídia
-content.creationdate=data
-content.modificationdate=última modificação
-content.status=Status
-content.type=Tipo de artículo
-content.import_date=Importar data
-content.lastchange_date=Última modificação
-
-content.create_date=Data
-content.published=publicado
-content.comments=Comentários
-
-
-contentlist.htmltitle=Artigos
-contentlist.comments=comentários
 
-# language
-language.htmltitle=Línguas
-language.name=Língua
-language.code=Linguagem do código
+# content
+content.htmltitle = Artigo
+content.owner = Dono
+content.language = L\u00edngua
+content.articletype = Tipo de artigo
+content.topic = Assunto
+content.title = T\u00edtulo longo
+content.subtitle = Sub-t\u00edtulo 
+content.edittitle = Conte\u00fado do t\u00edtulo
+content.location = Localiza\u00e7\u00e3o
+content.creator = Autor(a)
+content.creator.email = E-mail
+content.creator.url = Endere\u00e7o na web
+content.creator.address = Endere\u00e7o
+content.creator.telephone = Telefone
+content.abstract = Sum\u00e1rio
+content.content = Conte\u00fado
+content.html = HTML?
+content.comment = Coment\u00e1rio Interno
+content.internal = (interno)
+
+content.attachments = Arquivos atribuidos
+content.images = Imagens
+content.audio = \u00c1udio
+content.video = V\u00eddeo
+content.other = Outra m\u00eddia
+content.media = M\u00eddia
+content.addimage = adicionar imagem
+content.uploadimage = adicionar imagem
+content.addaudio = adicionar \u00e1udio
+content.uploadaudio = adicionar \u00e1udio
+content.addvideo = adicionar v\u00eddeo
+content.uploadvideo = adicionar v\u00eddeo
+content.addother = adicionar outro tipo de arquivo de m\u00eddia
+content.uploadother = adicionar outro tipo de arquivo de m\u00eddia
+
+content.creationdate = data
+content.modificationdate = \u00faltima modifica\u00e7\u00e3o
+content.status = Status
+content.type = Tipo de art\u00edculo
+content.import_date = Importar data
+content.lastchange_date = \u00daltima modifica\u00e7\u00e3o
+content.create_date = Data
+content.published = publicado
+content.comments = Coment\u00e1rios
+
+content.family = Pais e filhos
+content.children = Filhos
+content.viewchildren = ver
+content.parent = Pai
+content.viewparent = ver
+content.clearparent = des-selecionar
+content.selectparent = selecionar
+
+content.operation.hide = esconder
+content.operation.unhide = des-esconder
+content.operation.newswire = newswire
+
+contentsearch.value = busca
+contentsearch.field = campo
+contentsearch.field.title = T\u00edtulo
+contentsearch.field.creator = Autor
+contentsearch.field.contents = Conte\u00fado
+
+contentsearch.publishedstate = estado da publica\u00e7\u00e3o
+contentsearch.publishedstate.hidden = escondido
+contentsearch.publishedstate.published = publicado
+
+contentsearch.articletype = tipo de arquivo
+
+contentsearch.order = ordenar
+contentsearch.order.datedesc = mais novos primeiro
+contentsearch.order.dateasc = mais antigos primeiro
+contentsearch.order.title = T\u00edtulo
+contentsearch.order.creator = Autor
+contentsearch.searchbutton = Buscar
+
+
+#contentlist
+contentlist.htmltitle = Artigos
+contentlist.comments = coment\u00e1rios
+contentlist.select = selecionar
 
-languagelist.htmltitle=Línguas
 
-# imcs
-linkimcs.htmltitle=Links dos CMIs
-linkimcs.name=Nome
-linkimcs.continent=Continente
-linkimcs.new_parent=New Parent
-linkimcs.url=URL
-linkimcs.sort_by=Sortcriteria
-linkimcs.language=Língua
-linkimcs.parent=parent
+# language
+language.htmltitle = L\u00ednguas
+language.name = L\u00edngua
+language.code = Linguagem do c\u00f3digo
 
-linkimcslist.htmltitle=Lista de Links dos CMIs
-linkimcslist.search_in=Procure pelo texto em
+languagelist.htmltitle = L\u00ednguas
 
 # login
-login.htmltitle=login
-login.info=Esta parte só pode ser acessada por grupos autorizados. Se você quiser participar de um grupo editorial, por favor entre em contato conosco através do {0}.
-login.title=login
-login.name=Login
-login.password=Password
-login.language=Língua
-login.submit=  OK
+login.htmltitle = login
+login.info = Esta parte s\u00f3 \u00e9 acessada pelo coletivo editorial. Se voc\u00ea quiser participar do coletivo, por favor entre em contato conosco atrav\u00e9s do {0}.
+login.title = login
+login.name = Login
+login.password = Password
+login.language = L\u00edngua
+login.submit = OK
+
 
 # mediafolder
-mediafolder.htmltitle=mediafolder
-mediafolder.date=data
-mediafolder.name=nome
-mediafolder.location=localização
-mediafolder.keywords=palavras-chaves
-mediafolder.comment=comentário
+mediafolder.htmltitle = mediafolder
+mediafolder.date = data
+mediafolder.name = nome
+mediafolder.location = localiza\u00e7\u00e3o
+mediafolder.keywords = palavras-chaves
+mediafolder.comment = coment\u00e1rio
+
+mediafolderlist.htmltitle = lista dos arquivos de m\u00eddia
 
-mediafolderlist.htmltitle=lista dos arquivos de mídia
 
 # message
-message.htmltitle=mensagens
-message.date=data
-message.title=título
-message.creator=Autor(a)
-message.text=texto
-message.textinfo=(máx. 5 lines / 250 characters)
+message.htmltitle = mensagens
+message.date = data
+message.title = t\u00edtulo
+message.creator = Autor(a)
+message.text = texto
+message.textinfo = (m\u00e1x. 5 linhas / 250 characters)
 
-messagelist.htmltitle=lista de mensagens
+messagelist.htmltitle = lista de mensagens
 
 # admin start page
-start.htmltitle=administração
-start.openpostings.title=PUBLICAÇÕES ABERTAS
-start.comments.title=COMENTÁRIOS
-start.breaking.title=ÚLTIMAS NOTÍCIAS
-start.breaking.new=adicione última notícia
-start.content.title=ARTIGOS
-start.content.new=novo artigo
-start.show=mostrar
-
-start.content.hidden=esconder artigos
-start.content.not_published=artigos que (ainda) não foram publicados
-start.content.with_media=com mídia
-start.content.last_changes=últimas mudanças 
-start.content.with_comments=com comentários internos 
-start.content.all=todos artigos
-start.content.search=busca
-
-start.allarticlesoftype=Mostre todos "{0}" artigos
-
-
-start.producers.title=GENERATE MANUALLY
-start.producers.produceAllNew=Generate all new
-start.producers.advanced=Advanced page (use com cuidado!)
+start.htmltitle = administra\u00e7\u00e3o
+
+start.content.new = novo artigo
+start.show = mostrar
+start.open_by_id = abrir no.
+
+start.content.hidden = esconder artigos
+start.content.not_published = artigos que (ainda) n\u00e3o foram publicados
+start.content.with_media = com m\u00eddia
+start.content.last_changes = \u00faltimas mudan\u00e7as 
+start.content.with_comments = com coment\u00e1rios internos 
+start.content.all = todos artigos
+start.content.search = busca
+
+start.allarticlesoftype = Mostre todos "{0}" artigos
+
+start.producers.title = GENERATE MANUALLY
+start.producers.produceAllNew = Generate all new
+start.producers.advanced = Advanced page (use com cuidado!)
+
+start.administer.title = ADMINISTRAR
+start.administer.comments = coment\u00e1rios
+
+start.breaking.title = \u00daLTIMAS NOT\u00cdCIAS
+start.list.title = LISTAR
+start.fileedit.includes.title = editar aquivos de inclus\u00e3o
+start.addandedit.title = ADICIONAR / EDITAR
+start.extra.title = EXTRA
+start.search.title = BUSCAR
+start.other_media.title = OUTRA M\u00cdDIA
+start.images.title = FOTOS
+start.video.title = V\u00cdDEO
+start.audio.title = \u00c1UDIO
+start.media.title = M\u00cdDIA
+start.mediafolder.title = ARQUIVOS DE M\u00cdDIA
+start.languages.title = L\u00cdNGUAS
+start.imcs.title = CMIS
+start.messageboard.title = Quadro de Mensagens Interno
+start.messageboard.no_messages = nenhuma mensagem
+
+start.superusermenu = Super-user functions (use com cuidado!)
 
 
+# topic
+topic.htmltitle = assunto
+topic.title = Nome
+topic.description = descri\u00e7\u00e3o
+topic.filename = Nome do arquivo 
+topic.main_url = p\u00e1gina principal de informa\u00e7\u00e3o
+topic.archive_url = Arquivar url
 
+topiclist.htmltitle = lisa de assuntos 
 
-start.topics.title=ASSUNTOS 
-start.other_media.title=OUTRA MÍDIA
-start.images.title=FOTOS
-start.video.title=VÍDEO
-start.audio.title=ÁUDIO
-start.mediafolder.title=ARQUIVOS DE MÍDIA
-start.languages.title=LÍNGUAS
-start.imcs.title=CMIS
-start.messageboard.title=Quadro de Mensagens Interno
-start.messageboard.no_messages=nenhuma mensagem
 
-start.superusermenu=Super-user functions (use com cuidado!)
+# users
+user.htmltitle = Usu\u00e1rio
+user.login = Login
+user.password = Senha
+user.password2 = Repita a senha
+user.admin = Administra\u00e7\u00e3o
 
-start.editfiles.title=EDITE OS ARQUIVOS
-start.editfiles.include=Incluir arquivos
+userlist.htmltitle = Usu\u00e1rios
 
-# topic
-topic.htmltitle=assunto
-topic.title=Nome
-topic.description=descrição
-topic.filename=Nome do arquivo 
-topic.main_url=página principal de informação
-topic.archive_url=Arquivar url
 
-topiclist.htmltitle=lisa de assuntos 
+#articletype
+articletype.htmltitle = Tipo de artigo 
+articletype.id = identidade
+articletype.name = Nome
 
-# users
-user.htmltitle=Usuário
-user.login=Login
-user.password=Password
-user.admin=Administração
+articletypelist.htmltitle = Tipo de artigos
 
-userlist.htmltitle=Usuários
 
 
-articletype.htmltitle=Tipo de artigo 
-articletype.id=identidade
-articletype.name=Nome
+#commentstatus
+commentstatus.htmltitle = Status dos coment\u00e1rios
+commentstatus.id = identidade
+commentstatus.name = Nome
 
-articletypelist.htmltitle=Tipo de artigos
-commentstatus.htmltitle=Status dos comentários
-commentstatus.id=identidade
-commentstatus.name=Nome
+commentstatuslist.htmltitle = Comment status values
 
-commentstatuslist.htmltitle=Comment status values
 
 
 #file editing
-fileeditlist.htmltitle = Arquivos editáveis
-fileeditlist.filename = Nome do arquivo
-fileedit.filename = Nome do arquivo
 fileedit.htmltitle = Editar arquivo
+fileedit.filename = Nome do arquivo
+fileedit.subdirectory = Subdiret\u00f3rio
+
+fileeditlist.htmltitle = Arquivos edit\u00e1veis
+fileeditlist.filename = Nome do arquivo
+fileeditlist.dirname = Subdiret\u00f3rio
 
 
 #producers
@@ -297,9 +381,10 @@ producer.verb.enqueue = enqueue
 
 producer.job.name = Job
 producer.job.status = Status
-producer.job.date = Última modificação
+producer.job.date = \u00daltima modifica\u00e7\u00e3o
 producer.job.cancel = cancelar
 producer.job.abort = abortar
+producer.job.empty = Fila vazia
 
 producer.jobqueue.title = Current jobs
 producer.jobqueue.refresh = refresh
@@ -308,49 +393,95 @@ producer.producerlist.title = Add a new job
 producerqueue.htmltitle = Generate manually
 
 
-superusermenu.htmltitle = funções dos super-usuários
-superusermenu.topics = Manutenção dos assuntos
-superusermenu.articletypes = Manutenção dos tipos de artigos
-superusermenu.comment_statuses = Manutenção comment status values
-superusermenu.users = Manutenção de usuários
-superusermenu.languages = Manutenção de línguas
-superusermenu.imcs = Manutenção de CMIs (absoleto)
+#superusermenu
+superusermenu.htmltitle = fun\u00e7\u00f5es dos super-usu\u00e1rios
+superusermenu.manage = ADMINISTRAR
+superusermenu.topics = Manuten\u00e7\u00e3o dos assuntos
+superusermenu.articletypes = Manuten\u00e7\u00e3o dos tipos de artigos
+superusermenu.comment_statuses = Manuten\u00e7\u00e3o comment status values
+superusermenu.users = Manuten\u00e7\u00e3o de usu\u00e1rios
+superusermenu.languages = Manuten\u00e7\u00e3o de l\u00ednguas
+superusermenu.abuse = aplicar medidas anti-abuso
+superusermenu.imcs = Manuten\u00e7\u00e3o de CMIs (absoleto)
+
 
+#abuse
+abuse.htmltitle = medidas anti-abuso
+
+abuse.setting = Configura\u00e7\u00e3o
+abuse.value = Valor
+
+abuse.disableopenpostings = Desligar a publica\u00e7\u00e3o aberta
+abuse.openpostingpassword = Pedir senha para a publica\u00e7\u00e3o aberta
+abuse.logpostings = Logar IP's para a publica\u00e7\u00e3o aberta
+abuse.logsize = Tamanho do log
+abuse.cookies = Use cookies para usu\u00e1rios bloqueados
+abuse.articleaction = A\u00e7\u00e3o para artigo bloqueado
+abuse.commentaction = A\u00e7\u00e3o para coment\u00e1rios bloqueados
+
+abuse.showlog = Mostar log dos IP's
+abuse.showfilters = Administrar os filtros
+
+abuse.log.time = tempo
+abuse.log.address = n\u00famero IP
+abuse.log.object = Objeto
+abuse.log.browser = Browser
+
+abuse.filters = Filtros
+abuse.filter.type = Tipo
+abuse.filtertype.ip = N\u00famero IP
+abuse.filtertype.regexp = Express\u00e3o Regular
+abuse.filter.expression = Express\u00e3o
 
 
 # head
-head.start=começar
-head.logout=desconectar
-head.help=ajuda
-head.search=busca
-head.logged_in=conectado
+head.start = come\u00e7ar
+head.logout = desconectar
+head.help = ajuda
+head.search = busca
+head.logged_in = conectado
 
 # foot
-foot.top=top
+foot.top = topo
+
+
+########## dynamic values ##########
+
+# (users can add new types, how to translate these)
+# suggestion if not in bundle use value as Text
 
 
 # Article types
-articletypes.openposting=Publicação aberta
-articletypes.newswire=Notícias
-articletypes.feature=Editorial
-articletypes.topicspecial=Topic-special
-articletypes.startspecial=Startpage-special
+articletypes.openposting = Publica\u00e7\u00e3o aberta
+articletypes.newswire = Not\u00edcias
+articletypes.feature = Editorial
+articletypes.topicspecial = Topic-special
+articletypes.startspecial = Startpage-special
 
 # Comment status values
-commentstatus.normal=Normal
+commentstatus.normal = Normal
+commentstatus.good = Bom
+commentstatus.bad = Mau
+
+
 
 ########## error ##########
+error.htmltitle = o sistema causou um erro
+error.title = O sistema causou um erro
+error.text = Isto pode acontecer. Mesmo se voc\u00ea n\u00e3o entender a mensagem de erro, ela pode ajudar muito o <a href="mailto:{0}">{1}</a>:
+error.text2 = Enta\u00f5 por favor mande um email com o <font color="Red">texto em vermelho</font> e coloque informa\u00e7\u00f5es detalhadas sobre o que que aconteceu para chegar a este erro <a href="mailto:{0}">{1}</a>. Obrigada!
 
-error.htmltitle=o sistema causou um erro
-error.title=O sistema causou um erro
-error.text=Isto pode acontecer. Mesmo se você não entender a mensagem de erro, ela pode ajudar muito o <a href="mailto:{0}">{1}</a>:
-error.text2=Entaõ por favor mande um email com o <font color="Red">red text</font> e coloque informações detalhadas sobre o que que aconteceu para chegar a este erro <a href="mailto:{0}">{1}</a>. Obrigada!
+usererror.htmltitle = validation error
+usererror.title = Validation error
+usererror.text = Sua entrada causou o seguinte erro:
+usererror.what_to_do = Por favor pressione a tecla de retorno e tente novamente
 
-usererror.htmltitle=validation error
-usererror.title=Validation error
-usererror.text=Sua entrada causou o seguinte erro:
-usererror.what_to_do=Por favor pressione a tecla de retorno e tente novamente
+media.error.unsupportedformat = O formato do arquivo que voc\u00ea enviou n\u00e3o \u00e9 suportado
+user.error.missingpasswords = A nova senha deve ser digitada duas vezes
+user.error.passwordmismatch = As senhas n\u00e3o s\u00e3o iguais
+user.error.missingpassword = Uma senha deve ser digitada
 
-infomessage.title = Informação
-infoanguage codeQueue = O seu pedido foi adicionada à fila de pedidos.
 
+########## infomessages ##########
+infomessage.htmltitle = Informa\u00e7\u00e3o
+infomessage.produceAllNewAddedToQueue = Seu pedido foi adicionado a fila.
index d49ca7e..ec64b43 100755 (executable)
@@ -1,6 +1,6 @@
 ########## admin ##########
 # language: svenska
-# $Id: admin_sv.properties,v 1.6 2003/04/26 23:20:24 zapata Exp $
+# $Id: admin_sv.properties,v 1.7 2003/09/03 18:29:00 zapata Exp $
 
 languagename=Svenska
 
@@ -96,7 +96,7 @@ comment.phone=Telefon
 comment.email=Email
 comment.url=Url
 comment.creator=F&ouml;rfattare
-comment.article=F&ouml;r artikel
+comment.article=Artikel
 comment.html=HTML?
 comment.status=Status 
 comment.language=Spr&aring;k
index f10b4a6..d9ce6ab 100755 (executable)
@@ -77,15 +77,14 @@ CREATE SEQUENCE "webdb_users_id_seq" start 1 increment 1 maxvalue 2147483647 min
 CREATE TABLE "webdb_users" (
        "id" integer DEFAULT nextval('webdb_users_id_seq'::text) NOT NULL,
        "login" character varying(16) NOT NULL,
-       "password" character varying(16) NOT NULL,
+       "password" character varying(255) NOT NULL,
        "is_admin" boolean DEFAULT '0' NOT NULL,
+       "comment" text,
        Constraint "webdb_users_pkey" Primary Key ("id")
 );
 
 CREATE  INDEX "idx_webdb_user_log_pas_is_admin" on "webdb_users" using btree ( "login" "varchar_ops", "password" "varchar_ops", "is_admin" "bool_ops" );
 
-CREATE  INDEX "idx_webdb_user_log_pas" on "webdb_users" using btree ( "login" "varchar_ops", "password" "varchar_ops" );
-
 --
 -- article type
 --
@@ -315,6 +314,9 @@ CREATE TABLE "other_media" (
 )
 INHERITS ("uploaded_media");
 
+CREATE        INDEX "idx_othermedia_is_published_produced" on "other_media" using btree ( "is_published" "bool_ops", "is_produced" "bool_ops" );
+CREATE UNIQUE INDEX "idx_othermedia_id" on "other_media" using btree ( "id" "int4_ops" );
+
 --
 -- content
 --
diff --git a/dbscripts/extra/hashpasswords.sh b/dbscripts/extra/hashpasswords.sh
new file mode 100755 (executable)
index 0000000..258bf61
--- /dev/null
@@ -0,0 +1,42 @@
+#!/bin/bash
+
+# DON'T RUN THIS SCRIPT UNLESS YOU KNOW WHAT YOU ARE DOING
+#
+# bash script to md5-hash all passwords: RUN ONLY ONCE!
+# md5sum needs to be installed
+# 
+# this script is not enough to use md5-hashed passwords: an
+# appropriate localizer needs to be set up as well.
+
+
+usage () {
+  echo "usage: $0 dbname"
+}
+
+if [ $# -ne 1 ]; then
+  usage 
+  exit;
+fi;
+
+
+# to get a backslash in the first pass sql script\r
+s1="\\"\r
+# to get a backslash in the second pass sql script\r
+s2="\\\\"\r
+# to get an escaped backslash in the second pass sql script:\r
+s3="\\\\\\\\"\r
+
+SCRIPT_FILE="/tmp/hashpasswords.$$.sql"
+
+echo psql $1 -P format=unaligned -t -X -F "" -c \
+  "select '${s2}set hashedpassword ${s1}'${s2}${s1}'${s1}' \`echo -n \"'||password||'\" | md5sum \`   \\r
+            \"${TEXT_SOURCE_PATH}\$(basename \"' || trim($2) || '\")\"\` ${s1}'${s2}${s1}'\\'\n',  \\r
+                'update webdb_users set password=:hashedpassword where id = '||id from webdb_users" > $SCRIPT_FILE\r
+
+
+# execute the script
+#psql -f ${SCRIPT_FILE} -d template1
+cat SCRIPT_FILE
+
+rm ${SCRIPT_FILE}
index d02e109..64a6cc9 100755 (executable)
@@ -1,4 +1,3 @@
-
 --
 -- Selected TOC Entries:
 --
@@ -10,8 +9,5 @@
 
 
 -- Disable triggers
-UPDATE "pg_class" SET "reltriggers" = 0 WHERE "relname" = 'media_folder';
-
 INSERT INTO "media_folder" VALUES (7,'openposting','20020329','','openposting','media anonymously uploaded','2002-03-29 14:45:53+01',NULL);
 -- Enable triggers
-UPDATE pg_class SET reltriggers = (SELECT count(*) FROM pg_trigger where pg_class.oid = tgrelid) WHERE relname = 'media_folder';
diff --git a/dbscripts/updates/update20030704.sql b/dbscripts/updates/update20030704.sql
new file mode 100755 (executable)
index 0000000..ddd1e2c
--- /dev/null
@@ -0,0 +1,49 @@
+-- update script 2003-07-04 by Zapata
+-- * makes the password field longer in webdb_users
+-- * adds a comments field to webdb_users;
+-- This script will terminate with an error the second time it's run,
+--   so running this script when it isn't needed can't do any harm.
+--
+
+BEGIN TRANSACTION;
+
+ALTER TABLE "webdb_users" RENAME TO "webdb_users_old";
+DROP INDEX "webdb_users_pkey";
+DROP INDEX "idx_webdb_user_log_pas";
+  
+CREATE TABLE "webdb_users" (
+       "id" integer DEFAULT nextval('webdb_users_id_seq'::text) NOT NULL,
+       "login" character varying(16) NOT NULL,
+       "password" character varying(255) NOT NULL,
+       "is_admin" boolean DEFAULT '0' NOT NULL,
+       "comment" text,
+       Constraint "webdb_users_pkey" Primary Key ("id")
+);
+
+INSERT INTO "webdb_users" (
+  "id", 
+  "login", 
+  "password",
+  "is_admin"
+)
+SELECT
+  "id", 
+  "login", 
+  "password",
+  "is_admin"
+FROM "webdb_users_old";
+
+UPDATE  pg_class
+SET
+  relowner = (SELECT relowner FROM pg_class WHERE relname='webdb_users_old'),
+  relacl =   (SELECT relacl FROM pg_class WHERE relname='webdb_users_old')
+WHERE 
+  relname = 'webdb_users';
+
+DROP TABLE "webdb_users_old";
+
+DROP INDEX "idx_webdb_user_log_pas_is_admin" on "webdb_users" using btree ( "login" "varchar_ops", "password" "varchar_ops", "is_admin" "bool_ops" );
+  
+-- that's it!
+  
+COMMIT TRANSACTION;
index 4ddc03b..215b9c3 100755 (executable)
@@ -1,6 +1,6 @@
 MIR INSTALLATION HOWTO
 
-Last updated: $Date: 2003/01/18 08:44:09 $
+Last updated: $Date: 2003/09/03 18:29:00 $
 ----------------------------------------------------------------
 
 Here is a short installation-howto of Mir.
@@ -8,12 +8,11 @@ Here is a short installation-howto of Mir.
 
 prerequisites: 
 
-- tomcat 4.0.4 (4.0.3 and below have some bad bugs) or above (3.3 works too as
-  of 04.04.2002, but this could change)
+- tomcat 4.0.4+ or 3.3 (4.0.3 and below have some bad bugs) 
   tomcat is available from http://jakarta.apache.org/tomcat/
 - apache 1.3.x. with mod_jk.so. As far as I can tell the connector for 2.x is
   still rather undocumented. http://httpd.apache.org
-- postgres 7.1.x or 7.2.x. http://www.postgresql.org
+- postgres 7.1+
 - ant (a java-based make) 
 - jaxp-1.1 (a SAX 2.0 compliant XML parser, comes with ant >= 1.4)
 - the JAI image framework (Java Advanced Imaging) versin 1.1.1 . get it from 
@@ -34,7 +33,7 @@ CVS LOGIN:
 
 CVS CHECKOUT:
 
-       cvs -d :pserver:anonymous@mir.indymedia.org:/var/lib/cvs co mir 
+       cvs -d :pserver:anonymous@mir.indymedia.org:/var/lib/cvs co -r MIR_1_1 mir
 
 
 2. customize the config: 
@@ -59,9 +58,7 @@ Now, change the install directory and group in perms.sh
 
        edit perms.sh 
 
-
-4. copy the mir/templates-dist-directory to mir/templates
-
+4. There is NO step 4!!
 
 5. compile. For this step, you have to make sure that the TOMCAT_HOME
 environment variable is set to the root of your tomcat installation.
@@ -74,11 +71,10 @@ the permissions and owners correctly.
 
 
 6. Link in the webapps directory of tomcat to the install directory (the 
-directory is called "Mir" and is located in the same directory in which 
-you installed the "mir" directory). (Here and in the rest of this document,
+directory is in mir/bin/mir (Here and in the rest of this document,
 we assume you called the link "Mir", but this could be named anything.)
-       cd /path/to/tomcat/webapps (tomcat-4.0.x/webapps)
-       ln -s /path/to/Mir Mir
+       cd ${TOMCAT_HOME}/webapps 
+       ln -s /path/to/mir/bin/mir Mir
 
 with tomcat 4.0.x, you could dynamically reload and stop the Mir webapp without
 restarting tomcat by using the "Manager App" with the following url:
@@ -104,64 +100,24 @@ task instead of the superuser. This is because if Mir uses the superuser to
 connect to the database and anybody manages to find out the password Mir 
 uses to connect, the attacker can take over the complete database. So, in
 the following examples, we assume that the database name is "Mir", the
-database user will be "mir" and the password is "joshua". Please note that
+database user will be "joe" and the password is "joshua". Please note that
 this particular password is far from being a good one. Watch "Wargames" for
 details. =B) 
 
+
 To access the database as the database superuser, you either have to log in
 as postgres on Unix level (which we don't recommend because you will need
 another user to have a login shell and a password which makes system
 penetration more likely) or you have to tell PostgreSQL with each
-application call that you want to connect as a specific user. If you access
-the database from any other user's account, use the -U flag to connect to
-PostgreSQL as the database superuser ("postgres"):
-
-       createdb -U postgres --encoding=unicode Mir 
-
-Please note that if you create the database from inside the psql application,
-the database name will likely be converted to lowercase letters.
-
-
-8b. create an unprivileged database user for Mir
-First, connect to the database as the database's superuser. 
-
-       psql -U postgres Mir
-
-Now we create the actual user. Please choose a password that is hard to 
-guess instead of "joshua". Good passwords have characters and numerals in
-it, have no link to its owner (like being her birthday, age, name of her 
-husband, dog, child, car, favourite beer brand). A good password looks like
-this: "8ncx4un".
-    
-    CREATE USER Mir WITH PASSWORD 'joshua' NOCREATEDB NOCREATEUSER;
+application call that you want to connect as a specific user. In the 
+following example we'll create the mir database as postgreSQL user 
+"pete".
 
-8c. create base table
-Please note that we use the superuser "postgres" to connect to the "Mir"
-database, /not/ the user "mir". 
+       cd mir/dbscripts
+       su postgres
+       ./createmirdb.sh mir pete joe joshua
 
-       psql -Upostgres -f dbscripts/create_pg.sql Mir
-    for i in dbscripts/help*.sql ; do psql -Upostgres -f $i Mir ; done
-    for i in dbscripts/populate*.sql ; do psql -Upostgres -f $i Mir ; done
-
-8d. Grant the required permissions to the new user
-
--- The following should be executed as the "postgres" DB user.
--- Note that ID_FROM_PG_USER and DATABASENAME should be replace with the 
-   appropriate field values from the 2 prior selects.
--- set owner of datbase
-select * from pg_database;
-select * from pg_user;
-update pg_database set datdba=ID_FROM_PG_USER where datname=DATABASENAME
-
--- find all tables to grant privs / select is just building sql
--- to be exectued
-
-select 'grant all on '||relname||' to "de_indy";'
-from pg_class
-where relname not like 'pg%'
-order by relname;
-
-8e. Apply neccessary changes to config.properties
+8b. Apply neccessary changes to config.properties
 
 Please open config.properties and look for the lines that begin with
 "Database.". The interesting properties are "Username", "Password", "Host"
@@ -173,38 +129,19 @@ in Mir/src nor in Mir/WEB-INF/classes nor in the directory tree you compiled
 Mir from) is world-readable. Else you wouldn't have to install a password,
 anyway.
 
-8f. Setup PostgreSQL so that all connections have to pass a password
+8c. Setup PostgreSQL so that all localhost connections have to pass a 
+password
 
-In /etc/postgresql/pg_hba.conf you should make sure that nobody can
-use the database without a password:
+In /etc/postgresql/pg_hba.conf, change the line with 127.0.0.1 as follows:
 
-local           all                                                                               password
 host         all         127.0.0.1     255.0.0.0           password
-host         all         0.0.0.0       0.0.0.0             reject
 
-This means: All local connections (i.e. psql without "-h hostname" option)
-have to authenticate themselves with a password. All connections from
-localhost (127.0.0.1) have to supply a password, too. All other connections
-are rejected. This line doen't have to be there if you have a properly
-configured firewall but even if you do have one, it adds to the security in
-case an attacker penetrates the firewall by some hack.
+This means: All connections from 127.0.0.1 to any database will have to 
+authenticate themselves with a password. Please refer to the PostgreSQL
+documentation if you want a different authentication setup. Make sure
+however that mir can connect to it's database using password authentication.
 
-If you can't access PostgreSQL after this for any reason, try and change
-"password" in /etc/postgresql/pg_hba.conf to "trust". This should disable
-any authentication method and make the database accessible again. Please use 
-this setting only temporarily because anybody who can access the PostgreSQL
-server could take over the database completely this way. After you fixed
-your password setting, switch the setting back to "password".
-You may want to change your PostgreSQL password from time to time to make
-database takeover harder. Rememer: Security is a process.
-
-
-
-9. Add the dupe prevention trigger to the database:
-       cd dbscripts/dupetrigger
-       
-       There, read INSTALL and follow the instructions.
-       
+9. For now, there's no step 9 either.
 
 10. Tweak mime-type extensions mappings in etc/web.xml file.
 
@@ -323,4 +260,4 @@ You can give these a try if anything goes wrong:
 
 ----------------------------------------------------------------
 
-$Date: 2003/01/18 08:44:09 $ - the Mir coders
+$Date: 2003/09/03 18:29:00 $ - the Mir coders
diff --git a/doc/INSTALL.postgresql b/doc/INSTALL.postgresql
deleted file mode 100755 (executable)
index 7311d29..0000000
+++ /dev/null
@@ -1,98 +0,0 @@
-postgresql - installation doku - version 7.1.x
--------------------------------------------------------------------------------------
-
-prerequisites:
-
-we installed postgres on machines with debian / kernel 2.2 / jdk 1.3 (blackdown),
-make sure you don't have postgresql installed via debian / apt-get. if you do
-purge the installation. 
-
-the following things have to be done as superuser (if not otherwise stated):
-
-
-1.  make sure you have:
-
-       libreadline-dev
-       perl-dev
-       ant >= 1.3
-       (blackdown) jdk1.3
-
-2.  get the tarball from postgresql.org
-    
-       tar xvfz postgresql-7.1.3.tar.gz
-
-3. configure
-
-       ./configure --enable-odbc --enable-syslog --with-perl --enable-multibyte=UNICODE \
-                   --enable-locale --enable-unicode-conversion --enable-recode --with-java
-
-4. make
-
- two problems with the compilation of the jdbc-driver might occur:
-
- a) an error message "no modern / no classic-compiler"
-    to get rid of this error you have to set a link in 
-
-    /usr/lib/j2re/lib/ext     
-    to: /usr/lib/j2sdk/lib/tools.jar 
-
- b) an error message "zip-file must have at least one entry"
-    to get rid of this error: make sure you have ant-1.3 installed
-
-5. make install
-
-6. pg_dumplo
-
-you should install "pg_dumplo" from the contrib part of the postgresql-source.
-this little programm enables you to dump the database *including* the oid (blobs). 
-
-   cd contrib/pg_dumplo
-   make
-   make install
-
-7. the start-scripts
-
-change to the start-scripts folder in the contrib-part.
-
-   cd ../start-scripts
-   cp linux /etc/init.d/postgresql
-   chmod a+x /etc/init.d/postgresql
-   update-rc.d postgresql defaults 
-       
-   edit the start-script in /etc/init.d/postgresql, and make sure 
-   postgresql is started with the "-i" option. to enable this insert
-   '-o "-i"' after 'start', which should look like:
-   
-       start) 
-               $ECHO_N "Starting PostgreSQL: "$ECHO_C 
-               su - $PGUSER -c "$DAEMON start -o '-i' -D '$PGDATA' -s -l PGLOG" 
-               echo "ok" 
-               ;; 
-
-
-
-8. adding a user / starting the database
-
-   adduser postgres
-   passwd postgres
-   mkdir /usr/local/pgsql/data
-   chown postgres /usr/local/pgsql/data
-   su - postgres
-   /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
-
-   /etc/init.d/postgresql start
-   /usr/local/pgsql/bin/createdb test
-   /usr/local/pgsql/bin/psql test
-
-8a. Postgresql user
-
-       See INSTALL.mir for basic dealing with postgresql user.
-       Use 'createdb -U postgres' to create a Database. Create
-       tables with different User inside the Database.
-
-
-Fine! - now you can continue with the postgresql-section in INSTALL.mir
-Good luck.
-
-
-
index 05b5106..553d837 100755 (executable)
@@ -1,4 +1,4 @@
-last changed: $Date: 2002/12/23 02:54:40 $ 2002 mir-coders
+last changed: $Date: 2003/09/03 18:29:00 $ 2002 mir-coders
 -------------------------------------------------------------------
 
 In all versions
@@ -8,11 +8,17 @@ In all versions
   thumbnail for a GIF or PNG image look like it has some television set snow in
   it. The workaround would be to upload Jpeg images if you can. We are looking
   into replacing JAI with another library.
+  Zapata: I fixed this (hopefully)
+
 * when deleting an item, be it an article or an uploaded media file, the action
   will remove the data/meta-data from the DB and prevent it from show up in
   lists, but it will not delete the file from the filesystem. hopefully this
   will be fixed before 1.1.0 is released and in 1.0.1. (FIXME: is this still a
   problem in the HEAD branch?)
+  Zapata: Deleting objects makes them untraceable and is thus generally a bad 
+  idea. It can be so configured (using producers.xml) that hidden stuff (articles, 
+  media) are deleted
+  
 * some obscure "under certain conditions" corner cases listed in our bug tracker
   at https://prod.indymedia.nl/mantis
 * some others that I'm forgetting now.
index 44a359a..8355d3b 100755 (executable)
@@ -23,22 +23,5 @@ these can be used as a basis to write your own custom scripts.
 
 USER MANAGMENT IN POSTGRESQL
 
--- set owner of datbase
-select * from pg_database;
-select * from pg_user;
-update pg_database set datdba=ID_FROM_PG_USER where datname=DATABASENAME
-
--- find all tables to grant privs / select is just building sql
--- to be exectued
-
-select 'grant all on '||relname||' to "de_indy";'
-from pg_class
-where relname not like 'pg%'
-order by relname;
-
--- alter table owner / select is just building sql
--- to be exectued
-select 'alter table '||relname||' owner to "de_indy";'
-from pg_class
-where relname not like 'pg%'
-order by relname;
+If you want to change the db user of a mir db, there's a script for 
+that in mir/dbscripts/extra.
index c7e68f0..c2b7956 100755 (executable)
@@ -1 +1 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\r<html>\r<head>\r  <title></title>\r</head>\r<body>\r<h1>mir developer mission statement </h1>\r<br>\rbuild creative free software that allows people to share and access content\rin an accesible way that promotes participation and is insensitive to repression,\rfocussing to the needs of progressive grassroots organization.<br>\r<br>\r<h2>mir key features:</h2>\r<ul>\r  <li>cms(content management system) implemented in the java programming\rlanguage with an emphasis on design and structure.</li>\r  <li>simplicity of mirroring content.</li>\r  <li>production system&nbsp; of the cms is independent of publication system\rlocation and type</li>\r  <li>support for multiple languages, media types and publication means</li>\r  <li>implements a wide range of content submission, approval and publication\rmodels without the need to alter the underlying code, from complete open\rposting to total editorial control</li>\r</ul>\r</body>\r</html>\r
\ No newline at end of file
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\r<html>\r<head>\r  <title></title>\r</head>\r<body>\r<h1>mir developer mission statement </h1>\r<br>\rbuild creative free software that allows people to share and access content\rin an accesible way that promotes participation and is insensitive to repression,\rfocussing to the needs of progressive grassroots organization.<br>\r<br>\r<h2>mir key features:</h2>\r<ul>\r  <li>cms(content management system) implemented in the java programming\rlanguage with an emphasis on design and structure.</li>\r  <li>simplicity of mirroring content.</li>\r  <li>production system&nbsp; of the cms is independent of publication system\rlocation and type</li>\r  <li>support for multiple languages, media types and publication means</li>\r  <li>implements a wide range of content submission, approval and publication\rmodels without the need to alter the underlying code, from complete open\rposting to total editorial control</li>\r</ul>\r</body>\r</html>
\ No newline at end of file
index ada8b79..a7e6c49 100755 (executable)
@@ -16,7 +16,7 @@ posting.nr_of_media=Number of Media Items (max 20)
 posting.nr_of_media.info=(Enter the number of files you want to upload and press the button <b>before</b> you enter data into the other fields.)
 posting.nr_of_media.submit=define number (max 20)
 posting.form.title=Publishing Form
-posting.title=<b>titel</b> of your article
+posting.title=<b>title</b> of your article
 posting.title.info=(Please use a clear and meaningful title)
 posting.topic=<b>Topic</b> of your Posting
 posting.topic.info=(multiple selection is possible. use the [Ctrl] key)
@@ -140,5 +140,11 @@ email.sent.text=The article has been forwarded to the specified address.
 email.error.invalidtoaddress=The address to send the article to is not valid
 email.error.invalidfromaddress=Your email address is not valid
 
+error.htmltitle=the system caused an error
+error.title=The system caused an error
+error.text=This can happen. Even if the following error message is not be comprehensible for you, <br>it might be helpful to <a href="mailto:{0}">{1}</a>:
+error.text2=So please send an e-mail with the <font color="Red">red text</font> and detailed information regarding the events that led to this error to <a href="mailto:{0}">{1}</a>. Thanks!
+
+
 
 
index ae7ff3f..f32ade0 100755 (executable)
@@ -46,9 +46,17 @@ Mir.Tech-email.name=mir-coders mailinglist
 Mir.Public-email.address=mir-coders@lists.indymedia.org
 Mir.Public-email.name=mir-coders mailinglist
 
-Mir.Version=1.1beta
+Mir.Version=pre 1.2
 DirectOpenposting=yes
 
+# Default timezone to display times in in admin, producers
+#
+# Leave empty to use the system's default
+Mir.DefaultTimezone=
+
+# Default date/time format
+Mir.DefaultDateTimeFormat = yyyy-MM-dd HH:mm
+
 #where to put the lucene index
 IndexPath=/tmp/index
 
@@ -60,7 +68,6 @@ Log.log4j.ConfigurationFile = etc/log4j.properties
 Log.Home = log
 
 Mir.Localizer=mircoders.localizer.basic.MirBasicLocalizer
-Mir.Localizer.Logfile=log/localizer.log
 
 # The location of the producer specifiations
 Mir.Localizer.ProducerConfigFile=etc/producer/producers.xml
@@ -111,13 +118,6 @@ Mir.Localizer.OpenPosting.CommentProducers= articles.changed;synchronization.run
 # Which producers need to be called after the "produce all new" link is clicked from admin
 Mir.Localizer.Producer.AllNewProducers= media.new;articles.changed;startpage.run;synchronization.run
 
-
-#note that you can't make pdf's without making fo's
-#this is actually now set in producers.xml
-#but these summarize what is said in there for the benefit of OpenMir 
-GenerateFO=yes
-GeneratePDF=yes
-
 #use rsync to mirror the website to a remote-host
 Rsync=no
 Rsync.Script.Path=/var/www/bin/rsync-copy
@@ -281,7 +281,6 @@ Database.Name=Mir
 # this sets the adaptor to be used
 
 Database.Adaptor=mir.storage.DatabaseAdaptorPostgresql
-Database.Logfile=log/dbentity.log
 
 #
 # configuration for adaptor postgres
index f6d9bcc..8051c66 100755 (executable)
@@ -1,5 +1,8 @@
 <html>
-<head><title>${lang("comment.htmltitle")}</title></head>
+<head>
+  <title>${lang("comment.htmltitle")}</title>
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
+</head>
 <body bgcolor="white" text="black" link="#006600" vlink="#009900" alink="red">
 
 <form action="${config["Producer.OpenAction"]}" method=post>
index 8cd8a6e..0c49459 100755 (executable)
@@ -6,7 +6,7 @@
        <meta name="description" content="${lang("posting.meta.description")}>
        <meta name="author" content="${lang("posting.meta.author")}>
        <meta name="keywords" content="${lang("posting.meta.keywords")}>
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}>
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
        <meta name="robots" content="index">
        <meta name="robots" content="follow">
        <style type="text/css" media="all">@import "forms.css";</style>
index b5eff3f..dbdb1c9 100755 (executable)
@@ -2,6 +2,8 @@
 <html>
   <head>
     <title>${lang("comment.htmltitle")}</title> 
+    <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
+    
   </head>
   
   <body marginwidth="0" marginheight="0" leftmargin="0" topmargin="0" bgcolor="#dddddd">
index f98ed27..d22dab1 100755 (executable)
@@ -6,7 +6,7 @@
        <meta name="author" content="${lang("posting.meta.author")}">
        <meta name="keywords" content="${lang("posting.meta.keywords")}">
        <!--<meta name="date" content="### Date ###Time">-->
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}">
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
        <meta name="robots" content="index">
        <meta name="robots" content="follow">
 
index 77aaf97..6ca865e 100755 (executable)
@@ -5,7 +5,7 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}">    
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">       
     <title>${config["Mir.Name"]} | ${article.title}</title>
        <meta name="keywords" content="indymedia,imc">
        <meta name="description" content="indymedia,imc">
                alert("Added article id to cookie!");           
        }
        
+       function clearNewsletter(){
+                document.cookie="myNewsletter= ;path=/";
+                alert("newsletter erased!");
+        }
+
+       function getNewsletter(){
+               var cookieValue=getCookie("myNewsletter");              
+               if (document.images)
+                   location.replace('${config["Producer.OpenAction"]}?do=getpdf&id='+cookieValue+'&forIE=.pdf');
+               else    
+                   location.href = '${config["Producer.OpenAction"]}?do=getpdf&id='+cookieValue+'&forIE=.pdf';
+       }
+       
        function getCookie(name){
                
                var cookies = document.cookie;
                                        </td></tr></table> 
 <br>
                                        <table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td bgcolor="#669999">
+            &nbsp;<a href="javascript:getNewsletter()">
+            <font color="#dddddd" size="+1"><b>${lang("article.newsletter_checkout")}&gt;&gt;</b></font></a>
+                                       </td></tr></table> 
+<br>
+                                       <table border="0" cellpadding="2" cellspacing="0" width="100%"><tr><td bgcolor="#669999">
             &nbsp;<a href="${config["Producer.OpenAction"]}?do=mail&mail_aid=${article.id}&mail_language=${language.code}">
             <font color="#dddddd" size="+1"><b>${lang("article.send_as_email")}&gt;&gt;</b></font></a>
                                        </td></tr></table>
index 5a5a464..8fd5fc5 100755 (executable)
@@ -1,7 +1,7 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}">
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
     <title>${config["Mir.Name"]} | ${lang("featurearchive.title")}</title>
        <meta name="keywords" content="${lang("general.keywords")}">
        <meta name="description" content="${lang("featurearchive.title")}">
index 8f15f3d..5b9b800 100755 (executable)
@@ -1,7 +1,7 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}">
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
     <title>${config["Mir.Name"]} | ${lang("newswirearchive.title")}</title>
        <meta name="keywords" content="${lang("general.keywords")}">
        <meta name="description" content="${lang("newswirearchive.title")}">
index 8836961..0cf6fbd 100755 (executable)
@@ -7,7 +7,7 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}">    
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">       
        <title>${config["Mir.Name"]}</title>
        <meta name="keywords" content="indymedia,imc">
        <meta name="description" content="indymedia,imc">
@@ -41,7 +41,7 @@
                        </td></tr></table>
                        <br>
                        <br>
-                       <font color="#cc0033" size="+3">&nbsp;&nbsp;&nbsp;<b><span id="indy">my.mir.indymedia.org</span></b></font>
+                       <font color="#cc0033" size="+3">&nbsp;&nbsp;&nbsp;<b><span id="indy">${config["Mir.Name"]}</span></b></font>
                </td>
        </tr>
        <tr>
index 2c4c095..e372834 100755 (executable)
@@ -1,7 +1,7 @@
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
-       <meta http-equiv="Content-Type" content="text/html; charset=${lang("htmlcharset")}">
+       <meta http-equiv="Content-Type" content="text/html; charset=${config["Mir.DefaultHTMLCharset"]}">
     <title>${config["Mir.Name"]} | ${topic.title}</title>
        <meta name="keywords" content="${lang("general.keywords")}">
        <meta name="description" content="${topic.description}">
index 57e7c5d..613ad35 100755 (executable)
@@ -43,6 +43,12 @@ todo       : check if necessary / update to version 1.1.1
              necessary?
 
 
+commons-codec
+------------------------------------------------
+version    : 1.1
+url        : http://jakarta.apache.org/commons/
+description: Needed for base64
+            
 commons-collections
 ------------------------------------------------
 version    : 2.1
index 55235f7..6ec9e62 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.lang.reflect.Method;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Vector;
-import javax.servlet.ServletException;
-import javax.servlet.UnavailableException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.apache.struts.util.MessageResources;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModel;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.generator.FreemarkerGenerator;
-import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
-import mir.misc.StringUtil;
-import mir.servlet.AbstractServlet;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleDispatch;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleUserExc;
-import mir.util.CachingRewindableIterator;
-import mir.util.ExceptionFunctions;
-import mir.util.StringRoutines;
-import mircoders.entity.EntityUsers;
-import mircoders.global.MirGlobal;
-import mircoders.module.ModuleMessage;
-import mircoders.module.ModuleUsers;
-import mircoders.servlet.ServletHelper;
-import mircoders.servlet.ServletModuleFileEdit;
-import mircoders.servlet.ServletModuleLocalizer;
-import mircoders.storage.DatabaseUsers;
-
-
-
-
-/**
- * Mir.java - main servlet, that dispatches to servletmodules
- *
- * @author $Author: zapata $
- * @version $Id: Mir.java,v 1.49 2003/05/08 02:43:41 zapata Exp $
- *
- */
-public class Mir extends AbstractServlet {
-  private static ModuleUsers usersModule = null;
-  private static ModuleMessage messageModule = null;
-  private final static Map servletModuleInstanceHash = new HashMap();
-  private static Locale fallbackLocale = null;
-
-  //I don't know about making this static cause it removes the
-  //possibility to change the config on the fly.. -mh
-  private static List loginLanguages = null;
-
-  protected TemplateModel getLoginLanguages() throws ServletException {
-    synchronized (Mir.class) {
-      try {
-        if (loginLanguages == null) {
-          MessageResources messageResources =
-            MessageResources.getMessageResources("bundles.adminlocal");
-          MessageResources messageResources2 =
-            MessageResources.getMessageResources("bundles.admin");
-
-          List languages =
-            StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");
-
-          loginLanguages = new Vector();
-
-          Iterator i = languages.iterator();
-
-          while (i.hasNext()) {
-            String code = (String) i.next();
-            Locale locale = new Locale(code, "");
-            String name = messageResources.getMessage(locale, "languagename");
-
-            if (name == null) {
-              name = messageResources2.getMessage(locale, "languagename");
-            }
-
-            if (name == null) {
-              name = code;
-            }
-
-            Map record = new HashMap();
-            record.put("name", name);
-            record.put("code", code);
-            loginLanguages.add(record);
-          }
-        }
-
-        return FreemarkerGenerator.makeAdapter(loginLanguages);
-      }
-      catch (Throwable t) {
-        throw new ServletException(t.getMessage());
-      }
-    }
-  }
-
-  // FIXME: this should probalby go into AbstractServlet so it can be used in
-  // OpenMir as well -mh
-  protected String getDefaultLanguage(HttpServletRequest aRequest) {
-    String defaultlanguage =
-      MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");
-
-    if (defaultlanguage.length() == 0) {
-      Locale locale = aRequest.getLocale();
-      defaultlanguage = locale.getLanguage();
-    }
-
-    return defaultlanguage;
-  }
-
-  protected synchronized Locale getFallbackLocale() throws ServletException {
-    try {
-      if (fallbackLocale == null) {
-        fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");
-      }
-    }
-    catch (Throwable t) {
-      throw new ServletException(t.getMessage());
-    }
-
-    return fallbackLocale;
-  }
-
-  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse)
-    throws ServletException, IOException, UnavailableException {
-    long startTime = System.currentTimeMillis();
-    long sessionConnectTime = 0;
-    EntityUsers userEntity;
-    HttpSession session;
-    String http = "";
-
-    configuration.addProperty("ServletName", getServletName());
-
-    session = aRequest.getSession(true);
-    userEntity = (EntityUsers) session.getAttribute("login.uid");
-
-    if (aRequest.getServerPort() == 443) {
-      http = "https";
-    }
-    else {
-      http = "http";
-    }
-
-    setNoCaching(aResponse);
-
-    Locale locale = new Locale(getDefaultLanguage(aRequest), "");
-
-    aResponse.setContentType("text/html; charset=" +
-        configuration.getString("Mir.DefaultHTMLCharset", "UTF-8"));
-
-    String moduleName = aRequest.getParameter("module");
-    checkLanguage(session, aRequest);
-
-    // Authentication
-    if (((moduleName != null) && moduleName.equals("login")) || (userEntity == null)) {
-      String user = aRequest.getParameter("login");
-      String passwd = aRequest.getParameter("password");
-      logger.debug("--login: evaluating for user: " + user);
-      userEntity = allowedUser(user, passwd);
-
-      if (userEntity == null) {
-        // login failed: redirecting to login
-        logger.warn("--login: failed!");
-        _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
-
-        return;
-      }
-      else if ((moduleName != null) && moduleName.equals("login")) {
-        // login successful
-        logger.info("--login: successful! setting uid: " + userEntity.getId());
-        session.setAttribute("login.uid", userEntity);
-        logger.debug("--login: trying to retrieve login.target");
-
-        String target = (String) session.getAttribute("login.target");
-
-        if (target != null) {
-          logger.debug("Redirect: " + target);
-
-          int serverPort = aRequest.getServerPort();
-          String redirect = "";
-          String redirectString = "";
-
-          if (serverPort == 80) {
-            redirect =
-              aResponse.encodeURL(http + "://" + aRequest.getServerName() + target);
-            redirectString =
-              "<html><head><meta http-equiv=refresh content=\"1;URL=" +
-              redirect + "\"></head><body>going <a href=\"" + redirect +
-              "\">Mir</a></body></html>";
-          } else {
-            redirect =
-              aResponse.encodeURL(http + "://" + aRequest.getServerName() + ":" +
-                aRequest.getServerPort() + target);
-            redirectString =
-              "<html><head><meta http-equiv=refresh content=\"1;URL=" +
-              redirect + "\"></head><body>going <a href=\"" + redirect +
-              "\">Mir</a></body></html>";
-          }
-
-          aResponse.getWriter().println(redirectString);
-
-          //aResponse.sendRedirect(redirect);
-        } else {
-          // redirecting to default target
-          logger.debug("--login: no target - redirecting to default");
-          _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
-        }
-
-        return;
-      }
-       // if login succesful
-    }
-     // if login
-
-    if ((moduleName != null) && moduleName.equals("logout")) {
-      logger.info("--logout");
-      session.invalidate();
-
-      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
-
-      return;
-    }
-
-    // Check if authed!
-    if (userEntity == null) {
-      // redirect to loginpage
-      String redirectString = aRequest.getRequestURI();
-      String queryString = aRequest.getQueryString();
-
-      if ((queryString != null) && queryString.length()!=0) {
-        redirectString += ("?" + aRequest.getQueryString());
-        session.setAttribute("login.target", redirectString);
-      }
-
-      _sendLoginPage(aResponse, aRequest, aResponse.getWriter());
-
-      return;
-    }
-
-    // If no module is specified goto standard startpage
-    if ((moduleName == null) || moduleName.equals("")) {
-//      logger.debug("no module: redirect to standardpage");
-      _sendStartPage(aResponse, aRequest, aResponse.getWriter(), userEntity);
-
-      return;
-    }
-
-    try {
-      // get servletmodule by parameter and continue with dispacher
-      ServletModule smod = getServletModuleForName(moduleName);
-      ServletModuleDispatch.dispatch(smod, aRequest, aResponse);
-    }
-    catch (Throwable e) {
-      Throwable cause = ExceptionFunctions.traceCauseException(e);
-
-      if (cause instanceof ServletModuleUserExc)
-        handleUserError(aRequest, aResponse, aResponse.getWriter(), (ServletModuleUserExc) cause);
-      else
-        handleError(aRequest, aResponse, aResponse.getWriter(), cause);
-
-    }
-
-    // timing...
-    sessionConnectTime = System.currentTimeMillis() - startTime;
-    logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");
-  }
-
-  /**
-   *  Private method getServletModuleForName returns ServletModule
-   *  from Cache
-   *
-   * @param moduleName
-   * @return ServletModule
-   *
-   */
-  private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {
-    // Instance in Map ?
-    if (!servletModuleInstanceHash.containsKey(moduleName)) {
-      // was not found in hash...
-      try {
-        Class theServletModuleClass = null;
-
-        try {
-          // first we try to get ServletModule from stern.che3.servlet
-          theServletModuleClass =
-            Class.forName("mircoders.servlet.ServletModule" + moduleName);
-        } catch (ClassNotFoundException e) {
-          // on failure, we try to get it from lib-layer
-          theServletModuleClass =
-            Class.forName("mir.servlet.ServletModule" + moduleName);
-        }
-
-        Method m = theServletModuleClass.getMethod("getInstance", null);
-        ServletModule smod = (ServletModule) m.invoke(null, null);
-
-        // we put it into map for further reference
-        servletModuleInstanceHash.put(moduleName, smod);
-
-        return smod;
-      }
-      catch (Exception e) {
-        throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());
-      }
-    }
-    else {
-      return (ServletModule) servletModuleInstanceHash.get(moduleName);
-    }
-  }
-
-  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse,
-                               PrintWriter out, ServletModuleUserExc anException) {
-    try {
-      logger.info("user error: " + anException.getMessage());
-      SimpleHash modelRoot = new SimpleHash();
-      MessageResources messages = MessageResources.getMessageResources("bundles.admin");
-      modelRoot.put("errorstring",
-          new SimpleScalar(
-              messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters())
-          ));
-      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
-      HTMLTemplateProcessor.process(
-          aResponse,
-          MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"),
-          modelRoot,
-          null,
-          out,
-          getLocale(aRequest),
-          fallbackLocale);
-      out.close();
-    }
-    catch (Throwable e) {
-      logger.error("Error handling user error" + e.toString());
-    }
-
-  }
-
-  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse,PrintWriter out, Throwable anException) {
-
-    try {
-      logger.error("error: " + anException);
-      SimpleHash modelRoot = new SimpleHash();
-      modelRoot.put("errorstring", new SimpleScalar(anException.getMessage()));
-      modelRoot.put("date", new SimpleScalar(StringUtil.date2readableDateTime(
-                                               new GregorianCalendar())));
-      HTMLTemplateProcessor.process(
-          aResponse,MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"),
-          modelRoot,null,out, getLocale(aRequest), getFallbackLocale());
-      out.close();
-    }
-    catch (Throwable e) {
-      logger.error("Error handling error: " + e.toString());
-    }
-  }
-
-  /**
-   *  evaluate login for user / password
-   */
-  protected EntityUsers allowedUser(String user, String password) {
-    try {
-      if (usersModule == null) {
-        usersModule = new ModuleUsers(DatabaseUsers.getInstance());
-      }
-
-      return usersModule.getUserForLogin(user, password);
-    }
-    catch (Exception e) {
-      logger.debug(e.getMessage());
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
-      return null;
-    }
-  }
-
-  // Redirect-methods
-  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
-    PrintWriter out) {
-    String loginTemplate = configuration.getString("Mir.LoginTemplate");
-    String sessionUrl = aResponse.encodeURL("");
-
-    try {
-      SimpleHash mergeData = new SimpleHash();
-      SimpleList languages = new SimpleList();
-
-      mergeData.put("session", sessionUrl);
-
-      mergeData.put("defaultlanguage", getDefaultLanguage(aRequest));
-      mergeData.put("languages", getLoginLanguages());
-
-      HTMLTemplateProcessor.process(aResponse, loginTemplate, mergeData, null, out, getLocale(aRequest), getFallbackLocale());
-    }
-    catch (Throwable e) {
-      handleError(aRequest, aResponse, out, e);
-    }
-  }
-
-  private void _sendStartPage(HttpServletResponse aResponse, HttpServletRequest aRequest,
-    PrintWriter out, EntityUsers userEntity) {
-    String startTemplate = configuration.getString("Mir.StartTemplate");
-    String sessionUrl = aResponse.encodeURL("");
-
-    try {
-      Map mergeData = ServletHelper.makeGenerationData(aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()}, "bundles.admin", "bundles.adminlocal");
-      mergeData.put("messages",
-             new CachingRewindableIterator(
-               new EntityIteratorAdapter( "", "webdb_create desc", 10,
-                 MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));
-
-      mergeData.put("fileeditentries", ((ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());
-      mergeData.put("administeroperations", ((ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());
-
-      mergeData.put("searchvalue", null);
-      mergeData.put("searchfield", null);
-      mergeData.put("searchispublished", null);
-      mergeData.put("searcharticletype", null);
-      mergeData.put("searchorder", null);
-      mergeData.put("selectarticleurl", null);
-
-      ServletHelper.generateResponse(out, mergeData, startTemplate);
-    }
-    catch (Exception e) {
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      handleError(aRequest, aResponse, out, e);
-    }
-  }
-
-  public String getServletInfo() {
-    return "Mir " + configuration.getString("Mir.Version");
-  }
-
-  private void checkLanguage(HttpSession session, HttpServletRequest aRequest) {
-    // a lang parameter always sets the language
-    String lang = aRequest.getParameter("language");
-
-    if (lang != null) {
-      logger.info("selected language " + lang + " overrides accept-language");
-      setLanguage(session, lang);
-    }
-    // otherwise store language from accept header in session
-    else if (session.getAttribute("language") == null) {
-      logger.info("accept-language is " + aRequest.getLocale().getLanguage());
-      setLanguage(session, aRequest.getLocale().getLanguage());
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+import java.io.IOException;\r
+import java.lang.reflect.Method;\r
+import java.util.*;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+import javax.servlet.ServletConfig;\r
+import javax.servlet.ServletException;\r
+import javax.servlet.UnavailableException;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import org.apache.struts.util.MessageResources;\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.servlet.AbstractServlet;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleDispatch;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleUserExc;\r
+import mir.util.ExceptionFunctions;\r
+import mir.util.StringRoutines;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleMessage;\r
+import mircoders.module.ModuleUsers;\r
+import mircoders.servlet.ServletHelper;\r
+import mircoders.storage.DatabaseUsers;\r
+\r
+\r
+\r
+\r
+/**\r
+ * Mir.java - main servlet, that dispatches to servletmodules\r
+ *\r
+ * @author $Author: zapata $\r
+ * @version $Id: Mir.java,v 1.50 2003/09/03 18:29:01 zapata Exp $\r
+ *\r
+ */\r
+public class Mir extends AbstractServlet {\r
+  private static ModuleUsers usersModule = null;\r
+  private static ModuleMessage messageModule = null;\r
+  private final static Map servletModuleInstanceHash = new HashMap();\r
+  private static Locale fallbackLocale = null;\r
+\r
+  private static List loginLanguages = null;\r
+\r
+  protected List getLoginLanguages() throws ServletException {\r
+    synchronized (Mir.class) {\r
+      try {\r
+        if (loginLanguages == null) {\r
+          MessageResources messageResources =\r
+            MessageResources.getMessageResources("bundles.adminlocal");\r
+          MessageResources messageResources2 =\r
+            MessageResources.getMessageResources("bundles.admin");\r
+\r
+          List languages =\r
+            StringRoutines.splitString(MirGlobal.config().getString("Mir.Login.Languages", "en"), ";");\r
+\r
+          loginLanguages = new Vector();\r
+\r
+          Iterator i = languages.iterator();\r
+\r
+          while (i.hasNext()) {\r
+            String code = (String) i.next();\r
+            Locale locale = new Locale(code, "");\r
+            String name = messageResources.getMessage(locale, "languagename");\r
+\r
+            if (name == null) {\r
+              name = messageResources2.getMessage(locale, "languagename");\r
+            }\r
+\r
+            if (name == null) {\r
+              name = code;\r
+            }\r
+\r
+            Map record = new HashMap();\r
+            record.put("name", name);\r
+            record.put("code", code);\r
+            loginLanguages.add(record);\r
+          }\r
+        }\r
+\r
+        return loginLanguages;\r
+      }\r
+      catch (Throwable t) {\r
+        throw new ServletException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  public void init(ServletConfig config) throws ServletException {\r
+    super.init(config);\r
+\r
+    usersModule = new ModuleUsers(DatabaseUsers.getInstance());\r
+  }\r
+\r
+  protected String getDefaultLanguage(HttpServletRequest aRequest) {\r
+    String defaultlanguage =\r
+      MirGlobal.config().getString("Mir.Login.DefaultLanguage", "");\r
+\r
+    if (defaultlanguage.length() == 0) {\r
+      Locale locale = aRequest.getLocale();\r
+      defaultlanguage = locale.getLanguage();\r
+    }\r
+\r
+    return defaultlanguage;\r
+  }\r
+\r
+  protected synchronized Locale getFallbackLocale() throws ServletException {\r
+    try {\r
+      if (fallbackLocale == null) {\r
+        fallbackLocale = new Locale(MirPropertiesConfiguration.instance().getString("Mir.Admin.FallbackLanguage", "en"), "");\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletException(t.getMessage());\r
+    }\r
+\r
+    return fallbackLocale;\r
+  }\r
+\r
+  public EntityUsers checkCredentials(HttpServletRequest aRequest) throws ServletException {\r
+    try {\r
+      EntityUsers user = ServletHelper.getUser(aRequest);\r
+\r
+      String username = aRequest.getParameter("login");\r
+      String password = aRequest.getParameter("password");\r
+\r
+      if (username != null && password != null) {\r
+        user = usersModule.getUserForLogin(username, password);\r
+\r
+\r
+        ServletHelper.setUser(aRequest, user);\r
+      }\r
+\r
+      return user;\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace();\r
+\r
+      throw new ServletException(t.toString());\r
+    }\r
+  }\r
+\r
+  public void process(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletException, IOException, UnavailableException {\r
+    try {\r
+      long startTime = System.currentTimeMillis();\r
+      long sessionConnectTime = 0;\r
+\r
+      HttpSession session = aRequest.getSession(true);\r
+      setNoCaching(aResponse);\r
+      Locale locale = new Locale(getDefaultLanguage(aRequest), "");\r
+      aResponse.setContentType("text/html; charset=" +\r
+                               configuration.\r
+                               getString("Mir.DefaultHTMLCharset", "UTF-8"));\r
+\r
+      EntityUsers userEntity = checkCredentials(aRequest);\r
+\r
+      if (userEntity == null) {\r
+        String queryString = aRequest.getQueryString();\r
+\r
+        if ( (queryString != null) && (queryString.length() != 0) && session.getAttribute("login.target") == null &&\r
+             (aRequest.getParameter("module")==null ||\r
+              (!aRequest.getParameter("module").equals("login") && !aRequest.getParameter("module").equals("logout")))) {\r
+          session.setAttribute("login.target", queryString);\r
+        }\r
+\r
+        _sendLoginPage(aResponse, aRequest);\r
+      }\r
+      else {\r
+        String moduleName = aRequest.getParameter("module");\r
+        checkLanguage(session, aRequest);\r
+\r
+        if ( ( (moduleName == null) || moduleName.equals(""))) {\r
+          moduleName="Admin";\r
+        }\r
+\r
+\r
+        if (moduleName.equals("login")) {\r
+          String target = (String) session.getAttribute("login.target");\r
+\r
+          if (target != null) {\r
+            ServletHelper.redirect(aResponse, target);\r
+          }\r
+          else {\r
+            ServletHelper.redirect(aResponse, "");\r
+          }\r
+        }\r
+        else if (moduleName.equals("logout")) {\r
+          logger.info(userEntity.getValue("login") + " has logged out");\r
+          session.invalidate();\r
+          _sendLoginPage(aResponse, aRequest);\r
+          return;\r
+        }\r
+        else {\r
+          try {\r
+            ServletModule servletModule = getServletModuleForName(moduleName);\r
+            ServletModuleDispatch.dispatch(servletModule, aRequest, aResponse);\r
+\r
+            sessionConnectTime = System.currentTimeMillis() - startTime;\r
+            logger.info("EXECTIME (" + moduleName + "): " + sessionConnectTime + " ms");\r
+          }\r
+          catch (Throwable e) {\r
+            Throwable cause = ExceptionFunctions.traceCauseException(e);\r
+\r
+            if (cause instanceof ServletModuleUserExc)\r
+              handleUserError(aRequest, aResponse, (ServletModuleUserExc) cause);\r
+            else\r
+              handleError(aRequest, aResponse, cause);\r
+          }\r
+\r
+          if (aRequest.getParameter("killsession")!=null)\r
+            aRequest.getSession().invalidate();\r
+        }\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace();\r
+\r
+      throw new ServletException(t.toString());\r
+    }\r
+  }\r
+\r
+  /**\r
+   * caching routine to get a module for a module name\r
+   *\r
+   * @param moduleName the module name\r
+   * @return the requested module\r
+   * @throws ServletModuleExc\r
+   */\r
+\r
+  private static ServletModule getServletModuleForName(String moduleName) throws ServletModuleExc {\r
+    // Instance in Map ?\r
+    if (!servletModuleInstanceHash.containsKey(moduleName)) {\r
+      // was not found in hash...\r
+      try {\r
+        Class theServletModuleClass = null;\r
+\r
+        try {\r
+          // first we try to get ServletModule from stern.che3.servlet\r
+          theServletModuleClass =\r
+            Class.forName("mircoders.servlet.ServletModule" + moduleName);\r
+        }\r
+        catch (ClassNotFoundException e) {\r
+          // on failure, we try to get it from lib-layer\r
+          theServletModuleClass =\r
+            Class.forName("mir.servlet.ServletModule" + moduleName);\r
+        }\r
+\r
+        Method m = theServletModuleClass.getMethod("getInstance", null);\r
+        ServletModule smod = (ServletModule) m.invoke(null, null);\r
+\r
+        // we put it into map for further reference\r
+        servletModuleInstanceHash.put(moduleName, smod);\r
+\r
+        return smod;\r
+      }\r
+      catch (Exception e) {\r
+        throw new ServletModuleExc("*** error resolving classname for " + moduleName + " -- " + e.getMessage());\r
+      }\r
+    }\r
+    else {\r
+      return (ServletModule) servletModuleInstanceHash.get(moduleName);\r
+    }\r
+  }\r
+\r
+  private void handleUserError(HttpServletRequest aRequest, HttpServletResponse aResponse, ServletModuleUserExc anException) {\r
+    try {\r
+      logger.info("user error: " + anException.getMessage());\r
+\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});\r
+\r
+      MessageResources messages = MessageResources.getMessageResources("bundles.admin");\r
+      responseData.put("errorstring", messages.getMessage(getLocale(aRequest), anException.getMessage(), anException.getParameters()));\r
+      responseData.put("date", new GregorianCalendar().getTime());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.UserErrorTemplate"));\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("Error handling user error" + e.toString());\r
+    }\r
+  }\r
+\r
+  private void handleError(HttpServletRequest aRequest, HttpServletResponse aResponse, Throwable anException) {\r
+    try {\r
+      logger.error("error: " + anException);\r
+\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});\r
+\r
+      responseData.put("errorstring", anException.toString());\r
+      responseData.put("date", new GregorianCalendar().getTime());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, MirPropertiesConfiguration.instance().getString("Mir.ErrorTemplate"));\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("Error handling error: " + e.toString());\r
+    }\r
+  }\r
+\r
+  // Redirect-methods\r
+  private void _sendLoginPage(HttpServletResponse aResponse, HttpServletRequest aRequest) {\r
+    String loginTemplate = configuration.getString("Mir.LoginTemplate");\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale()});\r
+\r
+      responseData.put("defaultlanguage", getDefaultLanguage(aRequest));\r
+      responseData.put("languages", getLoginLanguages());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, loginTemplate);\r
+    }\r
+    catch (Throwable e) {\r
+      handleError(aRequest, aResponse, e);\r
+    }\r
+  }\r
+\r
+  public String getServletInfo() {\r
+    return "Mir " + configuration.getString("Mir.Version");\r
+  }\r
+}\r
index 8fcc1b8..f9f260d 100755 (executable)
@@ -46,7 +46,7 @@ import mircoders.servlet.ServletModuleOpenIndy;
  *  OpenMir.java - main servlet for open posting and comment feature to articles
  *
  *  @author RK 1999-2001, the mir-coders group
- *  @version $Id: OpenMir.java,v 1.36 2003/06/15 22:59:44 idfx Exp $
+ *  @version $Id: OpenMir.java,v 1.37 2003/09/03 18:29:01 zapata Exp $
  *
  */
 
@@ -100,32 +100,5 @@ public class OpenMir extends AbstractServlet {
   public String getServletInfo(){
     return "OpenMir "+configuration.getString("Mir.Version");
   }
-
-
-  /**
-   * Selects the language for the response.
-   *
-   * @param session
-   * @param aRequest
-   */
-  private void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {
-    String requestLanguage = aRequest.getParameter("language");
-    String sessionLanguage = (String) aSession.getAttribute("language");
-    String acceptLanguage = aRequest.getLocale().getLanguage();
-    String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
-
-    String language = requestLanguage;
-
-    if (language==null)
-      language = sessionLanguage;
-
-    if (language==null)
-      language = acceptLanguage;
-
-    if (language==null)
-      language = defaultLanguage;
-
-    setLanguage(aSession, language);
-  }
 }
 
index 3f92e20..38988b2 100755 (executable)
@@ -52,6 +52,9 @@ Abuse.Config=abuse.properties
 #    (The name is deliberately misleading)
 Abuse.CookieName=SessionIdentifier
 
+# If equal to 1, the IP log can't be used
+Abuse.DisallowIPLogging=0
+
 # The time the cookie will remain active in hours
 #   168 = 1 week
 Abuse.CookieMaxAge=168
@@ -83,6 +86,9 @@ Mir.Login.Languages=en;de;fr;nl;es;pt;eu;sv;tr;zh;gz
 Mir.Admin.FallbackLanguage=en
 
 
+# Which usernames have admin priviliges (, seperated usernames)
+AccessControl.SuperUsers = admin
+
 # the templates
 Mir.Localizer.Producer.GeneratorLibrary= default=freemarker(etc/producer/)
 Mir.Localizer.Admin.GeneratorLibrary= default=freemarker(templates/admin/)
@@ -265,7 +271,16 @@ Producer.HTML2FOStyleSheet=/some/dir/mir/etc/producer/html2fo.xsl
 #
 
 
+# an image which will appear at the top of the first page
+
+PDF.Header.Image=
+PDF.Header.ImageHeight=0
+
+#PDF.Header.Image=/home/john/mir/web/img/pdfbanner.png
+#PDF.Header.ImageHeight=70
+
 # a single line of big text which will appear at the top of the first page of all generated pdfs
+# if you set the String to nothing, this will be skipped
 
 PDF.Title.String=INDYMEDIA SOMEWHERE
 PDF.Title.FontSize=24
@@ -290,6 +305,7 @@ PDF.Index.FontFamily=helvetica
 PDF.Meta.Height=36
 PDF.Meta.FontSize=14
 PDF.Meta.FontFamily=helvetica 
+RDF.Meta.DateFormat=yyyy-MM-dd HH:mm
 
 # how to format the article description
 
@@ -348,18 +364,9 @@ Database.Username=postgres
 Database.Password=
 Database.Host=localhost
 Database.Name=Mir
+Database.Port=5432
+Database.Driver=org.postgresql.Driver
 
-#
-# this sets the adaptor to be used
-
-Database.Adaptor=mir.storage.DatabaseAdaptorPostgresql
-
-#
-# configuration for adaptor postgres
-# In this example, "Mir" is the dbname
-
-Adaptor.PostgreSQL.URL=jdbc:postgresql://localhost:5432/Mir
-Adaptor.PostgreSQL.Driver=org.postgresql.Driver
 
 #
 # Servlet / Module configurations
@@ -376,6 +383,14 @@ Mir.DefaultEncoding=UTF8
 # don't change this unless...
 Mir.DefaultHTMLCharset=UTF-8
 
+# Default timezone to display times in in admin, producers
+# 
+# Leave empty to use the system's default
+Mir.DefaultTimezone= 
+
+# Default date/time format
+Mir.DefaultDateTimeFormat = yyyy-MM-dd HH:mm
+
 
 
 
@@ -383,6 +398,8 @@ Localizer.OpenSession.article.EditTemplate = editarticle.template
 Localizer.OpenSession.article.DupeTemplate = dupearticle.template
 Localizer.OpenSession.article.DoneTemplate = donearticle.template
 Localizer.OpenSession.article.UnsupportedMediaTemplate = unsupportedmediatype.template
+Localizer.OpenSession.article.DefaultArticleType=newswire
+
 Localizer.OpenSession.comment.EditTemplate = editcomment.template
 Localizer.OpenSession.comment.DupeTemplate = dupecomment.template
 Localizer.OpenSession.comment.DoneTemplate = donecomment.template
@@ -421,88 +438,81 @@ Mir.StartTemplate=start_admin.template
 Mir.ErrorTemplate=error.template
 Mir.UserErrorTemplate=usererror.template
 
-ServletModule.Themen.ConfirmTemplate=confirm.template
-ServletModule.Themen.ObjektTemplate=topic.template
-ServletModule.Themen.ListTemplate=topiclist.template
+ServletModule.Default.ListSize = 30
 
-ServletModule.LinksImcs.ConfirmTemplate=confirm.template
-ServletModule.LinksImcs.ObjektTemplate=linksimcs.template
-ServletModule.LinksImcs.ListTemplate=linksimcslist.template
+ServletModule.Topics.DeleteConfirmationTemplate=confirm.template
+ServletModule.Topics.EditTemplate=topic.template
+ServletModule.Topics.ListTemplate=topiclist.template
 
-ServletModule.Users.ConfirmTemplate=confirm.template
-ServletModule.Users.ObjektTemplate=user.template
+ServletModule.Users.DeleteConfirmationTemplate=confirm.template
+ServletModule.Users.EditTemplate=user.template
 ServletModule.Users.ListTemplate=userlist.template
 
-ServletModule.Images.ConfirmTemplate=confirm.template
-ServletModule.Images.ObjektTemplate=image.template
+ServletModule.Images.DeleteConfirmationTemplate=confirm.template
+ServletModule.Images.EditTemplate=image.template
 ServletModule.Images.ListTemplate=imagelist.template
 
-ServletModule.Audio.ConfirmTemplate=confirm.template
-ServletModule.Audio.ObjektTemplate=audio.template
+ServletModule.Audio.DeleteConfirmationTemplate=confirm.template
+ServletModule.Audio.EditTemplate=audio.template
 ServletModule.Audio.ListTemplate=audiolist.template
 
-ServletModule.Video.ConfirmTemplate=confirm.template
-ServletModule.Video.ObjektTemplate=video.template
+ServletModule.Video.DeleteConfirmationTemplate=confirm.template
+ServletModule.Video.EditTemplate=video.template
 ServletModule.Video.ListTemplate=videolist.template
 
-ServletModule.OtherMedia.ConfirmTemplate=confirm.template
-ServletModule.OtherMedia.ObjektTemplate=media.template
+ServletModule.OtherMedia.DeleteConfirmationTemplate=confirm.template
+ServletModule.OtherMedia.EditTemplate=other.template
 ServletModule.OtherMedia.ListTemplate=medialist.template
 
-ServletModule.Content.ConfirmTemplate=confirm.template
-ServletModule.Content.ObjektTemplate=content.template
+ServletModule.Content.DeleteConfirmationTemplate=confirm.template
+ServletModule.Content.EditTemplate=content.template
 ServletModule.Content.ListTemplate=contentlist.template
 
-ServletModule.Mediafolder.ConfirmTemplate=confirm.template
-ServletModule.Mediafolder.ObjektTemplate=mediafolder.template
+ServletModule.Mediafolder.DeleteConfirmationTemplate=confirm.template
+ServletModule.Mediafolder.EditTemplate=mediafolder.template
 ServletModule.Mediafolder.ListTemplate=mediafolderlist.template
 
-#
-# config for ServletModuleComment - browsing/editing/deleting comments
-ServletModule.Comment.ConfirmTemplate=confirm.template
-ServletModule.Comment.ObjektTemplate=comment.template
+ServletModule.Comment.DeleteConfirmationTemplate=confirm.template
+ServletModule.Comment.EditTemplate=comment.template
 ServletModule.Comment.ListTemplate=commentlist.template
 
-#
-# config for ServletModuleHidden - lists all hidden articles of one month
 ServletModule.Hidden.ListTemplate=hiddenlist.template
 
-#
-# config for Breaking - browsing/editing/deleting breaking news
-ServletModule.Breaking.ConfirmTemplate=confirm.template
-ServletModule.Breaking.ObjektTemplate=breaking.template
+ServletModule.Breaking.DeleteConfirmationTemplate=confirm.template
+ServletModule.Breaking.EditTemplate=breaking.template
 ServletModule.Breaking.ListTemplate=breakinglist.template
 
-#
-# config for Breaking - editing text files
-ServletModule.FileEdit.ConfirmTemplate=confirm.template
-ServletModule.FileEdit.ObjektTemplate=fileedit.template
+ServletModule.FileEdit.DeleteConfirmationTemplate=confirm.template
+ServletModule.FileEdit.EditTemplate=fileedit.template
 ServletModule.FileEdit.ListTemplate=fileeditlist.template
 
-#
-# config for messages - browsing/editing/deleting internal messages
-ServletModule.Messages.ConfirmTemplate=confirm.template
-ServletModule.Messages.ObjektTemplate=message.template
-ServletModule.Messages.ListTemplate=messagelist.template
+ServletModule.Message.DeleteConfirmationTemplate=confirm.template
+ServletModule.Message.EditTemplate=message.template
+ServletModule.Message.ListTemplate=messagelist.template
 
-#
-# config for languages - browsing/editing/deleting languages
-ServletModule.Language.ConfirmTemplate=confirm.template
-ServletModule.Language.ObjektTemplate=language.template
+ServletModule.Language.DeleteConfirmationTemplate=confirm.template
+ServletModule.Language.EditTemplate=language.template
 ServletModule.Language.ListTemplate=languagelist.template
 
-#
-# config for article type
-ServletModule.ArticleType.ConfirmTemplate=confirm.template
+ServletModule.ArticleType.DeleteConfirmationTemplate=confirm.template
 ServletModule.ArticleType.EditTemplate=articletype.template
 ServletModule.ArticleType.ListTemplate=articletypelist.template
 
-#
-# config for comment status
-ServletModule.CommentStatus.ConfirmTemplate=confirm.template
+ServletModule.CommentStatus.DeleteConfirmationTemplate=confirm.template
 ServletModule.CommentStatus.EditTemplate=commentstatus.template
 ServletModule.CommentStatus.ListTemplate=commentstatuslist.template
 
+
+
+
+
+#
+# config for abuse
+ServletModule.Abuse.EditFilter.Template = abuse.filter.template\r
+ServletModule.Abuse.ListFilters.Template = abuse.filters.template\r
+ServletModule.Abuse.ViewLog.Template = abuse.log.template\r
+ServletModule.Abuse.Main.Template = abuse.template\r
+
 #
 # producer-related configs below
 #
index e4d8927..30823c0 100755 (executable)
@@ -31,7 +31,7 @@ package  mir.entity;
 
 import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
+import java.util.*;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
@@ -40,27 +40,22 @@ import mir.misc.StringUtil;
 import mir.storage.StorageObject;
 import mir.storage.StorageObjectExc;
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateHashModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-import freemarker.template.TemplateModelRoot;
 
 /**
  * Base class the entities are derived from. Provides base functionality of
  * an entity. Entities are used to represent rows of a database table.<p>
- * Interfacing TemplateHashModel and TemplateModelRoot to be freemarker compliant
  *
- * @version $Id: Entity.java,v 1.21 2003/05/03 00:21:22 zapata Exp $
+ * @version $Id: Entity.java,v 1.22 2003/09/03 18:29:01 zapata Exp $
  * @author rk
  *
  */
 
-public class Entity implements TemplateHashModel, TemplateModelRoot
+public class Entity
 {
   protected static MirPropertiesConfiguration configuration;
 
-  protected Map theValuesHash; // tablekey / value
+//  protected Map theValuesHash; // tablekey / value
+  protected Map values;
   protected StorageObject theStorageObject;
   protected List streamedInput = null;
   protected LoggerWrapper logger;
@@ -76,37 +71,47 @@ public class Entity implements TemplateHashModel, TemplateModelRoot
 
   public Entity() {
     logger = new LoggerWrapper("Entity");
+
+    values = new HashMap();
   }
 
   /**
    * Constructor
    * @param StorageObject The StorageObject of the Entity.
    */
+
   public Entity(StorageObject StorageObject) {
     this();
+
     setStorage(StorageObject);
   }
 
-  /*
-   * Sets the StorageObject of the Entity.
+  /**
+   *
+   * @param storage
    */
+
   public void setStorage(StorageObject storage) {
     this.theStorageObject = storage;
   }
 
   /**
    * Sets the values of the Entity. (Only to be called by the Storage Object)
-   * @param theStringValues Map containing the new values of the Entity
+   *
+   * @param aMap Map containing the new values of the Entity
    */
 
-  public void setValues(Map theStringValues) {
-    /** @todo should be synchronized */
-    if (theStringValues != null) {
-      theValuesHash = new HashMap();
-      theValuesHash.putAll(theStringValues);
+  public void setValues(Map aMap) {
+    if (aMap!=null) {
+      Iterator i = aMap.entrySet().iterator();
+      synchronized(this) {
+        while (i.hasNext()) {
+          Map.Entry entry = (Map.Entry) i.next();
+
+          setValueForProperty( (String) entry.getKey(), (String) entry.getValue());
+        }
+      }
     }
-    else
-      logger.warn("Entity.setValues called with null Map");
   }
 
   /**
@@ -122,7 +127,7 @@ public class Entity implements TemplateHashModel, TemplateModelRoot
    * @param id
    */
   public void setId(String id) {
-    theValuesHash.put(theStorageObject.getIdName(), id);
+    setValueForProperty(theStorageObject.getIdName(), id);
   }
 
   /**
@@ -132,26 +137,15 @@ public class Entity implements TemplateHashModel, TemplateModelRoot
    */
   public String getValue(String field) {
     String returnValue = null;
+
     if (field != null) {
-      if (field.equals("webdb_create_formatted")) {
-        if (hasValueForField("webdb_create"))
-          returnValue = StringUtil.dateToReadableDate(getValue("webdb_create"));
-      }
-      else if (field.equals("webdb_lastchange_formatted")) {
-        if (hasValueForField("webdb_lastchange"))
-          returnValue = StringUtil.dateToReadableDate(getValue(
-              "webdb_lastchange"));
-      }
-      else
-        returnValue = (String) theValuesHash.get(field);
+      returnValue = (String) values.get(field);
     }
     return returnValue;
   }
 
   public boolean hasValueForField(String field) {
-    if (theValuesHash != null)
-      return theValuesHash.containsKey(field);
-    return false;
+    return values.containsKey(field);
   }
 
   /**
@@ -161,6 +155,7 @@ public class Entity implements TemplateHashModel, TemplateModelRoot
    */
   public String insert() throws StorageObjectExc {
     logger.debug("Entity: trying to insert ...");
+
     if (theStorageObject != null) {
       return theStorageObject.insert(this);
     }
@@ -183,12 +178,19 @@ public class Entity implements TemplateHashModel, TemplateModelRoot
    * @param theValue The new value of the field
    * @exception StorageObjectException
    */
-  public void setValueForProperty(String theProp, String theValue) throws
-      StorageObjectFailure {
-    if (isField(theProp))
-      theValuesHash.put(theProp, theValue);
-    else {
-      logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")");
+  public void setValueForProperty(String theProp, String theValue) throws StorageObjectFailure {
+    try {
+      if (isField(theProp))
+        values.put(theProp, theValue);
+      else {
+        logger.warn("Entity.setValueForProperty: Property not found: " + theProp + " (" + theValue + ")");
+      }
+    }
+    catch (Throwable t) {
+      logger.error("Entity.setValueForProperty: " + t.toString());
+      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));
+
+      throw new StorageObjectFailure(t);
     }
   }
 
@@ -251,31 +253,5 @@ public class Entity implements TemplateHashModel, TemplateModelRoot
 
     throw new StorageObjectFailure("Storage Object Exception in entity", e);
   }
-
-  // Now implements freemarkers TemplateHashModel
-  // two methods have to be overridden:
-  // 1. public boolean isEmpty() throws TemplateModelException
-  // 2. public TemplateModel get(java.lang.String key) throws TemplateModelException
-
-  public boolean isEmpty() throws TemplateModelException {
-    return (theValuesHash == null || theValuesHash.isEmpty()) ? true : false;
-  }
-
-  public TemplateModel get(java.lang.String key) throws TemplateModelException {
-    return new SimpleScalar(getValue(key));
-  }
-
-  public void put(java.lang.String key, TemplateModel model) {
-    // putting should only take place via setValue and is limited to the
-    // database fields associated with the entity. no additional freemarker
-    // stuff will be available via Entity.
-    logger.warn("put is called on entity! - the values will be lost!");
-  }
-
-  public void remove(java.lang.String key) {
-    // do we need this?
-  }
-
-  //////////////////////////////////////////////////////////////////////////////////
 }
 
index c2616f1..f792413 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mir.entity;
-
-import java.util.ArrayList;
-import java.util.Set;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.log.LoggerWrapper;
-import mir.storage.StorageObject;
-import mir.storage.store.StorableObject;
-import mir.storage.store.StoreContainerType;
-import mir.storage.store.StoreIdentifier;
-import mir.storage.store.StoreUtil;
-import freemarker.template.TemplateListModel;
-import freemarker.template.TemplateModel;
-
-/**
- *
- * Container class for lists of Entities.
- * Now implements freemarker.template.TemplateListModel
- * and @see mir.storage.store.StorableObject.
- *
- * @author <RK>
- * first version       27.6.1999
- *
- *  @version 1.0 (freemarker compliant & and storable in ObjectStore)
- */
-public class EntityList implements TemplateListModel, StorableObject {
-  protected static MirPropertiesConfiguration configuration;
-  protected LoggerWrapper logger;
-  private ArrayList           theEntityArrayList = new ArrayList();
-  private String              whereClause, orderClause;
-  private StorageObject       theStorage;
-  private int                 count, offset, limit;
-  private int                 offsetnext = -1, offsetprev = -1;
-  private int                 freemarkerListPointer=-1;
-
-
-  static {
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new RuntimeException("Unable to get configuration: " + e.getMessage());
-    }
-  }
-
-  /**
-   * Constructor.
-   */
-  public EntityList(){
-    logger = new LoggerWrapper("Entity.List");
-  }
-
-/* get/set EntityClass of Objects stored in EntityList */
-  public void setStorage(StorageObject storage) { this.theStorage=storage; }
-  public StorageObject getStorage() { return theStorage; }
-
-  public void setLimit(int limit) { this.limit = limit; }
-
-  /**
-   * Sets the WHERE clause that fetched the Entities of this EntityList from the database.
-   * @param wc The string that contains the WHERE clause
-   */
-  public void setWhere(String wc) {
-    this.whereClause = wc;
-  }
-
-  /**
-   * Returns the WHERE clause that returned this EntityList from the database
-   * @return whereClause The WHERE clause
-   */
-  public String getWhere() {
-    return whereClause;
-  }
-
-
-  /**
-   * Sets the sorting criterium of this EntityList
-   * @param oc
-   */
-  public void setOrder(String oc) {
-    this.orderClause = oc;
-  }
-
-  /**
-   * Returns the sorting criterium.
-   * @return orderClause The sort order
-   */
-  public String getOrder() {
-    return orderClause;
-  }
-
-  /**
-   * Sets the number of rows that match the WHERE clause
-   * @param i The number of rows that match the WHERE clause
-   */
-  public void setCount(int i) {
-    this.count = i;
-  }
-
-  /**
-   * Returns the number of rows that match the WHERE clause
-   * @return The number of rows ...
-   */
-  public int getCount() {
-    return count;
-  }
-
-  /**
-   * Sets the offset
-   * @param i The offset
-   */
-  public void setOffset(int i) {
-    offset = i;
-  }
-
-  /**
-   * Returns the offset
-   * @return offset
-   */
-  public int getOffset() {
-    return offset;
-  }
-
-  /**
-   * Sets the offset of the next batch of Entities.
-   * @param i The next offset
-   */
-  public void setNextBatch(int i) {
-    offsetnext = i;
-  }
-
-  /**
-   * Returns the offset of the next batch of Entities.
-   * @return offset of the next batch
-   */
-  public int getNextBatch() {
-    return offsetnext;
-  }
-
-  /**
-   * Returns whether there is a next batch within the WHERE clause
-   * @return true if yes, false if no.
-   */
-  public boolean hasNextBatch() {
-    return (offsetnext >= 0);
-  }
-
-  /**
-   * Sets the offset of the previous batch.
-   * @param i the previous offset
-   */
-  public void setPrevBatch(int i) {
-    offsetprev = i;
-  }
-
-  /**
-   * Returns the offset of the previous batch.
-   * @return offset of the previous batch
-   */
-  public int getPrevBatch() {
-    return offsetprev;
-  }
-
-  /**
-   * Returns whether there is a previous batch.
-   * @return true if yes, false if no
-   */
-  public boolean hasPrevBatch() {
-    return (offsetprev >= 0);
-  }
-
-  /**
-   * Returns the start index of the batch.
-   * @return
-   */
-  public int getFrom() {
-    return offset+1;
-  }
-
-  /**
-   * Returns the end index of the batch.
-   * @return
-   */
-  public int getTo() {
-    if (hasNextBatch())
-      return offsetnext;
-    else
-      return count;
-  }
-
-  /**
-   * Inserts an Entity into the EntityList.
-   * @param anEntity The entity to be inserted.
-   */
-
-  public void add (Entity anEntity) {
-    if (anEntity!=null)
-      theEntityArrayList.add(anEntity);
-    else
-      logger.warn("EntityList: add called with empty Entity");
-  }
-
-
-  /**
-   * @return The number of Entities in the EntityList.
-   */
-
-  public int size() {
-    return theEntityArrayList.size();
-  }
-
-
-  /**
-   * Returns the element at position i in the EntityList as Entity
-   * @param i the position of the element in question
-   * @return The element at position i.
-   */
-
-  public Entity elementAt(int i) {
-    /** @todo check if i is in list.size() */
-    return (Entity)theEntityArrayList.get(i);
-  }
-
-
-// The following methods have to be implemented
-// for this class to be an implementation of the
-// TemplateListModel of the Freemarker packages
-
-  public TemplateModel get(int i) { return elementAt(i); }
-  public boolean isRewound() { return (freemarkerListPointer==-1) ? true : false; }
-  public void rewind() { freemarkerListPointer=-1; }
-
-  public TemplateModel next() {
-    if (hasNext()) {
-    freemarkerListPointer++;return get(freemarkerListPointer); }
-    else return null;
-  }
-
-
-  /**
-   * Returns whether there is a next element
-   * @return true if there is a next element, else false
-   */
-
-  public boolean hasNext() {
-    return theEntityArrayList.size()>0 && freemarkerListPointer+2<=theEntityArrayList.size();
-  }
-
-
-  /**
-   * Returns whether EntityList is empty or not
-   * @return true in case of empty list, false otherwise
-   */
-
-  public boolean isEmpty() {
-    if (theEntityArrayList!=null)
-      return theEntityArrayList.size()<1 ;
-    else return false;
-  }
-
-
-// Methods to implement StorableObject
-
-  public Set getNotifyOnReleaseSet() { return null; }
-
-  public StoreIdentifier getStoreIdentifier() {
-    if ( theStorage!=null ) {
-      return
-      new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST,
-      StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(),
-      whereClause, orderClause, offset, limit ));
-    }
-    logger.warn("EntityList could not return StoreIdentifier");
-    return null;
-  }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package  mir.entity;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Set;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.StorageObject;\r
+import mir.storage.store.StorableObject;\r
+import mir.storage.store.StoreContainerType;\r
+import mir.storage.store.StoreIdentifier;\r
+import mir.storage.store.StoreUtil;\r
+\r
+/**\r
+ *\r
+ * Container class for lists of Entities.\r
+ * Now implements @see mir.storage.store.StorableObject.\r
+ *\r
+ * @author <RK>\r
+ * first version       27.6.1999\r
+ *\r
+ * @version 1.1 (cleaned up)\r
+ */\r
+public class EntityList implements StorableObject {\r
+  protected static MirPropertiesConfiguration configuration;\r
+  protected LoggerWrapper logger;\r
+  private ArrayList           theEntityArrayList = new ArrayList();\r
+  private String              whereClause, orderClause;\r
+  private StorageObject       theStorage;\r
+  private int                 count, offset, limit;\r
+  private int                 offsetnext = -1, offsetprev = -1;\r
+\r
+  static {\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (PropertiesConfigExc e) {\r
+      throw new RuntimeException("Unable to get configuration: " + e.getMessage());\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Constructor.\r
+   */\r
+  public EntityList(){\r
+    logger = new LoggerWrapper("Entity.List");\r
+  }\r
+\r
+/* get/set EntityClass of Objects stored in EntityList */\r
+  public void setStorage(StorageObject storage) { this.theStorage=storage; }\r
+  public StorageObject getStorage() { return theStorage; }\r
+\r
+  public void setLimit(int limit) { this.limit = limit; }\r
+\r
+  /**\r
+   * Sets the WHERE clause that fetched the Entities of this EntityList from the database.\r
+   * @param wc The string that contains the WHERE clause\r
+   */\r
+  public void setWhere(String wc) {\r
+    this.whereClause = wc;\r
+  }\r
+\r
+  /**\r
+   * Returns the WHERE clause that returned this EntityList from the database\r
+   * @return whereClause The WHERE clause\r
+   */\r
+  public String getWhere() {\r
+    return whereClause;\r
+  }\r
+\r
+\r
+  /**\r
+   * Sets the sorting criterium of this EntityList\r
+   * @param oc\r
+   */\r
+  public void setOrder(String oc) {\r
+    this.orderClause = oc;\r
+  }\r
+\r
+  /**\r
+   * Returns the sorting criterium.\r
+   * @return orderClause The sort order\r
+   */\r
+  public String getOrder() {\r
+    return orderClause;\r
+  }\r
+\r
+  /**\r
+   * Sets the number of rows that match the WHERE clause\r
+   * @param i The number of rows that match the WHERE clause\r
+   */\r
+  public void setCount(int i) {\r
+    this.count = i;\r
+  }\r
+\r
+  /**\r
+   * Returns the number of rows that match the WHERE clause\r
+   * @return The number of rows ...\r
+   */\r
+  public int getCount() {\r
+    return count;\r
+  }\r
+\r
+  /**\r
+   * Sets the offset\r
+   * @param i The offset\r
+   */\r
+  public void setOffset(int i) {\r
+    offset = i;\r
+  }\r
+\r
+  /**\r
+   * Returns the offset\r
+   * @return offset\r
+   */\r
+  public int getOffset() {\r
+    return offset;\r
+  }\r
+\r
+  /**\r
+   * Sets the offset of the next batch of Entities.\r
+   * @param i The next offset\r
+   */\r
+  public void setNextBatch(int i) {\r
+    offsetnext = i;\r
+  }\r
+\r
+  /**\r
+   * Returns the offset of the next batch of Entities.\r
+   * @return offset of the next batch\r
+   */\r
+  public int getNextBatch() {\r
+    return offsetnext;\r
+  }\r
+\r
+  /**\r
+   * Returns whether there is a next batch within the WHERE clause\r
+   * @return true if yes, false if no.\r
+   */\r
+  public boolean hasNextBatch() {\r
+    return (offsetnext >= 0);\r
+  }\r
+\r
+  /**\r
+   * Sets the offset of the previous batch.\r
+   * @param i the previous offset\r
+   */\r
+  public void setPrevBatch(int i) {\r
+    offsetprev = i;\r
+  }\r
+\r
+  /**\r
+   * Returns the offset of the previous batch.\r
+   * @return offset of the previous batch\r
+   */\r
+  public int getPrevBatch() {\r
+    return offsetprev;\r
+  }\r
+\r
+  /**\r
+   * Returns whether there is a previous batch.\r
+   * @return true if yes, false if no\r
+   */\r
+  public boolean hasPrevBatch() {\r
+    return (offsetprev >= 0);\r
+  }\r
+\r
+  /**\r
+   * Returns the start index of the batch.\r
+   * @return\r
+   */\r
+  public int getFrom() {\r
+    return offset+1;\r
+  }\r
+\r
+  /**\r
+   * Returns the end index of the batch.\r
+   * @return\r
+   */\r
+  public int getTo() {\r
+    if (hasNextBatch())\r
+      return offsetnext;\r
+    else\r
+      return count;\r
+  }\r
+\r
+  /**\r
+   * Inserts an Entity into the EntityList.\r
+   * @param anEntity The entity to be inserted.\r
+   */\r
+\r
+  public void add (Entity anEntity) {\r
+    if (anEntity!=null)\r
+      theEntityArrayList.add(anEntity);\r
+    else\r
+      logger.warn("EntityList: add called with empty Entity");\r
+  }\r
+\r
+\r
+  /**\r
+   * @return The number of Entities in the EntityList.\r
+   */\r
+\r
+  public int size() {\r
+    return theEntityArrayList.size();\r
+  }\r
+\r
+\r
+  /**\r
+   * Returns the element at position i in the EntityList as Entity\r
+   * @param i the position of the element in question\r
+   * @return The element at position i.\r
+   */\r
+\r
+  public Entity elementAt(int i) {\r
+    /** @todo check if i is in list.size() */\r
+    return (Entity)theEntityArrayList.get(i);\r
+  }\r
+\r
+\r
+\r
+// Methods to implement StorableObject\r
+\r
+  public Set getNotifyOnReleaseSet() { return null; }\r
+\r
+  public StoreIdentifier getStoreIdentifier() {\r
+    if ( theStorage!=null ) {\r
+      return\r
+      new StoreIdentifier( this, StoreContainerType.STOC_TYPE_ENTITYLIST,\r
+      StoreUtil.getEntityListUniqueIdentifierFor( theStorage.getTableName(),\r
+      whereClause, orderClause, offset, limit ));\r
+    }\r
+    logger.warn("EntityList could not return StoreIdentifier");\r
+    return null;\r
+  }\r
+\r
+}\r
diff --git a/source/mir/entity/EntityRelation.java b/source/mir/entity/EntityRelation.java
deleted file mode 100755 (executable)
index 5713a85..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.entity;
-
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
-
-public class EntityRelation {
-
-  public String         fromId;
-  public String         toId;
-  public StorageObject  storage;
-  public int            type;
-
-  public final static int TO_ONE    =  1;
-  public final static int TO_MANY   =  2;
-
-
-  /**
-   *  Kontruktor fuer EntityRelation
-   *  @param fromId ist der Feldname in der ausgehenden Tabelle fuer die Relation
-   *  @param toId ist der Feldname in der Zieltablle
-   *  @param storage ist das StorageObject, ueber das der Zugriff auf die abhaengige
-   *         Tabelle erfolgt.
-   *  @param type ist der Typ der EntityRelation (TO_ONE oder TO_MANY)
-   */
-
-  public EntityRelation(String fromId, String toId, StorageObject storage, int type) {
-      this.fromId = fromId;
-      this.toId = toId;
-      this.storage = storage;
-      this.type = type;
-  }
-
-  /**
-   *   @return Liefert eine abhaengige Entity mit den verknuepften
-   *           Entities, wenn es sich um eine TO_ONE Beziehung handelt, ansonsten
-   *           null.
-   */
-
-  public Entity getOne(Entity entity) throws StorageObjectExc {
-    if (type==TO_ONE) {
-      return storage.selectById(entity.getValue(fromId));
-    }
-    else return null;
-  }
-
-  /**
-   *   @return Liefert eine freemarker.template.SimpleList mit den verknuepften
-   *           Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
-   *           null.
-   */
-
-  public EntityList getMany(Entity entity) throws StorageObjectFailure{
-    if (type==TO_MANY) {
-      return storage.selectByFieldValue(toId, entity.getValue(fromId));
-    }
-    else return null;
-  }
-
-  /**
-   *   @return Liefert eine freemarker.template.SimpleList mit den verknuepften
-   *           Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
-   *           null.
-   */
-
-  public EntityList getMany(Entity entity, String order) throws StorageObjectFailure{
-    if (type==TO_MANY) {
-      return storage.selectByWhereClause(toId+"="+entity.getValue(fromId), order,-1);
-    }
-    else return null;
-  }
-
-  /**
-   *   @return Liefert eine freemarker.template.SimpleList mit den verknuepften
-   *           Entities, wenn es sich um eine TO_MANY Liste handelt, ansonsten
-   *           null.
-   */
-
-  public EntityList getMany(Entity entity, String order, String whereClause) throws StorageObjectFailure{
-    if (type==TO_MANY) {
-      return storage.selectByWhereClause(toId + "=" + entity.getValue(fromId) + " and " + whereClause, order,-1);
-    }
-    else return null;
-  }
-
-  /**
-   *   @return The reference name of the related table.
-   */
-
-  public String getName() {
-    return "to" + storage.getTableName();
-  }
-
-
-}
index 8162bb9..68cdf2f 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.entity.adapter;
 
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.util.DateToMapAdapter;
+import java.util.Calendar;\r
+import java.util.Date;\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Map;\r
+import java.util.TimeZone;\r
+\r
+import mir.entity.Entity;\r
+import mir.misc.StringUtil;\r
+import mir.util.GeneratorFormatAdapters;
 
 public class EntityAdapterDefinition {
-  Map calculatedFields;
+  private Map calculatedFields;
 
   public EntityAdapterDefinition() {
     calculatedFields = new HashMap();
@@ -61,12 +63,12 @@ public class EntityAdapterDefinition {
     calculatedFields.put(aFieldName, aField);
   }
 
-  public void addMirDateField(String aDestinationFieldName, String aSourceFieldName) {
-    addCalculatedField(aDestinationFieldName, new MirDateField(aSourceFieldName));
+  public void addMirDateField(String aDestinationFieldName, String aSourceFieldName, String aDefaultTimezone) {
+    addCalculatedField(aDestinationFieldName, new MirDateField(aSourceFieldName, aDefaultTimezone));
   }
 
-  public void addDBDateField(String aDestinationFieldName, String aSourceFieldName) {
-    addCalculatedField(aDestinationFieldName, new DBDateField(aSourceFieldName));
+  public void addDBDateField(String aDestinationFieldName, String aSourceFieldName, String aDefaultTimezone) {
+    addCalculatedField(aDestinationFieldName, new DBDateField(aSourceFieldName, aDefaultTimezone));
   }
 
   public interface CalculatedField {
@@ -75,80 +77,62 @@ public class EntityAdapterDefinition {
 
   private class MirDateField implements CalculatedField {
     private String fieldName;
+    private String defaultTimezone;
 
-    public MirDateField(String aFieldName) {
+    public MirDateField(String aFieldName, String aDefaultTimezone) {
       fieldName = aFieldName;
+      defaultTimezone = aDefaultTimezone;
     }
 
     public Object getValue(EntityAdapter anEntityAdapter) {
 
-      Map result = new HashMap();
-      String textValue = anEntityAdapter.getEntity().getValue(fieldName);
-      Calendar calendar = GregorianCalendar.getInstance();
-      int year;
-      int month;
-      int day;
-      Date date;
-
-      if (textValue!=null) {
-        try {
-          year = Integer.parseInt(textValue.substring(0,4));
-          month = Integer.parseInt(textValue.substring(4,6));
-          day = Integer.parseInt(textValue.substring(6,8));
-
-          calendar.set(year, month-1, day);
-          date = calendar.getTime();
-          ;
-
-          result.put("date", date);
-          result.put("formatted", new DateToMapAdapter(date));
-
-        }
-        catch (Throwable t) {
-          result=null;
-        }
-      }
-      return result;
-    }
+         Object result = null;
+         String textValue = anEntityAdapter.getEntity().getValue(fieldName);
+         Calendar calendar = GregorianCalendar.getInstance();
+         int year;
+         int month;
+         int day;
+         Date date;
+
+         if (textValue!=null) {
+           try {
+             year = Integer.parseInt(textValue.substring(0,4));
+             month = Integer.parseInt(textValue.substring(4,6));
+             day = Integer.parseInt(textValue.substring(6,8));
+
+             calendar.setTimeZone(TimeZone.getTimeZone(defaultTimezone));
+             calendar.set(year, month-1, day);
+
+             date = calendar.getTime();
+
+             result = new GeneratorFormatAdapters.DateFormatAdapter(date, defaultTimezone);
+           }
+           catch (Throwable t) {
+             result=null;
+           }
+         }
+         return result;
+       }
   }
 
   private class DBDateField implements CalculatedField {
     private String fieldName;
+    private String defaultTimezone;
 
-    public DBDateField(String aFieldName) {
+    public DBDateField(String aFieldName, String aDefaultTimezone) {
       fieldName = aFieldName;
+      defaultTimezone = aDefaultTimezone;
     }
 
     public Object getValue(EntityAdapter anEntityAdapter) {
+      Object result = null;
+      String text = anEntityAdapter.getEntity().getValue(fieldName);
 
-      Map result = new HashMap();
-      String textValue = anEntityAdapter.getEntity().getValue(fieldName);
-      Calendar calendar = GregorianCalendar.getInstance();
-      int year;
-      int month;
-      int day;
-      int hours;
-      int minutes;
-
-      Date date;
-
-      if (textValue!=null) {
+      if (text!=null) {
         try {
-          year = Integer.parseInt(textValue.substring(0,4));
-          month = Integer.parseInt(textValue.substring(5,7));
-          day = Integer.parseInt(textValue.substring(8,10));
-          hours = Integer.parseInt(textValue.substring(11,13));
-          minutes = Integer.parseInt(textValue.substring(14,16));
-
-          calendar.set(year, month-1, day, hours, minutes);
-          date = calendar.getTime();
-
-          result.put("date", date);
-          result.put("formatted", new DateToMapAdapter(date));
-          result.put("raw", textValue);
+          result = new GeneratorFormatAdapters.DateFormatAdapter(StringUtil.convertMirInternalDateToDate(text), defaultTimezone);
         }
         catch (Throwable t) {
-          result=null;
         }
       }
 
diff --git a/source/mir/entity/adapter/EntityAdapterEngine.java b/source/mir/entity/adapter/EntityAdapterEngine.java
new file mode 100755 (executable)
index 0000000..4237c27
--- /dev/null
@@ -0,0 +1,71 @@
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mir.entity.adapter;\r
+\r
+import java.util.List;\r
+\r
+import mir.entity.EntityBrowser;\r
+import mir.storage.*;\r
+\r
+/**\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class EntityAdapterEngine {\r
+  private EntityAdapterEngine() {\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aStorage\r
+   * @param aDefinition\r
+   * @param aQualifier\r
+   * @param anOrder\r
+   * @param aLimit\r
+   * @param anOffset\r
+   * @return\r
+   */\r
+  static public List retrieveAdapterList(EntityAdapterModel aModel, String aDefinition, String aQualifier, String anOrder, int aLimit, int anOffset) {\r
+    try {\r
+      EntityBrowser browser = new EntityBrowser(aModel.getMappingForName(aDefinition).getStorage(), aQualifier, anOrder, 30, aLimit, anOffset);\r
+\r
+      return new EntityListAdapter(aModel, aDefinition, browser, aLimit);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new StorageObjectFailure(t);\r
+    }\r
+  }\r
+}
\ No newline at end of file
diff --git a/source/mir/entity/adapter/EntityAdapterFailure.java b/source/mir/entity/adapter/EntityAdapterFailure.java
new file mode 100755 (executable)
index 0000000..8620a93
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.entity.adapter;
+
+import multex.Failure;
+
+public class EntityAdapterFailure extends Failure {
+  public EntityAdapterFailure(String msg,Throwable cause) {
+    super(msg,cause);
+  }
+
+  public EntityAdapterFailure(Throwable aCause) {
+    this (aCause.getMessage(), aCause);
+  }
+}
\ No newline at end of file
index 0c29089..0d4ea50 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.entity.adapter;
@@ -48,9 +48,23 @@ public class EntityAdapterModel {
     return mapping.getDefinition().makeEntityAdapter( anEntity, this );
   }
 
+  public EntityAdapter createNewEntity( String aName ) throws EntityAdapterExc {
+    try {
+      Mapping mapping = getMappingForName(aName);
+      StorageObject storage = mapping.storage;
+      Entity entity = (Entity) storage.getEntityClass().newInstance();
+      entity.setStorage(storage);
+
+      return mapping.getDefinition().makeEntityAdapter(entity, this);
+    }
+    catch (Throwable t) {
+      throw new EntityAdapterFailure(t);
+    }
+  }
+
   public void addMapping( String aName, StorageObject aStorage, EntityAdapterDefinition aDefinition ) {
     entityAdapterMappings.put( aName, new Mapping( aStorage, aDefinition ) );
-    }
+  }
 
   public Mapping getMappingForName( String aName ) throws EntityAdapterExc {
     if (!entityAdapterMappings.containsKey(aName))
index 5bf6ae4..f7ae65d 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.entity.adapter;
-
-import java.util.AbstractList;
-import java.util.List;
-import java.util.Vector;
-
-import mir.entity.EntityBrowser;
-
-public class EntityListAdapter extends AbstractList {
-  private int skip;
-  private int maximumLength;
-  private EntityBrowser browser;
-  private boolean exhausted = false;
-  private boolean skipped = false;
-
-  private List cache;
-
-  protected EntityListAdapter(EntityBrowser aBrowser, int aSkip, int aMaximumLength) {
-    browser = aBrowser;
-    skip = aSkip;
-    maximumLength = aMaximumLength;
-    cache = new Vector();
-  }
-
-  protected EntityListAdapter(EntityBrowser aBrowser, int aMaximumLength) {
-    this(aBrowser, 0, aMaximumLength);
-  }
-
-  protected EntityListAdapter(EntityBrowser aBrowser) {
-    this(aBrowser, 0, -1);
-  }
-
-  private void skip() {
-    int i;
-
-    try {
-      if (!skipped) {
-        for(i=0; i<skip; i++)
-          if (browser.hasNext())
-            browser.next();
-      }
-      skipped=true;
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.getMessage());
-    }
-  }
-
-  private void fetchNext() {
-    try {
-      if (!exhausted) {
-        if (browser.hasNext())
-          cache.add(browser.next());
-
-        exhausted = !browser.hasNext() || (maximumLength>0 && cache.size()>=maximumLength) ;
-      }
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.getMessage());
-    }
-
-  }
-
-  private void exhaust() {
-    skip();
-
-    while (!exhausted)
-      fetchNext();
-  }
-
-  private void fetchUntil(int anIndex) {
-    skip();
-
-    while (!exhausted && anIndex>=cache.size())
-      fetchNext();
-  }
-
-  public int size() {
-    exhaust();
-
-    return cache.size();
-  }
-
-  public Object get(int anIndex) {
-    fetchUntil(anIndex);
-    return cache.get(anIndex);
-  }
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.entity.adapter;\r
+\r
+import java.util.AbstractList;\r
+import java.util.List;\r
+import java.util.Vector;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityBrowser;\r
+\r
+public class EntityListAdapter extends AbstractList {\r
+  private int skip;\r
+  private int maximumLength;\r
+  private EntityBrowser browser;\r
+  private EntityAdapterModel model;\r
+  private String definition;\r
+  private boolean exhausted = false;\r
+  private boolean skipped = false;\r
+\r
+  private List cache;\r
+\r
+  protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aSkip, int aMaximumLength) {\r
+    model = aModel;\r
+    definition = aDefinition;\r
+    browser = aBrowser;\r
+    skip = aSkip;\r
+    maximumLength = aMaximumLength;\r
+    cache = new Vector();\r
+  }\r
+\r
+  protected EntityListAdapter(EntityAdapterModel aModel, String aDefinition, EntityBrowser aBrowser, int aMaximumLength) {\r
+    this(aModel, aDefinition, aBrowser, 0, aMaximumLength);\r
+  }\r
+\r
+  protected EntityListAdapter(EntityAdapterModel aModel, String  aDefinition, EntityBrowser aBrowser) {\r
+    this(aModel, aDefinition, aBrowser, 0, -1);\r
+  }\r
+\r
+  private void skip() {\r
+    int i;\r
+\r
+    try {\r
+      if (!skipped) {\r
+        for(i=0; i<skip; i++)\r
+          if (browser.hasNext())\r
+            browser.next();\r
+      }\r
+      skipped=true;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.getMessage());\r
+    }\r
+  }\r
+\r
+  private void fetchNext() {\r
+    try {\r
+      if (!exhausted) {\r
+        if (browser.hasNext())\r
+          cache.add(model.makeEntityAdapter(definition, (Entity) browser.next()));\r
+\r
+        exhausted = !browser.hasNext() || (maximumLength>0 && cache.size()>=maximumLength) ;\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.getMessage());\r
+    }\r
+\r
+  }\r
+\r
+  private void exhaust() {\r
+    skip();\r
+\r
+    while (!exhausted)\r
+      fetchNext();\r
+  }\r
+\r
+  private void fetchUntil(int anIndex) {\r
+    skip();\r
+\r
+    while (!exhausted && anIndex>=cache.size())\r
+      fetchNext();\r
+  }\r
+\r
+  public int size() {\r
+    exhaust();\r
+\r
+    return cache.size();\r
+  }\r
+\r
+  public Object get(int anIndex) {\r
+    fetchUntil(anIndex);\r
+    return cache.get(anIndex);\r
+  }\r
 }
\ No newline at end of file
index 97ee1e3..8b5ec61 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.generator;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import mir.log.LoggerWrapper;
-import mir.util.RewindableIterator;
-
-import org.apache.commons.beanutils.*;
-
-import freemarker.template.FileTemplateCache;
-import freemarker.template.SimpleScalar;
-import freemarker.template.Template;
-import freemarker.template.TemplateHashModel;
-import freemarker.template.TemplateListModel;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-import freemarker.template.TemplateModelRoot;
-import freemarker.template.TemplateScalarModel;
-
-
-public class FreemarkerGenerator implements Generator {
-  private Template template;
-
-  public FreemarkerGenerator(Template aTemplate) {
-    template = aTemplate;
-  }
-
-  public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure {
-    if (!(anOutputWriter instanceof PrintWriter))
-      throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter");
-
-    try {
-      template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter);
-    }
-    catch (Throwable t) {
-      t.printStackTrace();
-      aLogger.error("Exception occurred: "+t.getMessage());
-      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      throw new GeneratorFailure( t );
-    }
-  }
-
-  private static TemplateScalarModel makeStringAdapter(String aString) {
-    return new SimpleScalar(aString);
-  }
-
-  private static TemplateHashModel makeMapAdapter(Map aMap)  {
-    return new MapAdapter(aMap);
-  }
-
-  private static TemplateListModel makeIteratorAdapter(Iterator anIterator) {
-    return new IteratorAdapter(anIterator);
-  }
-
-  private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) {
-    return new FunctionAdapter(aFunction);
-  }
-
-  private static TemplateHashModel makeBeanAdapter(Object anObject)  {
-    return new BeanAdapter(anObject);
-  }
-
-  public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {
-    if (anObject == null)
-      return null;
-
-    if (anObject instanceof TemplateModel)
-      return (TemplateModel) anObject;
-    else if (anObject instanceof Generator.GeneratorFunction)
-      return makeFunctionAdapter((Generator.GeneratorFunction) anObject);
-    else if (anObject instanceof Integer)
-      return makeStringAdapter(((Integer) anObject).toString());
-    else if (anObject instanceof Boolean) {
-      if (((Boolean) anObject).booleanValue())
-        return makeStringAdapter("1");
-      else
-        return makeStringAdapter("0");
-    }
-    else if (anObject instanceof String)
-      return makeStringAdapter((String) anObject);
-    else if (anObject instanceof Map)
-      return makeMapAdapter((Map) anObject);
-    else if (anObject instanceof Iterator)
-      return makeIteratorAdapter((Iterator) anObject);
-    else if (anObject instanceof List)
-      return makeIteratorAdapter(((List) anObject).iterator());
-    else
-      return makeBeanAdapter(anObject);
-//      throw new TemplateModelException("Unadaptable class: " + anObject.getClass().getName());
-  }
-
-  private static class MapAdapter implements TemplateModelRoot {
-    private Map map;
-    private Map valuesCache;
-
-    private MapAdapter(Map aMap) {
-      map = aMap;
-      valuesCache = new HashMap();
-    }
-
-    public void put(String aKey, TemplateModel aModel) {
-      valuesCache.put(aKey, aModel);
-    }
-
-    public void remove(String aKey) {
-      // ML: kinda tricky...
-    }
-
-    public boolean isEmpty() {
-      return map.isEmpty();
-    }
-
-    public TemplateModel get(String aKey) throws TemplateModelException {
-      try {
-        if (!valuesCache.containsKey(aKey)) {
-          Object value = map.get(aKey);
-
-          if (value == null && !map.containsKey(aKey)) {
-            throw new TemplateModelException("MapAdapter: no key "+aKey+" available");
-          }
-
-          valuesCache.put(aKey, makeAdapter(value));
-        }
-
-        return (TemplateModel) valuesCache.get(aKey);
-      }
-      catch (TemplateModelException e) {
-        throw e;
-      }
-      catch (Throwable t) {
-        throw new TemplateModelException(t.getMessage());
-      }
-    }
-  }
-
-  private static class IteratorAdapter implements TemplateListModel {
-    private Iterator iterator;
-    private List valuesCache;
-    private int position;
-
-    private IteratorAdapter(Iterator anIterator) {
-      iterator = anIterator;
-
-      valuesCache = new Vector();
-      position=0;
-
-
-      if (iterator instanceof RewindableIterator) {
-        ((RewindableIterator) iterator).rewind();
-      }
-    }
-
-    public boolean isEmpty() {
-      return valuesCache.isEmpty() && !iterator.hasNext();
-    }
-
-    private void getUntil(int anIndex) throws TemplateModelException {
-      while (valuesCache.size()<=anIndex && iterator.hasNext())
-      {
-        valuesCache.add(makeAdapter(iterator.next()));
-      }
-    };
-
-    public TemplateModel get(int anIndex) throws TemplateModelException {
-      TemplateModel result;
-
-      getUntil(anIndex);
-
-      if (anIndex<valuesCache.size())
-      {
-        result = (TemplateModel) valuesCache.get(anIndex);
-
-        return result;
-      }
-      else
-        throw new TemplateModelException( "Iterator out of bounds" );
-    }
-
-    public boolean hasNext() {
-      return position<valuesCache.size() || iterator.hasNext();
-    }
-
-    public boolean isRewound() {
-      return position==0;
-    }
-
-    public TemplateModel next() throws TemplateModelException {
-      TemplateModel result;
-
-      if (hasNext()) {
-        result = get(position);
-        position++;
-      }
-      else
-        throw new TemplateModelException( "Iterator out of bounds" );
-
-      return result;
-    }
-
-    public void rewind() {
-      position=0;
-    }
-  }
-
-  private static class ListAdapter implements TemplateListModel {
-    List list;
-    List valuesCache;
-    int position;
-
-    private ListAdapter(List aList) {
-      list = aList;
-      valuesCache = new Vector();
-      position=0;
-    }
-
-    public boolean isEmpty() {
-      return list.isEmpty();
-    }
-
-    public TemplateModel get(int i) throws TemplateModelException {
-
-      if (i>=valuesCache.size() && i<list.size()) {
-        for(int j=valuesCache.size(); j<=i; j++) {
-          valuesCache.add(makeAdapter(list.get(j)));
-        }
-      }
-
-      if (i<valuesCache.size())
-        return (TemplateModel) valuesCache.get(i);
-      else
-        throw new TemplateModelException( "Iterator out of bounds" );
-    }
-
-    public boolean hasNext() {
-      return position<list.size();
-    }
-
-    public boolean isRewound() {
-      return position==0;
-    }
-
-    public TemplateModel next() throws TemplateModelException {
-      TemplateModel result;
-
-      if (hasNext()) {
-        result = get(position);
-        position++;
-      }
-      else {
-        throw new TemplateModelException( "Iterator out of bounds" );
-      }
-
-      return result;
-    }
-
-    public void rewind() {
-      position = 0;
-    }
-  }
-
-  private static class FunctionAdapter implements TemplateMethodModel {
-    private Generator.GeneratorFunction function;
-
-    public FunctionAdapter(Generator.GeneratorFunction aFunction) {
-      function = aFunction;
-    }
-
-    public TemplateModel exec(List anArguments) throws TemplateModelException {
-      try {
-        return makeAdapter(function.perform(anArguments));
-      }
-      catch (Throwable t) {
-        throw new TemplateModelException(t.getMessage());
-      }
-    }
-
-    public boolean isEmpty() {
-      return false;
-    }
-
-  }
-
-  private static class BeanAdapter implements TemplateHashModel {
-    private Object object;
-
-    public BeanAdapter(Object anObject) {
-      object = anObject;
-    }
-
-    public void put(String aKey, TemplateModel aModel)  throws TemplateModelException  {
-      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.put not supported");
-    }
-
-    public void remove(String aKey) throws TemplateModelException  {
-      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.remove not supported");
-    }
-
-    public boolean isEmpty() {
-      return false;
-    }
-
-    public TemplateModel get(String aKey) throws TemplateModelException {
-      try {
-        if (PropertyUtils.isReadable(object, aKey))
-          return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey));
-        else
-          return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey));
-      }
-      catch (Throwable t) {
-        throw new TemplateModelException(t.getMessage());
-      }
-    }
-  }
-
-  public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {
-    private FileTemplateCache templateCache;
-
-    public FreemarkerGeneratorLibrary(String aTemplateRoot) {
-      templateCache = new FileTemplateCache( aTemplateRoot+"/" );
-      templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);
-    }
-
-    public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {
-      Template template = (Template) templateCache.getItem(anIdentifier, "template");
-
-      if (template==null) {
-        throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier);
-      }
-
-      return new FreemarkerGenerator(template);
-    }
-  }
-
-  public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory {
-    private String basePath;
-
-    public FreemarkerGeneratorLibraryFactory(String aBasePath) {
-      basePath = aBasePath;
-    }
-
-    public GeneratorLibrary makeLibrary(String anInitializationString) {
-      return new FreemarkerGeneratorLibrary(basePath+anInitializationString);
-    };
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.generator;\r
+\r
+import java.io.PrintWriter;\r
+import java.util.Date;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import org.apache.commons.beanutils.MethodUtils;\r
+import org.apache.commons.beanutils.PropertyUtils;\r
+import freemarker.template.FileTemplateCache;\r
+import freemarker.template.SimpleScalar;\r
+import freemarker.template.Template;\r
+import freemarker.template.TemplateHashModel;\r
+import freemarker.template.TemplateListModel;\r
+import freemarker.template.TemplateMethodModel;\r
+import freemarker.template.TemplateModel;\r
+import freemarker.template.TemplateModelException;\r
+import freemarker.template.TemplateModelRoot;\r
+import freemarker.template.TemplateScalarModel;\r
+import mir.log.LoggerWrapper;\r
+import mir.util.GeneratorFormatAdapters;\r
+import mir.util.RewindableIterator;\r
+\r
+\r
+public class FreemarkerGenerator implements Generator {\r
+  private Template template;\r
+\r
+  public FreemarkerGenerator(Template aTemplate) {\r
+    template = aTemplate;\r
+  }\r
+\r
+  public void generate(Object anOutputWriter, Map aValues, LoggerWrapper aLogger) throws GeneratorExc, GeneratorFailure {\r
+    if (!(anOutputWriter instanceof PrintWriter))\r
+      throw new GeneratorExc("Writer for a FreemarkerGenerator must be a PrintWriter");\r
+\r
+    try {\r
+      template.process((TemplateModelRoot) makeMapAdapter(aValues), (PrintWriter) anOutputWriter);\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace();\r
+      aLogger.error("Exception occurred: "+t.getMessage());\r
+      t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
+      throw new GeneratorFailure( t );\r
+    }\r
+  }\r
+\r
+  private static TemplateScalarModel makeStringAdapter(String aString) {\r
+    return new SimpleScalar(aString);\r
+  }\r
+\r
+  private static TemplateHashModel makeMapAdapter(Map aMap)  {\r
+    return new MapAdapter(aMap);\r
+  }\r
+\r
+  private static TemplateListModel makeIteratorAdapter(Iterator anIterator) {\r
+    return new IteratorAdapter(anIterator);\r
+  }\r
+\r
+  private static TemplateMethodModel makeFunctionAdapter(Generator.GeneratorFunction aFunction) {\r
+    return new FunctionAdapter(aFunction);\r
+  }\r
+\r
+  private static TemplateHashModel makeBeanAdapter(Object anObject)  {\r
+    return new BeanAdapter(anObject);\r
+  }\r
+\r
+  public static TemplateModel makeAdapter(Object anObject) throws TemplateModelException {\r
+    if (anObject == null)\r
+      return null;\r
+\r
+    if (anObject instanceof TemplateModel)\r
+      return (TemplateModel) anObject;\r
+    else if (anObject instanceof Generator.GeneratorFunction)\r
+      return makeFunctionAdapter((Generator.GeneratorFunction) anObject);\r
+    else if (anObject instanceof Integer)\r
+      return makeStringAdapter(((Integer) anObject).toString());\r
+    else if (anObject instanceof Boolean) {\r
+      if (((Boolean) anObject).booleanValue())\r
+        return makeStringAdapter("1");\r
+      else\r
+        return makeStringAdapter("0");\r
+    }\r
+    else if (anObject instanceof String)\r
+      return makeStringAdapter((String) anObject);\r
+    else if (anObject instanceof Map)\r
+      return makeMapAdapter((Map) anObject);\r
+    else if (anObject instanceof Iterator)\r
+      return makeIteratorAdapter((Iterator) anObject);\r
+    else if (anObject instanceof List)\r
+      return makeIteratorAdapter(((List) anObject).iterator());\r
+    else if (anObject instanceof Number)\r
+      return makeAdapter(new GeneratorFormatAdapters.NumberFormatAdapter((Number) anObject));\r
+    else if (anObject instanceof Date)\r
+      return makeAdapter(new GeneratorFormatAdapters.DateFormatAdapter((Date) anObject));\r
+    else\r
+      return makeBeanAdapter(anObject);\r
+  }\r
+\r
+  private static class MapAdapter implements TemplateModelRoot {\r
+    private Map map;\r
+    private Map valuesCache;\r
+\r
+    private MapAdapter(Map aMap) {\r
+      map = aMap;\r
+      valuesCache = new HashMap();\r
+    }\r
+\r
+    public void put(String aKey, TemplateModel aModel) {\r
+      valuesCache.put(aKey, aModel);\r
+    }\r
+\r
+    public void remove(String aKey) {\r
+    }\r
+\r
+    public boolean isEmpty() {\r
+      return map.isEmpty();\r
+    }\r
+\r
+    public TemplateModel get(String aKey) throws TemplateModelException {\r
+      try {\r
+        if (!valuesCache.containsKey(aKey)) {\r
+          Object value = map.get(aKey);\r
+\r
+          if (value == null && !map.containsKey(aKey)) {\r
+            throw new TemplateModelException("MapAdapter: no key "+aKey+" available");\r
+          }\r
+\r
+          valuesCache.put(aKey, makeAdapter(value));\r
+        }\r
+\r
+        return (TemplateModel) valuesCache.get(aKey);\r
+      }\r
+      catch (TemplateModelException e) {\r
+        throw e;\r
+      }\r
+      catch (Throwable t) {\r
+        throw new TemplateModelException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  private static class IteratorAdapter implements TemplateListModel {\r
+    private Iterator iterator;\r
+    private List valuesCache;\r
+    private int position;\r
+\r
+    private IteratorAdapter(Iterator anIterator) {\r
+      iterator = anIterator;\r
+\r
+      valuesCache = new Vector();\r
+      position=0;\r
+\r
+\r
+      if (iterator instanceof RewindableIterator) {\r
+        ((RewindableIterator) iterator).rewind();\r
+      }\r
+    }\r
+\r
+    public boolean isEmpty() {\r
+      return valuesCache.isEmpty() && !iterator.hasNext();\r
+    }\r
+\r
+    private void getUntil(int anIndex) throws TemplateModelException {\r
+      while (valuesCache.size()<=anIndex && iterator.hasNext())\r
+      {\r
+        valuesCache.add(makeAdapter(iterator.next()));\r
+      }\r
+    };\r
+\r
+    public TemplateModel get(int anIndex) throws TemplateModelException {\r
+      TemplateModel result;\r
+\r
+      getUntil(anIndex);\r
+\r
+      if (anIndex<valuesCache.size())\r
+      {\r
+        result = (TemplateModel) valuesCache.get(anIndex);\r
+\r
+        return result;\r
+      }\r
+      else\r
+        throw new TemplateModelException( "Iterator out of bounds" );\r
+    }\r
+\r
+    public boolean hasNext() {\r
+      return position<valuesCache.size() || iterator.hasNext();\r
+    }\r
+\r
+    public boolean isRewound() {\r
+      return position==0;\r
+    }\r
+\r
+    public TemplateModel next() throws TemplateModelException {\r
+      TemplateModel result;\r
+\r
+      if (hasNext()) {\r
+        result = get(position);\r
+        position++;\r
+      }\r
+      else\r
+        throw new TemplateModelException( "Iterator out of bounds" );\r
+\r
+      return result;\r
+    }\r
+\r
+    public void rewind() {\r
+      position=0;\r
+    }\r
+  }\r
+\r
+  private static class ListAdapter implements TemplateListModel {\r
+    List list;\r
+    List valuesCache;\r
+    int position;\r
+\r
+    private ListAdapter(List aList) {\r
+      list = aList;\r
+      valuesCache = new Vector();\r
+      position=0;\r
+    }\r
+\r
+    public boolean isEmpty() {\r
+      return list.isEmpty();\r
+    }\r
+\r
+    public TemplateModel get(int i) throws TemplateModelException {\r
+\r
+      if (i>=valuesCache.size() && i<list.size()) {\r
+        for(int j=valuesCache.size(); j<=i; j++) {\r
+          valuesCache.add(makeAdapter(list.get(j)));\r
+        }\r
+      }\r
+\r
+      if (i<valuesCache.size())\r
+        return (TemplateModel) valuesCache.get(i);\r
+      else\r
+        throw new TemplateModelException( "Iterator out of bounds" );\r
+    }\r
+\r
+    public boolean hasNext() {\r
+      return position<list.size();\r
+    }\r
+\r
+    public boolean isRewound() {\r
+      return position==0;\r
+    }\r
+\r
+    public TemplateModel next() throws TemplateModelException {\r
+      TemplateModel result;\r
+\r
+      if (hasNext()) {\r
+        result = get(position);\r
+        position++;\r
+      }\r
+      else {\r
+        throw new TemplateModelException( "Iterator out of bounds" );\r
+      }\r
+\r
+      return result;\r
+    }\r
+\r
+    public void rewind() {\r
+      position = 0;\r
+    }\r
+  }\r
+\r
+  private static class FunctionAdapter implements TemplateMethodModel {\r
+    private Generator.GeneratorFunction function;\r
+\r
+    public FunctionAdapter(Generator.GeneratorFunction aFunction) {\r
+      function = aFunction;\r
+    }\r
+\r
+    public TemplateModel exec(List anArguments) throws TemplateModelException {\r
+      try {\r
+        return makeAdapter(function.perform(anArguments));\r
+      }\r
+      catch (Throwable t) {\r
+        throw new TemplateModelException(t.getMessage());\r
+      }\r
+    }\r
+\r
+    public boolean isEmpty() {\r
+      return false;\r
+    }\r
+\r
+  }\r
+\r
+  private static class BeanAdapter implements TemplateHashModel {\r
+    private Object object;\r
+\r
+    public BeanAdapter(Object anObject) {\r
+      object = anObject;\r
+    }\r
+\r
+    public void put(String aKey, TemplateModel aModel)  throws TemplateModelException  {\r
+      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.put not supported");\r
+    }\r
+\r
+    public void remove(String aKey) throws TemplateModelException  {\r
+      throw new TemplateModelException("FreemarkerGenerator$BeanAdapter.remove not supported");\r
+    }\r
+\r
+    public boolean isEmpty() {\r
+      return false;\r
+    }\r
+\r
+    public TemplateModel get(String aKey) throws TemplateModelException {\r
+      try {\r
+        if (PropertyUtils.isReadable(object, aKey))\r
+          return makeAdapter(PropertyUtils.getSimpleProperty(object, aKey));\r
+        else\r
+          return makeAdapter(MethodUtils.invokeExactMethod(object, "get", aKey));\r
+      }\r
+      catch (Throwable t) {\r
+        throw new TemplateModelException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  public static class FreemarkerGeneratorLibrary implements GeneratorLibrary {\r
+    private FileTemplateCache templateCache;\r
+\r
+    public FreemarkerGeneratorLibrary(String aTemplateRoot) {\r
+      templateCache = new FileTemplateCache( aTemplateRoot+"/" );\r
+      templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);\r
+    }\r
+\r
+    public Generator makeGenerator(String anIdentifier) throws GeneratorExc, GeneratorFailure {\r
+      Template template = (Template) templateCache.getItem(anIdentifier, "template");\r
+\r
+      if (template==null) {\r
+        throw new GeneratorExc("FreemarkerGeneratorLibrary: Can't find template "+templateCache.getDirectory()+anIdentifier);\r
+      }\r
+\r
+      return new FreemarkerGenerator(template);\r
+    }\r
+  }\r
+\r
+  public static class FreemarkerGeneratorLibraryFactory implements GeneratorLibraryFactory {\r
+    private String basePath;\r
+\r
+    public FreemarkerGeneratorLibraryFactory(String aBasePath) {\r
+      basePath = aBasePath;\r
+    }\r
+\r
+    public GeneratorLibrary makeLibrary(String anInitializationString) {\r
+      return new FreemarkerGeneratorLibrary(basePath+anInitializationString);\r
+    };\r
+  }\r
+}\r
index 7d7e461..3f10ca7 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
 package mir.generator;
 
+import java.io.*;
 import java.util.List;
 import java.util.Map;
 
@@ -49,4 +50,8 @@ public interface Generator {
   public static interface GeneratorFunction {
     public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure;
   }
+
+  public static interface GeneratorTransformer {
+    public void perform(Reader aSource, PrintWriter anOutput) throws GeneratorExc, GeneratorFailure;
+  }
 }
index 298809e..40f21a1 100755 (executable)
  */
 package  mir.media;
 
-import java.io.InputStream;
-
+import java.io.InputStream;\r
+import java.util.List;\r
+\r
 import mir.entity.Entity;
-import freemarker.template.SimpleList;
 
 /**
  * Interface for Media handling in Mir. All media handlers
@@ -79,7 +79,7 @@ import freemarker.template.SimpleList;
  * ) and just override the things that need to be specific. see MediaHandlerAudio
  *
  * @author <mh@nadir.org>, the Mir-coders group
- * @version $Id: MirMedia.java,v 1.18 2003/04/29 02:36:50 zapata Exp $
+ * @version $Id: MirMedia.java,v 1.19 2003/09/03 18:29:01 zapata Exp $
  */
 
 public interface  MirMedia{
@@ -144,7 +144,7 @@ public interface  MirMedia{
    * @see mir.entity.Entity
    * @see mir.misc.StringUtil
    */
-  public abstract SimpleList getURL (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure;
+  public abstract List getURL (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure;
 
         /**
    * Returns the absolute filesystem path to where the media
diff --git a/source/mir/misc/HTMLTemplateProcessor.java b/source/mir/misc/HTMLTemplateProcessor.java
deleted file mode 100755 (executable)
index 5728168..0000000
+++ /dev/null
@@ -1,399 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.misc;
-
-import java.io.PrintWriter;
-import java.net.URLEncoder;
-import java.util.GregorianCalendar;
-import java.util.Iterator;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import javax.servlet.http.HttpServletResponse;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.entity.Entity;
-import mir.entity.EntityList;
-import mir.generator.FreemarkerGenerator;
-import mir.log.LoggerWrapper;
-import mir.storage.StorageObjectFailure;
-import mir.util.GeneratorHTMLFunctions;
-import mir.util.GeneratorIntegerFunctions;
-import mir.util.ResourceBundleGeneratorFunction;
-
-import org.apache.struts.util.MessageResources;
-
-import freemarker.template.FileTemplateCache;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-import freemarker.template.SimpleScalar;
-import freemarker.template.Template;
-import freemarker.template.TemplateModelRoot;
-
-/**
- * Hilfsklasse zum Mergen von Template und Daten
- */
-public final class HTMLTemplateProcessor {
-
-  public static String templateDir;
-  private static final String[] bundles = { "bundles.adminlocal", "bundles.admin" };
-  private static MirPropertiesConfiguration configuration;
-  private static FileTemplateCache templateCache;
-  private static String docRoot;
-  private static String actionRoot;
-  private static LoggerWrapper logger;
-
-  static {
-    // ML: configuration is not thread safe: it's risky to use it like this
-    //     actually I don't see why HTMLTemplateProcessor needs to be a
-    //     class with static methods. This causes more problems than it solves.
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      e.printStackTrace();
-    }
-
-    logger = new LoggerWrapper("TemplateEngine");
-
-    templateDir =
-        configuration.getStringWithHome("Mir.TemplateDir");
-    templateCache = new FileTemplateCache(templateDir);
-    templateCache.setLoadingPolicy(FileTemplateCache.LOAD_ON_DEMAND);
-    // gone in freemarker 1.7.1: templateCache.startAutoUpdate();
-
-
-    docRoot = configuration.getString("RootUri");
-    try {
-      actionRoot = docRoot +configuration.getString("Producer.ActionServlet");
-    }
-    catch (ConfigException ce) {
-      // if  Producer.ActionServlet is not set in the conf file
-      actionRoot = docRoot + "/Mir";
-    }
-  }
-
-  /**
-   * empty private constructor, to avoid instantiation
-   */
-  private HTMLTemplateProcessor() {
-  }
-
-  /**
-   * Wandelt Liste mit Entities <code>entList</code> in freemarker-Struktur um, mischt die Daten mit
-   * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
-   * <code>out</code>
-   *
-   * @param templateFilename
-   * @param entList
-   * @param out
-   * @exception HTMLParseException
-   */
-
-  public static void process(HttpServletResponse res, String templateFilename, EntityList entList, PrintWriter out, Locale locale, Locale aFallbackLocale) throws HTMLParseException {
-    process(res, templateFilename, entList, (String)null, (TemplateModelRoot) null, out, locale, aFallbackLocale);
-  }
-
-  /**
-   * Wandelt Entitylist in freemarker-Struktur um, f?gt <code>additionalModel</code>
-       * unter dem Namen <code>additionalModelName</code> ein und mischt die Daten mit
-   * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
-   * <code>out</code>
-   *
-   * @param templateFilename
-   * @param entList
-   * @param additionalModelName
-   * @param additionalModel
-   * @param out
-   * @exception HTMLParseException
-   */
-
-  public static void process(HttpServletResponse res, String templateFilename,
-                             EntityList entList, String additionalModelName,
-                             TemplateModelRoot additionalModel, PrintWriter out,
-                             Locale locale, Locale aFallbackLocale) throws HTMLParseException {
-
-    SimpleHash modelRoot = new SimpleHash();
-
-    if (entList == null) {
-      process(null, templateFilename, modelRoot, null, out, locale, aFallbackLocale);
-    }
-    else {
-      try {
-        modelRoot = makeSimpleHashWithEntitylistInfos(entList);
-
-        // Quickhack um mal ein Popup mit reinzunhemen ..
-        if (additionalModelName != null && additionalModel != null)
-          modelRoot.put(additionalModelName, additionalModel);
-
-        process(res, templateFilename, modelRoot, null, out, locale, aFallbackLocale);
-      }
-      catch (StorageObjectFailure e) {
-        throw new HTMLParseException(e.toString());
-      }
-    }
-  }
-
-
-  /**
-   * Mischt die freemarker-Struktur <code>tmr</code> mit
-   * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
-   * <code>out</code>
-   *
-   * @param templateFilename
-   * @param mergeData
-   * @param out
-   * @exception HTMLParseException
-   */
-  public static void process(HttpServletResponse res, String templateFilename,
-                             TemplateModelRoot tmr, PrintWriter out,
-                             Locale locale, Locale aFallbackLocale) throws HTMLParseException {
-    process(res, templateFilename, tmr, null, out, locale, aFallbackLocale);
-  }
-
-  /**
-   * Mischt die freemarker-Struktur <code>tmr</code> mit
-   * Template <code>templateFilename</code> und gibt das Ergebnis an den PrintWriter
-   * <code>out</code>
-   *
-   * @param templateFilename
-   * @param mergeData
-   * @param out
-   * @exception HTMLParseException
-   */
-  public static void process(HttpServletResponse res, String templateFilename,
-                             TemplateModelRoot tmr, TemplateModelRoot extra,
-                             PrintWriter out, Locale locale, Locale aFallbackLocale) throws HTMLParseException {
-
-    if (out == null)
-      throw new HTMLParseException("no outputstream");
-    Template tmpl = getTemplateFor(templateFilename);
-    if (tmpl == null)
-      throw new HTMLParseException("no template: " + templateFilename);
-    if (tmr == null)
-      tmr = new SimpleHash();
-
-      /** @todo  what is this for? (rk) */
-    SimpleHash configHash = new SimpleHash();
-
-    // pass the whole config hash to the templates
-    Iterator it = configuration.getKeys();
-    String key;
-    while (it.hasNext()) {
-      key = (String) it.next();
-      configHash.put(key, new SimpleScalar(
-        configuration.getString(key))
-      );
-    }
-
-    // this does not come directly from the config file
-    configHash.put("docRoot", new SimpleScalar(docRoot));
-
-    configHash.put("actionRoot", new SimpleScalar(res.encodeURL(actionRoot)));
-    configHash.put("now",
-                   new SimpleScalar(StringUtil.date2readableDateTime(new GregorianCalendar())));
-
-    // this conform to updated freemarker syntax
-    configHash.put("compressWhitespace",
-                   new freemarker.template.utility.CompressWhitespace());
-
-    SimpleHash utilityHash = new SimpleHash();
-    try {
-      utilityHash.put("compressWhitespace",
-                      new freemarker.template.utility.CompressWhitespace());
-      utilityHash.put("encodeURI",
-                      FreemarkerGenerator.makeAdapter(new GeneratorHTMLFunctions.
-          encodeURIGeneratorFunction()));
-      utilityHash.put("encodeHTML",
-                      FreemarkerGenerator.makeAdapter(new GeneratorHTMLFunctions.
-          encodeHTMLGeneratorFunction()));
-      utilityHash.put("isOdd",
-                      FreemarkerGenerator.makeAdapter(new GeneratorIntegerFunctions.
-          isOddFunction()));
-      utilityHash.put("increment",
-                      FreemarkerGenerator.makeAdapter(new GeneratorIntegerFunctions.
-          incrementFunction()));
-    }
-    catch (Throwable t) {
-      throw new HTMLParseException(t.getMessage());
-    }
-
-    SimpleHash outPutHash = new SimpleHash();
-
-    if (extra != null) {
-      outPutHash.put("extra", extra);
-    }
-    outPutHash.put("data", tmr);
-    outPutHash.put("config", configHash);
-    outPutHash.put("utility", utilityHash);
-
-    MessageResources messages[] = new MessageResources[bundles.length];
-
-    for (int i=0; i<bundles.length; i++) {
-      messages[i] = MessageResources.getMessageResources(bundles[i]);
-    }
-
-    try {
-      outPutHash.put("lang", FreemarkerGenerator.makeAdapter(new ResourceBundleGeneratorFunction(new Locale[] {locale, aFallbackLocale}, messages)));
-    }
-    catch (Throwable t) {
-      throw new HTMLParseException(t.toString());
-    }
-
-    tmpl.process(outPutHash, out);
-  }
-
-  /**
-   *   Converts Entity-List to SimpleList of SimpleHashes.
-   *   @param aList ist eine Liste von Entity
-   *   @return eine freemarker.template.SimpleList von SimpleHashes.
-   *
-   *    @deprecated EntityLists comply with TemplateListModel now.
-   */
-  public static SimpleList makeSimpleList(EntityList aList) throws StorageObjectFailure {
-    logger.warn("using deprecated makeSimpleList(entityList) - a waste of resources");
-    SimpleList simpleList = new SimpleList();
-    if (aList != null) {
-      for (int i = 0; i < aList.size(); i++) {
-        simpleList.add(aList.elementAt(i));
-      }
-    }
-    return simpleList;
-  }
-
-  /**
-   *  Konvertiert ein EntityList in ein freemarker.template.SimpleHash-Modell. Im Hash
-   *  sind die einzelnen Entities ueber ihre id zu erreichen.
-   *  @param aList ist die EntityList
-   *  @return SimpleHash mit den entsprechenden freemarker Daten
-   *
-   */
-  public static SimpleHash makeSimpleHash(EntityList aList) throws
-      StorageObjectFailure {
-    SimpleHash simpleHash = new SimpleHash();
-    Entity currentEntity;
-
-    if (aList != null) {
-      for (int i = 0; i < aList.size(); i++) {
-        currentEntity = (Entity) aList.elementAt(i);
-        simpleHash.put(currentEntity.getId(), currentEntity);
-      }
-    }
-    return simpleHash;
-  }
-
-  /**
-   *  Konvertiert ein Hashtable mit den keys und values als String
-   *  in ein freemarker.template.SimpleHash-Modell
-   *  @param mergeData der Map mit den String / String Daten
-   *  @return SimpleHash mit den entsprechenden freemarker Daten
-   *
-   */
-  public static SimpleHash makeSimpleHash(Map mergeData) {
-    SimpleHash modelRoot = new SimpleHash();
-    String aField;
-    if (mergeData != null) {
-      Set set = mergeData.keySet();
-      Iterator it = set.iterator();
-      for (int i = 0; i < set.size(); i++) {
-        aField = (String) it.next();
-        modelRoot.put(aField, (String) mergeData.get(aField));
-      }
-    }
-    return modelRoot;
-  }
-
-  /**
-   * Converts EntityList in SimpleHash and adds additional information
-   * to the returned SimpleHash
-   *
-   * @param entList
-   * @return SimpleHash returns SimpleHash with the converted EntityList plus
-   *        additional Data about the list.
-   * @exception StorageObjectException
-   */
-
-  public static SimpleHash makeSimpleHashWithEntitylistInfos(EntityList entList) throws
-      StorageObjectFailure {
-    SimpleHash modelRoot = new SimpleHash();
-    if (entList != null) {
-      modelRoot.put("contentlist", entList);
-      modelRoot.put("count",
-                    new SimpleScalar( (new Integer(entList.getCount())).toString()));
-      if (entList.getWhere() != null) {
-        modelRoot.put("where", new SimpleScalar(entList.getWhere()));
-        modelRoot.put("where_encoded",
-                      new SimpleScalar(URLEncoder.encode(entList.getWhere())));
-      }
-      if (entList.getOrder() != null) {
-        modelRoot.put("order", new SimpleScalar(entList.getOrder()));
-        modelRoot.put("order_encoded",
-                      new SimpleScalar(URLEncoder.encode(entList.getOrder())));
-      }
-      modelRoot.put("from",
-                    new SimpleScalar( (new Integer(entList.getFrom())).toString()));
-      modelRoot.put("to",
-                    new SimpleScalar( (new Integer(entList.getTo())).toString()));
-
-      if (entList.hasNextBatch())
-        modelRoot.put("next",
-                      new SimpleScalar( (new Integer(entList.getNextBatch())).
-                                       toString()));
-      if (entList.hasPrevBatch())
-        modelRoot.put("prev",
-                      new SimpleScalar( (new Integer(entList.getPrevBatch())).
-                                       toString()));
-    }
-    return modelRoot;
-  }
-
-  /**
-   * Private methods to get template from a templateFilename
-   * @param templateFilename
-   * @return Template
-   * @exception HTMLParseException
-   */
-  private static Template getTemplateFor(String templateFilename) throws
-      HTMLParseException {
-    Template returnTemplate = null;
-    if (templateFilename != null)
-      returnTemplate = (Template) templateCache.getItem(templateFilename,
-          "template");
-
-    if (returnTemplate == null) {
-      logger.error("CACHE (ERR): Unknown template: " + templateFilename);
-      throw new HTMLParseException("Templatefile: " + templateFilename + " not found.");
-    }
-
-    return returnTemplate;
-  }
-}
\ No newline at end of file
index bb26ae7..5588286 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mir.misc;
-
-import gnu.regexp.RE;
-import gnu.regexp.REException;
-
-import java.io.File;
-import java.text.NumberFormat;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.StringTokenizer;
-
-/**
- * Statische Hilfsmethoden zur Stringbehandlung
- *
- * @version $Id: StringUtil.java,v 1.33 2003/04/21 12:42:52 idfx Exp $
- * @author mir-coders group
- *
- */
-public final class StringUtil {
-
-  private static RE   re_newline2br, re_brbr2p, re_mail, re_url, re_tags,
-                      re_tables, re_forbiddenTags;
-
-  private StringUtil() { }  // this avoids contruction
-
-  static {
-    try {
-      //precompile regex
-      re_newline2br = new RE("(\r?\n){1}");
-      re_brbr2p     = new RE("(<br>\r?\n<br>){1,}");
-      re_mail       = new RE("([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)");
-      re_url        = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");
-      re_tags       = new RE("<[^>]*>",RE.REG_ICASE);
-                       re_tables = new RE("<[ \t\r\n/]*(table|td|tr)[ \t\r\n]*>",RE.REG_ICASE);
-                       re_forbiddenTags = new RE("<[ \t\r\n/]*(body|head|script)[ \t\r\n]*>",RE.REG_ICASE);
-    }
-    catch (REException e){
-      System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());
-    }
-  }
-
-  /**
-   * Formats a number with the specified minimum and maximum number of digits.
-   **/
-  public static synchronized String zeroPaddingNumber(long value, int minDigits,
-      int maxDigits)
-  {
-    NumberFormat numberFormat = NumberFormat.getInstance();
-    numberFormat.setMinimumIntegerDigits(minDigits);
-    numberFormat.setMaximumIntegerDigits(maxDigits);
-    return numberFormat.format(value);
-  }
-
-  /**
-   * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)
-   * @param theDate
-   * @return 8-ziffriger String (yyyymmdd)
-   */
-
-  public static final String date2webdbDate (GregorianCalendar theDate) {
-    StringBuffer webdbDate = new StringBuffer();
-    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
-    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
-    webdbDate.append(pad2(theDate.get(Calendar.DATE)));
-    return  webdbDate.toString();
-  }
-
-  /**
-   * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)
-   * @param theDate
-   * @return 12-ziffriger String (yyyymmdd)
-   */
-
-  public static final String date2webdbDateTime (GregorianCalendar theDate) {
-    StringBuffer webdbDate = new StringBuffer();
-    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
-    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
-    webdbDate.append(pad2(theDate.get(Calendar.DATE)));
-    webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
-    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
-    return  webdbDate.toString();
-  }
-
-  /**
-   * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)
-   * @param theDate
-   * @return w3approved datetime
-   */
-
-  public static final String date2w3DateTime (GregorianCalendar theDate) {
-    StringBuffer webdbDate = new StringBuffer();
-    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));
-    webdbDate.append("-");
-    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));
-    webdbDate.append("-");
-    webdbDate.append(pad2(theDate.get(Calendar.DATE)));
-    webdbDate.append("T");
-    webdbDate.append(pad2(theDate.get(Calendar.HOUR)));
-    webdbDate.append(":");
-    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));
-    webdbDate.append(":");
-    webdbDate.append(pad2(theDate.get(Calendar.SECOND)));
-    //assumes you are an hour-multiple away from UTC....
-    int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));
-    if (offset < 0){
-      webdbDate.append("-");
-    }
-    else{
-      webdbDate.append("+");
-    }
-    webdbDate.append(pad2(Math.abs(offset)));
-    webdbDate.append(":00");
-    return  webdbDate.toString();
-  }
-
-  /**
-   * wandelt Calendar in dd.mm.yyyy / hh.mm um
-   * @param theDate
-   * @return String mit (dd.mm.yyyy / hh.mm um)
-   */
-  public static String date2readableDateTime (GregorianCalendar theDate) {
-    String readable = "";
-    int hour;
-    readable += pad2(theDate.get(Calendar.DATE));
-    readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);
-    readable += "." + String.valueOf(theDate.get(Calendar.YEAR));
-    hour = theDate.get(Calendar.HOUR);
-    if (theDate.get(Calendar.AM_PM) == Calendar.PM)
-      hour += 12;
-    readable += " / " + pad2(hour);
-    readable += ":" + pad2(theDate.get(Calendar.MINUTE));
-    return  readable;
-  }
-
-  /**
-  *  deleteForbiddenTags
-  *  this method deletes all <script>, <body> and <head>-tags
-  */
-  public static final String deleteForbiddenTags(String haystack) {
-    return re_forbiddenTags.substituteAll(haystack,"");
-  }
-
-       /**
-        *  deleteHTMLTableTags
-        *  this method deletes all <table>, <tr> and <td>-tags
-        */
-  public static final String deleteHTMLTableTags(String haystack) {
-    return re_tables.substituteAll(haystack,"");
-  }
-
-  /**
-   * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>
-   * getrennt ist.
-   *
-   * @param webdbDate
-   * @return String mit <code>/yyyy/mm/dd</code>
-   */
-  public static final String webdbDate2path (String webdbDate) {
-    StringBuffer path = new StringBuffer();
-    path.append("/").append(webdbDate.substring(0, 4));
-    path.append("/").append(webdbDate.substring(4, 6));
-    path.append("/");
-    //who did this?
-    //path.append("/").append(webdbDate.substring(6, 8));
-    return  path.toString();
-  }
-
-  /**
-   * converts string from format: yyyy-mm-dd__hh:mm:ss.d
-   * to dd.mm.yyyy hh:mm
-   */
-  public static String dateToReadableDate(String date) {
-    StringBuffer returnDate = new StringBuffer();
-    if (date!=null) {
-
-      returnDate.append(date.substring(8,10)).append('.');
-      returnDate.append(date.substring(5,7)).append('.');
-      returnDate.append(date.substring(0,4)).append(' ');
-      returnDate.append(date.substring(11,16));
-    }
-    return returnDate.toString();
-  }
-
-  /**
-   * converts string from format: yyyy-mm-dd__hh:mm:ss.d
-   * to yyyy
-   */
-  public static String dateToYear (String date) {
-    StringBuffer returnDate = new StringBuffer();
-    if (date!=null) {
-
-      returnDate.append(date.substring(0,4));
-    }
-    return returnDate.toString();
-  }
-
-  /**
-   * converts string from format: yyyy-mm-dd__hh:mm:ss.d
-   * to [m]m
-   */
-  public static String dateToMonth (String date) {
-    StringBuffer returnDate = new StringBuffer();
-    if (date!=null) {
-      if (!date.substring(5,6).equalsIgnoreCase("0")) returnDate.append(date.substring(5,7));
-      else returnDate.append(date.substring(6,7));
-    }
-    return returnDate.toString();
-  }
-
-  /**
-   * converts string from format: yyyy-mm-dd__hh:mm:ss.d
-   * to [d]d
-   */
-  public static String dateToDayOfMonth (String date) {
-    StringBuffer returnDate = new StringBuffer();
-    if (date!=null) {
-      if (!date.substring(8,9).equalsIgnoreCase("0")) returnDate.append(date.substring(8,10));
-      else returnDate.append(date.substring(9,10));
-    }
-    return returnDate.toString();
-  }
-
-  /**
-   * converts string from format: yyyy-mm-dd__hh:mm:ss.d
-   * to hh:mm
-   */
-  public static String dateToTime (String date) {
-    StringBuffer returnDate = new StringBuffer();
-    if (date!=null) {
-      returnDate.append(date.substring(11,16));
-    }
-    return returnDate.toString();
-  }
-
-  /**
-   * Splits the provided CSV text into a list. stolen wholesale from
-   * from Jakarta Turbine StrinUtils.java -mh
-   *
-   * @param text      The CSV list of values to split apart.
-   * @param separator The separator character.
-   * @return          The list of values.
-   */
-  public static String[] split(String text, String separator)
-  {
-    StringTokenizer st = new StringTokenizer(text, separator);
-    String[] values = new String[st.countTokens()];
-    int pos = 0;
-    while (st.hasMoreTokens())
-    {
-      values[pos++] = st.nextToken();
-    }
-    return values;
-  }
-
-  /**
-   * Joins the elements of the provided array into a single string
-   * containing a list of CSV elements. Stolen wholesale from Jakarta
-   * Turbine StringUtils.java. -mh
-   *
-   * @param list      The list of values to join together.
-   * @param separator The separator character.
-   * @return          The CSV text.
-   */
-  public static String join(String[] list, String separator)
-  {
-    StringBuffer csv = new StringBuffer();
-    for (int i = 0; i < list.length; i++)
-    {
-      if (i > 0)
-      {
-      csv.append(separator);
-    }
-    csv.append(list[i]);
-    }
-    return csv.toString();
-  }
-
-  /**
-   * Wandelet String in byte[] um.
-   * @param s
-   * @return byte[] des String
-   */
-
-  public static byte[] stringToBytes(String s) {
-    String crlf = System.getProperty("line.separator");
-    if (!crlf.equals("\n"))
-      s = replace(s, "\n", crlf);
-    // byte[] buf = new byte[s.length()];
-    byte[] buf = s.getBytes();
-    return buf;
-  }
-
-  /**
-   * Ersetzt in String <code>s</code> das <code>pattern</code> durch <code>substitute</code>
-   * @param s
-   * @param pattern
-   * @param substitute
-   * @return String mit den Ersetzungen
-   */
-  public static String replace(String s, String pattern, String substitute) {
-    int i = 0, pLen = pattern.length(), sLen = substitute.length();
-    StringBuffer buf = new StringBuffer(s.length());
-    while (true) {
-      int j = s.indexOf(pattern, i);
-      if (j < 0) {
-        buf.append(s.substring(i));
-        break;
-      } else {
-        buf.append(s.substring(i, j));
-        buf.append(substitute);
-        i = j+pLen;
-      }
-    }
-    return buf.toString();
-  }
-
-  /**
-   * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>
-   * @param s
-   * @param pattern
-   * @param substitute
-   * @return String mit den Ersetzungen
-   */
-  public static String regexpReplace(String haystack, String pattern, String substitute) {
-    try {
-      RE regex = new RE(pattern);
-      return regex.substituteAll(haystack,substitute);
-    } catch(REException ex){
-      return null;
-    }
-  }
-
-
-
-
-  /**
-   * F?gt einen Separator an den Pfad an
-   * @param path
-   * @return Pfad mit Separator am Ende
-   */
-  public static final String addSeparator (String path) {
-    return  path.length() == 0 || path.endsWith(File.separator) ? path : path
-                          + File.separatorChar;
-  }
-
-  /**
-   * F?gt ein <code>/</code> ans ende des Strings and
-   * @param path
-   * @return Pfad mit <code>/</code> am Ende
-   */
-  public static final String addSlash (String path) {
-    return  path.length() == 0 || path.endsWith("/") ? path : path + '/';
-  }
-
-  /**
-   * L?scht <code>/</code> am Ende des Strings, falls vorhanden
-   * @param path
-   * @return String ohne <code>/</code> am Ende
-   */
-  public static final String removeSlash (String path) {
-    return  path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()
-        - 1) : path;
-  }
-
-  /**
-   * Checks to see if the path is absolute by looking for a leading file
-   * separater
-   * @param path
-   * @return
-   */
-  public static boolean isAbsolutePath (String path) {
-    return  path.startsWith(File.separator);
-  }
-
-  /**
-   * L?scht Slash am Anfang des Strings
-   * @param path
-   * @return
-   */
-  public static String removeFirstSlash (String path) {
-    return  path.startsWith("/") ? path.substring(1) : path;
-  }
-
-  /**
-   * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)
-   * @return zwistellige Zahl
-   */
-  public static String pad2 (int number) {
-    return  number < 10 ? "0" + number : String.valueOf(number);
-  }
-
-  /**
-   * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)
-   *
-   * @return 3-stellige Zahl
-   */
-  public static String pad3 (int number) {
-    return  number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);
-  }
-
-  /**
-   * Konvertiert Unix-Linefeeds in Win-Linefeeds
-   * @param s
-   * @return Konvertierter String
-   */
-  public static String unixLineFeedsToWin(String s) {
-    int i = -1;
-    while (true) {
-      i = s.indexOf('\n', i+1);
-      if (i < 0) break;
-      if ((i == 0 || s.charAt(i-1) != '\r') &&
-          (i == s.length()-1 || s.charAt(i+1) != '\r')) {
-        s = s.substring(0, i)+'\r'+s.substring(i);
-        i++;
-      }
-    }
-    return s;
-  }
-
- /**
-  * schnellere Variante der String.toLowerCase()-Routine
-  *
-  * @return String in Kleinbuchsten
-  */
-  public static String toLowerCase(String s) {
-    int l = s.length();
-    char[] a = new char[l];
-    for (int i = 0; i < l; i++)
-      a[i] = Character.toLowerCase(s.charAt(i));
-    return new String(a);
-  }
-
-  /**
-   * Findet <code>element</code> im String-Array <code>array</code>
-   * @param array
-   * @param element
-   * @return Fundstelle als int oder -1
-   */
-  public static int indexOf(String[] array, String element) {
-    if (array != null)
-      for (int i = 0; i < array.length; i++)
-        if (array[i].equals(element))
-          return i;
-    return -1;
-  }
-
-  /**
-   * Testet auf Vorkommen von <code>element</code> in <code>array</code>
-   * @param array String-Array
-   * @param element
-   * @return true wenn <code>element</code> vorkommt, sonst false
-   */
-  public static boolean contains(String[] array, String element) {
-    return indexOf(array, element) >= 0;
-  }
-
-  /**
-   * Ermittelt CRC-Pr?fsumme von String <code>s</code>
-   * @param s
-   * @return CRC-Pr?fsumme
-   */
-  public static int getCRC(String s) {
-    int h = 0;
-    char val[] = s.toCharArray();
-    int len = val.length;
-
-    for (int i = 0 ; i < len; i++) {
-      h &= 0x7fffffff;
-      h = (((h >> 30) | (h << 1)) ^ (val[i]+i));
-    }
-
-    return (h << 8) | (len & 0xff);
-  }
-
-  /**
-   * Liefert Default-Wert def zur?ck, wenn String <code>s</code>
-   * kein Integer ist.
-   *
-   * @param s
-   * @param def
-   * @return geparster int aus s oder def
-   */
-  public static int parseInt(String s, int def) {
-    if (s == null) return def;
-    try {
-      return Integer.parseInt(s);
-    } catch (NumberFormatException e) {
-      return def;
-    }
-  }
-
-  /**
-   * Liefert Defaultwert def zur?ck, wenn s nicht zu einem float geparsed werden kann.
-   * @param s
-   * @param def
-   * @return geparster float oder def
-   */
-  public static float parseFloat(String s, float def) {
-    if (s == null) return def;
-    try {
-      return new Float(s).floatValue();
-    } catch (NumberFormatException e) {
-      return def;
-    }
-  }
-
-  /**
-   * Findet Ende eines Satzes in String <code>text</code>
-   * @param text
-   * @param startIndex
-   * @return index des Satzendes, oder -1
-   */
-  public static int findEndOfSentence(String text, int startIndex) {
-    while (true) {
-      int i = text.indexOf('.', startIndex);
-      if (i < 0) return -1;
-      if (i > 0 && !Character.isDigit(text.charAt(i-1)) &&
-          (i+1 >= text.length()
-          || text.charAt(i+1) == ' '
-          || text.charAt(i+1) == '\n'
-          || text.charAt(i+1) == '\t'))
-        return i+1;
-      startIndex = i+1;
-    }
-  }
-
-  /**
-   * Findet Wortende in String <code>text</code> ab <code>startIndex</code>
-   * @param text
-   * @param startIndex
-   * @return Index des Wortendes, oder -1
-   */
-  public static int findEndOfWord(String text, int startIndex) {
-    int i = text.indexOf(' ', startIndex),
-    j = text.indexOf('\n', startIndex);
-    if (i < 0) i = text.length();
-    if (j < 0) j = text.length();
-    return Math.min(i, j);
-  }
-
-
-  /**
-   *  convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)
-   *  in den html-tag <p>
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben
-   */
-  public static String convertNewline2P(String haystack) {
-    return re_brbr2p.substituteAll(haystack,"\n</p><p>");
-  }
-
-  /**
-   *  convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)
-   *  in den html-tag <br>
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben
-   */
-  public static String convertNewline2Break(String haystack) {
-    return re_newline2br.substituteAll(haystack,"$0<br />");
-  }
-
-  /**
-   *  createMailLinks wandelt text im email-adressenformat
-   *  in einen klickbaren link um
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben
-   */
-  public static String createMailLinks(String haystack) {
-    return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");
-  }
-
-
-  /**
-   *  createMailLinks wandelt text im email-adressenformat
-   *  in einen klickbaren link um
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben
-   */
-  public static String createMailLinks(String haystack, String imageRoot, String mailImage) {
-    return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/>&#160;<a href=\"mailto:$0\">$0</a>");
-  }
-
-
-  /**
-   *  createURLLinks wandelt text im url-format
-   *  in einen klickbaren link um
-   *  nur sinnvoll, wenn text nicht im html-format eingegeben
-   */
-  public static String createURLLinks(String haystack) {
-    return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");
-  }
-
-  /**
-   * this routine takes text in url format and makes
-   * a clickaeble "<href>" link removing any "illegal" html tags
-   * @param haystack, the url
-   * @param title, the href link text
-   * @param imagRoot, the place to find icons
-   * @param extImage, the url of the icon to show next to the link
-   * @return a String containing the url
-   */
-  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {
-    if (title == null) {
-      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">$0</a>");
-    } else {
-      title = removeHTMLTags(title);
-      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">"+title+"</a>");
-    }
-  }
-
-  /**
-   * this routine takes text in url format and makes
-   * a clickaeble "<href>" link removing any "illegal" html tags
-   * @param haystack, the url
-   * @param imageRoot, the place to find icons
-   * @param extImage, the url of the icon to show next to the link
-   * @param intImage, unused
-   * @return a String containing the url
-   */
-  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {
-    return createURLLinks(haystack, title, imageRoot, extImage);
-  }
-
-  /**
-   * this method deletes all html tags
-   */
-  public static final String removeHTMLTags(String haystack){
-    return re_tags.substituteAll(haystack,"");
-  }
-
-  /**
-   * this method deletes all but the approved tags html tags
-   * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all
-   */
-  public static String approveHTMLTags(String haystack){
-    try {
-      String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";
-      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";
-      String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";
-
-      // kill all the bad tags that have attributes
-      String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";
-      RE regex = new RE(s,RE.REG_ICASE);
-      haystack = regex.substituteAll(haystack,"");
-
-      // kill all the bad tags that are attributeless
-      regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);
-      haystack = regex.substituteAll(haystack,"");
-
-      // kill all the tags which have a javascript attribute like onLoad
-      regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);
-      haystack = regex.substituteAll(haystack,"");
-
-      // kill all the tags which include a url to an unacceptable protocol
-      regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);
-      haystack = regex.substituteAll(haystack,"");
-
-      return haystack;
-    } catch(REException ex){
-      ex.printStackTrace();
-      return null;
-    }
-  }
-
-
-  /**
-   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
-   *  htmlcodierten string auf und returnt einen htmlcodierten String
-   */
-  public static String createHTML(String content){
-    content=convertNewline2Break(content);
-    content=convertNewline2P(content);
-    content=createMailLinks(content);
-    content=createURLLinks(content);
-    return content;
-  }
-
-
-  /**
-   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht
-   *  htmlcodierten string auf und returnt einen htmlcodierten String
-   */
-  public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){
-    content=convertNewline2Break(content);
-    content=convertNewline2P(content);
-    content=createMailLinks(content,producerDocRoot,mailImage);
-    content=createURLLinks(content,null,producerDocRoot,extImage,intImage);
-    return content;
-  }
-
-}
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package  mir.misc;\r
+\r
+import java.text.NumberFormat;\r
+import java.util.Calendar;\r
+import java.util.Date;\r
+import java.util.GregorianCalendar;\r
+import java.util.TimeZone;\r
+\r
+import gnu.regexp.RE;\r
+import gnu.regexp.REException;\r
+\r
+/**\r
+ * Statische Hilfsmethoden zur Stringbehandlung\r
+ *\r
+ * @version $Id: StringUtil.java,v 1.34 2003/09/03 18:29:02 zapata Exp $\r
+ * @author mir-coders group\r
+ *\r
+ */\r
+public final class StringUtil {\r
+\r
+  private static RE   re_newline2br, re_brbr2p, re_mail, re_url, re_tags,\r
+                      re_tables, re_forbiddenTags;\r
+\r
+  private StringUtil() { }  // this avoids contruction\r
+\r
+  static {\r
+    try {\r
+      //precompile regex\r
+      re_newline2br = new RE("(\r?\n){1}");\r
+      re_brbr2p     = new RE("(<br>\r?\n<br>){1,}");\r
+      re_mail       = new RE("\\b([a-zA-Z0-9_.-]+)@([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_.-]+)\\b");\r
+      re_url        = new RE("((https://)|(http://)|(ftp://)){1}([a-zA-Z0-9_-]+).([a-zA-Z0-9_.:-]+)/?([^ \t\r\n<>\\)\\]]+[^ \t\r\n.,<>\\)\\]])");\r
+      re_tags       = new RE("<[^>]*>",RE.REG_ICASE);\r
+      re_tables = new RE("<[ \t\r\n/]*(table|td|tr)[ \t\r\n]*>",RE.REG_ICASE);\r
+      re_forbiddenTags = new RE("<[ \t\r\n/]*(html|meta|body|head|script)[ \t\r\n]*>",RE.REG_ICASE);\r
+    }\r
+    catch (REException e){\r
+      System.err.println("FATAL: StringUtil: could not precompile REGEX: "+e.toString());\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Formats a number with the specified minimum and maximum number of digits.\r
+   **/\r
+  public static synchronized String zeroPaddingNumber(long value, int minDigits,\r
+      int maxDigits)\r
+  {\r
+    NumberFormat numberFormat = NumberFormat.getInstance();\r
+    numberFormat.setMinimumIntegerDigits(minDigits);\r
+    numberFormat.setMaximumIntegerDigits(maxDigits);\r
+    return numberFormat.format(value);\r
+  }\r
+\r
+  /**\r
+   * Wandelt Datum in einen 8-ziffrigen String um (yyyymmdd)\r
+   * @param theDate\r
+   * @return 8-ziffriger String (yyyymmdd)\r
+   */\r
+\r
+  public static final String date2webdbDate (GregorianCalendar theDate) {\r
+    StringBuffer webdbDate = new StringBuffer();\r
+    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));\r
+    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));\r
+    webdbDate.append(pad2(theDate.get(Calendar.DATE)));\r
+    return  webdbDate.toString();\r
+  }\r
+\r
+  /**\r
+   * Wandelt Calendar in einen 12-ziffrigen String um (yyyymmddhhmm)\r
+   * @param theDate\r
+   * @return 12-ziffriger String (yyyymmdd)\r
+   */\r
+\r
+  public static final String date2webdbDateTime (GregorianCalendar theDate) {\r
+    StringBuffer webdbDate = new StringBuffer();\r
+    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));\r
+    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));\r
+    webdbDate.append(pad2(theDate.get(Calendar.DATE)));\r
+    webdbDate.append(pad2(theDate.get(Calendar.HOUR)));\r
+    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));\r
+    return  webdbDate.toString();\r
+  }\r
+\r
+  /**\r
+   * Return a http://www.w3.org/TR/NOTE-datetime formatted date (yyyy-mm-ddThh:mm:ssTZ)\r
+   * @param theDate\r
+   * @return w3approved datetime\r
+   */\r
+\r
+  public static final String date2w3DateTime (GregorianCalendar theDate) {\r
+    StringBuffer webdbDate = new StringBuffer();\r
+    webdbDate.append(String.valueOf(theDate.get(Calendar.YEAR)));\r
+    webdbDate.append("-");\r
+    webdbDate.append(pad2(theDate.get(Calendar.MONTH) + 1));\r
+    webdbDate.append("-");\r
+    webdbDate.append(pad2(theDate.get(Calendar.DATE)));\r
+    webdbDate.append("T");\r
+    webdbDate.append(pad2(theDate.get(Calendar.HOUR_OF_DAY)));\r
+    webdbDate.append(":");\r
+    webdbDate.append(pad2(theDate.get(Calendar.MINUTE)));\r
+    webdbDate.append(":");\r
+    webdbDate.append(pad2(theDate.get(Calendar.SECOND)));\r
+    //assumes you are an hour-multiple away from UTC....\r
+    int offset=(theDate.get(Calendar.ZONE_OFFSET)/(60*60*1000));\r
+    if (offset < 0){\r
+      webdbDate.append("-");\r
+    }\r
+    else{\r
+      webdbDate.append("+");\r
+    }\r
+    webdbDate.append(pad2(Math.abs(offset)));\r
+    webdbDate.append(":00");\r
+    return  webdbDate.toString();\r
+  }\r
+\r
+  /**\r
+   * wandelt Calendar in dd.mm.yyyy / hh.mm um\r
+   * @param theDate\r
+   * @return String mit (dd.mm.yyyy / hh.mm um)\r
+   */\r
+  public static String date2readableDateTime (GregorianCalendar theDate) {\r
+    String readable = "";\r
+    int hour;\r
+    readable += pad2(theDate.get(Calendar.DATE));\r
+    readable += "." + pad2(theDate.get(Calendar.MONTH) + 1);\r
+    readable += "." + String.valueOf(theDate.get(Calendar.YEAR));\r
+    hour = theDate.get(Calendar.HOUR);\r
+    if (theDate.get(Calendar.AM_PM) == Calendar.PM)\r
+      hour += 12;\r
+    readable += " / " + pad2(hour);\r
+    readable += ":" + pad2(theDate.get(Calendar.MINUTE));\r
+    return  readable;\r
+  }\r
+\r
+  /**\r
+  *  deleteForbiddenTags\r
+  *  this method deletes all <script>, <body> and <head>-tags\r
+  */\r
+  public static final String deleteForbiddenTags(String haystack) {\r
+    return re_forbiddenTags.substituteAll(haystack,"");\r
+  }\r
+\r
+  /**\r
+   *  deleteHTMLTableTags\r
+   *  this method deletes all <table>, <tr> and <td>-tags\r
+   */\r
+  public static final String deleteHTMLTableTags(String haystack) {\r
+    return re_tables.substituteAll(haystack,"");\r
+  }\r
+\r
+  /**\r
+   * wandelt eine Datum in einen 8-buchstabigen String, der durch <code>/</code>\r
+   * getrennt ist.\r
+   *\r
+   * @param webdbDate\r
+   * @return String mit <code>/yyyy/mm/dd</code>\r
+   */\r
+  public static final String webdbDate2path (String webdbDate) {\r
+    StringBuffer path = new StringBuffer();\r
+    path.append("/").append(webdbDate.substring(0, 4));\r
+    path.append("/").append(webdbDate.substring(4, 6));\r
+    path.append("/");\r
+    //who did this?\r
+    //path.append("/").append(webdbDate.substring(6, 8));\r
+    return  path.toString();\r
+  }\r
+\r
+  /**\r
+   * Ersetzt in String <code>s</code> das Regexp <code>pattern</code> durch <code>substitute</code>\r
+   * @param s\r
+   * @param pattern\r
+   * @param substitute\r
+   * @return String mit den Ersetzungen\r
+   */\r
+  public static String regexpReplace(String haystack, String pattern, String substitute) {\r
+    try {\r
+      RE regex = new RE(pattern);\r
+      return regex.substituteAll(haystack,substitute);\r
+    } catch(REException ex){\r
+      return null;\r
+    }\r
+  }\r
+\r
+  /**\r
+   * L?scht <code>/</code> am Ende des Strings, falls vorhanden\r
+   * @param path\r
+   * @return String ohne <code>/</code> am Ende\r
+   */\r
+  public static final String removeSlash (String path) {\r
+    return  path.length() > 1 && path.endsWith("/") ? path.substring(0, path.length()\r
+        - 1) : path;\r
+  }\r
+\r
+  /**\r
+   * formatiert eine Zahl (0-99) zweistellig (z.B. 5 -> 05)\r
+   * @return zwistellige Zahl\r
+   */\r
+  public static String pad2 (int number) {\r
+    return  number < 10 ? "0" + number : String.valueOf(number);\r
+  }\r
+\r
+  /**\r
+   * formatiert eine Zahl (0-999) dreistellig (z.B. 7 -> 007)\r
+   *\r
+   * @return 3-stellige Zahl\r
+   */\r
+  public static String pad3 (int number) {\r
+    return  number < 10 ? "00" + number : number < 100 ? "0" + number : String.valueOf(number);\r
+  }\r
+\r
+  /**\r
+   * Liefert Default-Wert def zur?ck, wenn String <code>s</code>\r
+   * kein Integer ist.\r
+   *\r
+   * @param s\r
+   * @param def\r
+   * @return geparster int aus s oder def\r
+   */\r
+  public static int parseInt(String s, int def) {\r
+    if (s == null) return def;\r
+    try {\r
+      return Integer.parseInt(s);\r
+    } catch (NumberFormatException e) {\r
+      return def;\r
+    }\r
+  }\r
+\r
+\r
+  /**\r
+   *  convertNewline2P ist eine regex-routine zum umwandeln von 2 oder mehr newlines (\n)\r
+   *  in den html-tag <p>\r
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
+   */\r
+  public static String convertNewline2P(String haystack) {\r
+    return re_brbr2p.substituteAll(haystack,"\n</p><p>");\r
+  }\r
+\r
+  /**\r
+   *  convertNewline2Break ist eine regex-routine zum umwandeln von 1 newline (\n)\r
+   *  in den html-tag <br>\r
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
+   */\r
+  public static String convertNewline2Break(String haystack) {\r
+    return re_newline2br.substituteAll(haystack,"$0<br />");\r
+  }\r
+\r
+  /**\r
+   *  createMailLinks wandelt text im email-adressenformat\r
+   *  in einen klickbaren link um\r
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
+   */\r
+  public static String createMailLinks(String haystack) {\r
+    return re_mail.substituteAll(haystack,"<a href=\"mailto:$0\">$0</a>");\r
+  }\r
+\r
+\r
+  /**\r
+   *  createMailLinks wandelt text im email-adressenformat\r
+   *  in einen klickbaren link um\r
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
+   */\r
+  public static String createMailLinks(String haystack, String imageRoot, String mailImage) {\r
+    return re_mail.substituteAll(haystack,"<img src=\""+imageRoot+"/"+mailImage+"\" border=\"0\"/>&#160;<a href=\"mailto:$0\">$0</a>");\r
+  }\r
+\r
+\r
+  /**\r
+   *  createURLLinks wandelt text im url-format\r
+   *  in einen klickbaren link um\r
+   *  nur sinnvoll, wenn text nicht im html-format eingegeben\r
+   */\r
+  public static String createURLLinks(String haystack) {\r
+    return re_url.substituteAll(haystack,"<a href=\"$0\">$0</a>");\r
+  }\r
+\r
+  /**\r
+   * this routine takes text in url format and makes\r
+   * a clickaeble "<href>" link removing any "illegal" html tags\r
+   * @param haystack, the url\r
+   * @param title, the href link text\r
+   * @param imagRoot, the place to find icons\r
+   * @param extImage, the url of the icon to show next to the link\r
+   * @return a String containing the url\r
+   */\r
+  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage) {\r
+    if (title == null) {\r
+      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">$0</a>");\r
+    } else {\r
+      title = removeHTMLTags(title);\r
+      return re_url.substituteAll(haystack,"<img src=\""+imageRoot+"/"+extImage+"\" border=\"0\"/>&#160;<a href=\"$0\">"+title+"</a>");\r
+    }\r
+  }\r
+\r
+  /**\r
+   * this routine takes text in url format and makes\r
+   * a clickaeble "<href>" link removing any "illegal" html tags\r
+   * @param haystack, the url\r
+   * @param imageRoot, the place to find icons\r
+   * @param extImage, the url of the icon to show next to the link\r
+   * @param intImage, unused\r
+   * @return a String containing the url\r
+   */\r
+  public static String createURLLinks(String haystack, String title, String imageRoot,String extImage,String intImage) {\r
+    return createURLLinks(haystack, title, imageRoot, extImage);\r
+  }\r
+\r
+  /**\r
+   * this method deletes all html tags\r
+   */\r
+  public static final String removeHTMLTags(String haystack){\r
+    return re_tags.substituteAll(haystack,"");\r
+  }\r
+\r
+  /**\r
+   * this method deletes all but the approved tags html tags\r
+   * it also deletes approved tags which contain malicious-looking attributes and doesn't work at all\r
+   */\r
+  public static String approveHTMLTags(String haystack){\r
+    try {\r
+      String approvedTags="a|img|h1|h2|h3|h4|h5|h6|br|b|i|strong|p";\r
+      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";\r
+      String approvedProtocols="rtsp|http|ftp|https|freenet|mailto";\r
+\r
+      // kill all the bad tags that have attributes\r
+      String s = "<\\s*/?\\s*(?!(("+approvedTags+")\\s))\\w+\\s[^>]*>";\r
+      RE regex = new RE(s,RE.REG_ICASE);\r
+      haystack = regex.substituteAll(haystack,"");\r
+\r
+      // kill all the bad tags that are attributeless\r
+      regex = new RE("<\\s*/?\\s*(?!(("+approvedTags+")\\s*>))\\w+\\s*>",RE.REG_ICASE);\r
+      haystack = regex.substituteAll(haystack,"");\r
+\r
+      // kill all the tags which have a javascript attribute like onLoad\r
+      regex = new RE("<[^>]*("+badAttributes+")[^>]*>",RE.REG_ICASE);\r
+      haystack = regex.substituteAll(haystack,"");\r
+\r
+      // kill all the tags which include a url to an unacceptable protocol\r
+      regex = new RE("<\\s*a\\s+[^>]*href=(?!(\'|\")?("+approvedProtocols+"))[^>]*>",RE.REG_ICASE);\r
+      haystack = regex.substituteAll(haystack,"");\r
+\r
+      return haystack;\r
+    } catch(REException ex){\r
+      ex.printStackTrace();\r
+      return null;\r
+    }\r
+  }\r
+\r
+\r
+  /**\r
+   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht\r
+   *  htmlcodierten string auf und returnt einen htmlcodierten String\r
+   */\r
+  public static String createHTML(String content){\r
+    content=convertNewline2Break(content);\r
+    content=convertNewline2P(content);\r
+    content=createMailLinks(content);\r
+    content=createURLLinks(content);\r
+    return content;\r
+  }\r
+\r
+\r
+  /**\r
+   *  createHTML ruft alle regex-methoden zum unwandeln eines nicht\r
+   *  htmlcodierten string auf und returnt einen htmlcodierten String\r
+   */\r
+  public static String createHTML(String content,String producerDocRoot,String mailImage,String extImage,String intImage){\r
+    content=convertNewline2Break(content);\r
+    content=convertNewline2P(content);\r
+    content=createMailLinks(content,producerDocRoot,mailImage);\r
+    content=createURLLinks(content,null,producerDocRoot,extImage,intImage);\r
+    return content;\r
+  }\r
+\r
+  /**\r
+   * Converts mir's horrible internal date format (yyyy-MM-dd HH:mm:ss+zz) into a java Date\r
+   *\r
+   * @param anInternalDate\r
+   * @return\r
+   */\r
+  public static Date convertMirInternalDateToDate(String anInternalDate) {\r
+    Calendar calendar = new GregorianCalendar();\r
+\r
+    int year;\r
+    int month;\r
+    int day;\r
+    int hours;\r
+    int minutes;\r
+    int seconds;\r
+    int timezoneOffset;\r
+\r
+    year = Integer.parseInt(anInternalDate.substring(0,4));\r
+    month = Integer.parseInt(anInternalDate.substring(5,7));\r
+    day = Integer.parseInt(anInternalDate.substring(8,10));\r
+    hours = Integer.parseInt(anInternalDate.substring(11,13));\r
+    minutes = Integer.parseInt(anInternalDate.substring(14,16));\r
+    seconds = Integer.parseInt(anInternalDate.substring(17,19));\r
+\r
+    timezoneOffset = Integer.parseInt(anInternalDate.substring(20,22));\r
+    if (anInternalDate.charAt(19) == '-')\r
+      timezoneOffset = -timezoneOffset;\r
+\r
+    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));\r
+    calendar.set(year, month-1, day, hours, minutes, seconds);\r
+    calendar.add(Calendar.HOUR, -timezoneOffset);\r
+\r
+    return calendar.getTime();\r
+  }\r
+\r
+}\r
+\r
index ab2b583..7d0c5c5 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package  mir.module;
 
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.entity.EntityList;
+import java.util.Map;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityList;\r
 import mir.storage.StorageObject;
-import freemarker.template.SimpleHash;
 
 
 /**
@@ -233,14 +232,6 @@ public class AbstractModule {
   }
 
   /**
-   * Liefert den Lookuptable aller Objekte des StorageObjects
-   * @return freemarker.template.SimpleHash
-   */
-  public SimpleHash getHashData() {
-    return theStorage.getHashData();
-  }
-
-  /**
    * returns the number of rows
    */
   public int getSize(String where) throws ModuleExc, ModuleFailure {
index b643fa7..1aa17cd 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.producer;
@@ -40,6 +40,21 @@ import mir.entity.adapter.EntityIteratorAdapter;
 import mir.log.LoggerWrapper;
 import mir.util.ParameterExpander;
 
+/**
+ * <p>Title: EntityBatchingProducerNode</p>
+ * <p>Description:
+ *     This producer makes it possible to show articles in batches, like on archive
+ *     pages.
+ *
+ *     <emph> The order by clause should lead to a result set in <b>reverse order<b>:
+ *         the first row will be the last entity in the last batch
+ * </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
 public class EntityBatchingProducerNode implements ProducerNode {
   private String batchInfoKey;
   private String batchDataKey;
@@ -110,10 +125,6 @@ public class EntityBatchingProducerNode implements ProducerNode {
     int nrEntitiesPerBatch;
     int minNrEntitiesInFirstBatch;
 
-//  ML: The order by clause should lead to a result set in _reverse order_: the first row will be
-//      the last entity presented on the last page
-
-
     try {
       nrBatchesToProcess = ParameterExpander.evaluateIntegerExpressionWithDefault( aValueMap, nrBatchesToProcessExpression, -1 );
 
diff --git a/source/mir/producer/EntityDeletingProducerNode.java b/source/mir/producer/EntityDeletingProducerNode.java
new file mode 100755 (executable)
index 0000000..055e182
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.producer;
+
+import java.util.Map;
+import java.util.Vector;
+
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.util.CachingRewindableIterator;
+import mir.util.ParameterExpander;
+
+public class EntityDeletingProducerNode implements ProducerNode {
+  private String whereClause;
+  private EntityAdapterModel model;
+  private String definition;
+
+  public EntityDeletingProducerNode(EntityAdapterModel aModel, String aDefinition,
+      String aWhereClause) {
+    model = aModel;
+    definition = aDefinition;
+    whereClause = aWhereClause;
+  }
+
+  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
+    try {
+      EntityAdapterModel.Mapping mapping = model.getMappingForName(definition);
+
+      mapping.getStorage().deleteByWhereClause(ParameterExpander.expandExpression( aValueMap, whereClause ));
+    }
+    catch (Throwable t) {
+      aLogger.error("Error while deleting entities: " + t.toString());
+    }
+  };
+
+}
index 23ce108..295a63a 100755 (executable)
 
 package mir.producer;
 
-import java.io.PrintWriter;
-import java.util.Map;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.*;
 
+import mir.entity.Entity;
 import mir.entity.adapter.EntityAdapter;
+import mir.entity.adapter.EntityAdapterModel;
+import mir.log.LoggerWrapper;
 import mir.util.ParameterExpander;
+import mir.util.*;
 
 
-public abstract class EntityModifyingProducerNode implements ProducerNode {
-  String entityExpression;
-  String entityField;
-  String valueExpression;
+public class EntityModifyingProducerNode implements ProducerNode {
+  private String entityExpression;
+  private String definition;
+  private Map fields;
+  private boolean create;
+  private EntityAdapterModel model;
 
-  public EntityModifyingProducerNode(String anEntityExpression, String anEntityField, String aValueExpression) {
+  public EntityModifyingProducerNode(EntityAdapterModel aModel, boolean aCreate, String aDefinition, String anEntityExpression, Map aFieldValues) {
     entityExpression = anEntityExpression;
-    entityField = anEntityField;
-    valueExpression = aValueExpression;
+    definition = aDefinition;
+    create = aCreate;
+    model = aModel;
+    fields = new HashMap();
+    fields.putAll(aFieldValues);
   }
 
-  public void produce(Map aValueMap, String aVerb, PrintWriter aLogger) throws ProducerFailure {
-    Object entity;
+  public void addField(String aField, String aValueExpression) {
+    fields.put(aField, aValueExpression);
+  }
 
+  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerExc, ProducerFailure {
     try {
-      entity = ParameterExpander.findValueForKey( aValueMap, entityExpression );
+      Object entityAdapter;
+
+      if (create) {
+        entityAdapter = model.createNewEntity(definition);
+        ParameterExpander.setValueForKey(aValueMap, entityExpression, entityAdapter);
+      }
+      else {
+        entityAdapter = ParameterExpander.findValueForKey(aValueMap, entityExpression);
+      }
+
+      if (entityAdapter instanceof EntityAdapter) {
+        Entity entity = ((EntityAdapter) entityAdapter).getEntity();
+        Iterator i = fields.entrySet().iterator();
+        while (i.hasNext()) {
+          Map.Entry entry = (Map.Entry) i.next();
+          String entityField = (String) entry.getKey();
+          String valueExpression = (String) entry.getValue();
+
+          Object value = ParameterExpander.evaluateExpression(aValueMap, valueExpression);
+
+          if (value instanceof String)
+            entity.setValueForProperty(entityField, (String) value);
+          else if (value instanceof EntityAdapter)
+            entity.setValueForProperty(entityField, ((EntityAdapter) value).getEntity().getId());
+          else if (value instanceof Date) {
+            entity.setValueForProperty(entityField, JDBCStringRoutines.formatDate((Date) value));
+          }
+          else
+            aLogger.warn("Can't set value " + value + " for field " + entityField);
+        }
 
-      if (entity instanceof EntityAdapter) {
-        ((EntityAdapter) entity).getEntity().setValueForProperty(entityField, valueExpression);
-        ((EntityAdapter) entity).getEntity().update();
+        if (create)
+          entity.insert();
+        else
+          entity.update();
       }
       else
-        throw new Exception( entityExpression + " does not evaluate to an entity");
+        throw new ProducerExc( entityExpression + " does not evaluate to an entity");
     }
     catch (Throwable t) {
-      aLogger.println("Error while performing entity modifying operation: " + t.getMessage());
+      aLogger.error("Error while performing entity modification operation: " + t.getMessage());
+      t.printStackTrace(aLogger.asPrintWriter(aLogger.DEBUG_MESSAGE));
 
       throw new ProducerFailure(t.getMessage(), t);
     }
index 97b4072..94e6f42 100755 (executable)
@@ -40,6 +40,7 @@ public class FreeQueryProducerNode implements ProducerNode {
   public static final int QUERY_TYPE_SET = 1;
   public static final int QUERY_TYPE_ROW = 2;
   public static final int QUERY_TYPE_VALUE = 3;
+  public static final int QUERY_TYPE_UPDATE = 4;
 
   private Database database = new Database();
   private String key;
@@ -59,6 +60,9 @@ public class FreeQueryProducerNode implements ProducerNode {
 
     try {
       switch (type) {
+        case QUERY_TYPE_UPDATE:
+          result = new Integer(database.executeUpdate(ParameterExpander.expandExpression(aValueMap, query)));
+          break;
         case QUERY_TYPE_VALUE:
           result = database.executeFreeSingleValueSql(ParameterExpander.expandExpression(aValueMap, query));
           break;
diff --git a/source/mir/producer/ListEnumeratingProducerNode.java b/source/mir/producer/ListEnumeratingProducerNode.java
new file mode 100755 (executable)
index 0000000..6dc6d01
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.producer;
+
+import java.util.*;
+import java.util.Map;
+
+import mir.entity.adapter.EntityAdapterModel;
+import mir.entity.adapter.EntityIteratorAdapter;
+import mir.log.LoggerWrapper;
+import mir.util.*;
+
+public class ListEnumeratingProducerNode extends ProducerNodeDecorator {
+  private String key;
+  private String listExpression;
+
+  public ListEnumeratingProducerNode( String aKey, String aListExpression, ProducerNode aSubNode) {
+    super(aSubNode);
+
+    key = aKey;
+    listExpression = aListExpression;
+  }
+
+  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure, ProducerExc {
+    Iterator browser;
+    Object list;
+
+    try {
+      list = ParameterExpander.evaluateExpression(aValueMap, listExpression);
+      if (list != null) {
+        if (list instanceof Collection)
+          browser = ( (Collection) list).iterator();
+        else if (list instanceof Iterator)
+          browser = (Iterator) list;
+        else
+          throw new ProducerExc("Can't enumarate a " + list.getClass().getName());
+
+        if (browser instanceof RewindableIterator) {
+          ( (RewindableIterator) browser).rewind();
+        }
+
+        while (browser.hasNext() && !isAborted(aValueMap)) {
+          ParameterExpander.setValueForKey(aValueMap, key, browser.next());
+          super.produce(aValueMap, aVerb, aLogger);
+        }
+      }
+    }
+    catch (Throwable t) {
+      aLogger.error("Exception occurred inside an ListEnumeratingProducerNode: " + t.getMessage());
+    }
+  };
+}
index 8bf57cb..e4f3da1 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.producer;
@@ -47,10 +47,9 @@ public class NodedProducer implements Producer {
     verb = aVerb;
     baseValues = aBaseValues;
     isAborted = false;
-    isAborted = false;
   }
 
-  public void produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc {
+  public boolean produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc {
     Map valueMap;
 
     valueMap = new HashMap();
@@ -61,6 +60,7 @@ public class NodedProducer implements Producer {
 
     synchronized(this) {
       isFinished=true;
+      return !isAborted;
     }
   };
 
index 776049c..a7ffe93 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.producer;
@@ -32,6 +32,14 @@ package mir.producer;
 import mir.log.LoggerWrapper;
 
 public interface Producer {
-  public void produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc;
+  /**
+   *
+   *
+   * @param aLogger
+   * @return <code>false</code> if aborted,<code>true</code> if not
+   * @throws ProducerFailure
+   * @throws ProducerExc
+   */
+  public boolean produce( LoggerWrapper aLogger ) throws ProducerFailure, ProducerExc;
   public void abort();
 }
index ac41f28..6dae7c6 100755 (executable)
@@ -40,20 +40,31 @@ import mir.util.ParameterExpander;
 public class RSSProducerNode implements ProducerNode {
   private String key;
   private String url;
+  private String version;
 
-  public RSSProducerNode(String aKey, String anURL) {
+  public RSSProducerNode(String aKey, String anURL, String aVersion) {
     key = aKey;
     url = anURL;
+    version = aVersion;
   }
 
   public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
     try {
+      RSSData rssData = null;
       String expandedKey = ParameterExpander.expandExpression( aValueMap, key );
       String expandedUrl = ParameterExpander.expandExpression( aValueMap, url );
+      String expandedVersion = ParameterExpander.expandExpression( aValueMap, version );
 
       ParameterExpander.setValueForKey(aValueMap, expandedKey, null);
-      RSSReader reader = new RSSReader();
-      RSSData rssData = reader.parseUrl(expandedUrl);
+
+      if (version.equals("1.0")) {
+        RSSReader reader = new RSSReader();
+        rssData = reader.parseUrl(expandedUrl);
+      }
+      else if (version.equals("0.91")) {
+        RSS091Reader reader = new RSS091Reader();
+        rssData = reader.parseUrl(expandedUrl);
+      }
       ParameterExpander.setValueForKey(aValueMap, expandedKey, rssData);
     }
     catch (Throwable t) {
index b458fed..90bef9d 100755 (executable)
@@ -43,17 +43,22 @@ import mir.log.LoggerWrapper;
 import mir.producer.ConditionalProducerNode;
 import mir.producer.DirCopyingProducerNode;
 import mir.producer.EntityBatchingProducerNode;
+import mir.producer.EntityDeletingProducerNode;
 import mir.producer.EntityEnumeratingProducerNode;
 import mir.producer.EntityListProducerNode;
+import mir.producer.EntityModifyingProducerNode;
 import mir.producer.EvaluatedAssignmentProducerNode;
 import mir.producer.ExpandedAssignmentProducerNode;
 import mir.producer.FileDateSettingProducerNode;
 import mir.producer.FileDeletingProducerNode;
+import mir.producer.FreeQueryProducerNode;
 import mir.producer.GeneratingProducerNode;
+import mir.producer.ListEnumeratingProducerNode;
 import mir.producer.LoggingProducerNode;
 import mir.producer.LoopProducerNode;
 import mir.producer.ProducerNode;
-import mir.producer.*;
+import mir.producer.RDFAggregatorProducerNode;
+import mir.producer.RSSProducerNode;
 import mir.producer.ResourceBundleProducerNode;
 import mir.producer.ScriptCallingProducerNode;
 import mir.util.XMLReader;
@@ -86,6 +91,10 @@ public class DefaultProducerNodeBuilders {
     aBuilderLibrary.registerFactory("List", new ListProducerNodeBuilder.factory(aModel));
     aBuilderLibrary.registerFactory("Batch", new BatchingProducerNodeBuilder.factory(aModel));
 
+    aBuilderLibrary.registerFactory("UpdateEntity", new UpdateEntityProducerNodeBuilder.factory(aModel));
+    aBuilderLibrary.registerFactory("CreateEntity", new CreateEntityProducerNodeBuilder.factory(aModel));
+    aBuilderLibrary.registerFactory("DeleteEntity", new DeleteEntityProducerNodeBuilder.factory(aModel));
+
     aBuilderLibrary.registerFactory("Generate",
         new GeneratingProducerNodeBuilder.factory(aGeneratorLibrary, aWriterEngine));
   }
@@ -184,17 +193,21 @@ public class DefaultProducerNodeBuilders {
   public static class EnumeratingProducerNodeBuilder extends AbstractProducerNodeBuilder {
     private final static String   ENUMERATION_KEY_ATTRIBUTE = KEY_ATTRIBUTE;
     private final static String   ENUMERATION_DEFINITION_ATTRIBUTE = DEFINITION_ATTRIBUTE;
+    private final static String   ENUMERATION_LIST_ATTRIBUTE = "list";
     private final static String   ENUMERATION_SELECTION_ATTRIBUTE = SELECTION_ATTRIBUTE;
     private final static String   ENUMERATION_ORDER_ATTRIBUTE = ORDER_ATTRIBUTE;
     private final static String   ENUMERATION_DEFAULT_SUBNODE = "default";
     private final static String   ENUMERATION_LIMIT_ATTRIBUTE = LIMIT_ATTRIBUTE;
     private final static String   ENUMERATION_SKIP_ATTRIBUTE = SKIP_ATTRIBUTE;
-    private final static String[] ENUMERATION_REQUIRED_ATTRIBUTES = { ENUMERATION_KEY_ATTRIBUTE, ENUMERATION_DEFINITION_ATTRIBUTE };
-    private final static String[] ENUMERATION_OPTIONAL_ATTRIBUTES = { ENUMERATION_SELECTION_ATTRIBUTE, ENUMERATION_ORDER_ATTRIBUTE, ENUMERATION_LIMIT_ATTRIBUTE, ENUMERATION_SKIP_ATTRIBUTE};
+    private final static String[] ENUMERATION_LIST_REQUIRED_ATTRIBUTES = { ENUMERATION_LIST_ATTRIBUTE, ENUMERATION_KEY_ATTRIBUTE };
+    private final static String[] ENUMERATION_LIST_OPTIONAL_ATTRIBUTES = { };
+    private final static String[] ENUMERATION_QUERY_REQUIRED_ATTRIBUTES = { ENUMERATION_DEFINITION_ATTRIBUTE, ENUMERATION_KEY_ATTRIBUTE };
+    private final static String[] ENUMERATION_QUERY_OPTIONAL_ATTRIBUTES = { ENUMERATION_SELECTION_ATTRIBUTE, ENUMERATION_ORDER_ATTRIBUTE, ENUMERATION_LIMIT_ATTRIBUTE, ENUMERATION_SKIP_ATTRIBUTE};
     private final static String[] ENUMERATION_SUBNODES = {ENUMERATION_DEFAULT_SUBNODE};
 
     private String key;
     private String definition;
+    private String list;
     private String selection;
     private String order;
     private String limit;
@@ -208,10 +221,20 @@ public class DefaultProducerNodeBuilders {
     }
 
     public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc  {
-      XMLReaderTool.checkAttributes(anAttributes, ENUMERATION_REQUIRED_ATTRIBUTES, ENUMERATION_OPTIONAL_ATTRIBUTES);
+      definition = (String) anAttributes.get(ENUMERATION_DEFINITION_ATTRIBUTE);
+      list = (String) anAttributes.get(ENUMERATION_LIST_ATTRIBUTE);
+
+      if ((list==null && definition==null) || (list!=null && definition!=null))
+        throw new ProducerConfigExc("Exactly one of "+ENUMERATION_DEFINITION_ATTRIBUTE+" and "+ENUMERATION_LIST_ATTRIBUTE+" must be set");
+
+
+      if (list!=null)
+        XMLReaderTool.checkAttributes(anAttributes, ENUMERATION_LIST_REQUIRED_ATTRIBUTES, ENUMERATION_LIST_OPTIONAL_ATTRIBUTES);
+      if (definition!=null)
+        XMLReaderTool.checkAttributes(anAttributes, ENUMERATION_QUERY_REQUIRED_ATTRIBUTES, ENUMERATION_QUERY_OPTIONAL_ATTRIBUTES);
+
 
       key = (String) anAttributes.get(ENUMERATION_KEY_ATTRIBUTE);
-      definition = (String) anAttributes.get(ENUMERATION_DEFINITION_ATTRIBUTE);
       selection = (String) XMLReaderTool.getStringAttributeWithDefault(anAttributes, ENUMERATION_SELECTION_ATTRIBUTE, "");
       order = (String) XMLReaderTool.getStringAttributeWithDefault(anAttributes, ENUMERATION_ORDER_ATTRIBUTE, "");
       limit = (String) anAttributes.get(ENUMERATION_LIMIT_ATTRIBUTE);
@@ -219,7 +242,10 @@ public class DefaultProducerNodeBuilders {
     };
 
     public ProducerNode constructNode() {
-      return new EntityEnumeratingProducerNode(key, model, definition, selection, order, limit, skip, getSubNode(ENUMERATION_DEFAULT_SUBNODE ));
+      if (definition!=null)
+        return new EntityEnumeratingProducerNode(key, model, definition, selection, order, limit, skip, getSubNode(ENUMERATION_DEFAULT_SUBNODE ));
+      else
+        return new ListEnumeratingProducerNode(key, list, getSubNode(ENUMERATION_DEFAULT_SUBNODE ));
     };
 
     public static class factory implements ProducerNodeBuilderFactory {
@@ -237,6 +263,106 @@ public class DefaultProducerNodeBuilders {
 
 ////////////////////////////////////////////////////////////////////////////////
 
+  public static class UpdateEntityProducerNodeBuilder extends AbstractProducerNodeBuilder {
+    private final static String   UPDATE_KEY_ATTRIBUTE = KEY_ATTRIBUTE;
+    private final static String   UPDATE_DEFINITION_ATTRIBUTE = DEFINITION_ATTRIBUTE;
+    private final static String[] UPDATE_SUBNODES = {};
+
+    private String key;
+    private String definition;
+    private Map fieldValues;
+
+    private EntityAdapterModel model;
+
+    public UpdateEntityProducerNodeBuilder(EntityAdapterModel aModel) {
+      super(UPDATE_SUBNODES);
+
+      model = aModel;
+      fieldValues = new HashMap();
+    }
+
+    public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc  {
+      key = (String) anAttributes.get(UPDATE_KEY_ATTRIBUTE);
+
+      if (key == null)
+        throw new XMLReader.XMLReaderExc("missing required attribute '" + UPDATE_KEY_ATTRIBUTE + "'" );
+      definition = (String) anAttributes.get(UPDATE_DEFINITION_ATTRIBUTE);
+
+      fieldValues.putAll(anAttributes);
+      fieldValues.remove(UPDATE_KEY_ATTRIBUTE);
+      fieldValues.remove(UPDATE_DEFINITION_ATTRIBUTE);
+    };
+
+    public ProducerNode constructNode() {
+      return new EntityModifyingProducerNode(model, false, definition, key, fieldValues);
+    };
+
+    public static class factory implements ProducerNodeBuilderFactory {
+      private EntityAdapterModel model;
+
+      public factory(EntityAdapterModel aModel) {
+        model = aModel;
+      }
+
+      public ProducerNodeBuilder makeBuilder() {
+        return new UpdateEntityProducerNodeBuilder(model);
+      }
+    }
+  }
+
+////////////////////////////////////////////////////////////////////////////////
+
+  public static class CreateEntityProducerNodeBuilder extends AbstractProducerNodeBuilder {
+    private final static String   CREATEENTITY_KEY_ATTRIBUTE = KEY_ATTRIBUTE;
+    private final static String   CREATEENTITY_DEFINITION_ATTRIBUTE = DEFINITION_ATTRIBUTE;
+    private final static String[] CREATEENTITY_SUBNODES = {};
+
+    private String key;
+    private String definition;
+    private Map fieldValues;
+
+    private EntityAdapterModel model;
+
+    public CreateEntityProducerNodeBuilder(EntityAdapterModel aModel) {
+      super(CREATEENTITY_SUBNODES);
+
+      model = aModel;
+      fieldValues = new HashMap();
+    }
+
+    public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc  {
+      key = (String) anAttributes.get(CREATEENTITY_KEY_ATTRIBUTE);
+      definition = (String) anAttributes.get(CREATEENTITY_DEFINITION_ATTRIBUTE);
+
+      if (key == null)
+        throw new XMLReader.XMLReaderExc("missing required attribute '" + CREATEENTITY_KEY_ATTRIBUTE + "'" );
+      if (definition == null)
+        throw new XMLReader.XMLReaderExc("missing required attribute '" + CREATEENTITY_DEFINITION_ATTRIBUTE + "'" );
+
+      fieldValues.putAll(anAttributes);
+      fieldValues.remove(CREATEENTITY_KEY_ATTRIBUTE);
+      fieldValues.remove(CREATEENTITY_DEFINITION_ATTRIBUTE);
+    };
+
+    public ProducerNode constructNode() {
+      return new EntityModifyingProducerNode(model, true, definition, key, fieldValues);
+    };
+
+    public static class factory implements ProducerNodeBuilderFactory {
+      private EntityAdapterModel model;
+
+      public factory(EntityAdapterModel aModel) {
+        model = aModel;
+      }
+
+      public ProducerNodeBuilder makeBuilder() {
+        return new CreateEntityProducerNodeBuilder(model);
+      }
+    }
+  }
+
+////////////////////////////////////////////////////////////////////////////////
+
   public static class LoopProducerNodeBuilder extends AbstractProducerNodeBuilder {
     private final static String   LOOP_CONDITION_ATTRIBUTE = "condition";
     private final static String   LOOP_LIMIT_ATTRIBUTE = LIMIT_ATTRIBUTE;
@@ -322,6 +448,50 @@ public class DefaultProducerNodeBuilders {
 
 ////////////////////////////////////////////////////////////////////////////////
 
+  public static class DeleteEntityProducerNodeBuilder extends AbstractProducerNodeBuilder {
+    private final static String   DELETEENTITY_DEFINITION_ATTRIBUTE = DEFINITION_ATTRIBUTE;
+    private final static String   DELETEENTITY_SELECTION_ATTRIBUTE = SELECTION_ATTRIBUTE;
+    private final static String[] DELETEENTITY_REQUIRED_ATTRIBUTES = { DELETEENTITY_SELECTION_ATTRIBUTE, DELETEENTITY_DEFINITION_ATTRIBUTE };
+    private final static String[] DELETEENTITY_OPTIONAL_ATTRIBUTES = { };
+    private final static String[] DELETEENTITY_SUBNODES = {};
+
+    private String definition;
+    private String selection;
+
+    private EntityAdapterModel model;
+
+    public DeleteEntityProducerNodeBuilder(EntityAdapterModel aModel) {
+      super(DELETEENTITY_SUBNODES);
+
+      model = aModel;
+    }
+
+    public void setAttributes(Map anAttributes) throws ProducerConfigExc, XMLReader.XMLReaderExc {
+      XMLReaderTool.checkAttributes(anAttributes, DELETEENTITY_REQUIRED_ATTRIBUTES, DELETEENTITY_OPTIONAL_ATTRIBUTES);
+
+      definition = (String) anAttributes.get(DELETEENTITY_DEFINITION_ATTRIBUTE);
+      selection = (String) XMLReaderTool.getStringAttributeWithDefault(anAttributes, DELETEENTITY_SELECTION_ATTRIBUTE, "");
+    };
+
+    public ProducerNode constructNode() {
+      return new EntityDeletingProducerNode(model, definition, selection);
+    };
+
+    public static class factory implements ProducerNodeBuilderFactory {
+      private EntityAdapterModel model;
+
+      public factory(EntityAdapterModel aModel) {
+        model = aModel;
+      }
+
+      public ProducerNodeBuilder makeBuilder() {
+        return new DeleteEntityProducerNodeBuilder(model);
+      }
+    }
+  }
+
+////////////////////////////////////////////////////////////////////////////////
+
   public static class LoggingProducerNodeBuilder extends AbstractProducerNodeBuilder {
     private final static String   LOG_MESSAGE_ATTRIBUTE = "message";
     private final static String   LOG_TYPE_ATTRIBUTE = "type";
@@ -405,6 +575,8 @@ public class DefaultProducerNodeBuilders {
           type = FreeQueryProducerNode.QUERY_TYPE_ROW;
         else if (typeString.toLowerCase().equals("value"))
           type = FreeQueryProducerNode.QUERY_TYPE_VALUE;
+        else if (typeString.toLowerCase().equals("update"))
+          type = FreeQueryProducerNode.QUERY_TYPE_UPDATE;
         else
           throw new ProducerConfigExc("unknown query type: " + typeString + " (allowed are set, row and value)");
       }
@@ -646,8 +818,6 @@ public class DefaultProducerNodeBuilders {
     private final static String[] BATCHER_OPTIONAL_ATTRIBUTES = { BATCHER_SELECTION_ATTRIBUTE, BATCHER_ORDER_ATTRIBUTE, BATCHER_MINBATCHSIZE_ATTRIBUTE, BATCHER_SKIP_ATTRIBUTE, BATCHER_PROCESS_ATTRIBUTE };
     private final static String[] BATCHER_SUBNODES = { BATCHER_BATCH_SUBNODE, BATCHER_BATCHLIST_SUBNODE };
 
-    // ML: batchSize, minBatchSize, skip should be expressions!
-
     private EntityAdapterModel model;
     private String batchDataKey;
     private String batchInfoKey;
@@ -748,13 +918,15 @@ public class DefaultProducerNodeBuilders {
   public static class RSSProducerNodeBuilder extends AbstractProducerNodeBuilder {
     private final static String   RSS_KEY_ATTRIBUTE = KEY_ATTRIBUTE;
     private final static String   RSS_URL_ATTRIBUTE = URL_ATTRIBUTE;
+    private final static String   RSS_VERSION_ATTRIBUTE = "version";
 
     private final static String[] RSS_REQUIRED_ATTRIBUTES = { RSS_KEY_ATTRIBUTE, RSS_URL_ATTRIBUTE };
-    private final static String[] RSS_OPTIONAL_ATTRIBUTES = {  };
+    private final static String[] RSS_OPTIONAL_ATTRIBUTES = { RSS_VERSION_ATTRIBUTE };
     private final static String[] RSS_SUBNODES = {  };
 
     private String key;
     private String url;
+    private String version;
 
     public RSSProducerNodeBuilder() {
       super(RSS_SUBNODES);
@@ -765,10 +937,11 @@ public class DefaultProducerNodeBuilders {
 
       key = (String) anAttributes.get( RSS_KEY_ATTRIBUTE );
       url = (String) anAttributes.get( RSS_URL_ATTRIBUTE );
+      version = XMLReaderTool.getStringAttributeWithDefault(anAttributes, RSS_VERSION_ATTRIBUTE, "1.0");
     };
 
     public ProducerNode constructNode() {
-      return new RSSProducerNode(key, url);
+      return new RSSProducerNode(key, url, version);
     };
   }
 
index 2de7d06..dd91805 100755 (executable)
@@ -43,7 +43,7 @@ import mir.producer.ProducerFactory;
 import mir.producer.ProducerNode;
 import mir.producer.SimpleProducerVerb;
 import mir.util.XMLReader;
-import mir.util.XMLReaderTool;
+import mir.util.*;
 
 public class ProducerConfigReader {
   private ProducerNodeBuilderLibrary builderLibrary;
@@ -69,11 +69,13 @@ public class ProducerConfigReader {
 
     }
     catch (Throwable e) {
-      if ((e instanceof XMLReader.XMLReaderExc) && ((XMLReader.XMLReaderExc) e).getHasLocation()) {
-        XMLReader.XMLReaderExc f = (XMLReader.XMLReaderExc) e;
+      Throwable root = ExceptionFunctions.traceCauseException(e);
+
+      if ((root instanceof XMLReader.XMLReaderExc) && ((XMLReader.XMLReaderExc) root).getHasLocation()) {
+        XMLReader.XMLReaderExc f = (XMLReader.XMLReaderExc) root;
         throw new ProducerConfigFailure("'" + f.getMessage()+"' in " + f.getFilename()+"(line " + f.getLineNr()+", column " + f.getColumnNr() + ")", e);
       }
-      throw new ProducerConfigFailure( e );
+      throw new ProducerConfigFailure(root);
     }
   }
 
@@ -409,8 +411,7 @@ public class ProducerConfigReader {
           }
         }
         else
-          throw new XMLReader.XMLReaderExc("Unknown producer node tag: '" +
-                                           aTag + "'");
+          throw new XMLReader.XMLReaderExc("Unknown producer node tag: '" + aTag + "'");
       }
       catch (Throwable t) {
         throw new XMLReader.XMLReaderFailure(t);
index 254f099..b0c68a9 100755 (executable)
@@ -29,7 +29,8 @@
  */
 package mir.rss;
 
-import java.util.*;
+import java.util.HashMap;\r
+import java.util.Map;
 
 public class RDFResource {
   private String identifier;
@@ -50,6 +51,10 @@ public class RDFResource {
     return identifier;
   }
 
+  public void setIdentifier(String aNewValue) {
+    identifier = aNewValue;
+  }
+
   public String getRdfClass() {
     return rdfClass;
   }
@@ -63,6 +68,6 @@ public class RDFResource {
   }
 
   public String toString() {
-    return rdfClass + " ("+identifier+")";
+    return rdfClass + " ("+identifier+") + ["+properties+"]";
   }
 }
\ No newline at end of file
diff --git a/source/mir/rss/RSS091Reader.java b/source/mir/rss/RSS091Reader.java
new file mode 100755 (executable)
index 0000000..85fd95c
--- /dev/null
@@ -0,0 +1,337 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.rss;
+
+import java.io.InputStream;
+import java.net.URL;
+import java.util.List;
+import java.util.*;
+import java.util.Vector;
+import java.text.*;
+
+import mir.util.XMLReader;
+import mir.util.*;
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+
+public class RSS091Reader {
+  private final static String MAPPED_CHANNEL_PROPERTIES[][]  =
+     {
+       {"link",        "rss:link"        },
+       {"title",       "rss:title"       },
+       {"description", "rss:description" },
+       {"item",        "rss:item" },
+       {"language",    "dc:language" }
+     };
+
+  private final static String MAPPED_ITEM_PROPERTIES[][]  =
+    {
+      {"link",        "rss:link"        },
+      {"title",       "rss:title"       },
+      {"description", "rss:description" },
+      {"author",      "dc:creator" },
+    };
+
+  private Map mappedChannelProperties = new HashMap();
+  private Map mappedItemProperties = new HashMap();
+
+  public RSS091Reader() {
+    int i;
+
+    for (i=0; i<MAPPED_CHANNEL_PROPERTIES.length; i++) {
+      mappedChannelProperties.put(MAPPED_CHANNEL_PROPERTIES[i][0], MAPPED_CHANNEL_PROPERTIES[i][1]);
+    }
+
+    for (i=0; i<MAPPED_ITEM_PROPERTIES.length; i++) {
+      mappedItemProperties.put(MAPPED_ITEM_PROPERTIES[i][0], MAPPED_ITEM_PROPERTIES[i][1]);
+    }
+  }
+
+  public RSSData parseInputStream(InputStream aStream) throws RSSExc, RSSFailure {
+    try {
+      XMLReader xmlReader = new XMLReader(false);
+      RSSData result = new RSSData();
+      xmlReader.parseInputStream(aStream, new RootSectionHandler(result));
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new RSSFailure(t);
+    }
+  }
+
+  public RSSData parseUrl(String anUrl) throws RSSExc, RSSFailure {
+    try {
+      InputStream inputStream = (InputStream) new URL(anUrl).getContent(new Class[] {InputStream.class});
+
+      if (inputStream==null)
+        throw new RSSExc("RSSChannel.parseUrl: Can't get url content");
+
+      return parseInputStream(inputStream);
+    }
+    catch (Throwable t) {
+      throw new RSSFailure(t);
+    }
+  }
+
+  private class RootSectionHandler extends XMLReader.AbstractSectionHandler {
+    private RSSData data;
+
+    public RootSectionHandler(RSSData aData) {
+      data = aData;
+    }
+
+    public XMLReader.SectionHandler startElement(XMLReader.XMLName aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      if (aTag.getLocalName().equals("rss")) {
+        return new RSS091SectionHandler(data);
+      }
+      else
+        throw new XMLReader.XMLReaderFailure(new RSSExc("'rss' tag expected"));
+    };
+
+    public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+      if (aCharacters.trim().length()>0)
+        throw new XMLReader.XMLReaderExc("No character data allowed here");
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+    };
+  }
+
+  private class RSS091SectionHandler extends XMLReader.AbstractSectionHandler {
+    private RSSData data;
+
+
+    public RSS091SectionHandler(RSSData aData) {
+      data = aData;
+    }
+
+    public XMLReader.SectionHandler startElement(XMLReader.XMLName aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      if (aTag.getLocalName().equals("channel"))
+        return new RSS091ChannelSectionHandler(data);
+      else
+        throw new XMLReader.XMLReaderExc("channel tag expected, " + aTag.getLocalName() + " found");
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+      if (aCharacters.trim().length()>0)
+        throw new XMLReader.XMLReaderExc("No character data allowed here");
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+    };
+  }
+
+  private class RSS091ChannelSectionHandler extends XMLReader.AbstractSectionHandler {
+    private String currentTag;
+
+    private RSSData data;
+    private List items;
+    private RDFResource channel;
+    private Map attributes;
+
+    public RSS091ChannelSectionHandler(RSSData aData) {
+      data = aData;
+      items = new Vector();
+      channel = new RDFResource("rss:channel");
+      attributes = new HashMap();
+    }
+
+    public XMLReader.SectionHandler startElement(XMLReader.XMLName aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      String tag = aTag.getLocalName();
+
+      if (tag.equals("item"))
+        return new RSS091ItemSectionHandler();
+      else if (mappedChannelProperties.containsKey(tag)) {
+        currentTag=(String) mappedChannelProperties.get(tag);
+        return new PCDATASectionHandler();
+      }
+      else
+        return new DiscardingSectionHandler();
+    };
+
+    public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
+      if (aHandler instanceof PCDATASectionHandler) {
+        attributes.put(currentTag, (((PCDATASectionHandler) aHandler).getData()));
+      }
+      else if (aHandler instanceof RSS091ItemSectionHandler) {
+        items.add((((RSS091ItemSectionHandler) aHandler).getItem()));
+      }
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+      if (aCharacters.trim().length()>0)
+        throw new XMLReader.XMLReaderExc("No character data allowed here");
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+      Iterator i = items.iterator();
+
+      while (i.hasNext()) {
+        data.addResource((RDFResource) i.next());
+      }
+    };
+  }
+
+  private class RSS091ItemSectionHandler extends XMLReader.AbstractSectionHandler {
+    private String currentTag;
+
+    private RDFResource item;
+    private Map attributes;
+
+    public RSS091ItemSectionHandler() {
+      attributes = new HashMap();
+    }
+
+    public XMLReader.SectionHandler startElement(XMLReader.XMLName aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      String tag = aTag.getLocalName();
+      System.out.println(tag);
+
+      if (mappedItemProperties.containsKey(tag)) {
+        currentTag=(String) mappedItemProperties.get(tag);
+        return new PCDATASectionHandler();
+      }
+      else
+        return new DiscardingSectionHandler();
+    };
+
+    public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
+      if (aHandler instanceof PCDATASectionHandler) {
+        attributes.put(currentTag, (((PCDATASectionHandler) aHandler).getData()));
+      }
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+      if (aCharacters.trim().length()>0)
+        throw new XMLReader.XMLReaderExc("No character data allowed here");
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+      item = new RDFResource("rss:item", (String) attributes.get("rss:link"));
+
+      Iterator i = attributes.entrySet().iterator();
+      while (i.hasNext()) {
+        Map.Entry entry = (Map.Entry) i.next();
+
+        item.set((String) entry.getKey(), entry.getValue());
+      }
+    };
+
+    public RDFResource getItem() {
+      return item;
+    }
+  }
+
+
+  private class PCDATASectionHandler extends XMLReader.AbstractSectionHandler {
+    private StringBuffer data;
+
+    public PCDATASectionHandler() {
+      data = new StringBuffer();
+    }
+
+    public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      throw new XMLReader.XMLReaderFailure(new RSSExc("No subtags allowed here"));
+    };
+
+    public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+      data.append(aCharacters);
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+    };
+
+    public String getData() {
+      return data.toString();
+    }
+  }
+
+
+  private class RDFSequenceSectionHandler extends XMLReader.AbstractSectionHandler {
+    private List items;
+
+    public RDFSequenceSectionHandler() {
+      items = new Vector();
+    }
+
+    public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      if (aTag.equals("rdf:li")) {
+        String item = (String) anAttributes.get("rdf:resource");
+
+        if (item!=null)
+          items.add(item);
+      }
+
+      return new DiscardingSectionHandler();
+    };
+
+    public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+    };
+
+    public List getItems() {
+      return items;
+    }
+  }
+
+  private class DiscardingSectionHandler extends XMLReader.AbstractSectionHandler {
+    public XMLReader.SectionHandler startElement(String aTag, Map anAttributes) throws XMLReader.XMLReaderExc {
+      return this;
+    };
+
+    public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
+    };
+
+    public void characters(String aCharacters) throws XMLReader.XMLReaderExc {
+    };
+
+    public void finishSection() throws XMLReader.XMLReaderExc {
+    };
+  }
+}
index 326e583..bdc6ae0 100755 (executable)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2001, 2002  The Mir-coders group
+ * Copyright (C) 2001, 2002 The Mir-coders group
  *
  * This file is part of Mir.
  *
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
  */
 
 package mir.rss;
index 550993a..ed03310 100755 (executable)
@@ -58,16 +58,22 @@ public class RSSBasicModule implements RSSModule {
   }
 
   public void addProperty(String aName, int aType) {
-    properties.put(aName, new RSSBasicModuleProperty(aName, aType));
+    properties.put(aName, new RSSBasicModuleProperty(aName, aType, false));
+  }
+
+  public void addMultiValuedProperty(String aName, int aType) {
+    properties.put(aName, new RSSBasicModuleProperty(aName, aType, true));
   }
 
   private class RSSBasicModuleProperty implements RSSModuleProperty {
     private String name;
     private int type;
+    private boolean multivalued;
 
-    public RSSBasicModuleProperty(String aName, int aType) {
+    public RSSBasicModuleProperty(String aName, int aType, boolean aMultiValued) {
       name = aName;
       type = aType;
+      multivalued = aMultiValued;
     }
 
     public String getName() {
@@ -77,5 +83,10 @@ public class RSSBasicModule implements RSSModule {
     public int getType() {
       return type;
     }
+
+    public boolean getIsMultiValued() {
+      return multivalued;
+    }
+
   }
 }
\ No newline at end of file
index eab7052..9eeb722 100755 (executable)
@@ -39,6 +39,7 @@ public interface RSSModule {
   public interface RSSModuleProperty {
     String getName();
     int getType();
+    boolean getIsMultiValued();
   }
 
   public String getNamespaceURI();
index 82a9a30..bdc850b 100755 (executable)
@@ -31,13 +31,13 @@ package mir.rss;
 
 import java.io.InputStream;
 import java.net.URL;
+import java.util.HashMap;
 import java.util.List;
-import java.util.*;
+import java.util.Map;
 import java.util.Vector;
-import java.text.*;
 
+import mir.util.DateTimeFunctions;
 import mir.util.XMLReader;
-import mir.util.*;
 
 /**
  *
@@ -50,11 +50,17 @@ import mir.util.*;
  */
 
 public class RSSReader {
-  private static final String RDF_NAMESPACE_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
-  private static final String RSS_1_0_NAMESPACE_URI = "http://purl.org/rss/1.0/";
-  private static final String DUBLINCORE_NAMESPACE_URI = "http://purl.org/dc/elements/1.1/";
-  private static final String EVENT_NAMESPACE_URI = "http://purl.org/rss/1.0/modules/event/";
-  private static final String TAXONOMY_NAMESPACE_URI = "http://web.resource.org/rss/1.0/modules/taxonomy/";
+  public static final String RDF_NAMESPACE_URI = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
+  public static final String RSS_1_0_NAMESPACE_URI = "http://purl.org/rss/1.0/";
+  public static final String RSS_0_9_NAMESPACE_URI = "http://my.netscape.com/rdf/simple/0.9/";
+  public static final String DUBLINCORE_NAMESPACE_URI = "http://purl.org/dc/elements/1.1/";
+  public static final String EVENT_NAMESPACE_URI = "http://purl.org/rss/1.0/modules/event/";
+  public static final String TAXONOMY_NAMESPACE_URI = "http://web.resource.org/rss/1.0/modules/taxonomy/";
+  public static final String DUBLINCORE_TERMS_NAMESPACE_URI = "http://purl.org/dc/terms/";
+  public static final String CONTENT_NAMESPACE_URI = "http://purl.org/rss/1.0/modules/content/";
+
+  // ML: to be localized:
+  public static final String V2V_NAMESPACE_URI = "http://v2v.indymedia.de/rss/";
 
   private static final XMLReader.XMLName RDF_ABOUT_PARAMETER = new XMLReader.XMLName(RDF_NAMESPACE_URI, "about");
   private static final XMLReader.XMLName RDF_SEQUENCE_TAG = new XMLReader.XMLName(RDF_NAMESPACE_URI, "Seq");
@@ -67,7 +73,6 @@ public class RSSReader {
   private List modules;
   private Map namespaceURItoModule;
   private Map moduleToPrefix;
-  private RSSModule rdfModule;
 
   public RSSReader() {
     modules = new Vector();
@@ -76,13 +81,30 @@ public class RSSReader {
 
     registerModule(new RSSBasicModule(RDF_NAMESPACE_URI, "RDF module"), "rdf");
     registerModule(new RSSBasicModule(RSS_1_0_NAMESPACE_URI, "RSS 1.0 module"), "rss");
+    registerModule(new RSSBasicModule(RSS_0_9_NAMESPACE_URI, "RSS 0.9 module"), "rss");
 
-    RSSBasicModule dcModule = new RSSBasicModule(DUBLINCORE_NAMESPACE_URI, "Dublin Core RSS module 1.1");
-    dcModule.addProperty("date", RSSBasicModule.W3CDTF_PROPERTY_TYPE);
+    RSSBasicModule dcModule = new RSSBasicModule(DUBLINCORE_NAMESPACE_URI, "RSS Dublin Core 1.1");
+    dcModule.addProperty("date", RSSModule.W3CDTF_PROPERTY_TYPE);
     registerModule(dcModule, "dc");
 
+    RSSBasicModule dcTermsModule = new RSSBasicModule(DUBLINCORE_TERMS_NAMESPACE_URI, "RSS Qualified Dublin core");
+    dcTermsModule.addProperty("created", RSSModule.W3CDTF_PROPERTY_TYPE);
+    dcTermsModule.addProperty("issued", RSSModule.W3CDTF_PROPERTY_TYPE);
+    dcTermsModule.addProperty("modified", RSSModule.W3CDTF_PROPERTY_TYPE);
+    dcTermsModule.addProperty("dateAccepted", RSSModule.W3CDTF_PROPERTY_TYPE);
+    dcTermsModule.addProperty("dateCopyrighted", RSSModule.W3CDTF_PROPERTY_TYPE);
+    dcTermsModule.addProperty("dateSubmitted", RSSModule.W3CDTF_PROPERTY_TYPE);
+    registerModule(dcTermsModule, "dcterms");
+
+    RSSBasicModule v2vTermsModule = new RSSBasicModule(V2V_NAMESPACE_URI, "indymedia v2v RSS module");
+    v2vTermsModule.addMultiValuedProperty("topic", RSSModule.PCDATA_PROPERTY_TYPE);
+    v2vTermsModule.addMultiValuedProperty("genre", RSSModule.PCDATA_PROPERTY_TYPE);
+    v2vTermsModule.addMultiValuedProperty("link", RSSModule.PCDATA_PROPERTY_TYPE);
+    registerModule(v2vTermsModule, "v2v");
+
     registerModule(new RSSBasicModule(EVENT_NAMESPACE_URI, "Event RSS module"), "ev");
     registerModule(new RSSBasicModule(TAXONOMY_NAMESPACE_URI, "Taxonomy RSS module"), "taxo");
+    registerModule(new RSSBasicModule(CONTENT_NAMESPACE_URI  , "Content RSS module"), "content");
   }
 
   public void registerModule(RSSModule aModule, String aPrefix) {
@@ -178,10 +200,6 @@ public class RSSReader {
   private XMLReader.SectionHandler makePropertyValueSectionHandler(XMLReader.XMLName aTag, Map anAttributes) {
     RSSModule module = (RSSModule) namespaceURItoModule.get(aTag.getNamespaceURI());
 
-    if (aTag.getLocalName().equals("date"))
-      aTag = aTag;
-
-
     if (module!=null) {
       RSSModule.RSSModuleProperty property = module.getPropertyForName(aTag.getLocalName());
 
@@ -201,12 +219,34 @@ public class RSSReader {
               return new DateSectionHandler();
         }
       }
-
     }
 
     return new FlexiblePropertyValueSectionHandler();
   }
 
+  private void usePropertyValueSectionHandler(RDFResource aResource, PropertyValueSectionHandler aHandler, XMLReader.XMLName aTag) {
+    RSSModule module = (RSSModule) namespaceURItoModule.get(aTag.getNamespaceURI());
+
+    if (module!=null) {
+      RSSModule.RSSModuleProperty property = module.getPropertyForName(aTag.getLocalName());
+
+      if (property!=null && property.getIsMultiValued()) {
+        List value = (List) aResource.get(makeQualifiedName(aTag));
+
+        if (value==null) {
+          value = new Vector();
+          aResource.set(makeQualifiedName(aTag), value);
+        }
+
+        value.add(aHandler.getValue());
+
+        return;
+      }
+    }
+
+    aResource.set(makeQualifiedName(aTag), aHandler.getValue());
+  }
+
   private String makeQualifiedName(XMLReader.XMLName aName) {
     String result=aName.getLocalName();
     RSSModule module = (RSSModule) namespaceURItoModule.get(aName.getNamespaceURI());
@@ -237,7 +277,8 @@ public class RSSReader {
 
     public void endElement(XMLReader.SectionHandler aHandler) throws XMLReader.XMLReaderExc {
       if (aHandler instanceof PropertyValueSectionHandler) {
-        resource.set(makeQualifiedName(currentTag), ( (PropertyValueSectionHandler) aHandler).getValue());
+        usePropertyValueSectionHandler(resource, (PropertyValueSectionHandler) aHandler, currentTag);
+//        resource.set(makeQualifiedName(currentTag), ( (PropertyValueSectionHandler) aHandler).getValue());
       }
     };
 
@@ -250,6 +291,10 @@ public class RSSReader {
     };
 
     public RDFResource getResource() {
+      if (resource.getIdentifier()==null || resource.getIdentifier().length()==0) {
+        resource.setIdentifier(resource.get("rss:link").toString());
+      }
+
       return resource;
     }
   }
@@ -394,35 +439,11 @@ public class RSSReader {
     public Object getValue() {
       try {
         String expression = data.toString().trim();
-        SimpleParser parser = new SimpleParser(expression);
 
-        String year="";
-        String month="";
-        String day="";
-        String hour="";
-        String minutes="";
-
-          year = parser.parse(NUMBER);
-          parser.skip("-");
-          month = parser.parse(NUMBER);
-          parser.skip("-");
-          day = parser.parse(NUMBER);
-          parser.skip("T");
-          hour = parser.parse(NUMBER);
-          parser.skip(":");
-          minutes = parser.parse(NUMBER);
-
-          SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm");
-          d.setLenient(true);
-          expression = year + "-" + month + "-" + day + " " + hour + ":" + minutes;
-
-        System.out.println(expression);
-
-        Date result = d.parse(expression);
-
-        return result;
+        return DateTimeFunctions.parseW3CDTFString(expression);
       }
       catch (Throwable t) {
+
         return null;
       }
     }
index f611f66..92f102c 100755 (executable)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2001, 2002  The Mir-coders group
+ * Copyright (C) 2001, 2002 The Mir-coders group
  *
  * This file is part of Mir.
  *
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with the com.oreilly.servlet library, any library
- * licensed under the Apache Software License, The Sun (tm) Java Advanced
- * Imaging library (JAI), The Sun JIMI library (or with modified versions of
- * the above that use the same license as the above), and distribute linked
- * combinations including the two.  You must obey the GNU General Public
- * License in all respects for all of the code used other than the above
- * mentioned libraries.  If you modify this file, you may extend this exception
- * to your version of the file, but you are not obligated to do so.  If you do
- * not wish to do so, delete this exception statement from your version.
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
  */
 
 package mir.rss;
 
 import java.util.*;
+import mir.util.*;
+import gnu.regexp.RE;
+
 
 public class RSSTest {
 
   public static void main(String[] args) {
-    System.out.println("Testing...");
 
     RSSReader reader = new RSSReader();
+//..    RSS091Reader reader2 = new RSS091Reader();
     try {
-      RSSData wvl = reader.parseUrl("http://wvl.indymedia.org/features.rdf");
-      RSSData be = reader.parseUrl("http://belgium.indymedia.org/features.rdf");
+//      RE test = new RE(".*\\bLB\\b.*", RE.REG_ICASE);
+//      System.out.println(" LB II : " + test.isMatch("LB II"));
+//      System.out.println(" revised LB: " + test.isMatch("revised LB"));
+//      System.out.println(" revised LB II : " + test.isMatch("revised LB II"));
+//      System.out.println(" buLB: " + test.isMatch("buLB"));
+
+      RSSData nl = reader.parseUrl("http://biotechdev.mir.dnsalias.net/test.rss");
+//      RSSData it = reader.parseUrl("http://g8.mir.dnsalias.net/italynewswire.rss");
+//      Object result = StructuredContentParser.parse(" { a = 'b' 'as a' = [ 'asd' asd 'asdas asd as''asd' ] }") ;
+//      System.out.println("" + wvl.get("rss:item"));
+//      RSSData fr = reader2.parseUrl("http://paris.indymedia.org/backendg8.php3");
+//      RSSData be = reader.parseUrl("http://belgium.indymedia.org/features.rdf");
 
-      RSSAggregator agg = new RSSAggregator(10, "dc:date", true, null, null);
+//      RSSAggregator agg = new RSSAggregator(10, "dc:date", true, null, null);
 
-      agg.appendItems(wvl.getResourcesForRdfClass("rss:item"));
-      agg.appendItems(be.getResourcesForRdfClass("rss:item"));
+//      agg.appendItems(wvl.getResourcesForRdfClass("rss:item"));
+//      agg.appendItems(be.getResourcesForRdfClass("rss:item"));
 
-      Iterator i = agg.getItems().iterator();
+//      System.out.println(fr);
 
-      while (i.hasNext())
-        System.out.println(i.next().toString());
+//      Iterator i = fr.getResourcesForRdfClass("rss:item").iterator();
+//      while (i.hasNext())
+//        System.out.println(ParameterExpander.evaluateExpression((RDFResource) i.next(), "['dc:date']"));
 
-      System.out.println(agg.getItems());
+//      System.out.println(agg.getItems());
     }
     catch (Throwable t) {
       System.out.println("Exception: " + t.toString());
index cc2463e..5308bcc 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.servlet;
-
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Locale;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.log.LoggerWrapper;
-import mir.storage.DatabaseAdaptor;
-
-import com.codestudio.util.JDBCPool;
-import com.codestudio.util.JDBCPoolMetaData;
-import com.codestudio.util.SQLManager;
-
-/**
- * Title:        Mir
- * Description:  Abstract servlet-class
- * Copyright:    Copyright (c) 2001, 2002
- * Company:      Mir-coders group
- * @author       idfx, the Mir-coders group
- * @version      $Id: AbstractServlet.java,v 1.30 2003/04/26 00:42:21 zapata Exp $
- */
-
-public abstract class AbstractServlet extends HttpServlet {
-  protected static String lang;
-  protected LoggerWrapper logger;
-  protected MirPropertiesConfiguration configuration;
-
-  /**
-   * Constructor for AbstractServlet.
-   */
-  public AbstractServlet() {
-    super();
-    logger = new LoggerWrapper("Servlet");
-  }
-
-  protected void setNoCaching(HttpServletResponse aResponse) {
-    //nothing in Mir can or should be cached as it's all dynamic...
-    //
-    //this needs to be done here and not per page (via meta tags) as some
-    //browsers have problems w/ it per-page -mh
-    aResponse.setHeader("Pragma", "no-cache");
-    aResponse.setDateHeader("Expires", 0);
-    aResponse.setHeader("Cache-Control", "no-cache");
-  }
-
-  /**
-   * Bind the language to the session
-   */
-  protected void setLanguage(HttpSession session, String language) {
-    logger.debug("setting language to " + language);
-
-    session.setAttribute("language", language);
-    session.setAttribute("locale", new Locale(language, ""));
-  }
-
-  /**
-   * Get the session-bound language
-   */
-  protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {
-    String lang = (String) session.getAttribute("language");
-
-    if (lang == null || lang.length()==0) {
-      lang = getAcceptLanguage(aRequest);
-    }
-
-    return lang;
-  }
-
-  /**
-   * get the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public Locale getLocale(HttpServletRequest aRequest) {
-    Locale loc = null;
-    HttpSession session = aRequest.getSession(false);
-    if (session != null) {
-      // session can be null in case of logout
-      loc = (Locale) session.getAttribute("locale");
-    }
-    // if there is nothing in the session get it fron the accept-language
-    if (loc == null) {
-      loc = aRequest.getLocale();
-    }
-
-    logger.debug("getting locale: " + loc.getLanguage());
-
-    return loc;
-  }
-
-  /**
-   * Checks the Accept-Language of the client browser.
-   * If this language is available it returns its country-code,
-   * else it returns the standard-language
-   */
-  protected String getAcceptLanguage(HttpServletRequest aRequest) {
-    Locale loc = aRequest.getLocale();
-    lang = loc.getLanguage();
-    return lang;
-  }
-
-  /**
-   * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)
-   */
-  public void init(ServletConfig config) throws ServletException {
-    super.init(config);
-
-    MirPropertiesConfiguration.setContext(config.getServletContext());
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new ServletException(e);
-    }
-
-    String dbUser = configuration.getString("Database.Username");
-    String dbPassword = configuration.getString("Database.Password");
-    String dbHost = configuration.getString("Database.Host");
-    String dbAdapName = configuration.getString("Database.Adaptor");
-    String dbName = configuration.getString("Database.Name");
-
-    DatabaseAdaptor adaptor;
-    try {
-      adaptor = (DatabaseAdaptor) Class.forName(dbAdapName).newInstance();
-    }
-    catch (Exception e) {
-      throw new ServletException("Could not load DB adapator: " +
-                                 e.toString());
-    }
-
-    String dbDriver;
-    String dbUrl;
-    try {
-      dbDriver = adaptor.getDriver();
-      dbUrl = adaptor.getURL(dbUser, dbPassword, dbHost);
-    }
-    catch (Exception e) {
-      throw new ServletException(e);
-    }
-
-    JDBCPoolMetaData meta = new JDBCPoolMetaData();
-    meta.setDbname(dbName);
-    meta.setDriver(dbDriver);
-    meta.setURL(dbUrl);
-    meta.setUserName(dbUser);
-    meta.setPassword(dbPassword);
-    meta.setJNDIName("mir");
-    meta.setMaximumSize(10);
-    meta.setMinimumSize(1);
-    meta.setPoolPreparedStatements(false);
-    meta.setCacheEnabled(false);
-    meta.setCacheSize(15);
-    meta.setDebugging(false);
-//    meta.setLogFile(dblogfile+".pool");
-
-    SQLManager manager = SQLManager.getInstance();
-    JDBCPool pool = null;
-    if (manager != null) {
-      pool = manager.createPool(meta);
-    }
-  }
-
-  private void setEncoding(HttpServletRequest request){
-    try {
-      Class reqClass = request.getClass();
-      Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});
-      String encoding = configuration.getString("Mir.DefaultHTMLCharset");
-      method.invoke(request, new Object[]{encoding});
-    } catch (NoSuchMethodException e) {
-      // TODO set the encoding in a zapata-way
-//      logger.warn("set encoding not yet implemented: " + e.getMessage());
-    } catch (SecurityException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
-    } catch (IllegalArgumentException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
-    } catch (IllegalAccessException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
-    } catch (InvocationTargetException e) {
-      logger.error(e.getMessage());
-      e.printStackTrace();
-    }
-  }
-
-  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-    doPost(request, response);
-  }
-
-  protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-    if ( (configuration.getString("RootUri") == null) ||
-        configuration.getString("RootUri").equals("")) {
-      configuration.setProperty("RootUri", request.getContextPath());
-    }
-    setEncoding(request);
-    process(request, response);
-  }
-
-  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.servlet;\r
+\r
+import java.io.IOException;\r
+import java.lang.reflect.InvocationTargetException;\r
+import java.lang.reflect.Method;\r
+import java.sql.Connection;\r
+import java.util.Locale;\r
+\r
+import javax.servlet.ServletConfig;\r
+import javax.servlet.ServletException;\r
+import javax.servlet.http.HttpServlet;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import com.codestudio.util.JDBCPool;\r
+import com.codestudio.util.JDBCPoolMetaData;\r
+import com.codestudio.util.SQLManager;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.log.LoggerWrapper;\r
+\r
+import mircoders.global.MirGlobal;\r
+\r
+/**\r
+ * Title:        Mir\r
+ * Description:  Abstract servlet-class\r
+ * Copyright:    Copyright (c) 2001, 2002\r
+ * Company:      Mir-coders group\r
+ * @author       idfx, the Mir-coders group\r
+ * @version      $Id: AbstractServlet.java,v 1.31 2003/09/03 18:29:03 zapata Exp $\r
+ */\r
+\r
+public abstract class AbstractServlet extends HttpServlet {\r
+  protected static String lang;\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+\r
+  /**\r
+   * Constructor for AbstractServlet.\r
+   */\r
+  public AbstractServlet() {\r
+    super();\r
+  }\r
+\r
+  protected void setNoCaching(HttpServletResponse aResponse) {\r
+    //nothing in Mir can or should be cached as it's all dynamic...\r
+    //\r
+    //this needs to be done here and not per page (via meta tags) as some\r
+    //browsers have problems w/ it per-page -mh\r
+    aResponse.setHeader("Pragma", "no-cache");\r
+    aResponse.setDateHeader("Expires", 0);\r
+    aResponse.setHeader("Cache-Control", "no-cache");\r
+  }\r
+\r
+  /**\r
+   * Bind the language to the session\r
+   */\r
+  protected void setLanguage(HttpSession session, String language) {\r
+    logger.debug("setting language to " + language);\r
+\r
+    session.setAttribute("language", language);\r
+    session.setAttribute("locale", new Locale(language, ""));\r
+  }\r
+\r
+  /**\r
+   * Get the session-bound language\r
+   */\r
+  protected String getLanguage(HttpServletRequest aRequest, HttpSession session) {\r
+    String lang = (String) session.getAttribute("language");\r
+\r
+    if (lang == null || lang.length()==0) {\r
+      lang = getAcceptLanguage(aRequest);\r
+    }\r
+\r
+    return lang;\r
+  }\r
+\r
+  /**\r
+   * get the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  public Locale getLocale(HttpServletRequest aRequest) {\r
+    Locale loc = null;\r
+    HttpSession session = aRequest.getSession(false);\r
+    if (session != null) {\r
+      // session can be null in case of logout\r
+      loc = (Locale) session.getAttribute("locale");\r
+    }\r
+    // if there is nothing in the session get it fron the accept-language\r
+    if (loc == null) {\r
+      loc = aRequest.getLocale();\r
+    }\r
+\r
+    logger.debug("getting locale: " + loc.getLanguage());\r
+\r
+    return loc;\r
+  }\r
+\r
+  /**\r
+   * Checks the Accept-Language of the client browser.\r
+   * If this language is available it returns its country-code,\r
+   * else it returns the standard-language\r
+   */\r
+  protected String getAcceptLanguage(HttpServletRequest aRequest) {\r
+    Locale loc = aRequest.getLocale();\r
+    lang = loc.getLanguage();\r
+    return lang;\r
+  }\r
+\r
+  /**\r
+   * @see javax.servlet.Servlet#init(javax.servlet.ServletConfig)\r
+   */\r
+  public void init(ServletConfig config) throws ServletException {\r
+    super.init(config);\r
+\r
+    MirPropertiesConfiguration.setContext(config.getServletContext());\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletException("can't read configuration: " + t.toString());\r
+    }\r
+\r
+    logger = new LoggerWrapper("Servlet");\r
+\r
+    try {\r
+      MirGlobal.localizer();\r
+    }\r
+    catch (Throwable t) {\r
+      logger.fatal("can't get localizer: " + t.toString());\r
+      throw new ServletException("can't get localizer: " + t.toString());\r
+    }\r
+\r
+    String dbUser = configuration.getString("Database.Username");\r
+    String dbPassword = configuration.getString("Database.Password");\r
+    String dbHost = configuration.getString("Database.Host");\r
+    String dbPort = configuration.getString("Database.Port");\r
+    String dbAdapName = configuration.getString("Database.Adaptor");\r
+    String dbName = configuration.getString("Database.Name");\r
+    String dbDriver = configuration.getString("Database.Driver");\r
+    String dbUrl = "jdbc:postgresql://"+dbHost+":"+dbPort+"/"+dbName;\r
+    int dbMin = configuration.getInteger("Database.poolMin", 1);\r
+    int dbMax = configuration.getInteger("Database.poolMax", 10);\r
+\r
+    JDBCPoolMetaData meta = new JDBCPoolMetaData();\r
+    meta.setDbname(dbName);\r
+    meta.setDriver(dbDriver);\r
+    meta.setURL(dbUrl);\r
+    meta.setUserName(dbUser);\r
+    meta.setPassword(dbPassword);\r
+    meta.setJNDIName("mir");\r
+    meta.setMaximumSize(dbMax);\r
+    meta.setMinimumSize(dbMin);\r
+    meta.setPoolPreparedStatements(false);\r
+    meta.setCacheEnabled(false);\r
+    meta.setCacheSize(15);\r
+    meta.setDebugging(false);\r
+\r
+    SQLManager manager = SQLManager.getInstance();\r
+\r
+    JDBCPool pool = null;\r
+    if (manager != null) {\r
+      pool = manager.createPool(meta);\r
+    }\r
+\r
+    Connection connection;\r
+    try {\r
+      connection = pool.requestConnection();\r
+      pool.closeConnection(connection);\r
+    }\r
+    catch (Throwable t) {\r
+      logger.fatal("Can't connect to database: " + t.toString());\r
+      throw new ServletException("Can't connect to database: " + t.toString());\r
+    }\r
+  }\r
+\r
+  private void setEncoding(HttpServletRequest request){\r
+    try {\r
+      logger.info("Request has encoding: " + request.getCharacterEncoding());\r
+      logger.info("Config stipulates encoding: " + configuration.getString("Mir.DefaultHTMLCharset"));\r
+      Class reqClass = request.getClass();\r
+      Method method = reqClass.getMethod("setCharacterEncoding", new Class[]{String.class});\r
+      String encoding = configuration.getString("Mir.DefaultHTMLCharset");\r
+      method.invoke(request, new Object[]{encoding});\r
+      logger.info("Request now has encoding: " + request.getCharacterEncoding());\r
+    }\r
+    catch (NoSuchMethodException e) {\r
+      // TODO set the encoding in a zapata-way\r
+//      logger.warn("set encoding not yet implemented: " + e.getMessage());\r
+    }\r
+    catch (SecurityException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+    catch (IllegalArgumentException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+    catch (IllegalAccessException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+    catch (InvocationTargetException e) {\r
+      logger.error(e.getMessage());\r
+      e.printStackTrace();\r
+    }\r
+  }\r
+\r
+  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r
+    doPost(request, response);\r
+  }\r
+\r
+  protected final void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\r
+    if ((configuration.getString("RootUri") == null) || configuration.getString("RootUri").equals("")) {\r
+      configuration.setProperty("RootUri", request.getContextPath());\r
+    }\r
+    setEncoding(request);\r
+    process(request, response);\r
+  }\r
+\r
+  abstract public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;\r
+\r
+  /**\r
+   * Selects the language for the response.\r
+   *\r
+   * @param session\r
+   * @param aRequest\r
+   */\r
+  protected void checkLanguage(HttpSession aSession, HttpServletRequest aRequest) {\r
+    String requestLanguage = aRequest.getParameter("language");\r
+    String sessionLanguage = (String) aSession.getAttribute("language");\r
+    String acceptLanguage = aRequest.getLocale().getLanguage();\r
+    String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");\r
+\r
+    String language = requestLanguage;\r
+\r
+    if (language==null)\r
+      language = sessionLanguage;\r
+\r
+    if (language==null)\r
+      language = acceptLanguage;\r
+\r
+    if (language==null)\r
+      language = defaultLanguage;\r
+\r
+    setLanguage(aSession, language);\r
+  }\r
+}\r
index 12df8a9..42519db 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.servlet;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
-import mir.misc.LineFilterWriter;
-import mir.module.AbstractModule;
-import mir.storage.StorageObject;
-import mir.util.HTTPRequestParser;
-import freemarker.template.SimpleHash;
-import freemarker.template.TemplateModelRoot;
-
-
-
-
-/**
- * Abstract class ServletModule provides the base functionality for servlets.
- * Deriving a class from ServletModule enables class to insert/edit/update/delete
- * and list Entity from a Database via mainModule.
- *
- *
- *  Abstrakte Klasse ServletModule stellt die Basisfunktionalitaet der
- *  abgeleiteten ServletModule zur Verf?gung.
- *
- * @version 28.6.1999
- * @author RK
- */
-
-public abstract class ServletModule {
-
-  public String defaultAction;
-  protected LoggerWrapper logger;
-  protected MirPropertiesConfiguration configuration;
-  protected AbstractModule mainModule;
-  protected Locale fallbackLocale;
-  protected String templateListString;
-  protected String templateObjektString;
-  protected String templateConfirmString;
-
-
-  public ServletModule(){
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new RuntimeException("Can't get configuration: " + e.getMessage());
-    }
-
-    fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");
-  }
-
-
-  /**
-   * Singelton - Methode muss in den abgeleiteten Klassen ueberschrieben werden.
-   * @return ServletModule
-   */
-  public static ServletModule getInstance() {
-    return null;
-  }
-
-  /**
-   * get the module name to be used for generic operations like delete.
-   */
-  protected String getOperationModuleName() {
-    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());
-  }
-
-  /**
-   * get the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public Locale getLocale(HttpServletRequest req) {
-    Locale loc = null;
-    HttpSession session = req.getSession(false);
-    if (session != null) {
-      // session can be null in case of logout
-      loc = (Locale) session.getAttribute("locale");
-    }
-    // if there is nothing in the session get it fron the accept-language
-    if (loc == null) {
-      loc = req.getLocale();
-    }
-    return loc;
-  }
-
-  /**
-   * get the locale either from the session or the accept-language header ot the request
-   * this supersedes getLanguage for the new i18n
-   */
-  public Locale getFallbackLocale(HttpServletRequest req) {
-    return fallbackLocale;
-  }
-
-  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {
-    try {
-      aResponse.sendRedirect(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);
-    }
-  }
-
-  /**
-   *  list(req,res) - generische Listmethode. Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
-   *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   */
-  public void list(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    try {
-      EntityList theList;
-      String offsetParam = req.getParameter("offset");
-      int offset = 0;
-      PrintWriter out = res.getWriter();
-
-      // hier offsetcode bearbeiten
-      if (offsetParam != null && !offsetParam.equals("")) {
-        offset = Integer.parseInt(offsetParam);
-      }
-      if (req.getParameter("next") != null) {
-        offset = Integer.parseInt(req.getParameter("nextoffset"));
-      }
-      else {
-        if (req.getParameter("prev") != null) {
-          offset = Integer.parseInt(req.getParameter("prevoffset"));
-        }
-      }
-      theList = mainModule.getByWhereClause(null, offset);
-
-      HTMLTemplateProcessor.process(res, templateListString, theList, null, null, out, getLocale(req), getFallbackLocale(req));
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *  add(req,res) - generische Addmethode. Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   */
-  public void add(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-
-    try {
-      SimpleHash mergeData = new SimpleHash();
-      mergeData.put("new", "1");
-      deliver(req, res, mergeData, templateObjektString);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *  insert(req,res) - generische Insertmethode, folgt auf add.
-   *  Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
-   *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   */
-  public void insert(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      Map withValues = getIntersectingValues(req, mainModule.getStorageObject());
-      logger.debug("--trying to add...");
-      String id = mainModule.add(withValues);
-      logger.debug("--trying to deliver..." + id);
-      list(req, res);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *  delete(req,res) - generic delete method. Can be overridden in subclasses.
-   *
-   */
-
-  public void delete(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      String idParam = req.getParameter("id");
-
-      if (idParam == null)
-        throw new ServletModuleExc("Invalid call to delete: no id supplied");
-
-      String confirmParam = req.getParameter("confirm");
-      String cancelParam = req.getParameter("cancel");
-      if (confirmParam == null && cancelParam == null) {
-        SimpleHash mergeData = new SimpleHash();
-
-        mergeData.put("module", getOperationModuleName());
-        mergeData.put("infoString", getOperationModuleName() + ": " + idParam);
-        mergeData.put("id", idParam);
-        mergeData.put("where", req.getParameter("where"));
-        mergeData.put("order", req.getParameter("order"));
-        mergeData.put("offset", req.getParameter("offset"));
-        // this stuff is to be compatible with the other more advanced
-        // search method used for media and comments
-        mergeData.put("query_media_folder", req.getParameter("query_media_folder"));
-        mergeData.put("query_is_published", req.getParameter("query_is_published"));
-        mergeData.put("query_text", req.getParameter("query_text"));
-        mergeData.put("query_field", req.getParameter("query_field"));
-
-        deliver(req, res, mergeData, templateConfirmString);
-      }
-      else {
-        if (confirmParam != null && !confirmParam.equals("")) {
-          //theLog.printInfo("delete confirmed!");
-          mainModule.deleteById(idParam);
-          list(req, res); // back to list
-        }
-        else {
-          if (req.getParameter("where") != null)
-            list(req, res);
-          else
-            edit(req, res);
-        }
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
-   *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   */
-  public void edit(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    edit(req, res, req.getParameter("id"));
-  }
-
-  /**
-   *  edit(req,res) - generische Editmethode. Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
-   *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   */
-  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      deliver(aRequest, aResponse, mainModule.getById(anIdentifier), templateObjektString);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *  update(req,res) - generische Updatemethode. Wennn die Funktionalitaet
-   *  nicht reicht, muss sie in der abgeleiteten ServletModule-Klasse
-   *  ueberschreiben werden.
-   *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   */
-
-  public void update(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {
-    try {
-      String idParam = req.getParameter("id");
-      Map withValues = getIntersectingValues(req, mainModule.getStorageObject());
-
-      String id = mainModule.set(withValues);
-      String whereParam = req.getParameter("where");
-      String orderParam = req.getParameter("order");
-
-      if ((whereParam != null && !whereParam.equals("")) || (orderParam != null && !orderParam.equals(""))) {
-        list(req, res);
-      }
-      else {
-        edit(req, res);
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * deliver liefert das Template mit dem Filenamen templateFilename
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
-   * TemplateModelRoot rtm gemischt wurde
-   *
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
-   *   Daten, die ins Template gemerged werden sollen.
-   * @param tmpl Name des Templates
-   * @exception ServletModuleException
-   */
-  public void deliver(HttpServletRequest req, HttpServletResponse res, TemplateModelRoot rtm,
-         TemplateModelRoot popups, String templateFilename) throws ServletModuleFailure  {
-    if (rtm == null)
-      rtm = new SimpleHash();
-
-    try {
-      PrintWriter out = res.getWriter();
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, popups, out, getLocale(req), getFallbackLocale(req));
-
-      // we default to admin bundles here, which is not exactly beautiful...
-      // but this whole producer stuff is going to be rewritten soon.
-      // ServletModuleOpenIndy overwrites deliver() to use open bundles
-      // (br1)
-      out.close();
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-  /**
-   * deliver liefert das Template mit dem Filenamen templateFilename
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
-   * TemplateModelRoot rtm gemischt wurde
-   *
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
-   *   Daten, die ins Template gemerged werden sollen.
-   * @param tmpl Name des Templates
-   * @exception ServletModuleException
-   */
-  public void deliver(HttpServletRequest req, HttpServletResponse res,
-        TemplateModelRoot rtm, String templateFilename) throws ServletModuleFailure {
-    deliver(req, res, rtm, null, templateFilename);
-  }
-
-  /**
-   * deliver liefert das Template mit dem Filenamen templateFilename
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
-   * TemplateModelRoot rtm gemischt wurde
-   *
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
-   *   Daten, die ins Template gemerged werden sollen.
-   * @param tmpl Name des Templates
-   * @exception ServletModuleException
-   */
-  public void deliver_compressed(HttpServletRequest req, HttpServletResponse res,
-                                 TemplateModelRoot rtm, String templateFilename)
-      throws ServletModuleFailure {
-    if (rtm == null) rtm = new SimpleHash();
-    try {
-      PrintWriter out = new LineFilterWriter(res.getWriter());
-      //PrintWriter out =  res.getWriter();
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, null, out, getLocale(req), getFallbackLocale(req));
-      out.close();
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   * deliver liefert das Template mit dem Filenamen templateFilename
-   * an den HttpServletResponse res aus, nachdem es mit den Daten aus
-   * TemplateModelRoot rtm gemischt wurde
-   *
-   * @param out ist der OutputStream, in den die gergten Daten geschickt werden sollen.
-   * @param rtm beinahalten das freemarker.template.TempalteModelRoot mit den
-   *   Daten, die ins Template gemerged werden sollen.
-   * @param tmpl Name des Templates
-   * @exception ServletModuleException
-   */
-  private void deliver(HttpServletResponse res, HttpServletRequest req, PrintWriter out,
-                       TemplateModelRoot rtm, String templateFilename)
-      throws ServletModuleFailure {
-    try {
-      HTMLTemplateProcessor.process(res, templateFilename, rtm, null, out, getLocale(req), getFallbackLocale(req));
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  /**
-   *  Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem
-   *  Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des
-   *  doParameters ausgefuehrt.
-   *
-   * @return Name der Default-Action
-   */
-  public String defaultAction() {
-    return defaultAction;
-  }
-
-  /**
-   * Gets the fields from a httprequest and matches them with the metadata from
-   * the storage object. Returns the keys that match, with their values.
-   *
-   * @return Map with the values
-   */
-  public Map getIntersectingValues(HttpServletRequest req, StorageObject theStorage)
-      throws ServletModuleExc, ServletModuleFailure {
-
-    try {
-      HTTPRequestParser parser;
-      List theFieldList;
-
-      parser = new HTTPRequestParser(req);
-
-      theFieldList = theStorage.getFields();
-
-      Map withValues = new HashMap();
-      String aField, aValue;
-
-      for (int i = 0; i < theFieldList.size(); i++) {
-        aField = (String) theFieldList.get(i);
-
-        aValue = parser.getParameter(aField);
-        if (aValue != null)
-          withValues.put(aField, aValue);
-      }
-      return withValues;
-    }
-    catch (Throwable e) {
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-
-      throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e);
-    }
-  }
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.servlet;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.entity.adapter.EntityAdapterDefinition;\r
+import mir.entity.adapter.EntityAdapterEngine;\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.log.LoggerWrapper;\r
+import mir.module.AbstractModule;\r
+import mir.storage.StorageObject;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.URLBuilder;\r
+import mircoders.servlet.ServletHelper;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public abstract class ServletModule {\r
+  public String defaultAction;\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+  protected Locale fallbackLocale;\r
+\r
+  protected AbstractModule mainModule;\r
+  protected String definition;\r
+  protected EntityAdapterModel model;\r
+\r
+  protected String listGenerator;\r
+  protected String editGenerator;\r
+  protected String deleteConfirmationGenerator;\r
+  protected int nrEntitiesPerListPage;\r
+\r
+\r
+  public ServletModule(){\r
+    definition = null;\r
+    model = null;\r
+\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (PropertiesConfigExc e) {\r
+      throw new RuntimeException("Can't get configuration: " + e.getMessage());\r
+    }\r
+\r
+    listGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".ListTemplate");\r
+    editGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".EditTemplate");\r
+    deleteConfirmationGenerator = configuration.getString("ServletModule."+getOperationModuleName()+".DeleteConfirmationTemplate");\r
+    nrEntitiesPerListPage =\r
+        configuration.getInt("ServletModule."+getOperationModuleName()+".ListSize",\r
+        configuration.getInt("ServletModule.Default.ListSize", 20));\r
+\r
+    fallbackLocale = new Locale(configuration.getString("Mir.Admin.FallbackLanguage", "en"), "");\r
+  }\r
+\r
+\r
+  /**\r
+   * Singleton instance retrievel method. MUST be overridden in subclasses.\r
+   *\r
+   * @return ServletModule the single instance of the servletmodule class\r
+   */\r
+  public static ServletModule getInstance() {\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * Get the module name\r
+   *\r
+   * @return\r
+   */\r
+  protected String getOperationModuleName() {\r
+    return getClass().getName().substring((new String("mircoders.servlet.ServletModule")).length());\r
+  }\r
+\r
+  /**\r
+   * get the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  public Locale getLocale(HttpServletRequest aRequest) {\r
+    Locale loc = null;\r
+    HttpSession session = aRequest.getSession(false);\r
+    if (session != null) {\r
+      // session can be null in case of logout\r
+      loc = (Locale) session.getAttribute("locale");\r
+    }\r
+    // if there is nothing in the session get it fron the accept-language\r
+    if (loc == null) {\r
+      loc = aRequest.getLocale();\r
+    }\r
+    return loc;\r
+  }\r
+\r
+  /**\r
+   * get the locale either from the session or the accept-language header ot the request\r
+   * this supersedes getLanguage for the new i18n\r
+   */\r
+  public Locale getFallbackLocale(HttpServletRequest aRequest) {\r
+    return fallbackLocale;\r
+  }\r
+\r
+  /**\r
+   * Function to specify the default ordering for lists. May be overridden.\r
+   *\r
+   *\r
+   * @return\r
+   */\r
+  public String getDefaultListOrdering() {\r
+\r
+    if (mainModule!=null && mainModule.getStorageObject()!=null){\r
+      if (mainModule.getStorageObject().getFields().contains("webdb_create"))\r
+        return "webdb_create desc";\r
+    }\r
+\r
+    return "id asc";\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aResponse\r
+   * @param aQuery\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {\r
+    try {\r
+      aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/Mir?"+aQuery));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Generic list method\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+\r
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String where = requestParser.getParameter("where");\r
+    String order = requestParser.getParameterWithDefault("order", getDefaultListOrdering());\r
+    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
+\r
+    returnList(aRequest, aResponse, where, order, offset);\r
+  }\r
+\r
+\r
+  public void returnList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
+\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      List list =\r
+         EntityAdapterEngine.retrieveAdapterList(model, definition, aWhereClause, anOrderByClause, nrEntitiesPerListPage, anOffset);\r
+\r
+      responseData.put("nexturl", null);\r
+      responseData.put("prevurl", null);\r
+      responseData.put("module", getOperationModuleName());\r
+\r
+      count=mainModule.getSize(aWhereClause);\r
+\r
+      urlBuilder.setValue("module", getOperationModuleName());\r
+      urlBuilder.setValue("do", "list");\r
+      urlBuilder.setValue("where", aWhereClause);\r
+      urlBuilder.setValue("order", anOrderByClause);\r
+\r
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
+      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));\r
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
+      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));\r
+      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
+\r
+      responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
+      responseData.put("searchtext", requestParser.getParameter("searchtext"));\r
+      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
+      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));\r
+      responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
+\r
+      urlBuilder.setValue("offset", anOffset);\r
+      responseData.put("offset" , new Integer(anOffset).toString());\r
+      responseData.put("thisurl" , urlBuilder.getQuery());\r
+\r
+      if (count>anOffset+nrEntitiesPerListPage) {\r
+        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);\r
+        responseData.put("nexturl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      if (anOffset>0) {\r
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
+        responseData.put("prevurl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      responseData.put("entities", list);\r
+      responseData.put("from" , Integer.toString(anOffset+1));\r
+      responseData.put("count", Integer.toString(count));\r
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void editObject(HttpServletRequest aRequest, HttpServletResponse aResponse, Object anObject, boolean anIsNew, String anId) throws ServletModuleExc {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    EntityAdapterModel model;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      responseData.put("module", getOperationModuleName());\r
+      responseData.put("entity", anObject);\r
+      responseData.put("new", new Boolean(anIsNew));\r
+\r
+\r
+      urlBuilder.setValue("module", getOperationModuleName());\r
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+      if (anIsNew)\r
+        urlBuilder.setValue("do", "add");\r
+      else {\r
+        urlBuilder.setValue("id", anId);\r
+        urlBuilder.setValue("do", "edit");\r
+      }\r
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+\r
+  /**\r
+   * Generic add method\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
+\r
+    Map object = new HashMap();\r
+\r
+    Iterator i = mainModule.getStorageObject().getFields().iterator();\r
+\r
+    while (i.hasNext())\r
+      object.put(i.next(), "");\r
+\r
+    initializeNewObject(object, aRequest, aResponse);\r
+\r
+    editObject(aRequest, aResponse, object, true, null);\r
+  }\r
+\r
+  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+  }\r
+\r
+  /**\r
+   * Method called when the user edits an object.\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
+    edit(aRequest, aResponse, aRequest.getParameter("id"));\r
+  }\r
+\r
+  /**\r
+   * Generic edit method\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @param anIdentifier\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse, String anIdentifier)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
+    try {\r
+      editObject(aRequest, aResponse, model.makeEntityAdapter(definition, mainModule.getById(anIdentifier)), false, anIdentifier);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Generic update method\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+      String id = aRequest.getParameter("id");\r
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
+      mainModule.set(withValues);\r
+\r
+      String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+      if (returnUrl!=null) {\r
+        redirect(aResponse, returnUrl);\r
+      }\r
+      else {\r
+        edit(aRequest, aResponse, id);\r
+      }\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Generic insert method\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+      Map object = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
+\r
+      String id = processInstertedObject(object, aRequest, aResponse);\r
+\r
+      String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+      if (returnUrl!=null) {\r
+        redirect(aResponse, returnUrl);\r
+      }\r
+      else {\r
+        edit(aRequest, aResponse, id);\r
+      }\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public String processInstertedObject(Map anObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    try {\r
+      return mainModule.add(anObject);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  };\r
+\r
+  /**\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   */\r
+  public void confirmdelete(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    try {\r
+      String idParam = aRequest.getParameter("id");\r
+      String confirmParam = aRequest.getParameter("confirm");\r
+      String cancelParam = aRequest.getParameter("cancel");\r
+\r
+      if (confirmParam != null && !confirmParam.equals("")) {\r
+        mainModule.deleteById(idParam);\r
+        redirect(aResponse, aRequest.getParameter("okurl"));\r
+      }\r
+      else\r
+        redirect(aResponse, aRequest.getParameter("cancelurl"));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   * @throws ServletModuleUserExc\r
+   * @throws ServletModuleFailure\r
+   */\r
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure  {\r
+    try {\r
+      String idParam = aRequest.getParameter("id");\r
+\r
+      if (idParam == null)\r
+        throw new ServletModuleExc("Invalid call to delete: no id supplied");\r
+\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      responseData.put("module", getOperationModuleName());\r
+      responseData.put("id", idParam);\r
+      responseData.put("cancelurl", aRequest.getParameter("cancelurl"));\r
+      responseData.put("okurl", aRequest.getParameter("okurl"));\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, deleteConfirmationGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  /**\r
+   *  Wenn die abgeleitete Klasse diese Methode ueberschreibt und einen String mit einem\r
+   *  Methodennamen zurueckliefert, dann wird diese Methode bei fehlender Angabe des\r
+   *  doParameters ausgefuehrt.\r
+   *\r
+   * @return Name der Default-Action\r
+   */\r
+  public String defaultAction() {\r
+    return defaultAction;\r
+  }\r
+\r
+  /**\r
+   * Gets the fields from a httprequest and matches them with the metadata from\r
+   * the storage object. Returns the keys that match, with their values.\r
+   *\r
+   * @return Map with the values\r
+   */\r
+  public Map getIntersectingValues(HttpServletRequest aRequest, StorageObject theStorage)\r
+      throws ServletModuleExc, ServletModuleFailure {\r
+\r
+    try {\r
+      HTTPRequestParser parser;\r
+      List theFieldList;\r
+\r
+      parser = new HTTPRequestParser(aRequest);\r
+\r
+      theFieldList = theStorage.getFields();\r
+\r
+      Map withValues = new HashMap();\r
+      String aField, aValue;\r
+\r
+      for (int i = 0; i < theFieldList.size(); i++) {\r
+        aField = (String) theFieldList.get(i);\r
+\r
+        aValue = parser.getParameter(aField);\r
+        if (aValue != null)\r
+          withValues.put(aField, aValue);\r
+      }\r
+      return withValues;\r
+    }\r
+    catch (Throwable e) {\r
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
+\r
+      throw new ServletModuleFailure( "ServletModule.getIntersectingValues: " + e.getMessage(), e);\r
+    }\r
+  }\r
 }
\ No newline at end of file
index 88435d0..9d4ee83 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package  mir.servlet;
@@ -42,7 +42,7 @@ import mir.log.LoggerWrapper;
  * Dispatcher, calls the method passed to ServletModule Class, through the "do"
  * Parameter (via POST or GET)
  *
- * @version $Id: ServletModuleDispatch.java,v 1.15 2003/04/21 12:42:50 idfx Exp $
+ * @version $Id: ServletModuleDispatch.java,v 1.16 2003/09/03 18:29:03 zapata Exp $
  *
  * @Author rk
  *
@@ -52,56 +52,52 @@ public final class ServletModuleDispatch {
   private static LoggerWrapper logger = new LoggerWrapper("ServletModule.Dispatch");
   private static final Class[] SIGNATURE = { HttpServletRequest.class, HttpServletResponse.class };
 
- /**
-  * private constructor to prevent unwanted instantiation;
-  */
 /**
+   * private parameter-less constructor to prevent unwanted instantiation
+   */
 
   private ServletModuleDispatch () {
   }
 
   /**
-   *  Die Dispatch-Routine ruft das von dem Hauptservlet kommende ServletModule
-   *  mit dem per HttpServletRequest angegebenen Paramter <code>do</code> auf.
-   *  Ist kein Parameter angegeben, so wird versucht, in die <code>defaultAction</code>
-   *  des ServletModules zu springen.
+   * Method to dispatch servletmodule requests.
    *
-   * @param req Http-Request, das vom Dispatcher an die Methode des
-   *    ServletModules durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher an die Methode des
-   *    ServletModules durchgereicht wird
-   * @param sMod ServletModule, an das dispatched wird.
-   * @param mod Name des Modules als String (f?r Logfile)
+   * @param aServletModule
+   * @param aRequest
+   * @param aResponse
+   * @throws ServletModuleExc
+   * @throws ServletModuleUserExc
+   * @throws ServletModuleFailure
    */
 
-  public static void dispatch(ServletModule sMod, HttpServletRequest req,
-          HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
+  public static void dispatch(ServletModule aServletModule, HttpServletRequest aRequest,
+       HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
   {
-    String doParam = req.getParameter("do");
-    logger.info("ServletModuleDispatch: " + sMod.toString() + " with method " + doParam);
+    String doParam = aRequest.getParameter("do");
+    logger.info("ServletModuleDispatch: " + aServletModule.toString() + " with method " + doParam);
     if (doParam == null) {
-      if (sMod.defaultAction() != null)
-        doParam = sMod.defaultAction();
+      if (aServletModule.defaultAction() != null)
+        doParam = aServletModule.defaultAction();
       else
         throw new ServletModuleExc("no parameter do supplied!");
     }
 
     try {
-      Method method = sMod.getClass().getMethod(doParam,SIGNATURE);
+      Method method = aServletModule.getClass().getMethod(doParam,SIGNATURE);
       if (method != null) {
-        method.invoke(sMod,new Object[] {req,res} );
+        method.invoke(aServletModule,new Object[] {aRequest,aResponse} );
         return;
       }
       else logger.debug("method lookup unsuccesful");
     }
     catch ( InvocationTargetException e) {
-      logger.error( "invocation target exception: " + e.getMessage());
+      logger.error( "invocation target exception: " + e.toString());
       e.getTargetException().printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
 
       throw new ServletModuleFailure(e.getTargetException().getMessage(), e.getTargetException());
     }
     catch (Throwable t) {
-      logger.error( "ServletModuleDispatch: " + t.getMessage());
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+      logger.error( "ServletModuleDispatch: " + t.toString());
       throw new ServletModuleFailure(t);
     }
   }
diff --git a/source/mir/servlet/ServletModuleShow.java b/source/mir/servlet/ServletModuleShow.java
deleted file mode 100755 (executable)
index 447f5f0..0000000
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mir.servlet;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import freemarker.template.TemplateModelRoot;
-
-
-/**
- *  Standard ServletModule, dass eine Template anzeigt, und nicht
- *  mit Daten mischt. Damit ist es moeglich, einfache HTML-Seiten
- *  als templates zu benutzen. Damit kann auf einfache Weise die
- *  Funktionalitaet der Freemarker-Bibliothek (beispielsweise Navigationen
- *  per <code>include</code> einzubauen) benutzt werden. Die Templates
- *  werden aus dem per Konfiguration angegebenem template-Verzeichnis
- *  im Ordner "/html" genommen.
- *
- * @author RK
- */
-public class ServletModuleShow extends ServletModule {
-  private static ServletModuleShow instance = new ServletModuleShow();
-
-  /**
-   * Ein ServletModuleShow-Objekt wird ?ber getInstance geliefert. Es gibt zur
-   * Laufzeit nur ein Objekt (Singleton)
-   * @return ServletModuleShow
-   */
-  public static ServletModule getInstance() {
-    return instance;
-  }
-
-  /**
-   * Initialisierung leer.
-   */
-  private ServletModuleShow() {
-  }
-
-  /**
-   * defaultAction (s.a ServletModule)
-   * @return "show"
-   */
-  public String defaultAction() {
-    return "show";
-  }
-
-  /**
-   * Standardmethode, die die Funktionalitaet des ServletModules implementiert.
-   *
-   * @param req Http-Request, das vom Dispatcher durchgereicht wird
-   * @param res Http-Response, die vom Dispatcher durchgereicht wird
-   * @return String fuer Logfile
-   * @exception ServletModuleException
-   */
-  public void show(HttpServletRequest req, HttpServletResponse res) throws
-      ServletModuleExc {
-    try {
-      String idParam = req.getParameter("tmpl");
-      if (! (idParam == null || idParam.equals(""))) {
-        deliver(req, res, (TemplateModelRoot)null,
-                "html/" + idParam + ".template");
-      }
-      else {
-        throw new ServletModuleExc("Invalid template: " + idParam);
-      }
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-}
-
-
-
-
index fec51f6..319a8c8 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.session;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Vector;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpSession;
-
-import org.apache.commons.fileupload.FileItem;
-
-import mir.util.HTTPParsedRequest;
-
-public class HTTPAdapters {
-  public static class HTTPRequestAdapter implements Request {
-    private HttpServletRequest request;
-
-    public HTTPRequestAdapter(HttpServletRequest aRequest) {
-      request = aRequest;
-    }
-
-    public String getHeader(String aHeaderName) {
-      return request.getHeader(aHeaderName);
-    };
-
-    public String getParameter(String aName) {
-      return request.getParameter(aName);
-    };
-
-    public List getUploadedFiles() {
-      return new Vector();
-    };
-
-    public List getParameters(String aName) {
-      return Arrays.asList(request.getParameterValues(aName));
-    };
-
-    public HttpServletRequest getRequest() {
-      return request;
-    }
-  }
-
-  public static class HTTPParsedRequestAdapter implements Request {
-    private HTTPParsedRequest request;
-
-    public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) {
-      request = aRequest;
-    }
-
-    public String getHeader(String aHeaderName) {
-      return request.getHeader(aHeaderName);
-    };
-
-    public String getParameter(String aName) {
-      return request.getParameter(aName);
-    };
-
-    public List getParameters(String aName) {
-      return request.getParameterList(aName);
-    };
-
-    public List getUploadedFiles() {
-      List result = new Vector();
-      List files = request.getFiles();
-
-      for (int i=0; i<files.size(); i++) {
-        result.add(new CommonsUploadedFileAdapter((FileItem) files.get(i)));
-      }
-
-      return result;
-    };
-
-    public HttpServletRequest getRequest() {
-      return request.getRequest();
-    }
-  }
-
-  public static class HTTPSessionAdapter implements Session {
-    private HttpSession session;
-
-    public HTTPSessionAdapter(HttpSession aSession) {
-      session = aSession;
-    }
-    public Object getAttribute(String aName) {
-      return session.getAttribute(aName);
-    }
-
-    public void deleteAttribute(String aName) {
-      session.removeAttribute(aName);
-    }
-
-    public void setAttribute(String aName, Object aNewValue) {
-      if (aNewValue==null)
-        deleteAttribute(aName);
-      else
-        session.setAttribute(aName, aNewValue);
-    }
-
-    public void terminate() {
-      session.invalidate();
-    }
-  }
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.session;\r
+\r
+import java.util.Arrays;\r
+import java.util.List;\r
+import java.util.Vector;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpSession;\r
+\r
+import org.apache.commons.fileupload.FileItem;\r
+\r
+import mir.util.HTTPParsedRequest;\r
+\r
+public class HTTPAdapters {\r
+  public static class HTTPRequestAdapter implements Request {\r
+    private HttpServletRequest request;\r
+\r
+    public HTTPRequestAdapter(HttpServletRequest aRequest) {\r
+      request = aRequest;\r
+    }\r
+\r
+    public String getHeader(String aHeaderName) {\r
+      if (aHeaderName.equals("ip"))\r
+        return request.getRemoteAddr();\r
+\r
+      return request.getHeader(aHeaderName);\r
+    };\r
+\r
+    public String getParameter(String aName) {\r
+      return request.getParameter(aName);\r
+    };\r
+\r
+    public List getUploadedFiles() {\r
+      return new Vector();\r
+    };\r
+\r
+    public List getParameters(String aName) {\r
+      return Arrays.asList(request.getParameterValues(aName));\r
+    };\r
+\r
+    public HttpServletRequest getRequest() {\r
+      return request;\r
+    }\r
+  }\r
+\r
+  public static class HTTPParsedRequestAdapter implements Request {\r
+    private HTTPParsedRequest request;\r
+\r
+    public HTTPParsedRequestAdapter(HTTPParsedRequest aRequest) {\r
+      request = aRequest;\r
+    }\r
+\r
+    public String getHeader(String aHeaderName) {\r
+      if (aHeaderName.equals("ip"))\r
+        return request.getRequest().getRemoteAddr();\r
+\r
+      return request.getHeader(aHeaderName);\r
+    };\r
+\r
+    public String getParameter(String aName) {\r
+      return request.getParameter(aName);\r
+    };\r
+\r
+    public List getParameters(String aName) {\r
+      return request.getParameterList(aName);\r
+    };\r
+\r
+    public List getUploadedFiles() {\r
+      List result = new Vector();\r
+      List files = request.getFiles();\r
+\r
+      for (int i=0; i<files.size(); i++) {\r
+        result.add(new CommonsUploadedFileAdapter((FileItem) files.get(i)));\r
+      }\r
+\r
+      return result;\r
+    };\r
+\r
+    public HttpServletRequest getRequest() {\r
+      return request.getRequest();\r
+    }\r
+  }\r
+\r
+  public static class HTTPSessionAdapter implements Session {\r
+    private HttpSession session;\r
+\r
+    public HTTPSessionAdapter(HttpSession aSession) {\r
+      session = aSession;\r
+    }\r
+    public Object getAttribute(String aName) {\r
+      return session.getAttribute(aName);\r
+    }\r
+\r
+    public void deleteAttribute(String aName) {\r
+      session.removeAttribute(aName);\r
+    }\r
+\r
+    public void setAttribute(String aName, Object aNewValue) {\r
+      if (aName.equals("$httpsessiontimeout")) {\r
+        if (aNewValue instanceof Number) {\r
+          try {\r
+            session.setMaxInactiveInterval( ( (Number) aNewValue).intValue());\r
+          }\r
+          catch (Throwable t) {\r
+          }\r
+        }\r
+      }\r
+      else {\r
+        if (aNewValue == null)\r
+          deleteAttribute(aName);\r
+        else\r
+          session.setAttribute(aName, aNewValue);\r
+      }\r
+    }\r
+\r
+    public void terminate() {\r
+      session.invalidate();\r
+    }\r
+  }\r
 }
\ No newline at end of file
index 59d8c4b..b424af1 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.session;
diff --git a/source/mir/session/ValidationError.java b/source/mir/session/ValidationError.java
new file mode 100755 (executable)
index 0000000..5768240
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.session;
+
+import java.util.Arrays;
+import java.util.List;
+
+  /**
+   * Class that represents a validation error
+   *
+   * <p>Title: </p>
+   * <p>Description: </p>
+   * <p>Copyright: Copyright (c) 2003</p>
+   * <p>Company: </p>
+   * @author not attributable
+   * @version 1.0
+   */
+
+public class ValidationError {
+  private String field;
+  private String message;
+  private List parameters;
+  
+  public ValidationError(String aField, String aMessage) {
+    this (aField, aMessage, new String[] {});
+  }
+  
+  public ValidationError(String aField, String aMessage, Object aParameter) {
+    this (aField, aMessage, new Object[] {aParameter});
+  }
+  
+  public ValidationError(String aField, String aMessage, Object[] aParameters) {
+    field = aField;
+    message = aMessage;
+    parameters = Arrays.asList(aParameters);
+  }
+
+  public String getMessage() {
+    return message;
+  }
+  
+  public String getField() {
+    return field;
+  }
+  
+  public List getParameters() {
+    return parameters;
+    }
+}
+
+
diff --git a/source/mir/session/ValidationHelper.java b/source/mir/session/ValidationHelper.java
new file mode 100755 (executable)
index 0000000..015b9ab
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.session;
+
+import java.util.List;
+
+import mir.session.Request;
+import mir.session.ValidationError;
+
+
+public class ValidationHelper {
+  /**
+   * Convenience validation method to test whether a field has been filled in
+   *
+   * @param aRequest
+   * @param aFieldName
+   * @param anErrorMessageResource
+   * @param aValidationResults
+   * @return
+   */
+
+  public static boolean testFieldEntered(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
+    Object value = aRequest.getParameter(aFieldName);
+    if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) {
+      aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
+      return false;
+    }
+    else
+      return true;
+  }
+
+  /**
+   * Convenience validation method to test wether a field is numeric
+
+   * @param aRequest
+   * @param aFieldName
+   * @param anErrorMessageResource
+   * @param aValidationResults
+   * @return
+   */
+
+  public static boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
+    Object value = aRequest.getParameter(aFieldName);
+    if (value!=null) {
+      try {
+        Integer.parseInt((String) value);
+        return true;
+      }
+      catch (Throwable t) {
+        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
+        return false;
+      }
+    }
+    return true;
+  }
+
+  /**
+   * Convenience validation method to test whether a field exceeds a given length
+
+   * @param aRequest
+   * @param aFieldName
+   * @param aMaxLength
+   * @param anErrorMessageResource
+   * @param aValidationResults
+   * @return
+   */
+
+  public static boolean testFieldLength(Request aRequest, String aFieldName, int aMaxLength, String anErrorMessageResource, List aValidationResults) {
+    String value = aRequest.getParameter(aFieldName);
+
+    if (value!=null) {
+      if (value.length()>aMaxLength) {
+        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
+        return false;
+      }
+      else return true;
+    }
+    return true;
+  }
+}
index 01cd614..468c06b 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.storage;
-
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Timestamp;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.*;
-import java.util.Map;
-
-import com.codestudio.util.SQLManager;
-
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.entity.Entity;
-import mir.entity.EntityList;
-import mir.entity.StorableObjectEntity;
-import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
-import mir.misc.StringUtil;
-import mir.storage.store.ObjectStore;
-import mir.storage.store.StorableObject;
-import mir.storage.store.StoreContainerType;
-import mir.storage.store.StoreIdentifier;
-import mir.storage.store.StoreUtil;
-import mir.util.JDBCStringRoutines;
-
-
-/**
- * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.
- * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.
- * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.
- * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten
- * Treiber, Host, User und Passwort, ueber den der Zugriff auf die
- * Datenbank erfolgt.
- *
- * @version $Id: Database.java,v 1.45 2003/06/24 21:49:22 idfx Exp $
- * @author rk
- *
- */
-public class Database implements StorageObject {
-  private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
-  private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;
-
-
-  private static SimpleHash POPUP_EMPTYLINE = new SimpleHash();
-  protected static final ObjectStore o_store = ObjectStore.getInstance();
-  private static final int _millisPerHour = 60 * 60 * 1000;
-  private static final int _millisPerMinute = 60 * 1000;
-
-  static {
-    // always same object saves a little space
-    POPUP_EMPTYLINE.put("key", "");
-    POPUP_EMPTYLINE.put("value", "--");
-  }
-
-  protected LoggerWrapper logger;
-  protected MirPropertiesConfiguration configuration;
-  protected String theTable;
-  protected String theCoreTable = null;
-  protected String thePKeyName = "id";
-  protected int thePKeyType;
-  protected int thePKeyIndex;
-  protected boolean evaluatedMetaData = false;
-  protected ArrayList metadataFields;
-  protected ArrayList metadataLabels;
-  protected ArrayList metadataNotNullFields;
-  protected int[] metadataTypes;
-  protected Class theEntityClass;
-  protected SimpleList popupCache = null;
-  protected boolean hasPopupCache = false;
-  protected SimpleHash hashCache = null;
-  protected boolean hasTimestamp = true;
-  private String database_driver;
-  private String database_url;
-  private int defaultLimit;
-  protected DatabaseAdaptor theAdaptor;
-  private SimpleDateFormat _dateFormatterOut =
-    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-  private SimpleDateFormat _dateFormatterIn =
-    new SimpleDateFormat("yyyy-MM-dd HH:mm");
-  private Calendar _cal = new GregorianCalendar();
-
-  /**
-   * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.
-   * Aus diesem file werden <code>Database.Logfile</code>,
-   * <code>Database.Username</code>,<code>Database.Password</code>,
-   * <code>Database.Host</code> und <code>Database.Adaptor</code>
-   * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank
-   * erzeugt.
-   *
-   * @param   String confFilename Dateiname der Konfigurationsdatei
-   */
-  public Database() throws StorageObjectFailure {
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new StorageObjectFailure(e);
-    }
-    logger = new LoggerWrapper("Database");
-
-    String theAdaptorName = configuration.getString("Database.Adaptor");
-    defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));
-
-    try {
-      theEntityClass = GENERIC_ENTITY_CLASS;
-      theAdaptor = (DatabaseAdaptor) Class.forName(theAdaptorName).newInstance();
-    }
-    catch (Throwable e) {
-      logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());
-      throw new StorageObjectFailure("Error in Database() constructor.", e);
-    }
-  }
-
-  /**
-   * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt
-   * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,
-   * wird eine mir.entity.GenericEntity erzeugt.
-   *
-   * @return Class-Objekt der Entity
-   */
-  public java.lang.Class getEntityClass() {
-    return theEntityClass;
-  }
-
-  /**
-   * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also
-   * wieviel Datens?tze per Default selektiert werden.
-   *
-   * @return Standard-Anzahl der Datens?tze
-   */
-  public int getLimit() {
-    return defaultLimit;
-  }
-
-  /**
-   * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von
-   * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>
-   * @return Name des Primary-Keys
-   */
-  public String getIdName() {
-    return thePKeyName;
-  }
-
-  /**
-   * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.
-   *
-   * @return Name der Tabelle
-   */
-  public String getTableName() {
-    return theTable;
-  }
-
-  /*
-  *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS
-  *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet
-  *   wird.
-  *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst
-  *    the Table
-   */
-  public String getCoreTable() {
-    if (theCoreTable != null) {
-      return theCoreTable;
-    }
-    else {
-      return theTable;
-    }
-  }
-
-  /**
-   * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)
-   * @return int-Array mit den Typen der Felder
-   * @exception StorageObjectException
-   */
-  public int[] getTypes() throws StorageObjectFailure {
-    if (metadataTypes == null) {
-      get_meta_data();
-    }
-
-    return metadataTypes;
-  }
-
-  /**
-   * Liefert eine Liste der Labels der Tabellenfelder
-   * @return ArrayListe mit Labeln
-   * @exception StorageObjectException
-   */
-  public List getLabels() throws StorageObjectFailure {
-    if (metadataLabels == null) {
-      get_meta_data();
-    }
-
-    return metadataLabels;
-  }
-
-  /**
-   * Liefert eine Liste der Felder der Tabelle
-   * @return ArrayList mit Feldern
-   * @exception StorageObjectException
-   */
-  public List getFields() throws StorageObjectFailure {
-    if (metadataFields == null) {
-      get_meta_data();
-    }
-
-    return metadataFields;
-  }
-
-  /*
-  *   Gets value out of ResultSet according to type and converts to String
-  *   @param inValue  Wert aus ResultSet.
-  *   @param aType  Datenbanktyp.
-  *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich
-  *           dann /unsupported value/
-   */
-  private String getValueAsString(ResultSet rs, int valueIndex, int aType)
-    throws StorageObjectFailure {
-    String outValue = null;
-
-    if (rs != null) {
-      try {
-        switch (aType) {
-          case java.sql.Types.BIT:
-            outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";
-
-            break;
-
-          case java.sql.Types.INTEGER:
-          case java.sql.Types.SMALLINT:
-          case java.sql.Types.TINYINT:
-          case java.sql.Types.BIGINT:
-
-            int out = rs.getInt(valueIndex);
-
-            if (!rs.wasNull()) {
-              outValue = new Integer(out).toString();
-            }
-
-            break;
-
-          case java.sql.Types.NUMERIC:
-
-            /** @todo Numeric can be float or double depending upon
-             *  metadata.getScale() / especially with oracle */
-            long outl = rs.getLong(valueIndex);
-
-            if (!rs.wasNull()) {
-              outValue = new Long(outl).toString();
-            }
-
-            break;
-
-          case java.sql.Types.REAL:
-
-            float tempf = rs.getFloat(valueIndex);
-
-            if (!rs.wasNull()) {
-              tempf *= 10;
-              tempf += 0.5;
-
-              int tempf_int = (int) tempf;
-              tempf = (float) tempf_int;
-              tempf /= 10;
-              outValue = "" + tempf;
-              outValue = outValue.replace('.', ',');
-            }
-
-            break;
-
-          case java.sql.Types.DOUBLE:
-
-            double tempd = rs.getDouble(valueIndex);
-
-            if (!rs.wasNull()) {
-              tempd *= 10;
-              tempd += 0.5;
-
-              int tempd_int = (int) tempd;
-              tempd = (double) tempd_int;
-              tempd /= 10;
-              outValue = "" + tempd;
-              outValue = outValue.replace('.', ',');
-            }
-
-            break;
-
-          case java.sql.Types.CHAR:
-          case java.sql.Types.VARCHAR:
-          case java.sql.Types.LONGVARCHAR:
-            outValue = rs.getString(valueIndex);
-
-            break;
-
-          case java.sql.Types.LONGVARBINARY:
-            outValue = rs.getString(valueIndex);
-
-            break;
-
-          case java.sql.Types.TIMESTAMP:
-
-            // it's important to use Timestamp here as getting it
-            // as a string is undefined and is only there for debugging
-            // according to the API. we can make it a string through formatting.
-            // -mh
-            Timestamp timestamp = (rs.getTimestamp(valueIndex));
-
-            if (!rs.wasNull()) {
-              java.util.Date date = new java.util.Date(timestamp.getTime());
-              outValue = _dateFormatterOut.format(date);
-              _cal.setTime(date);
-
-              int offset =
-                  _cal.get(Calendar.ZONE_OFFSET) + _cal.get(Calendar.DST_OFFSET);
-              String tzOffset =
-                  StringUtil.zeroPaddingNumber(offset / _millisPerHour, 2, 2);
-              outValue = outValue + "+" + tzOffset;
-            }
-
-            break;
-
-          default:
-            outValue = "<unsupported value>";
-            logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");
-        }
-      } catch (SQLException e) {
-        throw new StorageObjectFailure("Could not get Value out of Resultset -- ",
-          e);
-      }
-    }
-
-    return outValue;
-  }
-
-  /*
-  *   select-Operator um einen Datensatz zu bekommen.
-  *   @param id Primaerschluessel des Datensatzes.
-  *   @return liefert EntityObject des gefundenen Datensatzes oder null.
-   */
-  public Entity selectById(String id) throws StorageObjectExc {
-    if ((id == null) || id.equals("")) {
-      throw new StorageObjectExc("Database.selectById: Missing id");
-    }
-
-    // ask object store for object
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {
-      String uniqueId = id;
-
-      if (theEntityClass.equals(StorableObjectEntity.class)) {
-        uniqueId += ("@" + theTable);
-      }
-
-      StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);
-      logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());
-
-      Entity hit = (Entity) o_store.use(search_sid);
-
-      if (hit != null) {
-        return hit;
-      }
-    }
-
-    Statement stmt = null;
-    Connection con = getPooledCon();
-    Entity returnEntity = null;
-
-    try {
-      ResultSet rs;
-
-      /** @todo better prepared statement */
-      String selectSql =
-        "select * from " + theTable + " where " + thePKeyName + "=" + id;
-      stmt = con.createStatement();
-      rs = executeSql(stmt, selectSql);
-
-      if (rs != null) {
-        if (evaluatedMetaData == false) {
-          evalMetaData(rs.getMetaData());
-        }
-
-        if (rs.next()) {
-          returnEntity = makeEntityFromResultSet(rs);
-        }
-        else {
-          logger.debug("No data for id: " + id + " in table " + theTable);
-        }
-
-        rs.close();
-      }
-      else {
-        logger.debug("No Data for Id " + id + " in Table " + theTable);
-      }
-    }
-    catch (SQLException sqe) {
-      throwSQLException(sqe, "selectById");
-      return null;
-    }
-    catch (NumberFormatException e) {
-      logger.error("ID is no number: " + id);
-    }
-    finally {
-      freeConnection(con, stmt);
-    }
-
-    return returnEntity;
-  }
-
-  /**
-   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
-   *   @param key  Datenbankfeld der Bedingung.
-   *   @param value  Wert die der key anehmen muss.
-   *   @return EntityList mit den gematchten Entities
-   */
-  public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {
-    return selectByFieldValue(aField, aValue, 0);
-  }
-
-  /**
-   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.
-   *   @param key  Datenbankfeld der Bedingung.
-   *   @param value  Wert die der key anehmen muss.
-   *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.
-   *   @return EntityList mit den gematchten Entities
-   */
-  public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {
-    return selectByWhereClause(aField + "=" + aValue, offset);
-  }
-
-  /**
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
-   * Also offset wird der erste Datensatz genommen.
-   *
-   * @param wc where-Clause
-   * @return EntityList mit den gematchten Entities
-   * @exception StorageObjectException
-   */
-  public EntityList selectByWhereClause(String where) throws StorageObjectFailure {
-    return selectByWhereClause(where, 0);
-  }
-
-  /**
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
-   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
-   *
-   * @param wc where-Clause
-   * @param offset ab welchem Datensatz.
-   * @return EntityList mit den gematchten Entities
-   * @exception StorageObjectException
-   */
-  public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {
-    return selectByWhereClause(whereClause, null, offset);
-  }
-
-  /**
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
-   * Also offset wird der erste Datensatz genommen.
-   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
-   *
-   * @param wc where-Clause
-   * @param ob orderBy-Clause
-   * @return EntityList mit den gematchten Entities
-   * @exception StorageObjectException
-   */
-  public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {
-    return selectByWhereClause(where, order, 0);
-  }
-
-  /**
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
-   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.
-   *
-   * @param wc where-Clause
-   * @param ob orderBy-Clause
-   * @param offset ab welchem Datensatz
-   * @return EntityList mit den gematchten Entities
-   * @exception StorageObjectException
-   */
-  public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {
-    return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);
-  }
-
-  /**
-   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.
-   * @param aWhereClause where-Clause
-   * @param anOrderByClause orderBy-Clause
-   * @param offset ab welchem Datensatz
-   * @param limit wieviele Datens?tze
-   * @return EntityList mit den gematchten Entities
-   * @exception StorageObjectException
-   */
-  public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,
-            int offset, int limit) throws StorageObjectFailure {
-
-    // check o_store for entitylist
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {
-      StoreIdentifier search_sid =
-          new StoreIdentifier(
-            theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,
-            StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));
-      EntityList hit = (EntityList) o_store.use(search_sid);
-
-      if (hit != null) {
-        logger.debug("CACHE (hit): " + search_sid.toString());
-
-        return hit;
-      }
-    }
-
-    // local
-    EntityList theReturnList = null;
-    Connection con = null;
-    Statement stmt = null;
-    ResultSet rs;
-    int offsetCount = 0;
-    int count = 0;
-
-    // build sql-statement
-
-    /** @todo count sql string should only be assembled if we really count
-     *  see below at the end of method //rk */
-    if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {
-      aWhereClause = null;
-    }
-
-    StringBuffer countSql =
-      new StringBuffer("select count(*) from ").append(theTable);
-    StringBuffer selectSql =
-      new StringBuffer("select * from ").append(theTable);
-
-    if (aWhereClause != null) {
-      selectSql.append(" where ").append(aWhereClause);
-      countSql.append(" where ").append(aWhereClause);
-    }
-
-    if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {
-      selectSql.append(" order by ").append(anOrderByClause);
-    }
-
-    if (theAdaptor.hasLimit()) {
-      if ((limit > -1) && (offset > -1)) {
-        selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);
-      }
-    }
-
-    // execute sql
-    try {
-      con = getPooledCon();
-      stmt = con.createStatement();
-
-      // selecting...
-      rs = executeSql(stmt, selectSql.toString());
-
-      if (rs != null) {
-        if (!evaluatedMetaData) {
-          evalMetaData(rs.getMetaData());
-        }
-
-        theReturnList = new EntityList();
-
-        Entity theResultEntity;
-
-        while (rs.next()) {
-          theResultEntity = makeEntityFromResultSet(rs);
-          theReturnList.add(theResultEntity);
-          offsetCount++;
-        }
-
-        rs.close();
-      }
-
-      // making entitylist infos
-      if (!(theAdaptor.hasLimit())) {
-        count = offsetCount;
-      }
-
-      if (theReturnList != null) {
-        // now we decide if we have to know an overall count...
-        count = offsetCount;
-
-        if ((limit > -1) && (offset > -1)) {
-          if (offsetCount == limit) {
-            /** @todo counting should be deffered to entitylist
-             *  getSize() should be used */
-            rs = executeSql(stmt, countSql.toString());
-
-            if (rs != null) {
-              if (rs.next()) {
-                count = rs.getInt(1);
-              }
-
-              rs.close();
-            }
-            else {
-              logger.error("Could not count: " + countSql);
-            }
-          }
-        }
-
-        theReturnList.setCount(count);
-        theReturnList.setOffset(offset);
-        theReturnList.setWhere(aWhereClause);
-        theReturnList.setOrder(anOrderByClause);
-        theReturnList.setStorage(this);
-        theReturnList.setLimit(limit);
-
-        if (offset >= limit) {
-          theReturnList.setPrevBatch(offset - limit);
-        }
-
-        if ((offset + offsetCount) < count) {
-          theReturnList.setNextBatch(offset + limit);
-        }
-
-        if (StoreUtil.implementsStorableObject(theEntityClass)) {
-          StoreIdentifier sid = theReturnList.getStoreIdentifier();
-          logger.debug("CACHE (add): " + sid.toString());
-          o_store.add(sid);
-        }
-      }
-    }
-    catch (SQLException sqe) {
-      throwSQLException(sqe, "selectByWhereClause");
-    }
-    finally {
-      try {
-        if (con != null) {
-          freeConnection(con, stmt);
-        }
-      } catch (Throwable t) {
-      }
-    }
-
-    return theReturnList;
-  }
-
-  /**
-   *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.
-   *
-   *  @param rs Das ResultSetObjekt.
-   *  @return Entity Die Entity.
-   */
-  private Entity makeEntityFromResultSet(ResultSet rs)
-    throws StorageObjectFailure {
-    /** @todo OS: get Pkey from ResultSet and consult ObjectStore */
-    Map theResultHash = new HashMap();
-    String theResult = null;
-    int theType;
-    Entity returnEntity = null;
-
-    try {
-      int size = metadataFields.size();
-
-      for (int i = 0; i < size; i++) {
-        // alle durchlaufen bis nix mehr da
-        theType = metadataTypes[i];
-
-        if (theType == java.sql.Types.LONGVARBINARY) {
-          InputStreamReader is =
-            (InputStreamReader) rs.getCharacterStream(i + 1);
-
-          if (is != null) {
-            char[] data = new char[32768];
-            StringBuffer theResultString = new StringBuffer();
-            int len;
-
-            while ((len = is.read(data)) > 0) {
-              theResultString.append(data, 0, len);
-            }
-
-            is.close();
-            theResult = theResultString.toString();
-          } else {
-            theResult = null;
-          }
-        } else {
-          theResult = getValueAsString(rs, (i + 1), theType);
-        }
-
-        if (theResult != null) {
-          theResultHash.put(metadataFields.get(i), theResult);
-        }
-      }
-
-      if (theEntityClass != null) {
-        returnEntity = (Entity) theEntityClass.newInstance();
-        returnEntity.setValues(theResultHash);
-        returnEntity.setStorage(this);
-
-        if (returnEntity instanceof StorableObject) {
-          logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);
-          o_store.add(((StorableObject) returnEntity).getStoreIdentifier());
-        }
-      } else {
-        throwStorageObjectException("Internal Error: theEntityClass not set!");
-      }
-    }
-    catch (IllegalAccessException e) {
-      throwStorageObjectException("No access! -- " + e.getMessage());
-    }
-    catch (IOException e) {
-      throwStorageObjectException("IOException! -- " + e.getMessage());
-    }
-    catch (InstantiationException e) {
-      throwStorageObjectException("No Instatiation! -- " + e.getMessage());
-    }
-    catch (SQLException sqe) {
-      throwSQLException(sqe, "makeEntityFromResultSet");
-
-      return null;
-    }
-
-    return returnEntity;
-  }
-
-  /**
-   * Inserts an entity into the database.
-   *
-   * @param theEntity
-   * @return der Wert des Primary-keys der eingef?gten Entity
-   */
-  public String insert(Entity theEntity) throws StorageObjectFailure {
-    //cache
-    invalidatePopupCache();
-
-    // invalidating all EntityLists corresponding with theEntityClass
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {
-      StoreContainerType stoc_type =
-        StoreContainerType.valueOf(theEntityClass,
-          StoreContainerType.STOC_TYPE_ENTITYLIST);
-      o_store.invalidate(stoc_type);
-    }
-
-    String returnId = null;
-    Connection con = null;
-    PreparedStatement pstmt = null;
-
-    try {
-      List streamedInput = theEntity.streamedInput();
-      StringBuffer f = new StringBuffer();
-      StringBuffer v = new StringBuffer();
-      String aField;
-      String aValue;
-      boolean firstField = true;
-
-      // make sql-string
-      for (int i = 0; i < getFields().size(); i++) {
-        aField = (String) getFields().get(i);
-
-        if (!aField.equals(thePKeyName)) {
-          aValue = null;
-
-          // exceptions
-          if (aField.equals("webdb_create") ||
-              aField.equals("webdb_lastchange")) {
-            aValue = "NOW()";
-          }
-          else {
-            if ((streamedInput != null) && streamedInput.contains(aField)) {
-              aValue = "?";
-            } else {
-              if (theEntity.hasValueForField(aField)) {
-                aValue =
-                  "'" +
-                  JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(
-                      aField)) + "'";
-              }
-            }
-          }
-
-          // wenn Wert gegeben, dann einbauen
-          if (aValue != null) {
-            if (firstField == false) {
-              f.append(",");
-              v.append(",");
-            }
-            else {
-              firstField = false;
-            }
-
-            f.append(aField);
-            v.append(aValue);
-          }
-        }
-      }
-       // end for
-
-      // insert into db
-      StringBuffer sqlBuf =
-        new StringBuffer("insert into ").append(theTable).append("(").append(f)
-                                        .append(") values (").append(v).append(")");
-      String sql = sqlBuf.toString();
-
-      logger.debug("INSERT: " + sql);
-      con = getPooledCon();
-      con.setAutoCommit(false);
-      pstmt = con.prepareStatement(sql);
-
-      if (streamedInput != null) {
-        for (int i = 0; i < streamedInput.size(); i++) {
-          String inputString =
-            (String) theEntity.getValue((String) streamedInput.get(i));
-          pstmt.setBytes(i + 1, inputString.getBytes());
-        }
-      }
-
-      int ret = pstmt.executeUpdate();
-
-      if (ret == 0) {
-        //insert failed
-        return null;
-      }
-
-      pstmt = con.prepareStatement(theAdaptor.getLastInsertSQL(this));
-
-      ResultSet rs = pstmt.executeQuery();
-      rs.next();
-      returnId = rs.getString(1);
-      theEntity.setId(returnId);
-    }
-    catch (SQLException sqe) {
-                       sqe.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));         
-      throwSQLException(sqe, "insert");
-    }
-    finally {
-      try {
-        con.setAutoCommit(true);
-      }
-      catch (Exception e) {
-                               e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      }
-
-      freeConnection(con, pstmt);
-    }
-
-    /** @todo store entity in o_store */
-    return returnId;
-  }
-
-  /**
-   * Updates an entity in the database
-   *
-   * @param theEntity
-   */
-  public void update(Entity theEntity) throws StorageObjectFailure {
-    Connection con = null;
-    PreparedStatement pstmt = null;
-
-    /** @todo this is stupid: why do we prepare statement, when we
-     *  throw it away afterwards. should be regular statement
-     *  update/insert could better be one routine called save()
-     *  that chooses to either insert or update depending if we
-     *  have a primary key in the entity. i don't know if we
-     *  still need the streamed input fields. // rk  */
-    /** @todo extension: check if Entity did change, otherwise we don't need
-     *  the roundtrip to the database */
-    /** invalidating corresponding entitylists in o_store*/
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {
-      StoreContainerType stoc_type =
-        StoreContainerType.valueOf(theEntityClass,
-          StoreContainerType.STOC_TYPE_ENTITYLIST);
-      o_store.invalidate(stoc_type);
-    }
-
-    List streamedInput = theEntity.streamedInput();
-    String id = theEntity.getId();
-    String aField;
-    StringBuffer fv = new StringBuffer();
-    boolean firstField = true;
-
-    //cache
-    invalidatePopupCache();
-
-    // build sql statement
-    for (int i = 0; i < getFields().size(); i++) {
-      aField = (String) metadataFields.get(i);
-
-      // only normal cases
-      if (  !(aField.equals(thePKeyName) ||
-            aField.equals("webdb_create") ||
-            aField.equals("webdb_lastchange") ||
-            ((streamedInput != null) && streamedInput.contains(aField)))) {
-        if (theEntity.hasValueForField(aField)) {
-          if (firstField == false) {
-            fv.append(", ");
-          }
-          else {
-            firstField = false;
-          }
-
-          fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");
-
-          //              fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");
-        }
-      }
-    }
-
-    StringBuffer sql =
-      new StringBuffer("update ").append(theTable).append(" set ").append(fv);
-
-    // exceptions
-    if (metadataFields.contains("webdb_lastchange")) {
-      sql.append(",webdb_lastchange=NOW()");
-    }
-
-    // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm
-    // format so anything extra will be ignored. -mh
-    if (metadataFields.contains("webdb_create") &&
-        theEntity.hasValueForField("webdb_create")) {
-      // minimum of 10 (yyyy-mm-dd)...
-      if (theEntity.getValue("webdb_create").length() >= 10) {
-        String dateString = theEntity.getValue("webdb_create");
-
-        // if only 10, then add 00:00 so it doesn't throw a ParseException
-        if (dateString.length() == 10) {
-          dateString = dateString + " 00:00";
-        }
-
-        // TimeStamp stuff
-        try {
-          java.util.Date d = _dateFormatterIn.parse(dateString);
-          Timestamp tStamp = new Timestamp(d.getTime());
-          sql.append(",webdb_create='" + tStamp.toString() + "'");
-        } catch (ParseException e) {
-          throw new StorageObjectFailure(e);
-        }
-      }
-    }
-
-    if (streamedInput != null) {
-      for (int i = 0; i < streamedInput.size(); i++) {
-        sql.append(",").append(streamedInput.get(i)).append("=?");
-      }
-    }
-
-    sql.append(" where id=").append(id);
-    logger.debug("UPDATE: " + sql);
-
-    try {
-      con = getPooledCon();
-      con.setAutoCommit(false);
-      pstmt = con.prepareStatement(sql.toString());
-
-      if (streamedInput != null) {
-        for (int i = 0; i < streamedInput.size(); i++) {
-          String inputString =
-            theEntity.getValue((String) streamedInput.get(i));
-          pstmt.setBytes(i + 1, inputString.getBytes());
-        }
-      }
-
-      pstmt.executeUpdate();
-    }
-    catch (SQLException sqe) {
-      throwSQLException(sqe, "update");
-    }
-    finally {
-      try {
-        con.setAutoCommit(true);
-      }
-      catch (Exception e) {
-        ;
-      }
-
-      freeConnection(con, pstmt);
-    }
-  }
-
-  /*
-  *   delete-Operator
-  *   @param id des zu loeschenden Datensatzes
-  *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.
-   */
-  public boolean delete(String id) throws StorageObjectFailure {
-    invalidatePopupCache();
-
-    // ostore send notification
-    if (StoreUtil.implementsStorableObject(theEntityClass)) {
-      String uniqueId = id;
-
-      if (theEntityClass.equals(StorableObjectEntity.class)) {
-        uniqueId += ("@" + theTable);
-      }
-
-      logger.debug("CACHE: (del) " + id);
-
-      StoreIdentifier search_sid =
-        new StoreIdentifier(theEntityClass,
-          StoreContainerType.STOC_TYPE_ENTITY, uniqueId);
-      o_store.invalidate(search_sid);
-    }
-
-    /** @todo could be prepared Statement */
-    Statement stmt = null;
-    Connection con = null;
-    int res = 0;
-    String sql =
-      "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";
-
-    //theLog.printInfo("DELETE " + sql);
-    try {
-      con = getPooledCon();
-      stmt = con.createStatement();
-      res = stmt.executeUpdate(sql);
-    } catch (SQLException sqe) {
-      throwSQLException(sqe, "delete");
-    } finally {
-      freeConnection(con, stmt);
-    }
-
-    return (res > 0) ? true : false;
-  }
-
-  /* noch nicht implementiert.
-  * @return immer false
-   */
-  public boolean delete(EntityList theEntityList) {
-    invalidatePopupCache();
-
-    return false;
-  }
-
-  /**
-   * Diese Methode sollte ueberschrieben werden, wenn fuer die abgeleitete Database-Klasse
-   * eine SimpleList mit Standard-Popupdaten erzeugt werden koennen soll.
-   * @return null
-   */
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return null;
-  }
-
-  /**
-   *  Holt Daten fuer Popups.
-   *  @param name  Name des Feldes.
-   *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
-   *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
-   */
-  public SimpleList getPopupData(String name, boolean hasNullValue)
-    throws StorageObjectFailure {
-    return getPopupData(name, hasNullValue, null);
-  }
-
-  /**
-   *  Holt Daten fuer Popups.
-   *  @param name  Name des Feldes.
-   *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
-   *  @param where  Schraenkt die Selektion der Datensaetze ein.
-   *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
-   */
-  public SimpleList getPopupData(String name, boolean hasNullValue, String where)
-    throws StorageObjectFailure {
-    return getPopupData(name, hasNullValue, where, null);
-  }
-
-  /**
-   *  Holt Daten fuer Popups.
-   *  @param name  Name des Feldes.
-   *  @param hasNullValue  Wenn true wird eine leerer  Eintrag fuer die Popups erzeugt.
-   *  @param where  Schraenkt die Selektion der Datensaetze ein.
-   *  @param order  Gibt ein Feld als Sortierkriterium an.
-   *  @return SimpleList Gibt freemarker.template.SimpleList zurueck.
-   */
-  public SimpleList getPopupData(String name, boolean hasNullValue,
-    String where, String order) throws StorageObjectFailure {
-    // caching
-    if (hasPopupCache && (popupCache != null)) {
-      return popupCache;
-    }
-
-    SimpleList simpleList = null;
-    Connection con = null;
-    Statement stmt = null;
-
-    // build sql
-    StringBuffer sql =
-      new StringBuffer("select ").append(thePKeyName).append(",").append(name)
-                                 .append(" from ").append(theTable);
-
-    if ((where != null) && !(where.length() == 0)) {
-      sql.append(" where ").append(where);
-    }
-
-    sql.append(" order by ");
-
-    if ((order != null) && !(order.length() == 0)) {
-      sql.append(order);
-    } else {
-      sql.append(name);
-    }
-
-    // execute sql
-    try {
-      con = getPooledCon();
-    } catch (Exception e) {
-      throw new StorageObjectFailure(e);
-    }
-
-    try {
-      stmt = con.createStatement();
-
-      ResultSet rs = executeSql(stmt, sql.toString());
-
-      if (rs != null) {
-        if (!evaluatedMetaData) {
-          get_meta_data();
-        }
-
-        simpleList = new SimpleList();
-
-        // if popup has null-selector
-        if (hasNullValue) {
-          simpleList.add(POPUP_EMPTYLINE);
-        }
-
-        SimpleHash popupDict;
-
-        while (rs.next()) {
-          popupDict = new SimpleHash();
-          popupDict.put("key", getValueAsString(rs, 1, thePKeyType));
-          popupDict.put("value", rs.getString(2));
-          simpleList.add(popupDict);
-        }
-
-        rs.close();
-      }
-    }
-    catch (Exception e) {
-      logger.error("getPopupData: " + e.getMessage());
-      throw new StorageObjectFailure(e);
-    } finally {
-      freeConnection(con, stmt);
-    }
-
-    if (hasPopupCache) {
-      popupCache = simpleList;
-    }
-
-    return simpleList;
-  }
-
-  /**
-   * Liefert alle Daten der Tabelle als SimpleHash zurueck. Dies wird verwandt,
-   * wenn in den Templates ein Lookup-Table benoetigt wird. Sollte nur bei kleinen
-   * Tabellen Verwendung finden.
-   * @return SimpleHash mit den Tabellezeilen.
-   */
-  public SimpleHash getHashData() {
-    /** @todo dangerous! this should have a flag to be enabled, otherwise
-     *  very big Hashes could be returned */
-    if (hashCache == null) {
-      try {
-        hashCache =
-          HTMLTemplateProcessor.makeSimpleHash(selectByWhereClause("", -1));
-      }
-      catch (StorageObjectFailure e) {
-        logger.debug(e.getMessage());
-      }
-    }
-
-    return hashCache;
-  }
-
-  /* invalidates the popupCache
-   */
-  protected void invalidatePopupCache() {
-    /** @todo  invalidates toooo much */
-    popupCache = null;
-    hashCache = null;
-  }
-
-  /**
-   * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.
-   * @param stmt Statemnt
-   * @param sql Sql-String
-   * @return ResultSet
-   * @exception StorageObjectException
-   */
-  public ResultSet executeSql(Statement stmt, String sql)
-                            throws StorageObjectFailure, SQLException {
-    ResultSet rs;
-    long startTime = System.currentTimeMillis();
-
-    try {
-      rs = stmt.executeQuery(sql);
-
-      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-    }
-    catch (SQLException e) {
-      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-      throw e;
-    }
-
-    return rs;
-  }
-/*
-  public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {
-    long startTime = System.currentTimeMillis();
-    Connection connection = null;
-    Statement statement = null;
-
-    try {
-      connection = getPooledCon();
-      statement = connection.createStatement();
-      ResultSet result;
-
-      result = statement.executeQuery(sql);
-
-      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-      return result;
-    }
-    catch (Throwable e) {
-      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-      throw new StorageObjectFailure(e);
-    }
-    finally {
-      if (connection!=null) {
-        freeConnection(connection, statement);
-      }
-    }
-  }
-*/
-  private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {
-    try {
-      Map result = new HashMap();
-      ResultSetMetaData metaData = aResultSet.getMetaData();
-      int nrColumns = metaData.getColumnCount();
-      for (int i=0; i<nrColumns; i++) {
-        result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));
-      }
-
-      return result;
-    }
-    catch (Throwable e) {
-      throw new StorageObjectFailure(e);
-    }
-  }
-
-  public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {
-    Connection connection = null;
-    Statement statement = null;
-    try {
-      List result = new Vector();
-      connection = getPooledCon();
-      statement = connection.createStatement();
-      ResultSet resultset = executeSql(statement, sql);
-      try {
-        while (resultset.next() && result.size() < aLimit) {
-          result.add(processRow(resultset));
-        }
-      }
-      finally {
-        resultset.close();
-      }
-
-      return result;
-    }
-    catch (Throwable e) {
-      throw new StorageObjectFailure(e);
-    }
-    finally {
-      if (connection!=null) {
-        freeConnection(connection, statement);
-      }
-    }
-  };
-
-  public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {
-    try {
-      List resultList = executeFreeSql(anSqlStatement, 1);
-      try {
-        if (resultList.size()>0)
-          return (Map) resultList.get(0);
-        else
-          return null;
-      }
-      finally {
-      }
-    }
-    catch (Throwable t) {
-      throw new StorageObjectFailure(t);
-    }
-  };
-
-  public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {
-    Map row = executeFreeSingleRowSql(sql);
-
-    if (row==null)
-      return null;
-
-    Iterator i = row.values().iterator();
-    if (i.hasNext())
-      return (String) i.next();
-    else
-      return null;
-  };
-
-  /**
-   * returns the number of rows in the table
-   */
-  public int getSize(String where) throws SQLException, StorageObjectFailure {
-    long startTime = System.currentTimeMillis();
-    String sql = "SELECT Count(*) FROM " + theTable;
-
-    if ((where != null) && (where.length() != 0)) {
-      sql = sql + " where " + where;
-    }
-
-    Connection con = null;
-    Statement stmt = null;
-    int result = 0;
-
-    try {
-      con = getPooledCon();
-      stmt = con.createStatement();
-
-      ResultSet rs = executeSql(stmt, sql);
-
-      while (rs.next()) {
-        result = rs.getInt(1);
-      }
-    }
-    catch (SQLException e) {
-      logger.error("Database.getSize: " + e.getMessage());
-    }
-    finally {
-      freeConnection(con, stmt);
-    }
-
-    //theLog.printInfo(theTable + " has "+ result +" rows where " + where);
-    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-
-    return result;
-  }
-
-  public int executeUpdate(Statement stmt, String sql)
-    throws StorageObjectFailure, SQLException {
-    int rs;
-    long startTime = System.currentTimeMillis();
-
-    try {
-      rs = stmt.executeUpdate(sql);
-
-      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-    }
-    catch (SQLException e) {
-      logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-      throw e;
-    }
-
-    return rs;
-  }
-
-  public int executeUpdate(String sql)
-    throws StorageObjectFailure, SQLException {
-    int result = -1;
-    long startTime = System.currentTimeMillis();
-    Connection con = null;
-    PreparedStatement pstmt = null;
-
-    try {
-      con = getPooledCon();
-      pstmt = con.prepareStatement(sql);
-      result = pstmt.executeUpdate();
-    }
-    catch (Throwable e) {
-      logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());
-      throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);
-    }
-    finally {
-      freeConnection(con, pstmt);
-    }
-
-    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);
-    return result;
-  }
-
-  /**
-   * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend
-   * @param md ResultSetMetaData
-   * @exception StorageObjectException
-   */
-  private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {
-    this.evaluatedMetaData = true;
-    this.metadataFields = new ArrayList();
-    this.metadataLabels = new ArrayList();
-    this.metadataNotNullFields = new ArrayList();
-
-    try {
-      int numFields = md.getColumnCount();
-      this.metadataTypes = new int[numFields];
-
-      String aField;
-      int aType;
-
-      for (int i = 1; i <= numFields; i++) {
-        aField = md.getColumnName(i);
-        metadataFields.add(aField);
-        metadataLabels.add(md.getColumnLabel(i));
-        aType = md.getColumnType(i);
-        metadataTypes[i - 1] = aType;
-
-        if (aField.equals(thePKeyName)) {
-          thePKeyType = aType;
-          thePKeyIndex = i;
-        }
-
-        if (md.isNullable(i) == ResultSetMetaData.columnNullable) {
-          metadataNotNullFields.add(aField);
-        }
-      }
-    }
-    catch (SQLException e) {
-      throwSQLException(e, "evalMetaData");
-    }
-  }
-
-  /**
-   *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,
-   *  um die alle Columns und Typen einer Tabelle zu ermitteln.
-   */
-  private void get_meta_data() throws StorageObjectFailure {
-    Connection con = null;
-    PreparedStatement pstmt = null;
-    String sql = "select * from " + theTable + " where 0=1";
-
-    try {
-      con = getPooledCon();
-      pstmt = con.prepareStatement(sql);
-
-      logger.debug("METADATA: " + sql);
-      ResultSet rs = pstmt.executeQuery();
-      evalMetaData(rs.getMetaData());
-      rs.close();
-    }
-    catch (SQLException e) {
-      throwSQLException(e, "get_meta_data");
-    }
-    finally {
-      freeConnection(con, pstmt);
-    }
-  }
-
-  public Connection getPooledCon() throws StorageObjectFailure {
-    Connection con = null;
-
-    try {
-      con = SQLManager.getInstance().requestConnection();
-    }
-    catch (SQLException e) {
-      logger.error("could not connect to the database " + e.getMessage());
-
-      throw new StorageObjectFailure("Could not connect to the database", e);
-    }
-
-    return con;
-  }
-
-  public void freeConnection(Connection con, Statement stmt)
-    throws StorageObjectFailure {
-    SQLManager.closeStatement(stmt);
-    SQLManager.getInstance().returnConnection(con);
-  }
-
-  /**
-   * Wertet SQLException aus und wirft dannach eine StorageObjectException
-   * @param sqe SQLException
-   * @param wo Funktonsname, in der die SQLException geworfen wurde
-   * @exception StorageObjectException
-   */
-  protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {
-    String state = "";
-    String message = "";
-    int vendor = 0;
-
-    if (sqe != null) {
-      state = sqe.getSQLState();
-      message = sqe.getMessage();
-      vendor = sqe.getErrorCode();
-    }
-
-    String information =
-        "SQL Error: " +
-        "state= " + state +
-        ", vendor= " + vendor +
-        ", message=" + message +
-        ", function= " + aFunction;
-
-    logger.error(information);
-
-    throw new StorageObjectFailure(information, sqe);
-  }
-
-  protected void _throwStorageObjectException(Exception e, String aFunction)
-    throws StorageObjectFailure {
-
-    if (e != null) {
-      logger.error(e.getMessage() + aFunction);
-      throw new StorageObjectFailure(aFunction, e);
-    }
-  }
-
-  /**
-   * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach
-   * eine StorageObjectException
-   * @param message Nachricht mit dem Fehler
-   * @exception StorageObjectException
-   */
-  void throwStorageObjectException(String aMessage) throws StorageObjectFailure {
-    logger.error(aMessage);
-    throw new StorageObjectFailure(aMessage, null);
-  }
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.storage;\r
+\r
+import java.io.IOException;\r
+import java.io.InputStreamReader;\r
+import java.sql.Connection;\r
+import java.sql.PreparedStatement;\r
+import java.sql.ResultSet;\r
+import java.sql.ResultSetMetaData;\r
+import java.sql.SQLException;\r
+import java.sql.Statement;\r
+import java.sql.Timestamp;\r
+import java.text.ParseException;\r
+import java.text.SimpleDateFormat;\r
+import java.util.ArrayList;\r
+import java.util.Calendar;\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.TimeZone;\r
+import java.util.Vector;\r
+\r
+import com.codestudio.util.SQLManager;\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.entity.Entity;\r
+import mir.entity.EntityList;\r
+import mir.entity.StorableObjectEntity;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.storage.store.ObjectStore;\r
+import mir.storage.store.StorableObject;\r
+import mir.storage.store.StoreContainerType;\r
+import mir.storage.store.StoreIdentifier;\r
+import mir.storage.store.StoreUtil;\r
+import mir.util.JDBCStringRoutines;\r
+\r
+\r
+/**\r
+ * Diese Klasse implementiert die Zugriffsschicht auf die Datenbank.\r
+ * Alle Projektspezifischen Datenbankklassen erben von dieser Klasse.\r
+ * In den Unterklassen wird im Minimalfall nur die Tabelle angegeben.\r
+ * Im Konfigurationsfile findet sich eine Verweis auf den verwendeten\r
+ * Treiber, Host, User und Passwort, ueber den der Zugriff auf die\r
+ * Datenbank erfolgt.\r
+ *\r
+ * @version $Id: Database.java,v 1.46 2003/09/03 18:29:03 zapata Exp $\r
+ * @author rk\r
+ *\r
+ */\r
+public class Database implements StorageObject {\r
+  private static Class GENERIC_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;\r
+  private static Class STORABLE_OBJECT_ENTITY_CLASS = mir.entity.StorableObjectEntity.class;\r
+\r
+\r
+  private static Map POPUP_EMPTYLINE = new HashMap();\r
+  protected static final ObjectStore o_store = ObjectStore.getInstance();\r
+  private static final int _millisPerHour = 60 * 60 * 1000;\r
+  private static final int _millisPerMinute = 60 * 1000;\r
+\r
+  static {\r
+    // always same object saves a little space\r
+    POPUP_EMPTYLINE.put("key", "");\r
+    POPUP_EMPTYLINE.put("value", "--");\r
+  }\r
+\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+  protected String theTable;\r
+  protected String theCoreTable = null;\r
+  protected String thePKeyName = "id";\r
+  protected int thePKeyType;\r
+  protected int thePKeyIndex;\r
+  protected boolean evaluatedMetaData = false;\r
+  protected ArrayList metadataFields;\r
+  protected ArrayList metadataLabels;\r
+  protected ArrayList metadataNotNullFields;\r
+  protected int[] metadataTypes;\r
+  protected Class theEntityClass;\r
+  protected List popupCache = null;\r
+  protected boolean hasPopupCache = false;\r
+  protected Map hashCache = null;\r
+  protected boolean hasTimestamp = true;\r
+  private String database_driver;\r
+  private String database_url;\r
+  private int defaultLimit;\r
+\r
+  TimeZone timezone;\r
+  SimpleDateFormat internalDateFormat;\r
+  SimpleDateFormat userInputDateFormat;\r
+/*\r
+  private SimpleDateFormat _dateFormatterOut;\r
+  private SimpleDateFormat _dateFormatterIn;\r
+  _dateFormatterOut = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
+  _dateFormatterIn = new SimpleDateFormat("yyyy-MM-dd HH:mm");\r
+*/\r
+\r
+  /**\r
+   * Kontruktor bekommt den Filenamen des Konfigurationsfiles ?bergeben.\r
+   * Aus diesem file werden <code>Database.Logfile</code>,\r
+   * <code>Database.Username</code>,<code>Database.Password</code>,\r
+   * <code>Database.Host</code> und <code>Database.Adaptor</code>\r
+   * ausgelesen und ein Broker f?r die Verbindugen zur Datenbank\r
+   * erzeugt.\r
+   *\r
+   * @param   String confFilename Dateiname der Konfigurationsdatei\r
+   */\r
+  public Database() throws StorageObjectFailure {\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (PropertiesConfigExc e) {\r
+      throw new StorageObjectFailure(e);\r
+    }\r
+    logger = new LoggerWrapper("Database");\r
+    timezone = TimeZone.getTimeZone(configuration.getString("Mir.DefaultTimezone"));\r
+    internalDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");\r
+    internalDateFormat.setTimeZone(timezone);\r
+\r
+    userInputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");\r
+    userInputDateFormat.setTimeZone(timezone);\r
+\r
+\r
+    String theAdaptorName = configuration.getString("Database.Adaptor");\r
+    defaultLimit = Integer.parseInt(configuration.getString("Database.Limit"));\r
+\r
+    try {\r
+      theEntityClass = GENERIC_ENTITY_CLASS;\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("Error in Database() constructor with " + theAdaptorName + " -- " + e.getMessage());\r
+      throw new StorageObjectFailure("Error in Database() constructor.", e);\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Liefert die Entity-Klasse zur?ck, in der eine Datenbankzeile gewrappt\r
+   * wird. Wird die Entity-Klasse durch die erbende Klasse nicht ?berschrieben,\r
+   * wird eine mir.entity.GenericEntity erzeugt.\r
+   *\r
+   * @return Class-Objekt der Entity\r
+   */\r
+  public java.lang.Class getEntityClass() {\r
+    return theEntityClass;\r
+  }\r
+\r
+  /**\r
+   * Liefert die Standardbeschr?nkung von select-Statements zur?ck, also\r
+   * wieviel Datens?tze per Default selektiert werden.\r
+   *\r
+   * @return Standard-Anzahl der Datens?tze\r
+   */\r
+  public int getLimit() {\r
+    return defaultLimit;\r
+  }\r
+\r
+  /**\r
+   * Liefert den Namen des Primary-Keys zur?ck. Wird die Variable nicht von\r
+   * der erbenden Klasse ?berschrieben, so ist der Wert <code>PKEY</code>\r
+   * @return Name des Primary-Keys\r
+   */\r
+  public String getIdName() {\r
+    return thePKeyName;\r
+  }\r
+\r
+  /**\r
+   * Liefert den Namen der Tabelle, auf das sich das Datenbankobjekt bezieht.\r
+   *\r
+   * @return Name der Tabelle\r
+   */\r
+  public String getTableName() {\r
+    return theTable;\r
+  }\r
+\r
+  /*\r
+  *   Dient dazu vererbte Tabellen bei objectrelationalen DBMS\r
+  *   zu speichern, wenn die id einer Tabelle in der parenttabelle verwaltet\r
+  *   wird.\r
+  *   @return liefert theCoreTabel als String zurueck, wenn gesetzt, sonst\r
+  *    the Table\r
+   */\r
+  public String getCoreTable() {\r
+    if (theCoreTable != null) {\r
+      return theCoreTable;\r
+    }\r
+    else {\r
+      return theTable;\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Liefert Feldtypen der Felder der Tabelle zurueck (s.a. java.sql.Types)\r
+   * @return int-Array mit den Typen der Felder\r
+   * @exception StorageObjectException\r
+   */\r
+  public int[] getTypes() throws StorageObjectFailure {\r
+    if (metadataTypes == null) {\r
+      get_meta_data();\r
+    }\r
+\r
+    return metadataTypes;\r
+  }\r
+\r
+  /**\r
+   * Liefert eine Liste der Labels der Tabellenfelder\r
+   * @return ArrayListe mit Labeln\r
+   * @exception StorageObjectException\r
+   */\r
+  public List getLabels() throws StorageObjectFailure {\r
+    if (metadataLabels == null) {\r
+      get_meta_data();\r
+    }\r
+\r
+    return metadataLabels;\r
+  }\r
+\r
+  /**\r
+   * Liefert eine Liste der Felder der Tabelle\r
+   * @return ArrayList mit Feldern\r
+   * @exception StorageObjectException\r
+   */\r
+  public List getFields() throws StorageObjectFailure {\r
+    if (metadataFields == null) {\r
+      get_meta_data();\r
+    }\r
+\r
+    return metadataFields;\r
+  }\r
+\r
+  /*\r
+  *   Gets value out of ResultSet according to type and converts to String\r
+  *   @param inValue  Wert aus ResultSet.\r
+  *   @param aType  Datenbanktyp.\r
+  *   @return liefert den Wert als String zurueck. Wenn keine Umwandlung moeglich\r
+  *           dann /unsupported value/\r
+   */\r
+  private String getValueAsString(ResultSet rs, int valueIndex, int aType)\r
+    throws StorageObjectFailure {\r
+    String outValue = null;\r
+\r
+    if (rs != null) {\r
+      try {\r
+        switch (aType) {\r
+          case java.sql.Types.BIT:\r
+            outValue = (rs.getBoolean(valueIndex) == true) ? "1" : "0";\r
+\r
+            break;\r
+\r
+          case java.sql.Types.INTEGER:\r
+          case java.sql.Types.SMALLINT:\r
+          case java.sql.Types.TINYINT:\r
+          case java.sql.Types.BIGINT:\r
+\r
+            int out = rs.getInt(valueIndex);\r
+\r
+            if (!rs.wasNull()) {\r
+              outValue = new Integer(out).toString();\r
+            }\r
+\r
+            break;\r
+\r
+          case java.sql.Types.NUMERIC:\r
+\r
+            /** @todo Numeric can be float or double depending upon\r
+             *  metadata.getScale() / especially with oracle */\r
+            long outl = rs.getLong(valueIndex);\r
+\r
+            if (!rs.wasNull()) {\r
+              outValue = new Long(outl).toString();\r
+            }\r
+\r
+            break;\r
+\r
+          case java.sql.Types.REAL:\r
+\r
+            float tempf = rs.getFloat(valueIndex);\r
+\r
+            if (!rs.wasNull()) {\r
+              tempf *= 10;\r
+              tempf += 0.5;\r
+\r
+              int tempf_int = (int) tempf;\r
+              tempf = (float) tempf_int;\r
+              tempf /= 10;\r
+              outValue = "" + tempf;\r
+              outValue = outValue.replace('.', ',');\r
+            }\r
+\r
+            break;\r
+\r
+          case java.sql.Types.DOUBLE:\r
+\r
+            double tempd = rs.getDouble(valueIndex);\r
+\r
+            if (!rs.wasNull()) {\r
+              tempd *= 10;\r
+              tempd += 0.5;\r
+\r
+              int tempd_int = (int) tempd;\r
+              tempd = (double) tempd_int;\r
+              tempd /= 10;\r
+              outValue = "" + tempd;\r
+              outValue = outValue.replace('.', ',');\r
+            }\r
+\r
+            break;\r
+\r
+          case java.sql.Types.CHAR:\r
+          case java.sql.Types.VARCHAR:\r
+          case java.sql.Types.LONGVARCHAR:\r
+            outValue = rs.getString(valueIndex);\r
+\r
+            break;\r
+\r
+          case java.sql.Types.LONGVARBINARY:\r
+            outValue = rs.getString(valueIndex);\r
+\r
+            break;\r
+\r
+          case java.sql.Types.TIMESTAMP:\r
+\r
+            // it's important to use Timestamp here as getting it\r
+            // as a string is undefined and is only there for debugging\r
+            // according to the API. we can make it a string through formatting.\r
+            // -mh\r
+            Timestamp timestamp = (rs.getTimestamp(valueIndex));\r
+\r
+            if (!rs.wasNull()) {\r
+              java.util.Date date = new java.util.Date(timestamp.getTime());\r
+\r
+              Calendar calendar = new GregorianCalendar();\r
+              calendar.setTime(date);\r
+              calendar.setTimeZone(timezone);\r
+              outValue = internalDateFormat.format(date);\r
+\r
+              int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);\r
+              String tzOffset = StringUtil.zeroPaddingNumber(Math.abs(offset) / _millisPerHour, 2, 2);\r
+\r
+              if (offset<0)\r
+                outValue = outValue + "-";\r
+              else\r
+                outValue = outValue + "+";\r
+              outValue = outValue + tzOffset;\r
+            }\r
+\r
+            break;\r
+\r
+          default:\r
+            outValue = "<unsupported value>";\r
+            logger.warn("Unsupported Datatype: at " + valueIndex + " (" + aType + ")");\r
+        }\r
+      } catch (SQLException e) {\r
+        throw new StorageObjectFailure("Could not get Value out of Resultset -- ",\r
+          e);\r
+      }\r
+    }\r
+\r
+    return outValue;\r
+  }\r
+\r
+  /*\r
+  *   select-Operator um einen Datensatz zu bekommen.\r
+  *   @param id Primaerschluessel des Datensatzes.\r
+  *   @return liefert EntityObject des gefundenen Datensatzes oder null.\r
+   */\r
+  public Entity selectById(String id) throws StorageObjectExc {\r
+    if ((id == null) || id.equals("")) {\r
+      throw new StorageObjectExc("Database.selectById: Missing id");\r
+    }\r
+\r
+    // ask object store for object\r
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+      String uniqueId = id;\r
+\r
+      if (theEntityClass.equals(StorableObjectEntity.class)) {\r
+        uniqueId += ("@" + theTable);\r
+      }\r
+\r
+      StoreIdentifier search_sid = new StoreIdentifier(theEntityClass, uniqueId);\r
+      logger.debug("CACHE: (dbg) looking for sid " + search_sid.toString());\r
+\r
+      Entity hit = (Entity) o_store.use(search_sid);\r
+\r
+      if (hit != null) {\r
+        return hit;\r
+      }\r
+    }\r
+\r
+    Statement stmt = null;\r
+    Connection con = getPooledCon();\r
+    Entity returnEntity = null;\r
+\r
+    try {\r
+      ResultSet rs;\r
+\r
+      /** @todo better prepared statement */\r
+      String selectSql =\r
+        "select * from " + theTable + " where " + thePKeyName + "=" + id;\r
+      stmt = con.createStatement();\r
+      rs = executeSql(stmt, selectSql);\r
+\r
+      if (rs != null) {\r
+        if (evaluatedMetaData == false) {\r
+          evalMetaData(rs.getMetaData());\r
+        }\r
+\r
+        if (rs.next()) {\r
+          returnEntity = makeEntityFromResultSet(rs);\r
+        }\r
+        else {\r
+          logger.debug("No data for id: " + id + " in table " + theTable);\r
+        }\r
+\r
+        rs.close();\r
+      }\r
+      else {\r
+        logger.debug("No Data for Id " + id + " in Table " + theTable);\r
+      }\r
+    }\r
+    catch (SQLException sqe) {\r
+      throwSQLException(sqe, "selectById");\r
+      return null;\r
+    }\r
+    catch (NumberFormatException e) {\r
+      logger.error("ID is no number: " + id);\r
+    }\r
+    finally {\r
+      freeConnection(con, stmt);\r
+    }\r
+\r
+    return returnEntity;\r
+  }\r
+\r
+  /**\r
+   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.\r
+   *   @param key  Datenbankfeld der Bedingung.\r
+   *   @param value  Wert die der key anehmen muss.\r
+   *   @return EntityList mit den gematchten Entities\r
+   */\r
+  public EntityList selectByFieldValue(String aField, String aValue) throws StorageObjectFailure {\r
+    return selectByFieldValue(aField, aValue, 0);\r
+  }\r
+\r
+  /**\r
+   *   select-Operator um Datensaetze zu bekommen, die key = value erfuellen.\r
+   *   @param key  Datenbankfeld der Bedingung.\r
+   *   @param value  Wert die der key anehmen muss.\r
+   *   @param offset  Gibt an ab welchem Datensatz angezeigt werden soll.\r
+   *   @return EntityList mit den gematchten Entities\r
+   */\r
+  public EntityList selectByFieldValue(String aField, String aValue, int offset) throws StorageObjectFailure {\r
+    return selectByWhereClause(aField + "=" + aValue, offset);\r
+  }\r
+\r
+  /**\r
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+   * Also offset wird der erste Datensatz genommen.\r
+   *\r
+   * @param wc where-Clause\r
+   * @return EntityList mit den gematchten Entities\r
+   * @exception StorageObjectException\r
+   */\r
+  public EntityList selectByWhereClause(String where) throws StorageObjectFailure {\r
+    return selectByWhereClause(where, 0);\r
+  }\r
+\r
+  /**\r
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
+   *\r
+   * @param wc where-Clause\r
+   * @param offset ab welchem Datensatz.\r
+   * @return EntityList mit den gematchten Entities\r
+   * @exception StorageObjectException\r
+   */\r
+  public EntityList selectByWhereClause(String whereClause, int offset) throws StorageObjectFailure {\r
+    return selectByWhereClause(whereClause, null, offset);\r
+  }\r
+\r
+  /**\r
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+   * Also offset wird der erste Datensatz genommen.\r
+   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
+   *\r
+   * @param wc where-Clause\r
+   * @param ob orderBy-Clause\r
+   * @return EntityList mit den gematchten Entities\r
+   * @exception StorageObjectException\r
+   */\r
+  public EntityList selectByWhereClause(String where, String order) throws StorageObjectFailure {\r
+    return selectByWhereClause(where, order, 0);\r
+  }\r
+\r
+  /**\r
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+   * Als maximale Anzahl wird das Limit auf der Konfiguration genommen.\r
+   *\r
+   * @param wc where-Clause\r
+   * @param ob orderBy-Clause\r
+   * @param offset ab welchem Datensatz\r
+   * @return EntityList mit den gematchten Entities\r
+   * @exception StorageObjectException\r
+   */\r
+  public EntityList selectByWhereClause(String whereClause, String orderBy, int offset) throws StorageObjectFailure {\r
+    return selectByWhereClause(whereClause, orderBy, offset, defaultLimit);\r
+  }\r
+\r
+  /**\r
+   * select-Operator liefert eine EntityListe mit den gematchten Datens?tzen zur?ck.\r
+   * @param aWhereClause where-Clause\r
+   * @param anOrderByClause orderBy-Clause\r
+   * @param offset ab welchem Datensatz\r
+   * @param limit wieviele Datens?tze\r
+   * @return EntityList mit den gematchten Entities\r
+   * @exception StorageObjectException\r
+   */\r
+  public EntityList selectByWhereClause(String aWhereClause, String anOrderByClause,\r
+            int offset, int limit) throws StorageObjectFailure {\r
+\r
+    // check o_store for entitylist\r
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+      StoreIdentifier search_sid =\r
+          new StoreIdentifier(\r
+            theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST,\r
+            StoreUtil.getEntityListUniqueIdentifierFor(theTable, aWhereClause, anOrderByClause, offset, limit));\r
+      EntityList hit = (EntityList) o_store.use(search_sid);\r
+\r
+      if (hit != null) {\r
+        logger.debug("CACHE (hit): " + search_sid.toString());\r
+\r
+        return hit;\r
+      }\r
+    }\r
+\r
+    // local\r
+    EntityList theReturnList = null;\r
+    Connection con = null;\r
+    Statement stmt = null;\r
+    ResultSet rs;\r
+    int offsetCount = 0;\r
+    int count = 0;\r
+\r
+    // build sql-statement\r
+\r
+    /** @todo count sql string should only be assembled if we really count\r
+     *  see below at the end of method //rk */\r
+    if ((aWhereClause != null) && (aWhereClause.trim().length() == 0)) {\r
+      aWhereClause = null;\r
+    }\r
+\r
+    StringBuffer countSql =\r
+      new StringBuffer("select count(*) from ").append(theTable);\r
+    StringBuffer selectSql =\r
+      new StringBuffer("select * from ").append(theTable);\r
+\r
+    if (aWhereClause != null) {\r
+      selectSql.append(" where ").append(aWhereClause);\r
+      countSql.append(" where ").append(aWhereClause);\r
+    }\r
+\r
+    if ((anOrderByClause != null) && !(anOrderByClause.trim().length() == 0)) {\r
+      selectSql.append(" order by ").append(anOrderByClause);\r
+    }\r
+\r
+    if ((limit > -1) && (offset > -1)) {\r
+      selectSql.append(" LIMIT ").append(limit).append(" OFFSET ").append(offset);\r
+    }\r
+\r
+    // execute sql\r
+    try {\r
+      con = getPooledCon();\r
+      stmt = con.createStatement();\r
+\r
+      // selecting...\r
+      rs = executeSql(stmt, selectSql.toString());\r
+\r
+      if (rs != null) {\r
+        if (!evaluatedMetaData) {\r
+          evalMetaData(rs.getMetaData());\r
+        }\r
+\r
+        theReturnList = new EntityList();\r
+\r
+        Entity theResultEntity;\r
+\r
+        while (rs.next()) {\r
+          theResultEntity = makeEntityFromResultSet(rs);\r
+          theReturnList.add(theResultEntity);\r
+          offsetCount++;\r
+        }\r
+\r
+        rs.close();\r
+      }\r
+\r
+      // making entitylist infos\r
+      count = offsetCount;\r
+\r
+      if (theReturnList != null) {\r
+        // now we decide if we have to know an overall count...\r
+        count = offsetCount;\r
+\r
+        if ((limit > -1) && (offset > -1)) {\r
+          if (offsetCount == limit) {\r
+            /** @todo counting should be deffered to entitylist\r
+             *  getSize() should be used */\r
+            rs = executeSql(stmt, countSql.toString());\r
+\r
+            if (rs != null) {\r
+              if (rs.next()) {\r
+                count = rs.getInt(1);\r
+              }\r
+\r
+              rs.close();\r
+            }\r
+            else {\r
+              logger.error("Could not count: " + countSql);\r
+            }\r
+          }\r
+        }\r
+\r
+        theReturnList.setCount(count);\r
+        theReturnList.setOffset(offset);\r
+        theReturnList.setWhere(aWhereClause);\r
+        theReturnList.setOrder(anOrderByClause);\r
+        theReturnList.setStorage(this);\r
+        theReturnList.setLimit(limit);\r
+\r
+        if (offset >= limit) {\r
+          theReturnList.setPrevBatch(offset - limit);\r
+        }\r
+\r
+        if ((offset + offsetCount) < count) {\r
+          theReturnList.setNextBatch(offset + limit);\r
+        }\r
+\r
+        if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+          StoreIdentifier sid = theReturnList.getStoreIdentifier();\r
+          logger.debug("CACHE (add): " + sid.toString());\r
+          o_store.add(sid);\r
+        }\r
+      }\r
+    }\r
+    catch (SQLException sqe) {\r
+      throwSQLException(sqe, "selectByWhereClause");\r
+    }\r
+    finally {\r
+      try {\r
+        if (con != null) {\r
+          freeConnection(con, stmt);\r
+        }\r
+      } catch (Throwable t) {\r
+      }\r
+    }\r
+\r
+    return theReturnList;\r
+  }\r
+\r
+  /**\r
+   *  Bastelt aus einer Zeile der Datenbank ein EntityObjekt.\r
+   *\r
+   *  @param rs Das ResultSetObjekt.\r
+   *  @return Entity Die Entity.\r
+   */\r
+  private Entity makeEntityFromResultSet(ResultSet rs)\r
+    throws StorageObjectFailure {\r
+    /** @todo OS: get Pkey from ResultSet and consult ObjectStore */\r
+    Map theResultHash = new HashMap();\r
+    String theResult = null;\r
+    int theType;\r
+    Entity returnEntity = null;\r
+\r
+    try {\r
+      int size = metadataFields.size();\r
+\r
+      for (int i = 0; i < size; i++) {\r
+        // alle durchlaufen bis nix mehr da\r
+        theType = metadataTypes[i];\r
+\r
+        if (theType == java.sql.Types.LONGVARBINARY) {\r
+          InputStreamReader is =\r
+            (InputStreamReader) rs.getCharacterStream(i + 1);\r
+\r
+          if (is != null) {\r
+            char[] data = new char[32768];\r
+            StringBuffer theResultString = new StringBuffer();\r
+            int len;\r
+\r
+            while ((len = is.read(data)) > 0) {\r
+              theResultString.append(data, 0, len);\r
+            }\r
+\r
+            is.close();\r
+            theResult = theResultString.toString();\r
+          } else {\r
+            theResult = null;\r
+          }\r
+        } else {\r
+          theResult = getValueAsString(rs, (i + 1), theType);\r
+        }\r
+\r
+        if (theResult != null) {\r
+          theResultHash.put(metadataFields.get(i), theResult);\r
+        }\r
+      }\r
+\r
+      if (theEntityClass != null) {\r
+        returnEntity = (Entity) theEntityClass.newInstance();\r
+        returnEntity.setStorage(this);\r
+        returnEntity.setValues(theResultHash);\r
+\r
+        if (returnEntity instanceof StorableObject) {\r
+          logger.debug("CACHE: ( in) " + returnEntity.getId() + " :" + theTable);\r
+          o_store.add(((StorableObject) returnEntity).getStoreIdentifier());\r
+        }\r
+      } else {\r
+        throwStorageObjectException("Internal Error: theEntityClass not set!");\r
+      }\r
+    }\r
+    catch (IllegalAccessException e) {\r
+      throwStorageObjectException("No access! -- " + e.getMessage());\r
+    }\r
+    catch (IOException e) {\r
+      throwStorageObjectException("IOException! -- " + e.getMessage());\r
+    }\r
+    catch (InstantiationException e) {\r
+      throwStorageObjectException("No Instatiation! -- " + e.getMessage());\r
+    }\r
+    catch (SQLException sqe) {\r
+      throwSQLException(sqe, "makeEntityFromResultSet");\r
+\r
+      return null;\r
+    }\r
+\r
+    return returnEntity;\r
+  }\r
+\r
+  /**\r
+   * Inserts an entity into the database.\r
+   *\r
+   * @param theEntity\r
+   * @return der Wert des Primary-keys der eingef?gten Entity\r
+   */\r
+  public String insert(Entity theEntity) throws StorageObjectFailure {\r
+    //cache\r
+    invalidatePopupCache();\r
+\r
+    // invalidating all EntityLists corresponding with theEntityClass\r
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+      StoreContainerType stoc_type =\r
+        StoreContainerType.valueOf(theEntityClass,\r
+          StoreContainerType.STOC_TYPE_ENTITYLIST);\r
+      o_store.invalidate(stoc_type);\r
+    }\r
+\r
+    String returnId = null;\r
+    Connection con = null;\r
+    PreparedStatement pstmt = null;\r
+\r
+    try {\r
+      List streamedInput = theEntity.streamedInput();\r
+      StringBuffer f = new StringBuffer();\r
+      StringBuffer v = new StringBuffer();\r
+      String aField;\r
+      String aValue;\r
+      boolean firstField = true;\r
+\r
+      // make sql-string\r
+      for (int i = 0; i < getFields().size(); i++) {\r
+        aField = (String) getFields().get(i);\r
+\r
+        if (!aField.equals(thePKeyName)) {\r
+          aValue = null;\r
+\r
+          // exceptions\r
+          if (!theEntity.hasValueForField(aField) && (\r
+              aField.equals("webdb_create") ||\r
+              aField.equals("webdb_lastchange"))) {\r
+            aValue = "NOW()";\r
+          }\r
+          else {\r
+            if ((streamedInput != null) && streamedInput.contains(aField)) {\r
+              aValue = "?";\r
+            }\r
+            else {\r
+              if (theEntity.hasValueForField(aField)) {\r
+                aValue =\r
+                  "'" +\r
+                   JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField)) + "'";\r
+              }\r
+            }\r
+          }\r
+\r
+          // wenn Wert gegeben, dann einbauen\r
+          if (aValue != null) {\r
+            if (firstField == false) {\r
+              f.append(",");\r
+              v.append(",");\r
+            }\r
+            else {\r
+              firstField = false;\r
+            }\r
+\r
+            f.append(aField);\r
+            v.append(aValue);\r
+          }\r
+        }\r
+      }\r
+       // end for\r
+\r
+      // insert into db\r
+      StringBuffer sqlBuf =\r
+        new StringBuffer("insert into ").append(theTable).append("(").append(f)\r
+                                        .append(") values (").append(v).append(")");\r
+      String sql = sqlBuf.toString();\r
+\r
+      logger.debug("INSERT: " + sql);\r
+      con = getPooledCon();\r
+      con.setAutoCommit(false);\r
+      pstmt = con.prepareStatement(sql);\r
+\r
+      if (streamedInput != null) {\r
+        for (int i = 0; i < streamedInput.size(); i++) {\r
+          String inputString =\r
+            (String) theEntity.getValue((String) streamedInput.get(i));\r
+          pstmt.setBytes(i + 1, inputString.getBytes());\r
+        }\r
+      }\r
+\r
+      int ret = pstmt.executeUpdate();\r
+\r
+      if (ret == 0) {\r
+        //insert failed\r
+        return null;\r
+      }\r
+\r
+      pstmt = con.prepareStatement("select currval('" + getCoreTable() + "_id_seq')");\r
+\r
+      ResultSet rs = pstmt.executeQuery();\r
+      rs.next();\r
+      returnId = rs.getString(1);\r
+      theEntity.setId(returnId);\r
+    }\r
+    catch (SQLException sqe) {\r
+      throwSQLException(sqe, "insert");\r
+    }\r
+    finally {\r
+      try {\r
+        con.setAutoCommit(true);\r
+      }\r
+      catch (Exception e) {\r
+      }\r
+\r
+      freeConnection(con, pstmt);\r
+    }\r
+\r
+    /** @todo store entity in o_store */\r
+    return returnId;\r
+  }\r
+\r
+  /**\r
+   * Updates an entity in the database\r
+   *\r
+   * @param theEntity\r
+   */\r
+  public void update(Entity theEntity) throws StorageObjectFailure {\r
+    Connection con = null;\r
+    PreparedStatement pstmt = null;\r
+\r
+    /** @todo this is stupid: why do we prepare statement, when we\r
+     *  throw it away afterwards. should be regular statement\r
+     *  update/insert could better be one routine called save()\r
+     *  that chooses to either insert or update depending if we\r
+     *  have a primary key in the entity. i don't know if we\r
+     *  still need the streamed input fields. // rk  */\r
+    /** @todo extension: check if Entity did change, otherwise we don't need\r
+     *  the roundtrip to the database */\r
+    /** invalidating corresponding entitylists in o_store*/\r
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+      StoreContainerType stoc_type =\r
+        StoreContainerType.valueOf(theEntityClass,\r
+          StoreContainerType.STOC_TYPE_ENTITYLIST);\r
+      o_store.invalidate(stoc_type);\r
+    }\r
+\r
+    List streamedInput = theEntity.streamedInput();\r
+    String id = theEntity.getId();\r
+    String aField;\r
+    StringBuffer fv = new StringBuffer();\r
+    boolean firstField = true;\r
+\r
+    //cache\r
+    invalidatePopupCache();\r
+\r
+    // build sql statement\r
+    for (int i = 0; i < getFields().size(); i++) {\r
+      aField = (String) metadataFields.get(i);\r
+\r
+      // only normal cases\r
+      if (  !(aField.equals(thePKeyName) ||\r
+            aField.equals("webdb_create") ||\r
+            aField.equals("webdb_lastchange") ||\r
+            ((streamedInput != null) && streamedInput.contains(aField)))) {\r
+        if (theEntity.hasValueForField(aField)) {\r
+          if (firstField == false) {\r
+            fv.append(", ");\r
+          }\r
+          else {\r
+            firstField = false;\r
+          }\r
+\r
+          fv.append(aField).append("='").append(JDBCStringRoutines.escapeStringLiteral((String) theEntity.getValue(aField))).append("'");\r
+\r
+          //              fv.append(aField).append("='").append(StringUtil.quote((String)theEntity.getValue(aField))).append("'");\r
+        }\r
+      }\r
+    }\r
+\r
+    StringBuffer sql =\r
+      new StringBuffer("update ").append(theTable).append(" set ").append(fv);\r
+\r
+    // exceptions\r
+    if (metadataFields.contains("webdb_lastchange")) {\r
+      sql.append(",webdb_lastchange=NOW()");\r
+    }\r
+\r
+    // special case: the webdb_create requires the field in yyyy-mm-dd HH:mm\r
+    // format so anything extra will be ignored. -mh\r
+    if (metadataFields.contains("webdb_create") &&\r
+        theEntity.hasValueForField("webdb_create")) {\r
+      // minimum of 10 (yyyy-mm-dd)...\r
+      if (theEntity.getValue("webdb_create").length() >= 10) {\r
+        String dateString = theEntity.getValue("webdb_create");\r
+\r
+        // if only 10, then add 00:00 so it doesn't throw a ParseException\r
+        if (dateString.length() == 10) {\r
+          dateString = dateString + " 00:00";\r
+        }\r
+\r
+        // TimeStamp stuff\r
+        try {\r
+          java.util.Date d = userInputDateFormat.parse(dateString);\r
+//          Timestamp tStamp = new Timestamp(d.getTime());\r
+          sql.append(",webdb_create='" + JDBCStringRoutines.formatDate(d) + "'");\r
+        }\r
+        catch (ParseException e) {\r
+          throw new StorageObjectFailure(e);\r
+        }\r
+      }\r
+    }\r
+\r
+    if (streamedInput != null) {\r
+      for (int i = 0; i < streamedInput.size(); i++) {\r
+        sql.append(",").append(streamedInput.get(i)).append("=?");\r
+      }\r
+    }\r
+\r
+    sql.append(" where id=").append(id);\r
+    logger.debug("UPDATE: " + sql);\r
+\r
+    try {\r
+      con = getPooledCon();\r
+      con.setAutoCommit(false);\r
+      pstmt = con.prepareStatement(sql.toString());\r
+\r
+      if (streamedInput != null) {\r
+        for (int i = 0; i < streamedInput.size(); i++) {\r
+          String inputString =\r
+            theEntity.getValue((String) streamedInput.get(i));\r
+          pstmt.setBytes(i + 1, inputString.getBytes());\r
+        }\r
+      }\r
+\r
+      pstmt.executeUpdate();\r
+    }\r
+    catch (SQLException sqe) {\r
+      throwSQLException(sqe, "update");\r
+    }\r
+    finally {\r
+      try {\r
+        con.setAutoCommit(true);\r
+      }\r
+      catch (Exception e) {\r
+        ;\r
+      }\r
+\r
+      freeConnection(con, pstmt);\r
+    }\r
+  }\r
+\r
+  /*\r
+  *   delete-Operator\r
+  *   @param id des zu loeschenden Datensatzes\r
+  *   @return boolean liefert true zurueck, wenn loeschen erfolgreich war.\r
+   */\r
+  public boolean delete(String id) throws StorageObjectFailure {\r
+    invalidatePopupCache();\r
+\r
+    // ostore send notification\r
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+      String uniqueId = id;\r
+\r
+      if (theEntityClass.equals(StorableObjectEntity.class)) {\r
+        uniqueId += ("@" + theTable);\r
+      }\r
+\r
+      logger.debug("CACHE: (del) " + id);\r
+\r
+      StoreIdentifier search_sid =\r
+        new StoreIdentifier(theEntityClass,\r
+          StoreContainerType.STOC_TYPE_ENTITY, uniqueId);\r
+      o_store.invalidate(search_sid);\r
+    }\r
+\r
+    /** @todo could be prepared Statement */\r
+    Statement stmt = null;\r
+    Connection con = null;\r
+    int res = 0;\r
+    String sql =\r
+      "delete from " + theTable + " where " + thePKeyName + "='" + id + "'";\r
+\r
+    //theLog.printInfo("DELETE " + sql);\r
+    try {\r
+      con = getPooledCon();\r
+      stmt = con.createStatement();\r
+      res = stmt.executeUpdate(sql);\r
+    } catch (SQLException sqe) {\r
+      throwSQLException(sqe, "delete");\r
+    } finally {\r
+      freeConnection(con, stmt);\r
+    }\r
+\r
+    return (res > 0) ? true : false;\r
+  }\r
+\r
+  /**\r
+   * Deletes entities based on a where clause\r
+   *\r
+   * @param aWhereClause\r
+   * @return\r
+   * @throws StorageObjectFailure\r
+   */\r
+  public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure {\r
+    invalidatePopupCache();\r
+    if (StoreUtil.implementsStorableObject(theEntityClass)) {\r
+      StoreContainerType stoc_type = StoreContainerType.valueOf(theEntityClass, StoreContainerType.STOC_TYPE_ENTITYLIST);\r
+      o_store.invalidate(stoc_type);\r
+    }\r
+\r
+    Statement stmt = null;\r
+    Connection con = null;\r
+    int res = 0;\r
+    String sql =\r
+      "delete from " + theTable + " where " + aWhereClause;\r
+\r
+    //theLog.printInfo("DELETE " + sql);\r
+    try {\r
+      con = getPooledCon();\r
+      stmt = con.createStatement();\r
+      res = stmt.executeUpdate(sql);\r
+    }\r
+    catch (SQLException sqe) {\r
+      throwSQLException(sqe, "delete");\r
+    }\r
+    finally {\r
+      freeConnection(con, stmt);\r
+    }\r
+\r
+    return res;\r
+  }\r
+\r
+  /* noch nicht implementiert.\r
+  * @return immer false\r
+   */\r
+  public boolean delete(EntityList theEntityList) {\r
+    invalidatePopupCache();\r
+\r
+    return false;\r
+  }\r
+\r
+  /* invalidates the popupCache\r
+   */\r
+  protected void invalidatePopupCache() {\r
+    /** @todo  invalidates toooo much */\r
+    popupCache = null;\r
+    hashCache = null;\r
+  }\r
+\r
+  /**\r
+   * Diese Methode fuehrt den Sqlstring <i>sql</i> aus und timed im Logfile.\r
+   * @param stmt Statemnt\r
+   * @param sql Sql-String\r
+   * @return ResultSet\r
+   * @exception StorageObjectException\r
+   */\r
+  public ResultSet executeSql(Statement stmt, String sql)\r
+                            throws StorageObjectFailure, SQLException {\r
+    ResultSet rs;\r
+    long startTime = System.currentTimeMillis();\r
+\r
+    try {\r
+      rs = stmt.executeQuery(sql);\r
+\r
+      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+    }\r
+    catch (SQLException e) {\r
+      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+      throw e;\r
+    }\r
+\r
+    return rs;\r
+  }\r
+/*\r
+  public ResultSet executeSql(String sql) throws StorageObjectFailure, SQLException {\r
+    long startTime = System.currentTimeMillis();\r
+    Connection connection = null;\r
+    Statement statement = null;\r
+\r
+    try {\r
+      connection = getPooledCon();\r
+      statement = connection.createStatement();\r
+      ResultSet result;\r
+\r
+      result = statement.executeQuery(sql);\r
+\r
+      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+      return result;\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error(e.getMessage() +"\n" + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+      throw new StorageObjectFailure(e);\r
+    }\r
+    finally {\r
+      if (connection!=null) {\r
+        freeConnection(connection, statement);\r
+      }\r
+    }\r
+  }\r
+*/\r
+  private Map processRow(ResultSet aResultSet) throws StorageObjectFailure, StorageObjectExc {\r
+    try {\r
+      Map result = new HashMap();\r
+      ResultSetMetaData metaData = aResultSet.getMetaData();\r
+      int nrColumns = metaData.getColumnCount();\r
+      for (int i=0; i<nrColumns; i++) {\r
+        result.put(metaData.getColumnName(i+1), getValueAsString(aResultSet, i+1, metaData.getColumnType(i+1)));\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable e) {\r
+      throw new StorageObjectFailure(e);\r
+    }\r
+  }\r
+\r
+  public List executeFreeSql(String sql, int aLimit) throws StorageObjectFailure, StorageObjectExc {\r
+    Connection connection = null;\r
+    Statement statement = null;\r
+    try {\r
+      List result = new Vector();\r
+      connection = getPooledCon();\r
+      statement = connection.createStatement();\r
+      ResultSet resultset = executeSql(statement, sql);\r
+      try {\r
+        while (resultset.next() && result.size() < aLimit) {\r
+          result.add(processRow(resultset));\r
+        }\r
+      }\r
+      finally {\r
+        resultset.close();\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable e) {\r
+      throw new StorageObjectFailure(e);\r
+    }\r
+    finally {\r
+      if (connection!=null) {\r
+        freeConnection(connection, statement);\r
+      }\r
+    }\r
+  };\r
+\r
+  public Map executeFreeSingleRowSql(String anSqlStatement) throws StorageObjectFailure, StorageObjectExc {\r
+    try {\r
+      List resultList = executeFreeSql(anSqlStatement, 1);\r
+      try {\r
+        if (resultList.size()>0)\r
+          return (Map) resultList.get(0);\r
+        else\r
+          return null;\r
+      }\r
+      finally {\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      throw new StorageObjectFailure(t);\r
+    }\r
+  };\r
+\r
+  public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc {\r
+    Map row = executeFreeSingleRowSql(sql);\r
+\r
+    if (row==null)\r
+      return null;\r
+\r
+    Iterator i = row.values().iterator();\r
+    if (i.hasNext())\r
+      return (String) i.next();\r
+    else\r
+      return null;\r
+  };\r
+\r
+  /**\r
+   * returns the number of rows in the table\r
+   */\r
+  public int getSize(String where) throws SQLException, StorageObjectFailure {\r
+    long startTime = System.currentTimeMillis();\r
+    String sql = "SELECT Count(*) FROM " + theTable;\r
+\r
+    if ((where != null) && (where.length() != 0)) {\r
+      sql = sql + " where " + where;\r
+    }\r
+\r
+    Connection con = null;\r
+    Statement stmt = null;\r
+    int result = 0;\r
+\r
+    try {\r
+      con = getPooledCon();\r
+      stmt = con.createStatement();\r
+\r
+      ResultSet rs = executeSql(stmt, sql);\r
+\r
+      while (rs.next()) {\r
+        result = rs.getInt(1);\r
+      }\r
+    }\r
+    catch (SQLException e) {\r
+      logger.error("Database.getSize: " + e.getMessage());\r
+    }\r
+    finally {\r
+      freeConnection(con, stmt);\r
+    }\r
+\r
+    //theLog.printInfo(theTable + " has "+ result +" rows where " + where);\r
+    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+\r
+    return result;\r
+  }\r
+\r
+  public int executeUpdate(Statement stmt, String sql)\r
+    throws StorageObjectFailure, SQLException {\r
+    int rs;\r
+    long startTime = System.currentTimeMillis();\r
+\r
+    try {\r
+      rs = stmt.executeUpdate(sql);\r
+\r
+      logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+    }\r
+    catch (SQLException e) {\r
+      logger.error("Failed: " + (System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+      throw e;\r
+    }\r
+\r
+    return rs;\r
+  }\r
+\r
+  public int executeUpdate(String sql)\r
+    throws StorageObjectFailure, SQLException {\r
+    int result = -1;\r
+    long startTime = System.currentTimeMillis();\r
+    Connection con = null;\r
+    PreparedStatement pstmt = null;\r
+\r
+    try {\r
+      con = getPooledCon();\r
+      pstmt = con.prepareStatement(sql);\r
+      result = pstmt.executeUpdate();\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("Database.executeUpdate(" + sql + "): " + e.getMessage());\r
+      throw new StorageObjectFailure("Database.executeUpdate(" + sql + "): " + e.getMessage(), e);\r
+    }\r
+    finally {\r
+      freeConnection(con, pstmt);\r
+    }\r
+\r
+    logger.debug((System.currentTimeMillis() - startTime) + "ms. for: " + sql);\r
+    return result;\r
+  }\r
+\r
+  /**\r
+   * Wertet ResultSetMetaData aus und setzt interne Daten entsprechend\r
+   * @param md ResultSetMetaData\r
+   * @exception StorageObjectException\r
+   */\r
+  private void evalMetaData(ResultSetMetaData md) throws StorageObjectFailure {\r
+    this.evaluatedMetaData = true;\r
+    this.metadataFields = new ArrayList();\r
+    this.metadataLabels = new ArrayList();\r
+    this.metadataNotNullFields = new ArrayList();\r
+\r
+    try {\r
+      int numFields = md.getColumnCount();\r
+      this.metadataTypes = new int[numFields];\r
+\r
+      String aField;\r
+      int aType;\r
+\r
+      for (int i = 1; i <= numFields; i++) {\r
+        aField = md.getColumnName(i);\r
+        metadataFields.add(aField);\r
+        metadataLabels.add(md.getColumnLabel(i));\r
+        aType = md.getColumnType(i);\r
+        metadataTypes[i - 1] = aType;\r
+\r
+        if (aField.equals(thePKeyName)) {\r
+          thePKeyType = aType;\r
+          thePKeyIndex = i;\r
+        }\r
+\r
+        if (md.isNullable(i) == ResultSetMetaData.columnNullable) {\r
+          metadataNotNullFields.add(aField);\r
+        }\r
+      }\r
+    }\r
+    catch (SQLException e) {\r
+      throwSQLException(e, "evalMetaData");\r
+    }\r
+  }\r
+\r
+  /**\r
+   *  Wertet die Metadaten eines Resultsets fuer eine Tabelle aus,\r
+   *  um die alle Columns und Typen einer Tabelle zu ermitteln.\r
+   */\r
+  private void get_meta_data() throws StorageObjectFailure {\r
+    Connection con = null;\r
+    PreparedStatement pstmt = null;\r
+    String sql = "select * from " + theTable + " where 0=1";\r
+\r
+    try {\r
+      con = getPooledCon();\r
+      pstmt = con.prepareStatement(sql);\r
+\r
+      logger.debug("METADATA: " + sql);\r
+      ResultSet rs = pstmt.executeQuery();\r
+      evalMetaData(rs.getMetaData());\r
+      rs.close();\r
+    }\r
+    catch (SQLException e) {\r
+      throwSQLException(e, "get_meta_data");\r
+    }\r
+    finally {\r
+      freeConnection(con, pstmt);\r
+    }\r
+  }\r
+\r
+  public Connection getPooledCon() throws StorageObjectFailure {\r
+    Connection con = null;\r
+\r
+    try {\r
+      con = SQLManager.getInstance().requestConnection();\r
+    }\r
+    catch (SQLException e) {\r
+      logger.error("could not connect to the database " + e.getMessage());\r
+\r
+      throw new StorageObjectFailure("Could not connect to the database", e);\r
+    }\r
+\r
+    return con;\r
+  }\r
+\r
+  public void freeConnection(Connection con, Statement stmt)\r
+    throws StorageObjectFailure {\r
+    SQLManager.closeStatement(stmt);\r
+    SQLManager.getInstance().returnConnection(con);\r
+  }\r
+\r
+  /**\r
+   * Wertet SQLException aus und wirft dannach eine StorageObjectException\r
+   * @param sqe SQLException\r
+   * @param wo Funktonsname, in der die SQLException geworfen wurde\r
+   * @exception StorageObjectException\r
+   */\r
+  protected void throwSQLException(SQLException sqe, String aFunction) throws StorageObjectFailure {\r
+    String state = "";\r
+    String message = "";\r
+    int vendor = 0;\r
+\r
+    if (sqe != null) {\r
+      state = sqe.getSQLState();\r
+      message = sqe.getMessage();\r
+      vendor = sqe.getErrorCode();\r
+    }\r
+\r
+    String information =\r
+        "SQL Error: " +\r
+        "state= " + state +\r
+        ", vendor= " + vendor +\r
+        ", message=" + message +\r
+        ", function= " + aFunction;\r
+\r
+    logger.error(information);\r
+\r
+    throw new StorageObjectFailure(information, sqe);\r
+  }\r
+\r
+  protected void _throwStorageObjectException(Exception e, String aFunction)\r
+    throws StorageObjectFailure {\r
+\r
+    if (e != null) {\r
+      logger.error(e.getMessage() + aFunction);\r
+      throw new StorageObjectFailure(aFunction, e);\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Loggt Fehlermeldung mit dem Parameter Message und wirft dannach\r
+   * eine StorageObjectException\r
+   * @param message Nachricht mit dem Fehler\r
+   * @exception StorageObjectException\r
+   */\r
+  void throwStorageObjectException(String aMessage) throws StorageObjectFailure {\r
+    logger.error(aMessage);\r
+    throw new StorageObjectFailure(aMessage, null);\r
+  }\r
 }
diff --git a/source/mir/storage/DatabaseAdaptor.java b/source/mir/storage/DatabaseAdaptor.java
deleted file mode 100755 (executable)
index 65874ca..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.storage;
-
-import java.util.Properties;
-
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-
-
-/**
- * Interfacedefinition f?r Datenbank-Adpatoren. Die Adaptoren legen
- * jeweils das Verhalten und die Befehlsm?chtigkeit der Datenbank
- * fest.
- *
- * @author <RK>
- *
- * @version $Id: DatabaseAdaptor.java,v 1.7 2003/04/21 12:42:47 idfx Exp $
- */
-public interface DatabaseAdaptor {
-  /* Liefert den Namen der Adaptorklasse
-   * @return Adaptorklasse als String
-   */
-  public abstract String getDriver() throws PropertiesConfigExc;
-
-  /**
-   * Liefert die URL f?r JDBC zur?ck, in den die Parameter user, pass und host
-   * eingef?gt werden. Die URL wird aus der Konfiguration geholt.
-   *
-   * @param user user als String
-   * @param pass passwort als String
-   * @param host host als String
-   * @return url als String
-   */
-  public abstract String getURL(String user, String pass, String host)
-    throws PropertiesConfigExc;
-
-  /**
-   * Gibt zur?ck, ob das SQL der Datenbank den <code>limit</code>-Befehl beherrscht.
-   * @return true wenn ja, sonst false
-   */
-  public abstract boolean hasLimit();
-
-  /**
-       * Liefert zur?ck, ob der <code>limit</code>-Befehl erst start und dann offset
-       * hat (true), oder umgekehrt. Nur Relevant, wenn hasLimit true zur?ckliefert.
-   *
-   * @return true wenn erstes, sonst false
-   */
-  public abstract boolean reverseLimit();
-
-  /**
-   * Liefert ein Properties-Objekt zurueck mit user und password.
-   * @param user
-   * @param password
-   * @return Properties
-   */
-  public abstract Properties getProperties(String user, String password);
-
-  /**
-   * Gibt SQL-Stringfragment zur?ck, mit dem nach einem insert-Befehl ermittelt
-   * werden kann, wie man den primary-Key des eingef?gten Datensatzes bekommt.
-   *
-   * @param theDB Database-Objekt, aus dem ggf. noetige Informationen geholt
-   * werden k?nnen, wie z.B. der Tabellenname
-   * @return SQL-Statement als String
-   */
-  public abstract String getLastInsertSQL(Database theDB);
-}
diff --git a/source/mir/storage/DatabaseAdaptorMySQL.java b/source/mir/storage/DatabaseAdaptorMySQL.java
deleted file mode 100755 (executable)
index 00970d9..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.storage;
-
-import java.util.Properties;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-
-
-/**
- * <b>Diese Klasse implementiert die abstrakte Klasse DatabaseAdaptor
- *
- * @author <RK>
- * @version 27.6.1999
- */
-public final class DatabaseAdaptorMySQL implements DatabaseAdaptor {
-  public String getDriver() throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.MySQL.Driver");
-  }
-
-  public String getURL(String user, String pass, String host)
-    throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.MySQL.URL");
-  }
-
-  public boolean hasLimit() {
-    return true;
-  }
-
-  public boolean reverseLimit() {
-    return false;
-  }
-
-  public Properties getProperties(String user, String password) {
-    return null;
-  }
-
-  public String getLastInsertSQL(Database theDB) {
-    return "select last_insert_id()";
-  }
-}
diff --git a/source/mir/storage/DatabaseAdaptorOracle.java b/source/mir/storage/DatabaseAdaptorOracle.java
deleted file mode 100755 (executable)
index f036648..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.storage;
-
-import java.util.Properties;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-
-
-/**
- * Diese Klasse implementiert Interface DatabaseAdaptor fuer Oracle
- *
- * @author <RK>
- * @version 15.05.2000
- */
-public final class DatabaseAdaptorOracle implements DatabaseAdaptor {
-  /**
-   * Liefert den Namen der Adaptorklasse <code>Adaptor.Oracle.Driver</code>
-   * f?r Oracle zur?ck.
-   * @return Adaptorklasse als String
-   */
-  public String getDriver() throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.Oracle.Driver");
-  }
-
-  /**
-   * Liefert die URL f?r JDBC zur?ck, in den die Parameter user, pass und host
-   * eingef?gt werden. Die URL wird aus der Konfiguration geholt.
-   *
-   * @param user user als String
-   * @param pass passwort als String
-   * @param host host als String
-   * @return url als String
-   */
-  public String getURL(String user, String pass, String host)
-    throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.Oracle.URL");
-
-    /** @todo   hier muesste bessererweise $HOST durch HOST ersetzt, etc. werden */
-  }
-
-  /**
-   * Gibt zur?ck, ob das SQL der Datenbank den <code>limit</code>-Befehl beherrscht.
-   * @return false
-   */
-  public boolean hasLimit() {
-    return false;
-  }
-
-  /**
-   * Liefert zur?ck, ob der <code>limit</code>-Befehl erst start und dann offset
-   * hat (true), oder umgekehrt. Nur Relevant, wenn hasLimit true zur?ckliefert.
-   *
-   * @return false
-   */
-  public boolean reverseLimit() {
-    return false;
-  }
-
-  /**
-   * Liefert ein Properties-Objekt zurueck mit user und password.
-   * @param user
-   * @param password
-   * @return Properties
-   */
-  public Properties getProperties(String user, String password) {
-    return null;
-  }
-
-  public String getLastInsertSQL(Database theDB) {
-    return "select currval('" + theDB.getCoreTable() + "_id_seq')";
-  }
-}
diff --git a/source/mir/storage/DatabaseAdaptorPostgresql.java b/source/mir/storage/DatabaseAdaptorPostgresql.java
deleted file mode 100755 (executable)
index 59ea2b5..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.storage;
-
-import java.util.Properties;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-
-
-/**
- * <b>Diese Klasse implementiert die abstrakte Klasse DatabaseAdaptor f?r Postgresql-Datenbanken
- *
- * @author <RK>
- * @version 30.12.2000
- */
-public final class DatabaseAdaptorPostgresql implements DatabaseAdaptor {
-  public String getDriver() throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.PostgreSQL.Driver");
-  }
-
-  public String getURL(String user, String pass, String host)
-    throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.PostgreSQL.URL");
-  }
-
-  public boolean hasLimit() {
-    return true;
-  }
-
-  public boolean reverseLimit() {
-    return true;
-  }
-
-  public Properties getProperties(String user, String password) {
-    return null;
-  }
-
-  public String getLastInsertSQL(Database theDB) {
-    return "select currval('" + theDB.getCoreTable() + "_id_seq')";
-  }
-}
diff --git a/source/mir/storage/DatabaseAdaptorSybase.java b/source/mir/storage/DatabaseAdaptorSybase.java
deleted file mode 100755 (executable)
index 3d9c808..0000000
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.storage;
-
-import java.util.Properties;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-
-
-/**
- * Diese Klasse implementiert Interface DatabaseAdaptor fuer Sybase
- *
- * @author <RK>
- * @version 15.05.2000
- */
-public final class DatabaseAdaptorSybase implements DatabaseAdaptor {
-  /**
-   * Liefert den Namen der Adaptorklasse <code>Adaptor.Sybase.Driver</code>
-   * f?r Sybase zur?ck.
-   * @return Adaptorklasse als String
-   */
-  public String getDriver() throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.Sybase.Driver");
-  }
-
-  /**
-   * Liefert die URL f?r JDBC zur?ck, in den die Parameter user, pass und host
-   * eingef?gt werden. Die URL wird aus der Konfiguration geholt.
-   *
-   * @param user user als String
-   * @param pass passwort als String
-   * @param host host als String
-   * @return url als String
-   */
-  public String getURL(String user, String pass, String host)
-    throws PropertiesConfigExc {
-    return MirPropertiesConfiguration.instance().getString("Adaptor.Sybase.URL");
-
-    /** @todo  hier muesste bessererweise $HOST durch HOST ersetzt, etc. werden */
-  }
-
-  /**
-   * Gibt zur?ck, ob das SQL der Datenbank den <code>limit</code>-Befehl beherrscht.
-   * @return false
-   */
-  public boolean hasLimit() {
-    return false;
-  }
-
-  /**
-   * Liefert zur?ck, ob der <code>limit</code>-Befehl erst start und dann offset
-   * hat (true), oder umgekehrt. Nur Relevant, wenn hasLimit true zur?ckliefert.
-   *
-   * @return false
-   */
-  public boolean reverseLimit() {
-    return false;
-  }
-
-  /**
-   * Liefert ein Properties-Objekt zurueck mit user und password.
-   * @param user
-   * @param password
-   * @return Properties
-   */
-  public Properties getProperties(String user, String password) {
-    Properties props = new Properties();
-    props.put("user", user);
-    props.put("password", password);
-
-    return props;
-  }
-
-  public String getLastInsertSQL(Database theDB) {
-    return "select currval('" + theDB.getCoreTable() + "_id_seq')";
-  }
-}
index 5e63c2b..921ce85 100755 (executable)
@@ -36,9 +36,6 @@ import java.sql.Statement;
 import java.util.List;
 import java.util.Map;
 
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-
 import mir.entity.Entity;
 import mir.entity.EntityList;
 
@@ -120,6 +117,15 @@ public interface StorageObject {
   abstract public boolean delete(String id) throws StorageObjectFailure;
 
   /**
+   * Deletes entities based on a where clause
+   *
+   * @param aWhereClause
+   * @return
+   * @throws StorageObjectFailure
+   */
+  public int deleteByWhereClause(String aWhereClause) throws StorageObjectFailure;
+
+  /**
    * Dokumentation siehe Database.java
    * @return ArrayList
    * @exception StorageObjectException
@@ -175,12 +181,6 @@ public interface StorageObject {
 
   /**
    * Dokumentation siehe Database.java
-   * @return SimpleHash
-   */
-  abstract public SimpleHash getHashData();
-
-  /**
-   * Dokumentation siehe Database.java
    * @return Connection
    * @exception StorageObjectException
    */
@@ -229,25 +229,14 @@ public interface StorageObject {
   abstract public String executeFreeSingleValueSql(String sql) throws StorageObjectFailure, StorageObjectExc ;
 
   /**
-   * Dokumentation siehe Database.java
    * @param con
    * @param stmt
    */
-  abstract public void freeConnection(Connection con, Statement stmt)
-    throws StorageObjectFailure;
-
-  /**
-   * Dokumentation siehe Database.java
-   * @return
-   */
-  abstract public SimpleList getPopupData() throws StorageObjectFailure;
+  abstract public void freeConnection(Connection con, Statement stmt) throws StorageObjectFailure;
 
-  abstract public int executeUpdate(Statement a, String sql)
-    throws StorageObjectFailure, SQLException;
+  abstract public int executeUpdate(Statement a, String sql) throws StorageObjectFailure, SQLException;
 
-  abstract public int executeUpdate(String sql)
-    throws StorageObjectFailure, SQLException;
+  abstract public int executeUpdate(String sql) throws StorageObjectFailure, SQLException;
 
-  abstract public int getSize(String where)
-    throws SQLException, StorageObjectFailure;
+  abstract public int getSize(String where) throws SQLException, StorageObjectFailure;
 }
diff --git a/source/mir/util/DateTimeFunctions.java b/source/mir/util/DateTimeFunctions.java
new file mode 100755 (executable)
index 0000000..691bd57
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.util;
+
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.SimpleTimeZone;
+import java.util.TimeZone;
+
+public class DateTimeFunctions {
+  /**
+   * private parameter-less constructor to prevent construction
+   */
+//  private static LoggerWrapper logger = new LoggerWrapper("Utility.DatTimeFunctions");
+
+
+  private DateTimeFunctions() {
+  }
+
+  /**
+   * Function to parse a <a href="http://www.w3.org/TR/NOTE-datetime">W3CDTF</a> formatted string.
+   *
+   *
+   * YYYY[-MM[-DD[Thh:mm[:ss[.s*]]TZD]]]
+   *
+   * @param aString
+   * @return
+   */
+  private final static String SPACE = "[\t\n\r ]*";
+  private final static String NUMBER = "[0-9]*";
+  private final static String TWODIGITNUMBER = "[0-9][0-9]";
+  private final static String FOURDIGITNUMBER = "[0-9][0-9][0-9][0-9]";
+  private final static String FRACTION = "(\\.[0-9]*)|)";
+  private final static String SIGN = "[-+]";
+  private final static String TZD = "(Z|(+|-)([0-9][0-9]:[0-9][0-9]|[0-9][0-9][0-9][0-9]))";
+
+  public static Date parseW3CDTFString(String aString) throws UtilExc, UtilFailure {
+    try {
+      int year = 1;
+      int month = 1;
+      int day = 1;
+      int hour = 0;
+      int minute = 0;
+      int second = 0;
+      int millisecond = 0;
+      int houroffset = 0;
+      int minuteoffset = 0;
+      boolean negativeOffset = false;
+
+
+      SimpleParser parser = new SimpleParser(aString.trim());
+      String part = parser.parse(NUMBER);
+      year=Integer.parseInt(part);
+      if (parser.parses("-")) {
+        parser.skip("-");
+        part = parser.parse(NUMBER);
+        month = Integer.parseInt(part);
+        if (parser.parses("-")) {
+          parser.skip("-");
+          part = parser.parse(NUMBER);
+          day = Integer.parseInt(part);
+          if (parser.parses("T")) {
+            parser.skip("T");
+            part = parser.parse(NUMBER);
+            hour = Integer.parseInt(part);
+            parser.skip(":");
+            part = parser.parse(NUMBER);
+            minute = Integer.parseInt(part);
+            if (parser.parses(":")) {
+              parser.skip(":");
+              part = parser.parse(NUMBER);
+              second = Integer.parseInt(part);
+              if (parser.parses("\\.")) {
+                parser.skip("\\.");
+                part = parser.parse(NUMBER).substring(0,3);
+                while (part.length()<3)
+                  part = "0" + part;
+                millisecond = Integer.parseInt(part);
+              }
+            }
+            if (parser.parses("Z|\\+|-")) {
+              String sign = parser.parse("Z|\\+|-");
+              if (sign.equals("+") || sign.equals("-")) {
+                if (parser.parses(TWODIGITNUMBER)) {
+                  part = parser.parse(TWODIGITNUMBER);
+                  houroffset = Integer.parseInt(part);
+                }
+                if (parser.parses(":"))
+                  parser.skip(":");
+                if (parser.parses(TWODIGITNUMBER)) {
+                  part = parser.parse(TWODIGITNUMBER);
+                  minuteoffset = Integer.parseInt(part);
+                }
+
+                if (sign.equals("-")) {
+                  negativeOffset=true;
+                }
+              }
+            }
+          }
+        }
+      }
+
+
+
+      String timeZoneID = "GMT";
+      if (negativeOffset)
+        timeZoneID = timeZoneID+"-";
+      timeZoneID = timeZoneID + StringRoutines.padStringLeft(Integer.toString(houroffset), 2, '0') +
+                                StringRoutines.padStringLeft(Integer.toString(minuteoffset), 2, '0');
+
+
+      TimeZone zone = TimeZone.getTimeZone(timeZoneID);
+
+      Calendar calendar = new GregorianCalendar(zone);
+      calendar.set(year, month-1, day, hour, minute, second);
+      calendar.set(Calendar.MILLISECOND, millisecond);
+
+      return calendar.getTime();
+    }
+    catch (Throwable t) {
+//      logger.error("DateTimeFunctions.parseW3CDTFString: error parsing " + aString + ": " + t.toString());
+
+      throw new UtilFailure(t);
+    }
+  }
+
+  public static String advancedDateFormat(String aFormat, Date aDate, String aTimeZone) {
+    return advancedDateFormat(aFormat, aDate, TimeZone.getTimeZone(aTimeZone));
+  }
+
+  public static String advancedDateFormat(String aFormat, Date aDate, TimeZone aTimeZone) {
+    SimpleDateFormat simpleFormat = new SimpleDateFormat(aFormat);
+
+    simpleFormat.setTimeZone(aTimeZone);
+    return simpleFormat.format(aDate);
+  }
+
+  public static String dateToSortableString(Date aDate) {
+    return advancedDateFormat("yyyyMMddHHmmss", aDate, "GMT");
+  }
+}
\ No newline at end of file
diff --git a/source/mir/util/DateToMapAdapter.java b/source/mir/util/DateToMapAdapter.java
deleted file mode 100755 (executable)
index 0115984..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.util;
-
-import java.text.SimpleDateFormat;
-import java.util.AbstractMap;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.HashSet;
-import java.util.Set;
-
-import mir.misc.StringUtil;
-
-public class DateToMapAdapter extends AbstractMap {
-  Date date;
-
-  public DateToMapAdapter(Date aDate) {
-    date = aDate;
-  }
-
-  public Object get(Object aKey) {
-    if (aKey instanceof String) {
-      try {
-        // ML: quick fix to allow for the dc encoding now...
-        if (((String) aKey).equals("dc")) {
-          GregorianCalendar calendar = new GregorianCalendar();
-          calendar.setTime(date);
-          return StringUtil.date2w3DateTime(calendar);
-        }
-        else
-          return new SimpleDateFormat((String) aKey).format(date);
-      }
-      catch (Throwable t) {
-        throw new RuntimeException( "Can't format date with format " + (String) aKey + ": " + t.getMessage());
-      }
-    }
-    else return null;
-  }
-
-  public Set entrySet() {
-    return new HashSet();
-  }
-}
\ No newline at end of file
diff --git a/source/mir/util/GeneratorDateTimeFunctions.java b/source/mir/util/GeneratorDateTimeFunctions.java
new file mode 100755 (executable)
index 0000000..e535f1a
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.util;
+
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+
+import mir.generator.Generator;
+import mir.generator.GeneratorExc;
+import mir.generator.GeneratorFailure;
+
+public class GeneratorDateTimeFunctions {
+  private GeneratorDateTimeFunctions() {
+  }
+
+  public static class FormatDateFunction implements Generator.GeneratorFunction {
+    private String defaultTimezone;
+
+    public FormatDateFunction(String aDefaultTimeZone) {
+      defaultTimezone = aDefaultTimeZone;
+    }
+
+    public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+      try {
+        if (aParameters.size()<2 || aParameters.size()>3)
+          throw new GeneratorExc("dateFormatFunction <date> <format> [<timezone>]: 2 or 3 parameters expected");
+
+        if (!(aParameters.get(0) instanceof Date) ||
+            !(aParameters.get(1) instanceof String) ||
+            ( aParameters.size()>2 &&
+             !(aParameters.get(2) instanceof String)))
+          throw new GeneratorExc("dateFormatFunction <date> <format> [<timezone>]: type mismatch");
+
+
+        Date date = (Date) aParameters.get(0);
+        SimpleDateFormat dateFormat = new SimpleDateFormat( (String) (aParameters.get(1)));
+
+        String timezoneString = "";
+        if (aParameters.size()>2)
+          timezoneString = (String) aParameters.get(2);
+        else
+          timezoneString = defaultTimezone;
+
+        TimeZone timezone = null;
+        try  {
+          timezone = TimeZone.getTimeZone(defaultTimezone);
+        }
+        catch (Throwable t) {
+        }
+
+        if (timezone == null)
+          timezone = TimeZone.getDefault();
+
+        dateFormat.setTimeZone(timezone);
+
+        return dateFormat.format(date);
+      }
+      catch (GeneratorExc e) {
+        throw e;
+      }
+      catch (Throwable t) {
+        throw new GeneratorFailure("encodeURIGeneratorFunction: " + t.getMessage(), t);
+      }
+    };
+  }
+
+
+  public static class DateTimeFunctions  {
+    private String defaultTimezone;
+    private Generator.GeneratorFunction formatDate;
+
+    public DateTimeFunctions(String aDefaultTimezone) {
+      defaultTimezone = aDefaultTimezone;
+    }
+
+    public Generator.GeneratorFunction getFormatDate() {
+      if (formatDate == null) {
+        formatDate = new FormatDateFunction(defaultTimezone);
+      }
+
+      return formatDate;
+    }
+  }
+
+}
diff --git a/source/mir/util/GeneratorFormatAdapters.java b/source/mir/util/GeneratorFormatAdapters.java
new file mode 100755 (executable)
index 0000000..2da18e5
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mir.util;
+
+import java.text.DateFormat;
+import java.text.DecimalFormat;
+import java.text.SimpleDateFormat;
+import java.util.AbstractMap;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TimeZone;
+
+import mir.generator.Generator;
+import mir.generator.GeneratorExc;
+import mir.generator.GeneratorFailure;
+import mir.misc.StringUtil;
+
+public class GeneratorFormatAdapters {
+  public static class NumberFormatAdapter {
+    private Number value;
+
+    public NumberFormatAdapter(Number aValue) {
+      value = aValue;
+    }
+
+    public Generator.GeneratorFunction getFormat() {
+      return new NumberFormattingFunction();
+    }
+
+    private class NumberFormattingFunction implements Generator.GeneratorFunction {
+      public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+        try {
+          if (aParameters.size() != 1 || ! (aParameters.get(0)instanceof String))
+            throw new GeneratorExc("NumberFormattingFunction <format> : exactly 1 string parameter expected");
+
+          return new DecimalFormat( (String) (aParameters.get(0))).format(value);
+        }
+        catch (GeneratorExc e) {
+          throw e;
+        }
+        catch (Throwable t) {
+          throw new GeneratorFailure("NumberFormattingFunction: " + t.getMessage(), t);
+        }
+      };
+    }
+  }
+
+  public static class DateFormatAdapter {
+    private Date value;
+    private TimeZone defaultTimezone;
+    private String defaultTimezoneName;
+
+    public DateFormatAdapter(Date aValue) {
+      this(aValue, "");
+    }
+
+    public DateFormatAdapter(Date aValue, String aDefaultTimezone) {
+      value = aValue;
+      defaultTimezoneName = aDefaultTimezone;
+      defaultTimezone = null;
+    }
+
+    private TimeZone getDefaultTimezone() {
+      if (defaultTimezone == null) {
+        try {
+          defaultTimezone = TimeZone.getTimeZone(defaultTimezoneName);
+        }
+        catch (Throwable t) {
+        }
+
+        if (defaultTimezone==null)
+          defaultTimezone = TimeZone.getDefault();
+      }
+
+      return defaultTimezone;
+    }
+
+    public Generator.GeneratorFunction getFormat() {
+      return new DateFormattingFunction();
+    }
+
+    public Map getFormatted() {
+      return new DateToMapAdapter();
+    }
+
+    public Date getDate() {
+      return value;
+    }
+
+    private class DateFormattingFunction implements Generator.GeneratorFunction {
+      public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+        try {
+          if (aParameters.size() < 1 || aParameters.size() > 2 ||
+              !(aParameters.get(0) instanceof String) || (aParameters.size()>1 && ! (aParameters.get(1) instanceof String)))
+            throw new GeneratorExc("DateFormattingFunction <format> [timezone]: 1 or 2 string parameters expected");
+
+          SimpleDateFormat dateFormat = new SimpleDateFormat( (String) (aParameters.get(0)));
+
+          TimeZone timezone = null;
+          if (aParameters.size() > 1) {
+            try  {
+              timezone = TimeZone.getTimeZone( (String) aParameters.get(1));
+            }
+            catch (Throwable t) {
+            }
+          }
+
+          if (timezone == null)
+            timezone = getDefaultTimezone();
+
+          dateFormat.setTimeZone(timezone);
+
+          return dateFormat.format(value);
+        }
+        catch (GeneratorExc e) {
+          throw e;
+        }
+        catch (Throwable t) {
+          throw new GeneratorFailure("DateFormattingFunction: " + t.getMessage(), t);
+        }
+      };
+    }
+
+    /**
+     *
+     * retained for backwards compatibility
+     *
+     * <p>Title: </p>
+     * <p>Description: </p>
+     * <p>Copyright: Copyright (c) 2003</p>
+     * <p>Company: </p>
+     * @author not attributable
+     * @version 1.0
+     */
+
+    public class DateToMapAdapter extends AbstractMap {
+      public Object get(Object aKey) {
+        if (aKey instanceof String) {
+          try {
+            // ML: quick fix to allow for the dc encoding now...
+            if ( ( (String) aKey).equals("dc")) {
+              GregorianCalendar calendar = new GregorianCalendar();
+              calendar.setTime(value);
+              calendar.setTimeZone(getDefaultTimezone());
+              return StringUtil.date2w3DateTime(calendar);
+            }
+            else {
+              DateFormat dateFormat = new SimpleDateFormat( (String) aKey);
+              dateFormat.setTimeZone(getDefaultTimezone());
+
+              return dateFormat.format(value);
+            }
+          }
+          catch (Throwable t) {
+            throw new RuntimeException("Can't format date with format " + (String) aKey + ": " + t.getMessage());
+          }
+        }
+        else
+          return null;
+      }
+
+      public Set entrySet() {
+        return new HashSet();
+      }
+    }
+  }
+}
\ No newline at end of file
index 1f03ec6..661ff56 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.util;
 
 import java.util.List;
+import java.io.*;
 
 import mir.generator.Generator;
 import mir.generator.GeneratorExc;
index a8cd266..e147b07 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.util;
@@ -63,4 +63,41 @@ public class GeneratorStringFunctions {
       }
     };
   }
+
+  public static class jdbcStringEscapeFunction implements Generator.GeneratorFunction {
+    public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+      try {
+        if (aParameters.size()!=1 || !(aParameters.get(0) instanceof String))
+          throw new GeneratorExc("jdbcStringEscapeFunction: 1 parameter expected: string ");
+
+        return JDBCStringRoutines.escapeStringLiteral((String) aParameters.get(0));
+      }
+      catch (GeneratorExc e) {
+        throw e;
+      }
+      catch (Throwable t) {
+        throw new GeneratorFailure(t);
+      }
+    };
+  }
+
+  public static class constructStructuredStringFunction implements Generator.GeneratorFunction {
+    public Object perform(List aParameters) throws GeneratorExc, GeneratorFailure {
+      try {
+        if (aParameters.size()!=1)
+          throw new GeneratorExc("constructStructureStringFunction: 1 parameter expected: string ");
+
+        if (aParameters.get(0)==null)
+          return StructuredContentParser.constructStringLiteral("");
+        else
+          return StructuredContentParser.constructStringLiteral("" + aParameters.get(0));
+      }
+      catch (GeneratorExc e) {
+        throw e;
+      }
+      catch (Throwable t) {
+        throw new GeneratorFailure(t);
+      }
+    };
+  }
 }
\ No newline at end of file
index 988d650..07f40a0 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -64,8 +64,16 @@ public class HTMLRoutines {
   }
 
   public static String encodeXML(String aText) {
-    final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"', '\'' };
-    final String[] ESCAPE_CODES = { "&amp;", "&lt;", "&gt;", "&quot;", "&apos;" };
+//#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
+    final char[] CHARACTERS_TO_ESCAPE = { '&', '<', '>', '"', '\'',
+        '\u0000', '\u0001', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0000', '\u000B',
+        '\u000C', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016',
+        '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E'  };
+    final String[] ESCAPE_CODES = { "&amp;", "&lt;", "&gt;", "&quot;", "&apos;",
+        "", "", "", "", "", "", "", "", "", "",
+        "", "", "", "", "", "", "", "", "", "",
+        "", "", "", "", "", "", "", ""};
+
 
     return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES);
   }
index ba30796..3ca02f1 100755 (executable)
@@ -59,7 +59,7 @@ public class HTTPParsedRequest {
   private LoggerWrapper logger;
 
   public HTTPParsedRequest(HttpServletRequest aRequest, String anEncoding, int aMaxUploadSize, String aTempDir) throws UtilExc, UtilFailure {
-    logger = new LoggerWrapper("Utility,HTTPParsedRequest");
+    logger = new LoggerWrapper("Utility.HTTPParsedRequest");
 
     request = aRequest;
     encoding = anEncoding;
index 951e458..54dbea5 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
 package mir.util;
 
+import java.util.*;
+
 import javax.servlet.http.HttpServletRequest;
 
 public class HTTPRequestParser {
@@ -74,6 +76,24 @@ public class HTTPRequestParser {
     }
   }
 
+  public List getParameterList(String aName) {
+    try {
+      List result = new Vector();
+      String items[] = request.getParameterValues(aName);
+
+      if (items!=null) {
+        for (int i=0; i<items.length; i++) {
+          result.add(items[i]);
+        }
+      }
+
+      return result;
+    }
+    catch (Throwable t) {
+      throw new RuntimeException("HTTPRequestParser.getParameterList: " + t.getMessage());
+    }
+  }
+
   public int getIntegerWithDefault(String aName, int aDefault) {
     int result = aDefault;
     String value = getParameter(aName);
index fcf2bca..cae60e5 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.util;
@@ -38,6 +38,9 @@ package mir.util;
  * @version 1.0
  */
 
+import java.util.*;
+import java.text.*;
+
 public class JDBCStringRoutines {
   private JDBCStringRoutines() {
   }
@@ -49,4 +52,9 @@ public class JDBCStringRoutines {
     return StringRoutines.replaceStringCharacters(aText, CHARACTERS_TO_ESCAPE, ESCAPE_CODES);
   }
 
+  public static String formatDate(Date aDate) {
+    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm 'UTC'");
+    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
+    return dateFormat.format(aDate);
+  }
 }
\ No newline at end of file
index fa60689..a65015b 100755 (executable)
@@ -168,33 +168,33 @@ public class ParameterExpander {
     return result.toString();
   }
 
-  public static boolean evaluateBooleanExpression(Map aMap, String anExpression) throws Exception {
+  public static boolean evaluateBooleanExpression(Object aMap, String anExpression) throws Exception {
     Parser parser = new Parser(anExpression, aMap);
 
     return parser.parseBoolean();
   }
 
-  public static String evaluateStringExpression(Map aMap, String anExpression) throws Exception {
+  public static String evaluateStringExpression(Object aMap, String anExpression) throws Exception {
     Parser parser = new Parser(anExpression, aMap);
 
     return parser.parseString();
   }
 
-  public static int evaluateIntegerExpressionWithDefault(Map aMap, String anExpression, int aDefault) throws Exception {
+  public static int evaluateIntegerExpressionWithDefault(Object aMap, String anExpression, int aDefault) throws Exception {
     if (anExpression == null || anExpression.trim().equals(""))
       return aDefault;
     else
       return evaluateIntegerExpression(aMap, anExpression);
   }
 
-  public static int evaluateIntegerExpression(Map aMap, String anExpression) throws Exception {
+  public static int evaluateIntegerExpression(Object aMap, String anExpression) throws Exception {
     Parser parser = new Parser(anExpression, aMap);
 
     return parser.parseInteger();
   }
 
-  public static Object evaluateExpression(Map aMap, String anExpression) throws Exception {
-    Parser parser = new Parser(anExpression, aMap);
+  public static Object evaluateExpression(Object aRoot, String anExpression) throws Exception {
+    Parser parser = new Parser(anExpression, aRoot);
 
     return parser.parseWhole();
   }
@@ -490,9 +490,9 @@ public class ParameterExpander {
 
   private static class Parser {
     private Scanner scanner;
-    private Map valueMap;
+    private Object valueMap;
 
-    public Parser(String anExpression, Map aValueMap) {
+    public Parser(String anExpression, Object aValueMap) {
       scanner = new Scanner(new Reader(anExpression));
       valueMap = aValueMap;
     }
@@ -560,10 +560,6 @@ public class ParameterExpander {
       do {
         expression = parse();
 
-        if (expression==null) {
-          throw new RuntimeException("expression expected");
-        }
-
         result.add(expression);
 
         token = scanner.scan();
@@ -804,6 +800,8 @@ public class ParameterExpander {
     }
 
     private String interpretAsString(Object aValue) {
+      if (aValue==null)
+        return "";
       if (aValue instanceof String)
         return (String) aValue;
       if (aValue instanceof Integer)
index ae88073..c76cbbd 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mir.util;
@@ -202,7 +202,6 @@ public class PropertiesManipulator {
   private final static String SEPARATOR = "[\t\n\r ]*[:=]?[\t\n\r ]*";
   private final static String VALUE = "(([\\\\].)|([^\\\\]))*";
 
-
   public static PropertiesManipulator readProperties(InputStream anInputStream) throws PropertiesManipulatorExc, PropertiesManipulatorFailure {
     return readProperties(anInputStream, "ISO-8859-1");
   }
index c641a58..a3ac35c 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mir.util;
-
-import gnu.regexp.RE;
-import gnu.regexp.REException;
-
-import java.util.List;
-import java.util.Vector;
-
-public class StringRoutines {
-
-  private StringRoutines() {
-  }
-
-  static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {
-    int i;
-    int result=-1;
-    int position;
-
-    for (i=0; i<aCharacters.length ; i++) {
-      position = aString.indexOf(aCharacters[i], aFrom);
-
-      if (position != -1 && ( result == -1 || position < result )) {
-        result = position;
-      }
-    }
-
-    return result;
-  }
-
-  static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {
-    if (aText==null)
-      return null;
-
-    int position, nextPosition;
-    int i;
-    StringBuffer result = new StringBuffer();
-
-    position=0;
-    do {
-      nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);
-
-      if (nextPosition<0)
-        nextPosition = aText.length();
-
-      result.append(aText.substring(position, nextPosition));
-
-      if (nextPosition<aText.length())
-        for (i=0; i<aCharactersToReplace.length; i++) {
-          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {
-            result.append(aStringsToSubstitute[i]);
-            break;
-          }
-        }
-      position=nextPosition+1;
-    }
-    while (nextPosition<aText.length()) ;
-
-    return result.toString();
-  }
-
-
-  public static String interpretAsString(Object aValue) throws Exception {
-    if (aValue instanceof String)
-      return (String) aValue;
-
-    if (aValue instanceof Integer)
-      return ((Integer) aValue).toString();
-
-    if (aValue == null)
-      return "";
-
-    throw new Exception("String expected, "+aValue+" found");
-  }
-
-  public static int interpretAsInteger(Object aValue) throws Exception {
-    if (aValue instanceof Integer)
-      return ((Integer) aValue).intValue();
-
-    if (aValue instanceof String)
-      try {
-        return Integer.parseInt((String) aValue);
-      }
-      catch (Throwable t) {
-        throw new Exception("Integer expected, "+aValue+" found");
-      }
-
-    throw new Exception("Integer expected, "+aValue+" found");
-  }
-
-  /**
-   *
-   * @param aSource
-   * @param aSearchExpression
-   * @param aReplacement
-   * @return
-   * @throws Exception
-   */
-  public static String performRegularExpressionReplacement(String aSource,
-      String aSearchExpression, String aReplacement) throws Exception {
-
-    RE regularExpression;
-
-    regularExpression = new RE(aSearchExpression);
-
-    return regularExpression.substituteAll(aSource, aReplacement);
-  }
-
-  /**
-   *
-   * @param aSource
-   * @param aSearchExpression
-   * @return
-   * @throws REException
-   */
-  public static boolean performRegularExpressionSearch(String aSource,
-      String aSearchExpression) throws REException {
-    RE regularExpression;
-
-    regularExpression = new RE(aSearchExpression);
-
-    return regularExpression.isMatch(aSource);
-  }
-
-  /**
-   * Separates a string based on a separator:
-   *     <code>seperateString("a:b:c", ":");</code> will lead to
-   *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>
-   *
-   * @param aString     The string to split
-   * @param aSeparator
-   * @return
-   */
-
-  public static List splitString(String aString, String aSeparator) {
-    List result= new Vector();
-    int previousPosition = 0;
-    int position;
-    int endOfNamePosition;
-
-    if (aString!=null) {
-      while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {
-        result.add(aString.substring(previousPosition, position));
-        previousPosition = position + aSeparator.length();
-      }
-      result.add(aString.substring(previousPosition, aString.length()));
-    }
-
-    return result;
-  }
-
-  /**
-   * Separates a String into at most 2 parts based on a separator:
-   * <ul>
-   *   <li>
-   *     <code>seperateString("a:b:c", ":");</code> will lead to
-   *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>
-   *   <li>
-   *     <code>seperateString("abc", ":");</code> will lead to
-   *     a List with a single String: <code>"abc"</code>
-   * </ul>
-   *
-   *
-   * @param aString
-   * @param aSeparator
-   * @return
-   */
-  public static List separateString(String aString, String aSeparator) {
-    List result= new Vector();
-    int previousPosition = 0;
-    int position;
-    int endOfNamePosition;
-
-    if((position = aString.indexOf(aSeparator, previousPosition))>=0) {
-      result.add(aString.substring(previousPosition, position));
-      previousPosition = position + aSeparator.length();
-    }
-
-    result.add(aString.substring(previousPosition, aString.length()));
-
-    return result;
-  }
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mir.util;\r
+\r
+import gnu.regexp.RE;\r
+import gnu.regexp.REException;\r
+\r
+import java.util.List;\r
+import java.util.Vector;\r
+\r
+public class StringRoutines {\r
+\r
+  private StringRoutines() {\r
+  }\r
+\r
+  public static int indexOfCharacters(String aString, char[] aCharacters, int aFrom) {\r
+    int i;\r
+    int result=-1;\r
+    int position;\r
+\r
+    for (i=0; i<aCharacters.length ; i++) {\r
+      position = aString.indexOf(aCharacters[i], aFrom);\r
+\r
+      if (position != -1 && ( result == -1 || position < result )) {\r
+        result = position;\r
+      }\r
+    }\r
+\r
+    return result;\r
+  }\r
+\r
+  public static String replaceStringCharacters(String aText, char[] aCharactersToReplace, String[] aStringsToSubstitute) {\r
+    if (aText==null)\r
+      return null;\r
+\r
+    int position, nextPosition;\r
+    int i;\r
+    StringBuffer result = new StringBuffer();\r
+\r
+    position=0;\r
+    do {\r
+      nextPosition = StringRoutines.indexOfCharacters(aText, aCharactersToReplace, position);\r
+\r
+      if (nextPosition<0)\r
+        nextPosition = aText.length();\r
+\r
+      result.append(aText.substring(position, nextPosition));\r
+\r
+      if (nextPosition<aText.length())\r
+        for (i=0; i<aCharactersToReplace.length; i++) {\r
+          if (aCharactersToReplace[i] == aText.charAt(nextPosition)) {\r
+            result.append(aStringsToSubstitute[i]);\r
+            break;\r
+          }\r
+        }\r
+      position=nextPosition+1;\r
+    }\r
+    while (nextPosition<aText.length()) ;\r
+\r
+    return result.toString();\r
+  }\r
+\r
+\r
+  public static String interpretAsString(Object aValue) throws Exception {\r
+    if (aValue instanceof String)\r
+      return (String) aValue;\r
+\r
+    if (aValue instanceof Integer)\r
+      return ((Integer) aValue).toString();\r
+\r
+    if (aValue == null)\r
+      return "";\r
+\r
+    throw new Exception("String expected, "+aValue+" found");\r
+  }\r
+\r
+  public static int interpretAsInteger(Object aValue) throws Exception {\r
+    if (aValue instanceof Integer)\r
+      return ((Integer) aValue).intValue();\r
+\r
+    if (aValue instanceof String)\r
+      try {\r
+        return Integer.parseInt((String) aValue);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new Exception("Integer expected, "+aValue+" found");\r
+      }\r
+\r
+    throw new Exception("Integer expected, "+aValue+" found");\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aSource\r
+   * @param aSearchExpression\r
+   * @param aReplacement\r
+   * @return\r
+   * @throws Exception\r
+   */\r
+  public static String performRegularExpressionReplacement(String aSource,\r
+      String aSearchExpression, String aReplacement) throws Exception {\r
+\r
+    RE regularExpression;\r
+\r
+    regularExpression = new RE(aSearchExpression);\r
+\r
+    return regularExpression.substituteAll(aSource, aReplacement);\r
+  }\r
+\r
+  /**\r
+   *\r
+   * @param aSource\r
+   * @param aSearchExpression\r
+   * @return\r
+   * @throws REException\r
+   */\r
+  public static boolean performRegularExpressionSearch(String aSource,\r
+      String aSearchExpression) throws REException {\r
+    RE regularExpression;\r
+\r
+    regularExpression = new RE(aSearchExpression);\r
+\r
+    return regularExpression.isMatch(aSource);\r
+  }\r
+\r
+  /**\r
+   * Separates a string based on a separator:\r
+   *     <code>seperateString("a:b:c", ":");</code> will lead to\r
+   *     a List with 3 Strings: <code>"a"</code>, <code>"b"</code> and <code>"c"</code>\r
+   *\r
+   * @param aString     The string to split\r
+   * @param aSeparator\r
+   * @return\r
+   */\r
+\r
+  public static List splitString(String aString, String aSeparator) {\r
+    List result= new Vector();\r
+    int previousPosition = 0;\r
+    int position;\r
+    int endOfNamePosition;\r
+\r
+    if (aString!=null) {\r
+      while ( (position = aString.indexOf(aSeparator, previousPosition)) >= 0) {\r
+        result.add(aString.substring(previousPosition, position));\r
+        previousPosition = position + aSeparator.length();\r
+      }\r
+      result.add(aString.substring(previousPosition, aString.length()));\r
+    }\r
+\r
+    return result;\r
+  }\r
+\r
+  /**\r
+   * Separates a String into at most 2 parts based on a separator:\r
+   * <ul>\r
+   *   <li>\r
+   *     <code>seperateString("a:b:c", ":");</code> will lead to\r
+   *     a List with 2 Strings: <code>"a"</code> and <code>"b:c"</code>\r
+   *   <li>\r
+   *     <code>seperateString("abc", ":");</code> will lead to\r
+   *     a List with a single String: <code>"abc"</code>\r
+   * </ul>\r
+   *\r
+   *\r
+   * @param aString\r
+   * @param aSeparator\r
+   * @return\r
+   */\r
+  public static List separateString(String aString, String aSeparator) {\r
+    List result= new Vector();\r
+    int previousPosition = 0;\r
+    int position;\r
+\r
+    if((position = aString.indexOf(aSeparator, previousPosition))>=0) {\r
+      result.add(aString.substring(previousPosition, position));\r
+      previousPosition = position + aSeparator.length();\r
+    }\r
+\r
+    result.add(aString.substring(previousPosition, aString.length()));\r
+\r
+    return result;\r
+  }\r
+\r
+  public static List splitStringWithEscape(String aString, char aSeparator, char anEscape) {\r
+    List result= new Vector();\r
+    int previousPosition = 0;\r
+    int position;\r
+    int endOfNamePosition;\r
+    StringBuffer currentItem = new StringBuffer();\r
+\r
+    if (aString!=null) {\r
+      while ((position = indexOfCharacters(aString, new char[] {aSeparator, anEscape}, previousPosition))>=0) {\r
+        currentItem.append(aString.substring(previousPosition, position));\r
+\r
+        if (aString.charAt(position)==aSeparator) {\r
+          result.add(currentItem.toString());\r
+          currentItem.delete(0, currentItem.length());\r
+        }\r
+        else {\r
+          if (aString.length()>position+1) {\r
+            position=position+1;\r
+            currentItem.append(aString.charAt(position));\r
+          }\r
+        }\r
+        previousPosition = position + 1;\r
+      }\r
+      currentItem.append(aString.substring(previousPosition, aString.length()));\r
+      result.add(currentItem.toString());\r
+    }\r
+\r
+    return result;\r
+  }\r
+\r
+  public static String replicateString(String aString, int aCount) {\r
+    StringBuffer result = new StringBuffer();\r
+\r
+    for (int i=0; i<aCount; i++)\r
+      result.append(aString);\r
+\r
+    return result.toString();\r
+  }\r
+\r
+  public static String replicateChar(char aCharacter, int aCount) {\r
+    char result[] = new char[aCount];\r
+\r
+    for (int i=0; i<aCount; i++)\r
+      result[i]= aCharacter;\r
+\r
+    return new String(result);\r
+  }\r
+\r
+  public static String padStringLeft(String aString, int aLength, char aPadCharacter) {\r
+    if (aString.length()<aLength)\r
+      return replicateChar(aPadCharacter, aLength-aString.length()) + aString;\r
+    else\r
+      return aString;\r
+  }\r
+\r
+  private static final char HEX_CHARACTERS[] = {\r
+      '0', '1', '2', '3', '4', '5', '6', '7',\r
+      '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'\r
+  };\r
+\r
+  public static String convertToHex(long aData, int aNumberOfDigits) {\r
+    StringBuffer result = new StringBuffer();\r
+\r
+    for (int digit = aNumberOfDigits-1; digit>=0; digit--) {\r
+      int value = (int) (aData >> (digit*4)) & 0xf;\r
+      result.append(HEX_CHARACTERS[value]);\r
+    }\r
+\r
+    return result.toString();\r
+  }\r
+\r
+  public static String convertToHex(byte[] aData) {\r
+    StringBuffer result = new StringBuffer();\r
+\r
+    for (int i = 0; i<aData.length; i++) {\r
+      result.append(convertToHex(aData[i], 2));\r
+\r
+    }\r
+\r
+    return result.toString();\r
+  }\r
 }
\ No newline at end of file
diff --git a/source/mir/util/StructuredContentParser.java b/source/mir/util/StructuredContentParser.java
new file mode 100755 (executable)
index 0000000..cc42565
--- /dev/null
@@ -0,0 +1,228 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mir.util;
+
+import java.util.*;
+
+
+/**
+ *
+ * <p>Title: </p>
+ * <p>Description:
+ *   Class to parse structured content:
+ *   <tt>
+ *      {
+ *        name = 'Countries'
+ *        countries = [ spain 'united kingdom' germany ]
+ *        cities = {
+ *          spain = [ 'madrid' barcelona bilbao ]
+ *          'united kingdom' = [ 'london' 'lancaster' ]
+ *          germany = [ 'berlin' 'bremen' ]
+ *        }
+ *      }
+ *   </tt>
+ *
+ *   And put it into a <code>String</code>/<code>Map</code>/<code>List</code> structure.
+ *  </p>
+ *  <p>
+ *    Parsing is be very optimistic: no exception is ever to be thrown.
+ *  </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
+ */
+public class StructuredContentParser {
+  public StructuredContentParser() {
+  }
+
+  private static class Scanner {
+    private String data;
+    private int position;
+
+    public Scanner(String aData) {
+      data = aData;
+      position = 0;
+    }
+
+    public String scanIdentifier() {
+      StringBuffer result = new StringBuffer();
+
+      while (!isAtEnd() && Character.isJavaIdentifierPart(peek())) {
+        result.append(scan());
+      }
+
+      return result.toString();
+    }
+
+    public String scanString() {
+      StringBuffer result = new StringBuffer();
+      char delimiter='\'';
+
+      if (!isAtEnd()) {
+        delimiter=scan();
+      }
+
+      boolean finished = false;
+
+      while (!finished && !isAtEnd()) {
+        char data = scan();
+
+        if (data == delimiter) {
+          if (!isAtEnd() && peek() == delimiter) {
+            scan();
+            result.append(data);
+          }
+          else
+            finished=true;
+        }
+        else
+          result.append(data);
+      }
+
+      return result.toString();
+    }
+
+    public void skipSpace() {
+      while (!isAtEnd() && Character.isWhitespace(peek()))
+        scan();
+    }
+
+    public boolean isAtEnd() {
+      return position >= data.length();
+    }
+
+    public char peek() {
+      if (!isAtEnd()) {
+        return data.charAt(position);
+      }
+      else
+        return '\0';
+    }
+
+    public char scan() {
+      if (!isAtEnd()) {
+        char result =data.charAt(position);
+        position++;
+        return result;
+      }
+      else
+        return '\0';
+    }
+  }
+
+  public static List parseList(Scanner aScanner) {
+    List result = new Vector();
+    aScanner.skipSpace();
+    if (aScanner.peek() == '[')
+      aScanner.scan();
+    aScanner.skipSpace();
+    Object object = parseObject(aScanner);
+
+    while (object != null) {
+      result.add(object);
+      aScanner.skipSpace();
+      object = parseObject(aScanner);
+    }
+
+    aScanner.skipSpace();
+    if (aScanner.peek() == ']')
+      aScanner.scan();
+
+    return result;
+  }
+
+  public static Map parseMap(Scanner aScanner) {
+    Map result = new HashMap();
+    aScanner.skipSpace();
+    if (aScanner.peek() == '{')
+      aScanner.scan();
+    aScanner.skipSpace();
+    Object key = parseObject(aScanner);
+    aScanner.skipSpace();
+    if (aScanner.peek() == '=')
+      aScanner.scan();
+    aScanner.skipSpace();
+    Object value = parseObject(aScanner);
+
+
+    while (key != null && value!=null) {
+      result.put(key, value);
+      aScanner.skipSpace();
+      key = parseObject(aScanner);
+      aScanner.skipSpace();
+      if (aScanner.peek() == '=')
+        aScanner.scan();
+      aScanner.skipSpace();
+      value = parseObject(aScanner);
+    }
+
+    aScanner.skipSpace();
+    if (aScanner.peek() == '}')
+      aScanner.scan();
+
+    return result;
+  }
+
+  public static Object parseObject(Scanner aScanner) {
+    Object result = null;
+
+    aScanner.skipSpace();
+
+    if (!aScanner.isAtEnd()) {
+      char data = aScanner.peek();
+
+      if (data == '[')
+        return parseList(aScanner);
+      if (data == '{')
+        return parseMap(aScanner);
+      if (data == '\'' || data == '"')
+        return aScanner.scanString();
+      if (Character.isJavaIdentifierPart(data))
+        return aScanner.scanIdentifier();
+    }
+
+    return null;
+  }
+
+  public static Object parse(String aData) {
+    Scanner scanner = new Scanner(aData);
+
+    return parseObject(scanner);
+  }
+
+  public static String constructStringLiteral(String aString) {
+    final char[] CHARACTERS_TO_ESCAPE = { '\'' };
+    final String[] ESCAPE_CODES = { "\'\'" };
+
+    return "'" +  StringRoutines.replaceStringCharacters(aString, CHARACTERS_TO_ESCAPE, ESCAPE_CODES) + "'";
+  }
+}
\ No newline at end of file
diff --git a/source/mir/util/Translate.java b/source/mir/util/Translate.java
new file mode 100755 (executable)
index 0000000..90785da
--- /dev/null
@@ -0,0 +1,593 @@
+// todo....figure out what license changes need to be made here...
+
+// HTMLParser Library v1_3_20030511 - A java-based parser for HTML
+// Copyright (C) Dec 31, 2000 Somik Raha
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+// Lesser General Public License for more details.
+// 
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+//
+// For any questions or suggestions, you can write to me at :
+// Email :somik@industriallogic.com
+// 
+// Postal Address : 
+// Somik Raha
+// Extreme Programmer & Coach
+// Industrial Logic Corporation
+// 2583 Cedar Street, Berkeley, 
+// CA 94708, USA
+// Website : http://www.industriallogic.com
+// 
+// This class was contributed by 
+// Derrick Oswald
+//
+
+package mir.util;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * Translate numeric character references and character entity references to unicode characters.
+ * Based on tables found at <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">
+ * http://www.w3.org/TR/REC-html40/sgml/entities.html</a>
+ * <p><b>Note: Do not edit! This class is created by the Generate class.</b>
+ * <p>Typical usage:
+ * <pre>
+ *      String s = Translate.decode (getTextFromHtmlPage ());
+ * </pre>
+ * @author <a href='mailto:DerrickOswald@users.sourceforge.net?subject=Character Reference Translation class'>Derrick Oswald</a>
+ */
+public class Translate
+{
+    /**
+     * Table mapping entity reference kernel to character.
+     * <p><code>String</code>-><code>Character</code>
+     */
+    protected static Map refChar;
+    static
+    {
+        refChar = new HashMap(1000);
+
+        // Portions © International Organization for Standardization 1986
+        // Permission to copy in any form is granted for use with
+        // conforming SGML systems and applications as defined in
+        // ISO 8879, provided this notice is included in all copies.
+        // Character entity set. Typical invocation:
+        // <!ENTITY % HTMLlat1 PUBLIC
+        // "-//W3C//ENTITIES Latin 1//EN//HTML">
+        // %HTMLlat1;
+        refChar.put ("nbsp",     new Character ('\u00a0')); // no-break space = non-breaking space, U+00A0 ISOnum
+        refChar.put ("iexcl",    new Character ('\u00a1')); // inverted exclamation mark, U+00A1 ISOnum
+        refChar.put ("cent",     new Character ('\u00a2')); // cent sign, U+00A2 ISOnum
+        refChar.put ("pound",    new Character ('\u00a3')); // pound sign, U+00A3 ISOnum
+        refChar.put ("curren",   new Character ('\u00a4')); // currency sign, U+00A4 ISOnum
+        refChar.put ("yen",      new Character ('\u00a5')); // yen sign = yuan sign, U+00A5 ISOnum
+        refChar.put ("brvbar",   new Character ('\u00a6')); // broken bar = broken vertical bar, U+00A6 ISOnum
+        refChar.put ("sect",     new Character ('\u00a7')); // section sign, U+00A7 ISOnum
+        refChar.put ("uml",      new Character ('\u00a8')); // diaeresis = spacing diaeresis, U+00A8 ISOdia
+        refChar.put ("copy",     new Character ('\u00a9')); // copyright sign, U+00A9 ISOnum
+        refChar.put ("ordf",     new Character ('\u00aa')); // feminine ordinal indicator, U+00AA ISOnum
+        refChar.put ("laquo",    new Character ('\u00ab')); // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum
+        refChar.put ("not",      new Character ('\u00ac')); // not sign, U+00AC ISOnum
+        refChar.put ("shy",      new Character ('\u00ad')); // soft hyphen = discretionary hyphen, U+00AD ISOnum
+        refChar.put ("reg",      new Character ('\u00ae')); // registered sign = registered trade mark sign, U+00AE ISOnum
+        refChar.put ("macr",     new Character ('\u00af')); // macron = spacing macron = overline = APL overbar, U+00AF ISOdia
+        refChar.put ("deg",      new Character ('\u00b0')); // degree sign, U+00B0 ISOnum
+        refChar.put ("plusmn",   new Character ('\u00b1')); // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum
+        refChar.put ("sup2",     new Character ('\u00b2')); // superscript two = superscript digit two = squared, U+00B2 ISOnum
+        refChar.put ("sup3",     new Character ('\u00b3')); // superscript three = superscript digit three = cubed, U+00B3 ISOnum
+        refChar.put ("acute",    new Character ('\u00b4')); // acute accent = spacing acute, U+00B4 ISOdia
+        refChar.put ("micro",    new Character ('\u00b5')); // micro sign, U+00B5 ISOnum
+        refChar.put ("para",     new Character ('\u00b6')); // pilcrow sign = paragraph sign, U+00B6 ISOnum
+        refChar.put ("middot",   new Character ('\u00b7')); // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum
+        refChar.put ("cedil",    new Character ('\u00b8')); // cedilla = spacing cedilla, U+00B8 ISOdia
+        refChar.put ("sup1",     new Character ('\u00b9')); // superscript one = superscript digit one, U+00B9 ISOnum
+        refChar.put ("ordm",     new Character ('\u00ba')); // masculine ordinal indicator, U+00BA ISOnum
+        refChar.put ("raquo",    new Character ('\u00bb')); // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum
+        refChar.put ("frac14",   new Character ('\u00bc')); // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum
+        refChar.put ("frac12",   new Character ('\u00bd')); // vulgar fraction one half = fraction one half, U+00BD ISOnum
+        refChar.put ("frac34",   new Character ('\u00be')); // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum
+        refChar.put ("iquest",   new Character ('\u00bf')); // inverted question mark = turned question mark, U+00BF ISOnum
+        refChar.put ("Agrave",   new Character ('\u00c0')); // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1
+        refChar.put ("Aacute",   new Character ('\u00c1')); // latin capital letter A with acute, U+00C1 ISOlat1
+        refChar.put ("Acirc",    new Character ('\u00c2')); // latin capital letter A with circumflex, U+00C2 ISOlat1
+        refChar.put ("Atilde",   new Character ('\u00c3')); // latin capital letter A with tilde, U+00C3 ISOlat1
+        refChar.put ("Auml",     new Character ('\u00c4')); // latin capital letter A with diaeresis, U+00C4 ISOlat1
+        refChar.put ("Aring",    new Character ('\u00c5')); // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1
+        refChar.put ("AElig",    new Character ('\u00c6')); // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
+        refChar.put ("Ccedil",   new Character ('\u00c7')); // latin capital letter C with cedilla, U+00C7 ISOlat1
+        refChar.put ("Egrave",   new Character ('\u00c8')); // latin capital letter E with grave, U+00C8 ISOlat1
+        refChar.put ("Eacute",   new Character ('\u00c9')); // latin capital letter E with acute, U+00C9 ISOlat1
+        refChar.put ("Ecirc",    new Character ('\u00ca')); // latin capital letter E with circumflex, U+00CA ISOlat1
+        refChar.put ("Euml",     new Character ('\u00cb')); // latin capital letter E with diaeresis, U+00CB ISOlat1
+        refChar.put ("Igrave",   new Character ('\u00cc')); // latin capital letter I with grave, U+00CC ISOlat1
+        refChar.put ("Iacute",   new Character ('\u00cd')); // latin capital letter I with acute, U+00CD ISOlat1
+        refChar.put ("Icirc",    new Character ('\u00ce')); // latin capital letter I with circumflex, U+00CE ISOlat1
+        refChar.put ("Iuml",     new Character ('\u00cf')); // latin capital letter I with diaeresis, U+00CF ISOlat1
+        refChar.put ("ETH",      new Character ('\u00d0')); // latin capital letter ETH, U+00D0 ISOlat1
+        refChar.put ("Ntilde",   new Character ('\u00d1')); // latin capital letter N with tilde, U+00D1 ISOlat1
+        refChar.put ("Ograve",   new Character ('\u00d2')); // latin capital letter O with grave, U+00D2 ISOlat1
+        refChar.put ("Oacute",   new Character ('\u00d3')); // latin capital letter O with acute, U+00D3 ISOlat1
+        refChar.put ("Ocirc",    new Character ('\u00d4')); // latin capital letter O with circumflex, U+00D4 ISOlat1
+        refChar.put ("Otilde",   new Character ('\u00d5')); // latin capital letter O with tilde, U+00D5 ISOlat1
+        refChar.put ("Ouml",     new Character ('\u00d6')); // latin capital letter O with diaeresis, U+00D6 ISOlat1
+        refChar.put ("times",    new Character ('\u00d7')); // multiplication sign, U+00D7 ISOnum
+        refChar.put ("Oslash",   new Character ('\u00d8')); // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1
+        refChar.put ("Ugrave",   new Character ('\u00d9')); // latin capital letter U with grave, U+00D9 ISOlat1
+        refChar.put ("Uacute",   new Character ('\u00da')); // latin capital letter U with acute, U+00DA ISOlat1
+        refChar.put ("Ucirc",    new Character ('\u00db')); // latin capital letter U with circumflex, U+00DB ISOlat1
+        refChar.put ("Uuml",     new Character ('\u00dc')); // latin capital letter U with diaeresis, U+00DC ISOlat1
+        refChar.put ("Yacute",   new Character ('\u00dd')); // latin capital letter Y with acute, U+00DD ISOlat1
+        refChar.put ("THORN",    new Character ('\u00de')); // latin capital letter THORN, U+00DE ISOlat1
+        refChar.put ("szlig",    new Character ('\u00df')); // latin small letter sharp s = ess-zed, U+00DF ISOlat1
+        refChar.put ("agrave",   new Character ('\u00e0')); // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1
+        refChar.put ("aacute",   new Character ('\u00e1')); // latin small letter a with acute, U+00E1 ISOlat1
+        refChar.put ("acirc",    new Character ('\u00e2')); // latin small letter a with circumflex, U+00E2 ISOlat1
+        refChar.put ("atilde",   new Character ('\u00e3')); // latin small letter a with tilde, U+00E3 ISOlat1
+        refChar.put ("auml",     new Character ('\u00e4')); // latin small letter a with diaeresis, U+00E4 ISOlat1
+        refChar.put ("aring",    new Character ('\u00e5')); // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1
+        refChar.put ("aelig",    new Character ('\u00e6')); // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1
+        refChar.put ("ccedil",   new Character ('\u00e7')); // latin small letter c with cedilla, U+00E7 ISOlat1
+        refChar.put ("egrave",   new Character ('\u00e8')); // latin small letter e with grave, U+00E8 ISOlat1
+        refChar.put ("eacute",   new Character ('\u00e9')); // latin small letter e with acute, U+00E9 ISOlat1
+        refChar.put ("ecirc",    new Character ('\u00ea')); // latin small letter e with circumflex, U+00EA ISOlat1
+        refChar.put ("euml",     new Character ('\u00eb')); // latin small letter e with diaeresis, U+00EB ISOlat1
+        refChar.put ("igrave",   new Character ('\u00ec')); // latin small letter i with grave, U+00EC ISOlat1
+        refChar.put ("iacute",   new Character ('\u00ed')); // latin small letter i with acute, U+00ED ISOlat1
+        refChar.put ("icirc",    new Character ('\u00ee')); // latin small letter i with circumflex, U+00EE ISOlat1
+        refChar.put ("iuml",     new Character ('\u00ef')); // latin small letter i with diaeresis, U+00EF ISOlat1
+        refChar.put ("eth",      new Character ('\u00f0')); // latin small letter eth, U+00F0 ISOlat1
+        refChar.put ("ntilde",   new Character ('\u00f1')); // latin small letter n with tilde, U+00F1 ISOlat1
+        refChar.put ("ograve",   new Character ('\u00f2')); // latin small letter o with grave, U+00F2 ISOlat1
+        refChar.put ("oacute",   new Character ('\u00f3')); // latin small letter o with acute, U+00F3 ISOlat1
+        refChar.put ("ocirc",    new Character ('\u00f4')); // latin small letter o with circumflex, U+00F4 ISOlat1
+        refChar.put ("otilde",   new Character ('\u00f5')); // latin small letter o with tilde, U+00F5 ISOlat1
+        refChar.put ("ouml",     new Character ('\u00f6')); // latin small letter o with diaeresis, U+00F6 ISOlat1
+        refChar.put ("divide",   new Character ('\u00f7')); // division sign, U+00F7 ISOnum
+        refChar.put ("oslash",   new Character ('\u00f8')); // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1
+        refChar.put ("ugrave",   new Character ('\u00f9')); // latin small letter u with grave, U+00F9 ISOlat1
+        refChar.put ("uacute",   new Character ('\u00fa')); // latin small letter u with acute, U+00FA ISOlat1
+        refChar.put ("ucirc",    new Character ('\u00fb')); // latin small letter u with circumflex, U+00FB ISOlat1
+        refChar.put ("uuml",     new Character ('\u00fc')); // latin small letter u with diaeresis, U+00FC ISOlat1
+        refChar.put ("yacute",   new Character ('\u00fd')); // latin small letter y with acute, U+00FD ISOlat1
+        refChar.put ("thorn",    new Character ('\u00fe')); // latin small letter thorn, U+00FE ISOlat1
+        refChar.put ("yuml",     new Character ('\u00ff')); // latin small letter y with diaeresis, U+00FF ISOlat1
+        // Mathematical, Greek and Symbolic characters for HTML
+        // Character entity set. Typical invocation:
+        // <!ENTITY % HTMLsymbol PUBLIC
+        // "-//W3C//ENTITIES Symbols//EN//HTML">
+        // %HTMLsymbol;
+        // Portions © International Organization for Standardization 1986:
+        // Permission to copy in any form is granted for use with
+        // conforming SGML systems and applications as defined in
+        // ISO 8879, provided this notice is included in all copies.
+        // Relevant ISO entity set is given unless names are newly introduced.
+        // New names (i.e., not in ISO 8879 list) do not clash with any
+        // existing ISO 8879 entity names. ISO 10646 character numbers
+        // are given for each character, in hex. CDATA values are decimal
+        // conversions of the ISO 10646 values and refer to the document
+        // character set. Names are ISO 10646 names.
+        // Latin Extended-B
+        refChar.put ("fnof",     new Character ('\u0192')); // latin small f with hook = function = florin, U+0192 ISOtech
+        // Greek
+        refChar.put ("Alpha",    new Character ('\u0391')); // greek capital letter alpha, U+0391
+        refChar.put ("Beta",     new Character ('\u0392')); // greek capital letter beta, U+0392
+        refChar.put ("Gamma",    new Character ('\u0393')); // greek capital letter gamma, U+0393 ISOgrk3
+        refChar.put ("Delta",    new Character ('\u0394')); // greek capital letter delta, U+0394 ISOgrk3
+        refChar.put ("Epsilon",  new Character ('\u0395')); // greek capital letter epsilon, U+0395
+        refChar.put ("Zeta",     new Character ('\u0396')); // greek capital letter zeta, U+0396
+        refChar.put ("Eta",      new Character ('\u0397')); // greek capital letter eta, U+0397
+        refChar.put ("Theta",    new Character ('\u0398')); // greek capital letter theta, U+0398 ISOgrk3
+        refChar.put ("Iota",     new Character ('\u0399')); // greek capital letter iota, U+0399
+        refChar.put ("Kappa",    new Character ('\u039a')); // greek capital letter kappa, U+039A
+        refChar.put ("Lambda",   new Character ('\u039b')); // greek capital letter lambda, U+039B ISOgrk3
+        refChar.put ("Mu",       new Character ('\u039c')); // greek capital letter mu, U+039C
+        refChar.put ("Nu",       new Character ('\u039d')); // greek capital letter nu, U+039D
+        refChar.put ("Xi",       new Character ('\u039e')); // greek capital letter xi, U+039E ISOgrk3
+        refChar.put ("Omicron",  new Character ('\u039f')); // greek capital letter omicron, U+039F
+        refChar.put ("Pi",       new Character ('\u03a0')); // greek capital letter pi, U+03A0 ISOgrk3
+        refChar.put ("Rho",      new Character ('\u03a1')); // greek capital letter rho, U+03A1
+        // there is no Sigmaf, and no U+03A2 character either
+        refChar.put ("Sigma",    new Character ('\u03a3')); // greek capital letter sigma, U+03A3 ISOgrk3
+        refChar.put ("Tau",      new Character ('\u03a4')); // greek capital letter tau, U+03A4
+        refChar.put ("Upsilon",  new Character ('\u03a5')); // greek capital letter upsilon, U+03A5 ISOgrk3
+        refChar.put ("Phi",      new Character ('\u03a6')); // greek capital letter phi, U+03A6 ISOgrk3
+        refChar.put ("Chi",      new Character ('\u03a7')); // greek capital letter chi, U+03A7
+        refChar.put ("Psi",      new Character ('\u03a8')); // greek capital letter psi, U+03A8 ISOgrk3
+        refChar.put ("Omega",    new Character ('\u03a9')); // greek capital letter omega, U+03A9 ISOgrk3
+        refChar.put ("alpha",    new Character ('\u03b1')); // greek small letter alpha, U+03B1 ISOgrk3
+        refChar.put ("beta",     new Character ('\u03b2')); // greek small letter beta, U+03B2 ISOgrk3
+        refChar.put ("gamma",    new Character ('\u03b3')); // greek small letter gamma, U+03B3 ISOgrk3
+        refChar.put ("delta",    new Character ('\u03b4')); // greek small letter delta, U+03B4 ISOgrk3
+        refChar.put ("epsilon",  new Character ('\u03b5')); // greek small letter epsilon, U+03B5 ISOgrk3
+        refChar.put ("zeta",     new Character ('\u03b6')); // greek small letter zeta, U+03B6 ISOgrk3
+        refChar.put ("eta",      new Character ('\u03b7')); // greek small letter eta, U+03B7 ISOgrk3
+        refChar.put ("theta",    new Character ('\u03b8')); // greek small letter theta, U+03B8 ISOgrk3
+        refChar.put ("iota",     new Character ('\u03b9')); // greek small letter iota, U+03B9 ISOgrk3
+        refChar.put ("kappa",    new Character ('\u03ba')); // greek small letter kappa, U+03BA ISOgrk3
+        refChar.put ("lambda",   new Character ('\u03bb')); // greek small letter lambda, U+03BB ISOgrk3
+        refChar.put ("mu",       new Character ('\u03bc')); // greek small letter mu, U+03BC ISOgrk3
+        refChar.put ("nu",       new Character ('\u03bd')); // greek small letter nu, U+03BD ISOgrk3
+        refChar.put ("xi",       new Character ('\u03be')); // greek small letter xi, U+03BE ISOgrk3
+        refChar.put ("omicron",  new Character ('\u03bf')); // greek small letter omicron, U+03BF NEW
+        refChar.put ("pi",       new Character ('\u03c0')); // greek small letter pi, U+03C0 ISOgrk3
+        refChar.put ("rho",      new Character ('\u03c1')); // greek small letter rho, U+03C1 ISOgrk3
+        refChar.put ("sigmaf",   new Character ('\u03c2')); // greek small letter final sigma, U+03C2 ISOgrk3
+        refChar.put ("sigma",    new Character ('\u03c3')); // greek small letter sigma, U+03C3 ISOgrk3
+        refChar.put ("tau",      new Character ('\u03c4')); // greek small letter tau, U+03C4 ISOgrk3
+        refChar.put ("upsilon",  new Character ('\u03c5')); // greek small letter upsilon, U+03C5 ISOgrk3
+        refChar.put ("phi",      new Character ('\u03c6')); // greek small letter phi, U+03C6 ISOgrk3
+        refChar.put ("chi",      new Character ('\u03c7')); // greek small letter chi, U+03C7 ISOgrk3
+        refChar.put ("psi",      new Character ('\u03c8')); // greek small letter psi, U+03C8 ISOgrk3
+        refChar.put ("omega",    new Character ('\u03c9')); // greek small letter omega, U+03C9 ISOgrk3
+        refChar.put ("thetasym", new Character ('\u03d1')); // greek small letter theta symbol, U+03D1 NEW
+        refChar.put ("upsih",    new Character ('\u03d2')); // greek upsilon with hook symbol, U+03D2 NEW
+        refChar.put ("piv",      new Character ('\u03d6')); // greek pi symbol, U+03D6 ISOgrk3
+        // General Punctuation
+        refChar.put ("bull",     new Character ('\u2022')); // bullet = black small circle, U+2022 ISOpub
+        // bullet is NOT the same as bullet operator, U+2219
+        refChar.put ("hellip",   new Character ('\u2026')); // horizontal ellipsis = three dot leader, U+2026 ISOpub
+        refChar.put ("prime",    new Character ('\u2032')); // prime = minutes = feet, U+2032 ISOtech
+        refChar.put ("Prime",    new Character ('\u2033')); // double prime = seconds = inches, U+2033 ISOtech
+        refChar.put ("oline",    new Character ('\u203e')); // overline = spacing overscore, U+203E NEW
+        refChar.put ("frasl",    new Character ('\u2044')); // fraction slash, U+2044 NEW
+        // Letterlike Symbols
+        refChar.put ("weierp",   new Character ('\u2118')); // script capital P = power set = Weierstrass p, U+2118 ISOamso
+        refChar.put ("image",    new Character ('\u2111')); // blackletter capital I = imaginary part, U+2111 ISOamso
+        refChar.put ("real",     new Character ('\u211c')); // blackletter capital R = real part symbol, U+211C ISOamso
+        refChar.put ("trade",    new Character ('\u2122')); // trade mark sign, U+2122 ISOnum
+        refChar.put ("alefsym",  new Character ('\u2135')); // alef symbol = first transfinite cardinal, U+2135 NEW
+        // alef symbol is NOT the same as hebrew letter alef,
+        // U+05D0 although the same glyph could be used to depict both characters
+        // Arrows
+        refChar.put ("larr",     new Character ('\u2190')); // leftwards arrow, U+2190 ISOnum
+        refChar.put ("uarr",     new Character ('\u2191')); // upwards arrow, U+2191 ISOnum
+        refChar.put ("rarr",     new Character ('\u2192')); // rightwards arrow, U+2192 ISOnum
+        refChar.put ("darr",     new Character ('\u2193')); // downwards arrow, U+2193 ISOnum
+        refChar.put ("harr",     new Character ('\u2194')); // left right arrow, U+2194 ISOamsa
+        refChar.put ("crarr",    new Character ('\u21b5')); // downwards arrow with corner leftwards = carriage return, U+21B5 NEW
+        refChar.put ("lArr",     new Character ('\u21d0')); // leftwards double arrow, U+21D0 ISOtech
+        // ISO 10646 does not say that lArr is the same as the 'is implied by' arrow
+        // but also does not have any other character for that function. So ? lArr can
+        // be used for 'is implied by' as ISOtech suggests
+        refChar.put ("uArr",     new Character ('\u21d1')); // upwards double arrow, U+21D1 ISOamsa
+        refChar.put ("rArr",     new Character ('\u21d2')); // rightwards double arrow, U+21D2 ISOtech
+        // ISO 10646 does not say this is the 'implies' character but does not have
+        // another character with this function so ?
+        // rArr can be used for 'implies' as ISOtech suggests
+        refChar.put ("dArr",     new Character ('\u21d3')); // downwards double arrow, U+21D3 ISOamsa
+        refChar.put ("hArr",     new Character ('\u21d4')); // left right double arrow, U+21D4 ISOamsa
+        // Mathematical Operators
+        refChar.put ("forall",   new Character ('\u2200')); // for all, U+2200 ISOtech
+        refChar.put ("part",     new Character ('\u2202')); // partial differential, U+2202 ISOtech
+        refChar.put ("exist",    new Character ('\u2203')); // there exists, U+2203 ISOtech
+        refChar.put ("empty",    new Character ('\u2205')); // empty set = null set = diameter, U+2205 ISOamso
+        refChar.put ("nabla",    new Character ('\u2207')); // nabla = backward difference, U+2207 ISOtech
+        refChar.put ("isin",     new Character ('\u2208')); // element of, U+2208 ISOtech
+        refChar.put ("notin",    new Character ('\u2209')); // not an element of, U+2209 ISOtech
+        refChar.put ("ni",       new Character ('\u220b')); // contains as member, U+220B ISOtech
+        // should there be a more memorable name than 'ni'?
+        refChar.put ("prod",     new Character ('\u220f')); // n-ary product = product sign, U+220F ISOamsb
+        // prod is NOT the same character as U+03A0 'greek capital letter pi' though
+        // the same glyph might be used for both
+        refChar.put ("sum",      new Character ('\u2211')); // n-ary sumation, U+2211 ISOamsb
+        // sum is NOT the same character as U+03A3 'greek capital letter sigma'
+        // though the same glyph might be used for both
+        refChar.put ("minus",    new Character ('\u2212')); // minus sign, U+2212 ISOtech
+        refChar.put ("lowast",   new Character ('\u2217')); // asterisk operator, U+2217 ISOtech
+        refChar.put ("radic",    new Character ('\u221a')); // square root = radical sign, U+221A ISOtech
+        refChar.put ("prop",     new Character ('\u221d')); // proportional to, U+221D ISOtech
+        refChar.put ("infin",    new Character ('\u221e')); // infinity, U+221E ISOtech
+        refChar.put ("ang",      new Character ('\u2220')); // angle, U+2220 ISOamso
+        refChar.put ("and",      new Character ('\u2227')); // logical and = wedge, U+2227 ISOtech
+        refChar.put ("or",       new Character ('\u2228')); // logical or = vee, U+2228 ISOtech
+        refChar.put ("cap",      new Character ('\u2229')); // intersection = cap, U+2229 ISOtech
+        refChar.put ("cup",      new Character ('\u222a')); // union = cup, U+222A ISOtech
+        refChar.put ("int",      new Character ('\u222b')); // integral, U+222B ISOtech
+        refChar.put ("there4",   new Character ('\u2234')); // therefore, U+2234 ISOtech
+        refChar.put ("sim",      new Character ('\u223c')); // tilde operator = varies with = similar to, U+223C ISOtech
+        // tilde operator is NOT the same character as the tilde, U+007E,
+        // although the same glyph might be used to represent both
+        refChar.put ("cong",     new Character ('\u2245')); // approximately equal to, U+2245 ISOtech
+        refChar.put ("asymp",    new Character ('\u2248')); // almost equal to = asymptotic to, U+2248 ISOamsr
+        refChar.put ("ne",       new Character ('\u2260')); // not equal to, U+2260 ISOtech
+        refChar.put ("equiv",    new Character ('\u2261')); // identical to, U+2261 ISOtech
+        refChar.put ("le",       new Character ('\u2264')); // less-than or equal to, U+2264 ISOtech
+        refChar.put ("ge",       new Character ('\u2265')); // greater-than or equal to, U+2265 ISOtech
+        refChar.put ("sub",      new Character ('\u2282')); // subset of, U+2282 ISOtech
+        refChar.put ("sup",      new Character ('\u2283')); // superset of, U+2283 ISOtech
+        // note that nsup, 'not a superset of, U+2283' is not covered by the Symbol
+        // font encoding and is not included. Should it be, for symmetry?
+        // It is in ISOamsn
+        refChar.put ("nsub",     new Character ('\u2284')); // not a subset of, U+2284 ISOamsn
+        refChar.put ("sube",     new Character ('\u2286')); // subset of or equal to, U+2286 ISOtech
+        refChar.put ("supe",     new Character ('\u2287')); // superset of or equal to, U+2287 ISOtech
+        refChar.put ("oplus",    new Character ('\u2295')); // circled plus = direct sum, U+2295 ISOamsb
+        refChar.put ("otimes",   new Character ('\u2297')); // circled times = vector product, U+2297 ISOamsb
+        refChar.put ("perp",     new Character ('\u22a5')); // up tack = orthogonal to = perpendicular, U+22A5 ISOtech
+        refChar.put ("sdot",     new Character ('\u22c5')); // dot operator, U+22C5 ISOamsb
+        // dot operator is NOT the same character as U+00B7 middle dot
+        // Miscellaneous Technical
+        refChar.put ("lceil",    new Character ('\u2308')); // left ceiling = apl upstile, U+2308 ISOamsc
+        refChar.put ("rceil",    new Character ('\u2309')); // right ceiling, U+2309 ISOamsc
+        refChar.put ("lfloor",   new Character ('\u230a')); // left floor = apl downstile, U+230A ISOamsc
+        refChar.put ("rfloor",   new Character ('\u230b')); // right floor, U+230B ISOamsc
+        refChar.put ("lang",     new Character ('\u2329')); // left-pointing angle bracket = bra, U+2329 ISOtech
+        // lang is NOT the same character as U+003C 'less than'
+        // or U+2039 'single left-pointing angle quotation mark'
+        refChar.put ("rang",     new Character ('\u232a')); // right-pointing angle bracket = ket, U+232A ISOtech
+        // rang is NOT the same character as U+003E 'greater than'
+        // or U+203A 'single right-pointing angle quotation mark'
+        // Geometric Shapes
+        refChar.put ("loz",      new Character ('\u25ca')); // lozenge, U+25CA ISOpub
+        // Miscellaneous Symbols
+        refChar.put ("spades",   new Character ('\u2660')); // black spade suit, U+2660 ISOpub
+        // black here seems to mean filled as opposed to hollow
+        refChar.put ("clubs",    new Character ('\u2663')); // black club suit = shamrock, U+2663 ISOpub
+        refChar.put ("hearts",   new Character ('\u2665')); // black heart suit = valentine, U+2665 ISOpub
+        refChar.put ("diams",    new Character ('\u2666')); // black diamond suit, U+2666 ISOpub
+        // Special characters for HTML
+        // Character entity set. Typical invocation:
+        // <!ENTITY % HTMLspecial PUBLIC
+        // "-//W3C//ENTITIES Special//EN//HTML">
+        // %HTMLspecial;
+        // Portions © International Organization for Standardization 1986:
+        // Permission to copy in any form is granted for use with
+        // conforming SGML systems and applications as defined in
+        // ISO 8879, provided this notice is included in all copies.
+        // Relevant ISO entity set is given unless names are newly introduced.
+        // New names (i.e., not in ISO 8879 list) do not clash with any
+        // existing ISO 8879 entity names. ISO 10646 character numbers
+        // are given for each character, in hex. CDATA values are decimal
+        // conversions of the ISO 10646 values and refer to the document
+        // character set. Names are ISO 10646 names.
+        // C0 Controls and Basic Latin
+        refChar.put ("quot",     new Character ('\u0022')); // quotation mark = APL quote, U+0022 ISOnum
+        refChar.put ("amp",      new Character ('\u0026')); // ampersand, U+0026 ISOnum
+        refChar.put ("lt",       new Character ('\u003c')); // less-than sign, U+003C ISOnum
+        refChar.put ("gt",       new Character ('\u003e')); // greater-than sign, U+003E ISOnum
+        // Latin Extended-A
+        refChar.put ("OElig",    new Character ('\u0152')); // latin capital ligature OE, U+0152 ISOlat2
+        refChar.put ("oelig",    new Character ('\u0153')); // latin small ligature oe, U+0153 ISOlat2
+        // ligature is a misnomer, this is a separate character in some languages
+        refChar.put ("Scaron",   new Character ('\u0160')); // latin capital letter S with caron, U+0160 ISOlat2
+        refChar.put ("scaron",   new Character ('\u0161')); // latin small letter s with caron, U+0161 ISOlat2
+        refChar.put ("Yuml",     new Character ('\u0178')); // latin capital letter Y with diaeresis, U+0178 ISOlat2
+        // Spacing Modifier Letters
+        refChar.put ("circ",     new Character ('\u02c6')); // modifier letter circumflex accent, U+02C6 ISOpub
+        refChar.put ("tilde",    new Character ('\u02dc')); // small tilde, U+02DC ISOdia
+        // General Punctuation
+        refChar.put ("ensp",     new Character ('\u2002')); // en space, U+2002 ISOpub
+        refChar.put ("emsp",     new Character ('\u2003')); // em space, U+2003 ISOpub
+        refChar.put ("thinsp",   new Character ('\u2009')); // thin space, U+2009 ISOpub
+        refChar.put ("zwnj",     new Character ('\u200c')); // zero width non-joiner, U+200C NEW RFC 2070
+        refChar.put ("zwj",      new Character ('\u200d')); // zero width joiner, U+200D NEW RFC 2070
+        refChar.put ("lrm",      new Character ('\u200e')); // left-to-right mark, U+200E NEW RFC 2070
+        refChar.put ("rlm",      new Character ('\u200f')); // right-to-left mark, U+200F NEW RFC 2070
+        refChar.put ("ndash",    new Character ('\u2013')); // en dash, U+2013 ISOpub
+        refChar.put ("mdash",    new Character ('\u2014')); // em dash, U+2014 ISOpub
+        refChar.put ("lsquo",    new Character ('\u2018')); // left single quotation mark, U+2018 ISOnum
+        refChar.put ("rsquo",    new Character ('\u2019')); // right single quotation mark, U+2019 ISOnum
+        refChar.put ("sbquo",    new Character ('\u201a')); // single low-9 quotation mark, U+201A NEW
+        refChar.put ("ldquo",    new Character ('\u201c')); // left double quotation mark, U+201C ISOnum
+        refChar.put ("rdquo",    new Character ('\u201d')); // right double quotation mark, U+201D ISOnum
+        refChar.put ("bdquo",    new Character ('\u201e')); // double low-9 quotation mark, U+201E NEW
+        refChar.put ("dagger",   new Character ('\u2020')); // dagger, U+2020 ISOpub
+        refChar.put ("Dagger",   new Character ('\u2021')); // double dagger, U+2021 ISOpub
+        refChar.put ("permil",   new Character ('\u2030')); // per mille sign, U+2030 ISOtech
+        refChar.put ("lsaquo",   new Character ('\u2039')); // single left-pointing angle quotation mark, U+2039 ISO proposed
+        // lsaquo is proposed but not yet ISO standardized
+        refChar.put ("rsaquo",   new Character ('\u203a')); // single right-pointing angle quotation mark, U+203A ISO proposed
+        // rsaquo is proposed but not yet ISO standardized
+        refChar.put ("euro",     new Character ('\u20ac')); // euro sign, U+20AC NEW
+    }
+
+    /**
+     * Table mapping character to entity reference kernel.
+     * <p><code>Character</code>-><code>String</code>
+     */
+    protected static Map charRefTable;
+    static
+    {
+        charRefTable = new HashMap (refChar.size ());
+        Iterator iterator = refChar.keySet ().iterator ();
+        while (iterator.hasNext ())
+        {
+            String key = (String)iterator.next ();
+            Character character = (Character)refChar.get (key);
+            charRefTable.put (character, key);
+        }
+    }
+
+    /**
+     * Private constructor.
+     * This class is fully static and thread safe.
+     */
+    private Translate ()
+    {
+    }
+
+    /**
+     * Convert a reference to a unicode character.
+     * Convert a single numeric character reference or character entity reference
+     * to a unicode character.
+     * @param string The string to convert. Of the form &xxxx; or &amp;#xxxx; with
+     * or without the leading ampersand or trailing semi-colon.
+     * @return The converted character or '\0' (zero) if the string is an
+     * invalid reference.
+     */
+    public static char convertToChar (String string)
+    {
+        int length;
+        Character item;
+        char ret;
+
+        ret = 0;
+
+        length = string.length ();
+        if (0 < length)
+        {
+            if ('&' == string.charAt (0))
+            {
+                string = string.substring (1);
+                length--;
+            }
+            if (0 < length)
+            {
+                if (';' == string.charAt (length - 1))
+                    string = string.substring (0, --length);
+                if (0 < length)
+                {
+                    if ('#' == string.charAt (0))
+                        try
+                        {
+                            ret = (char)Integer.parseInt (string.substring (1));
+                        }
+                        catch (NumberFormatException nfe)
+                        {
+                            /* failed conversion, return 0 */
+                        }
+                    else
+                    {
+                        item = (Character)refChar.get (string);
+                        if (null != item)
+                            ret = item.charValue ();
+                    }
+                }
+            }
+        }
+
+        return (ret);
+    }
+
+    /**
+     * Decode a string containing references.
+     * Change all numeric character reference and character entity references
+     * to unicode characters.
+     * @param string The string to translate.
+     */
+    public static String decode (String string)
+    {
+        int index;
+        int length;
+        int amp;
+        int semi;
+        String code;
+        char character;
+        StringBuffer ret;
+        ret = new StringBuffer (string.length ());
+        index = 0;
+        length = string.length ();
+        while ((index < length) && (-1 != (amp = string.indexOf ('&', index))))
+        {
+            ret.append (string.substring (index, amp));
+            index = amp + 1;
+            if (amp < length - 1)
+            {
+                semi = string.indexOf (';', amp);
+                if (-1 != semi)
+                    code = string.substring (amp, semi + 1);
+                else
+                    code = string.substring (amp);
+                if (0 != (character = convertToChar (code)))
+                    index += code.length () - 1;
+                else
+                    character = '&';
+            }
+            else
+                character = '&';
+            ret.append (character);
+        }
+        if (index < length)
+            ret.append (string.substring (index));
+        return (ret.toString ());
+    }
+
+    /**
+     * Convert a character to a character entity reference.
+     * Convert a unicode character to a character entity reference of
+     * the form &xxxx;.
+     * @param character The character to convert.
+     * @return The converted character or <code>null</code> if the character
+     * is not one of the known entity references.
+     */
+    public static String convertToString (Character character)
+    {
+        StringBuffer buffer;
+        String ret;
+        if (null != (ret = (String)charRefTable.get (character)))
+        {
+            buffer = new StringBuffer (ret.length () + 2);
+            buffer.append ('&');
+            buffer.append (ret);
+            buffer.append (';');
+            ret = buffer.toString ();
+        }
+        return (ret);
+    }
+
+    /**
+     * Convert a character to a numeric character reference.
+     * Convert a unicode character to a numeric character reference of
+     * the form &amp;#xxxx;.
+     * @param character The character to convert.
+     * @return The converted character.
+     */
+    public static String convertToString (int character)
+    {
+        StringBuffer ret;
+        ret = new StringBuffer (13); /* &#2147483647; */
+        ret.append ("&#");
+        ret.append (character);
+        ret.append (';');
+        return (ret.toString ());
+    }
+
+    /**
+     * Encode a string to use references.
+     * Change all characters that are not ASCII to their numeric character
+     * reference or character entity reference.
+     * This implementation is inefficient, allocating a new
+     * <code>Character</code> for each character in the string,
+     * but this class is primarily intended to decode strings
+     * so efficiency and speed in the encoding was not a priority.
+     * @param string The string to translate.
+     */
+    public static String encode (String string)
+    {
+        int length;
+        char c;
+        Character character;
+        String value;
+        StringBuffer ret;
+        ret = new StringBuffer (string.length () * 6);
+        length  = string.length ();
+        for (int i = 0; i < length; i++)
+        {
+            c = string.charAt (i);
+            character = new Character (c);
+            if (null != (value = convertToString (character)))
+                ret.append (value);
+            else if (!((c > 0x001F) && (c < 0x007F)))
+            {
+                value = convertToString (c);
+                ret.append (value);
+            }
+            else
+                ret.append (character);
+        }
+        return (ret.toString ());
+    }
+}
index 19628c8..954b2e7 100755 (executable)
@@ -88,8 +88,6 @@ public class XMLReader {
       Throwable t = ExceptionFunctions.traceCauseException(e);
 
       if (t instanceof XMLReaderExc) {
-        if (locator!=null && filename!=null)
-          ((XMLReaderExc) t).setLocation(filename, locator.getLineNumber(), locator.getColumnNumber());
         throw (XMLReaderExc) t;
       }
 
@@ -125,11 +123,33 @@ public class XMLReader {
         inputSource = new InputSource(anInputStream);
         parser.parse(inputSource, this);
       }
-      catch (ParserConfigurationException e) {
-        throw new XMLReaderExc("Internal exception: "+e.getMessage());
-      }
       catch (Throwable e) {
-        throw new XMLReaderFailure(e);
+        Throwable t = ExceptionFunctions.traceCauseException(e);
+
+        if (t instanceof XMLReaderExc) {
+          if (locator!=null && filename!=null)
+            ((XMLReaderExc) t).setLocation(filename, locator.getLineNumber(), locator.getColumnNumber());
+          throw (XMLReaderExc) t;
+        }
+
+        if (t instanceof SAXParseException) {
+          XMLReaderExc r = new XMLReaderExc(t.getMessage());
+
+          if (locator!=null && filename!=null)
+            r.setLocation(filename, locator.getLineNumber(), locator.getColumnNumber());
+
+          throw r;
+        }
+
+        if (t instanceof XMLReaderFailure) {
+          throw (XMLReaderFailure) t;
+        }
+
+        if (t instanceof ParserConfigurationException) {
+          throw new XMLReaderFailure("Internal exception: "+t.toString(), t);
+        }
+
+        throw new XMLReaderFailure(t);
       }
     }
 
diff --git a/source/mircoders/accesscontrol/AccessControl.java b/source/mircoders/accesscontrol/AccessControl.java
new file mode 100755 (executable)
index 0000000..7e15db7
--- /dev/null
@@ -0,0 +1,169 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+
+package mircoders.accesscontrol;
+
+import java.util.List;
+import java.util.Vector;
+
+import mir.config.MirPropertiesConfiguration;
+import mir.log.LoggerWrapper;
+import mircoders.entity.EntityUsers;
+
+public class AccessControl {
+  private UserAccessControl user;
+  private GeneralAccessControl general;
+  protected LoggerWrapper logger = new LoggerWrapper("Global.AccessControl");
+  protected MirPropertiesConfiguration configuration;
+
+  public AccessControl() {
+    try {
+      configuration = MirPropertiesConfiguration.instance();
+
+      user = new UserAccessControl(configuration.getVector("AccessControl.SuperUsers"));
+      general = new GeneralAccessControl();
+    }
+    catch (Throwable t) {
+      throw new RuntimeException(t.toString());
+    }
+  }
+
+  public UserAccessControl user() {
+    return user;
+  }
+
+  public GeneralAccessControl general() {
+    return general;
+  }
+
+  public class GeneralAccessControl {
+    public boolean mayDeleteArticles(EntityUsers aSubject) {
+      return configuration.getString("Mir.Localizer.Admin.AllowDeleteArticle", "0").equals("1");
+    }
+
+    public void assertMayDeleteArticles(EntityUsers aSubject) throws AuthorizationExc, AuthorizationFailure {
+      try {
+        if (!mayDeleteArticles(aSubject))
+          throw new AuthorizationExc("not allowed to delete articles");
+      }
+      catch (Throwable t) {
+        throw new AuthorizationFailure(t);
+      }
+    }
+
+    public boolean mayDeleteComments(EntityUsers aSubject) {
+      return configuration.getString("Mir.Localizer.Admin.AllowDeleteComment", "0").equals("1");
+    }
+
+    public void assertMayDeleteComments(EntityUsers aSubject) throws AuthorizationExc, AuthorizationFailure {
+      try {
+        if (!mayDeleteArticles(aSubject))
+          throw new AuthorizationExc("not allowed to delete comments");
+      }
+      catch (Throwable t) {
+        throw new AuthorizationFailure(t);
+      }
+    }
+  }
+
+  public class UserAccessControl {
+    private List superusers;
+
+    public UserAccessControl(List aSuperUsers) {
+      superusers = new Vector(aSuperUsers);
+    }
+
+    public void assertMayAddUsers(EntityUsers aSubject) throws AuthorizationExc, AuthorizationFailure {
+      try {
+        if (!mayAddUsers(aSubject))
+          throw new AuthorizationExc("not allowed to add users");
+      }
+      catch (Throwable t) {
+        throw new AuthorizationFailure(t);
+      }
+
+    }
+
+    public boolean mayAddUsers(EntityUsers aSubject) {
+      return superusers.contains(aSubject.getValue("login"));
+    }
+
+    public void assertMayEditUser(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure {
+      try {
+        if (!mayEditUser(aSubject, anObject))
+          throw new AuthorizationExc("not allowed to edit user " + anObject.getId());
+      }
+      catch (Throwable t) {
+        throw new AuthorizationFailure(t);
+      }
+
+    }
+
+    public boolean mayEditUser(EntityUsers aSubject, EntityUsers anObject) {
+      return superusers.contains(aSubject.getValue("login"));
+    }
+
+    public boolean mayEditUsers(EntityUsers aSubject) {
+      return superusers.contains(aSubject.getValue("login"));
+    }
+
+    public void assertMayDeleteUser(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure {
+      try {
+        if (!mayDeleteUser(aSubject, anObject))
+          throw new AuthorizationExc("not allowed to delete user " + anObject.getId());
+      }
+      catch (Throwable t) {
+        throw new AuthorizationFailure(t);
+      }
+    }
+
+    public boolean mayDeleteUser(EntityUsers aSubject, EntityUsers anObject) {
+      return superusers.contains(aSubject.getValue("login"));
+    }
+
+    public boolean mayDeleteUsers(EntityUsers aSubject) {
+      return superusers.contains(aSubject.getValue("login"));
+    }
+
+    public boolean mayChangeUserPassword(EntityUsers aSubject, EntityUsers anObject) {
+      return aSubject.getId().equals(anObject.getId()) || superusers.contains(aSubject.getValue("login"));
+    }
+
+    public void assertMayChangeUserPassword(EntityUsers aSubject, EntityUsers anObject) throws AuthorizationExc, AuthorizationFailure {
+      try {
+        if (!mayChangeUserPassword(aSubject, anObject))
+          throw new AuthorizationExc("not allowed to change user " + anObject.getId()+"'s password");
+      }
+      catch (Throwable t) {
+        throw new AuthorizationFailure(t);
+      }
+    }
+  }
+}
diff --git a/source/mircoders/accesscontrol/AuthorizationExc.java b/source/mircoders/accesscontrol/AuthorizationExc.java
new file mode 100755 (executable)
index 0000000..b6c373f
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.accesscontrol;
+
+import multex.Exc;
+
+public class AuthorizationExc extends Exc {
+  public AuthorizationExc(String aMessage) {
+    super(aMessage);
+  }
+}
diff --git a/source/mircoders/accesscontrol/AuthorizationFailure.java b/source/mircoders/accesscontrol/AuthorizationFailure.java
new file mode 100755 (executable)
index 0000000..90e3237
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2001, 2002 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.accesscontrol;
+
+import multex.Failure;
+
+public class AuthorizationFailure extends Failure {
+
+  public AuthorizationFailure(String aMessage, Throwable aCause) {
+    super (aMessage, aCause);
+  }
+
+  public AuthorizationFailure(Throwable aCause) {
+    this (aCause.getMessage(), aCause);
+  }
+}
index b5032b4..b51fe47 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -41,8 +41,8 @@ import mircoders.storage.DatabaseContent;
 /**
  * This class maps one line of the comment-table to a java-object.
  *
- * @author $Author: idfx $
- * @version $Revision: 1.16 $ $Date: 2003/04/21 12:42:53 $
+ * @author $Author: zapata $
+ * @version $Revision: 1.17 $ $Date: 2003/09/03 18:29:04 $
  */
 
 
@@ -66,10 +66,6 @@ public class EntityComment extends Entity
   public void setValues(Map theStringValues)
   {
     if (theStringValues != null) {
-      if (!theStringValues.containsKey("is_published")) {
-        theStringValues.put("is_published","0");
-      }
-
       if (theStringValues.containsKey("main_url")){
         if (((String)theStringValues.get("main_url")).equalsIgnoreCase("http://")) {
           theStringValues.remove("main_url");
index 5eb2bf5..968c06e 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -45,15 +45,12 @@ import mir.storage.StorageObjectFailure;
 import mircoders.storage.DatabaseContent;
 import mircoders.storage.DatabaseContentToMedia;
 import mircoders.storage.DatabaseContentToTopics;
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
 
 /**
  * this class implements mapping of one line of the database table content
  * to a java object
  *
- * @version $Id: EntityContent.java,v 1.19 2003/04/21 12:42:54 idfx Exp $
+ * @version $Id: EntityContent.java,v 1.20 2003/09/03 18:29:04 zapata Exp $
  * @author mir-coders group
  *
  */
@@ -164,87 +161,6 @@ public class EntityContent extends Entity
   }
 
   /**
-   * overridden method getValue to include formatted date into every
-   * entityContent
-   */
-
-  public TemplateModel get(java.lang.String key) throws TemplateModelException
-  {
-    if (key!=null) {
-      if (_entCache.containsKey(key)) {
-        return (TemplateModel)_entCache.get(key);
-      }
-      if (key.equals("to_comments")) {
-        try {
-          _entCache.put(key, getComments());
-          return (TemplateModel)_entCache.get(key);
-        }
-        catch (Exception ex) {
-          logger.warn("EntityContent.getComments: could not fetch data " + ex.toString());
-
-          throw new TemplateModelException(ex.toString());
-        }
-      }
-      if (key.equals("to_media_images")) {
-        try {
-          _entCache.put(key, getImagesForContent());
-          return (TemplateModel)_entCache.get(key);
-        }
-        catch (Exception ex) {
-          logger.warn("EntityContent.getImagesForContent: could not fetch data " + ex.toString());
-          throw new TemplateModelException(ex.toString());
-        }
-      }
-      if (key.equals("to_media_audio")) {
-        try {
-          _entCache.put(key, getAudioForContent());
-          return (TemplateModel)_entCache.get(key);
-        }
-        catch (Exception ex) {
-          logger.warn("EntityContent.getAudioForContent: could not fetch data " + ex.toString());
-          throw new TemplateModelException(ex.toString());
-        }
-      }
-      if (key.equals("to_media_video")) {
-        try {
-          _entCache.put(key, getVideoForContent());
-          return (TemplateModel)_entCache.get(key);
-        }
-        catch (Exception ex) {
-          logger.warn("EntityContent.getVideoForContent: could not fetch data " + ex.toString());
-          throw new TemplateModelException(ex.toString());
-        }
-      }
-      if (key.equals("to_media_other")) {
-        try {
-          _entCache.put(key, getOtherMediaForContent());
-          return (TemplateModel)_entCache.get(key);
-        }
-        catch (Exception ex) {
-          logger.warn("EntityContent.getOtherMediaForContent: could not fetch data " + ex.toString());
-          throw new TemplateModelException(ex.toString());
-        }
-      }
-      else if (key.equals("to_topics")) {
-        try {
-          _entCache.put(key,
-                        DatabaseContentToTopics.getInstance().getTopics(this));
-          return (TemplateModel)_entCache.get(key);
-        }
-        catch (Exception ex) {
-          logger.warn("EntityContent.getTopics: could not fetch data " + ex.toString());
-          throw new TemplateModelException(ex.toString());
-        }
-      }
-      else {
-        return new SimpleScalar(getValue(key));
-      }
-
-    }
-    return null;
-  }
-
-  /**
    * overridden method setValues to patch creator_main_url
    */
   public void setValues(Map theStringValues) {
@@ -261,15 +177,6 @@ public class EntityContent extends Entity
     super.setValues(theStringValues);
   }
 
-  /**
-   * fetches all the comments belonging to an article
-   *
-   * @return freemarker.template.SimpleList
-   */
-  private EntityList getComments() throws StorageObjectFailure {
-    return ((DatabaseContent)theStorageObject).getComments(this);
-  }
-
   private boolean hasMedia() throws StorageObjectFailure
   {
     if (_hasMedia == null) {
@@ -282,43 +189,4 @@ public class EntityContent extends Entity
     }
     return _hasMedia.booleanValue();
   }
-
-  //######## @todo all of the following getBlahForContent should have
-  // and optimized version where LIMIT=1 sql for list view.
-  private EntityList getImagesForContent()
-      throws StorageObjectFailure, TemplateModelException
-  {
-    if (hasMedia())
-      return DatabaseContentToMedia.getInstance().getImages(this);
-    else
-      return null;
-  }
-
-  private EntityList getAudioForContent()
-      throws StorageObjectFailure, TemplateModelException
-  {
-    if (hasMedia())
-      return DatabaseContentToMedia.getInstance().getAudio(this) ;
-    else
-      return null;
-  }
-
-  private EntityList getVideoForContent()
-      throws StorageObjectFailure, TemplateModelException
-  {
-    if (hasMedia())
-      return DatabaseContentToMedia.getInstance().getVideo(this) ;
-    else
-      return null;
-  }
-
-  private EntityList getOtherMediaForContent()
-      throws StorageObjectFailure, TemplateModelException
-  {
-    if (hasMedia())
-      return DatabaseContentToMedia.getInstance().getOther(this);
-    else
-      return null;
-  }
-
 }
diff --git a/source/mircoders/entity/EntityMedia.java b/source/mircoders/entity/EntityMedia.java
deleted file mode 100755 (executable)
index 029793a..0000000
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.entity;
-
-import mir.entity.Entity;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
-import mircoders.storage.DatabaseMedia;
-/**
- * Diese Klasse enth?lt die Daten eines MetaObjekts
- *
- * @author RK
- * @version 29.6.1999
- */
-
-
-public class EntityMedia extends Entity
-{
-
-  public EntityMedia(){
-    super();
-  }
-
-  public EntityMedia(StorageObject theStorage)
-  {
-    this();
-    setStorage(theStorage);
-  }
-
-  /**
-   * fetches the MediaType entry assiciated w/ this media
-   *
-   * @return mir.entity.Entity
-   */
-  public Entity getMediaType() throws StorageObjectFailure {
-    try {
-      return ( (DatabaseMedia) theStorageObject).getMediaType(this);
-    }
-    catch (StorageObjectFailure e) {
-      throw new StorageObjectFailure("getMediaType(): ", e);
-    }
-    catch (StorageObjectExc e) {
-      throw new StorageObjectFailure("getMediaType(): ", e);
-    }
-
-  }
-}
index 2d5e011..73bbea1 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.entity;
-
-import java.sql.SQLException;
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.media.MediaHelper;
-import mir.media.MirMedia;
-import mir.misc.NumberUtils;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import mircoders.storage.DatabaseUploadedMedia;
-import freemarker.template.SimpleList;
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-/**
- *
- * @author mh, mir-coders group
- * @version $Id: EntityUploadedMedia.java,v 1.26 2003/04/21 12:42:53 idfx Exp $
- */
-
-
-public class EntityUploadedMedia extends Entity {
-
-
-  public EntityUploadedMedia() {
-    super();
-
-    logger = new LoggerWrapper("Entity.UploadedMedia");
-  }
-
-  public EntityUploadedMedia(StorageObject theStorage) {
-    this();
-    setStorage(theStorage);
-  }
-
-  public void update() throws StorageObjectFailure {
-    super.update();
-    try {
-      theStorageObject.executeUpdate("update content set is_produced='0' where exists(select * from content_x_media where to_content=content.id and to_media=" + getId()+")");
-    }
-    catch (SQLException e) {
-      throwStorageObjectFailure(e, "EntityAudio :: update :: failed!! ");
-    }
-  }
-
-  public void setValues(Map theStringValues) {
-    if (theStringValues != null) {
-      if (!theStringValues.containsKey("is_published"))
-        theStringValues.put("is_published", "0");
-    }
-    super.setValues(theStringValues);
-  }
-
-
-  /**
-   * fetches the MediaType entry assiciated w/ this media
-   *
-   * @return mir.entity.Entity
-   */
-  public Entity getMediaType() throws StorageObjectFailure {
-    Entity ent = null;
-    try {
-      ent = DatabaseUploadedMedia.getInstance().getMediaType(this);
-    }
-    catch (StorageObjectFailure e) {
-      throwStorageObjectFailure(e, "get MediaType failed -- ");
-    }
-    return ent;
-  }
-
-  public String getValue(String key) {
-    String returnValue = null;
-
-    if (key != null) {
-      if (key.equals("big_icon"))
-        returnValue = getBigIconName();
-      else if (key.equals("descr") || key.equals("media_descr"))
-        returnValue = getDescr();
-      else if (key.equals("mediatype"))
-        returnValue = getMediaTypeString();
-      else if (key.equals("mimetype"))
-        returnValue = getMimeType();
-      else if (key.equals("human_readable_size")) {
-        String size = super.getValue("size");
-        if (size != null)
-          returnValue = NumberUtils.humanReadableSize(Double.parseDouble(size));
-      }
-      else
-        returnValue = super.getValue(key);
-    }
-    return returnValue;
-  }
-
-  public TemplateModel get(java.lang.String key) throws TemplateModelException {
-    if (key.equals("url"))
-      return getUrl();
-    return new SimpleScalar(getValue(key));
-  }
-
-  // @todo  all these methods should be merged into 1
-  // and the MediaHandler should be cached somehow.
-  private String getMediaTypeString() {
-    MirMedia mediaHandler = null;
-    Entity mediaType = null;
-
-    try {
-      mediaType = getMediaType();
-      mediaHandler = MediaHelper.getHandler(mediaType);
-      String t;
-      if (mediaHandler.isAudio())
-        return "audio";
-      else if (mediaHandler.isImage())
-        return "image";
-      else if (mediaHandler.isVideo())
-        return "video";
-      else
-        return "other";
-    }
-    catch (Exception ex) {
-      logger.warn("EntityUploadedMedia.getMediaTypeString: could not fetch data: " + ex.toString());
-    }
-    return null;
-  }
-
-  private String getBigIconName() {
-    MirMedia mediaHandler = null;
-    Entity mediaType = null;
-
-    try {
-      mediaType = getMediaType();
-      mediaHandler = MediaHelper.getHandler(mediaType);
-      return mediaHandler.getBigIconName();
-    }
-    catch (Exception ex) {
-      logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString());
-    }
-    return null;
-  }
-
-  private SimpleList getUrl() {
-    MirMedia mediaHandler = null;
-    Entity mediaType = null;
-
-    try {
-      mediaType = getMediaType();
-      mediaHandler = MediaHelper.getHandler(mediaType);
-      return mediaHandler.getURL(this, mediaType);
-    }
-    catch (Throwable t) {
-      logger.warn("EntityUploadedMedia.getUrl: could not fetch data: " + t.toString());
-    }
-    return null;
-  }
-
-  private String getDescr() {
-    MirMedia mediaHandler = null;
-    Entity mediaType = null;
-
-    try {
-      mediaType = getMediaType();
-      mediaHandler = MediaHelper.getHandler(mediaType);
-      return mediaHandler.getDescr(mediaType);
-    }
-    catch (Exception ex) {
-      logger.warn("EntityUploadedMedia.getDescr: could not fetch data: " + ex.toString());
-    }
-    return null;
-  }
-  private String getMimeType() {
-    Entity mediaType = null;
-
-    try {
-      mediaType = getMediaType();
-      return mediaType.getValue("mime_type");
-    }
-    catch (Exception ex) {
-      logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString());
-    }
-    return null;
-  }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.entity;\r
+\r
+import java.sql.SQLException;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaHelper;\r
+import mir.media.MirMedia;\r
+import mir.misc.NumberUtils;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import mircoders.storage.DatabaseUploadedMedia;\r
+\r
+/**\r
+ *\r
+ * @author mh, mir-coders group\r
+ * @version $Id: EntityUploadedMedia.java,v 1.27 2003/09/03 18:29:04 zapata Exp $\r
+ */\r
+\r
+\r
+public class EntityUploadedMedia extends Entity {\r
+\r
+\r
+  public EntityUploadedMedia() {\r
+    super();\r
+\r
+    logger = new LoggerWrapper("Entity.UploadedMedia");\r
+  }\r
+\r
+  public EntityUploadedMedia(StorageObject theStorage) {\r
+    this();\r
+    setStorage(theStorage);\r
+  }\r
+\r
+  public void update() throws StorageObjectFailure {\r
+    super.update();\r
+    try {\r
+      theStorageObject.executeUpdate("update content set is_produced='0' where exists(select * from content_x_media where to_content=content.id and to_media=" + getId()+")");\r
+    }\r
+    catch (SQLException e) {\r
+      throwStorageObjectFailure(e, "EntityAudio :: update :: failed!! ");\r
+    }\r
+  }\r
+\r
+  public void setValues(Map theStringValues) {\r
+    if (theStringValues != null) {\r
+      if (!theStringValues.containsKey("is_published"))\r
+        theStringValues.put("is_published", "0");\r
+    }\r
+    super.setValues(theStringValues);\r
+  }\r
+\r
+\r
+  /**\r
+   * fetches the MediaType entry assiciated w/ this media\r
+   *\r
+   * @return mir.entity.Entity\r
+   */\r
+  public Entity getMediaType() throws StorageObjectFailure {\r
+    Entity ent = null;\r
+    try {\r
+      ent = DatabaseUploadedMedia.getInstance().getMediaType(this);\r
+    }\r
+    catch (StorageObjectFailure e) {\r
+      throwStorageObjectFailure(e, "get MediaType failed -- ");\r
+    }\r
+    return ent;\r
+  }\r
+\r
+  public String getValue(String key) {\r
+    String returnValue = null;\r
+\r
+    if (key != null) {\r
+      if (key.equals("big_icon"))\r
+        returnValue = getBigIconName();\r
+      else if (key.equals("descr") || key.equals("media_descr"))\r
+        returnValue = getDescr();\r
+      else if (key.equals("mediatype"))\r
+        returnValue = getMediaTypeString();\r
+      else if (key.equals("mimetype"))\r
+        returnValue = getMimeType();\r
+      else if (key.equals("human_readable_size")) {\r
+        String size = super.getValue("size");\r
+        if (size != null)\r
+          returnValue = NumberUtils.humanReadableSize(Double.parseDouble(size));\r
+      }\r
+      else\r
+        returnValue = super.getValue(key);\r
+    }\r
+    return returnValue;\r
+  }\r
+\r
+  // @todo  all these methods should be merged into 1\r
+  // and the MediaHandler should be cached somehow.\r
+  private String getMediaTypeString() {\r
+    MirMedia mediaHandler = null;\r
+    Entity mediaType = null;\r
+\r
+    try {\r
+      mediaType = getMediaType();\r
+      mediaHandler = MediaHelper.getHandler(mediaType);\r
+      String t;\r
+      if (mediaHandler.isAudio())\r
+        return "audio";\r
+      else if (mediaHandler.isImage())\r
+        return "image";\r
+      else if (mediaHandler.isVideo())\r
+        return "video";\r
+      else\r
+        return "other";\r
+    }\r
+    catch (Exception ex) {\r
+      logger.warn("EntityUploadedMedia.getMediaTypeString: could not fetch data: " + ex.toString());\r
+    }\r
+    return null;\r
+  }\r
+\r
+  private String getBigIconName() {\r
+    MirMedia mediaHandler = null;\r
+    Entity mediaType = null;\r
+\r
+    try {\r
+      mediaType = getMediaType();\r
+      mediaHandler = MediaHelper.getHandler(mediaType);\r
+      return mediaHandler.getBigIconName();\r
+    }\r
+    catch (Exception ex) {\r
+      logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString());\r
+    }\r
+    return null;\r
+  }\r
+\r
+  private List getUrl() {\r
+    MirMedia mediaHandler = null;\r
+    Entity mediaType = null;\r
+\r
+    try {\r
+      mediaType = getMediaType();\r
+      mediaHandler = MediaHelper.getHandler(mediaType);\r
+      return mediaHandler.getURL(this, mediaType);\r
+    }\r
+    catch (Throwable t) {\r
+      logger.warn("EntityUploadedMedia.getUrl: could not fetch data: " + t.toString());\r
+    }\r
+    return null;\r
+  }\r
+\r
+  private String getDescr() {\r
+    MirMedia mediaHandler = null;\r
+    Entity mediaType = null;\r
+\r
+    try {\r
+      mediaType = getMediaType();\r
+      mediaHandler = MediaHelper.getHandler(mediaType);\r
+      return mediaHandler.getDescr(mediaType);\r
+    }\r
+    catch (Exception ex) {\r
+      logger.warn("EntityUploadedMedia.getDescr: could not fetch data: " + ex.toString());\r
+    }\r
+    return null;\r
+  }\r
+  private String getMimeType() {\r
+    Entity mediaType = null;\r
+\r
+    try {\r
+      mediaType = getMediaType();\r
+      return mediaType.getValue("mime_type");\r
+    }\r
+    catch (Exception ex) {\r
+      logger.warn("EntityUploadedMedia.getBigIconName: could not fetch data: " + ex.toString());\r
+    }\r
+    return null;\r
+  }\r
+\r
+}\r
index 15d6cca..e4b29fa 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.global;
-
-import gnu.regexp.RE;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Vector;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.session.HTTPAdapters;
-import mir.session.Request;
-import mir.util.DateToMapAdapter;
-import mir.util.InternetFunctions;
-import mir.util.StringRoutines;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-import mircoders.localizer.MirAdminInterfaceLocalizer;
-
-import org.apache.commons.collections.ExtendedProperties;
-
-
-public class Abuse {
-  private List filters;
-  private int maxIdentifier;
-  private LoggerWrapper logger;
-  private int logSize;
-  private boolean logEnabled;
-  private boolean openPostingDisabled;
-  private boolean openPostingPassword;
-  private boolean cookieOnBlock;
-  private String articleBlockAction;
-  private String commentBlockAction;
-  private List log;
-  private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");
-
-
-  private static final String IP_FILTER_TYPE="ip";
-  private static final String REGEXP_FILTER_TYPE="regexp";
-  private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");
-  private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");
-
-  public Abuse() {
-    logger = new LoggerWrapper("Global.Abuse");
-    filters = new Vector();
-    maxIdentifier = 0;
-    log = new Vector();
-
-    logSize = 100;
-    logEnabled = false;
-    articleBlockAction = "";
-    commentBlockAction = "";
-    openPostingPassword = false;
-    openPostingDisabled = false;
-    cookieOnBlock = false;
-
-    load();
-  }
-
-  public boolean checkIpFilter(String anIpAddress) {
-    synchronized (filters) {
-      Iterator i = filters.iterator();
-
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        try {
-          if ( (filter.getType().equals(IP_FILTER_TYPE)) &&
-              InternetFunctions.isIpAddressInNetwork(anIpAddress, filter.getExpression())) {
-            logger.debug("ip match on " + filter.getExpression());
-            return true;
-          }
-        }
-        catch (Throwable t) {
-          logger.warn("error while checking ip address " + anIpAddress + " over network " + filter.expression + ": " + t.getMessage());
-        }
-      }
-
-      return false;
-    }
-  }
-
-  private boolean checkRegExpFilter(Entity anEntity) {
-    synchronized (filters) {
-      Iterator i = filters.iterator();
-
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        if (filter.getType().equals(REGEXP_FILTER_TYPE)) {
-          try {
-            RE regularExpression = new RE(filter.getExpression(), RE.REG_ICASE);
-
-            Iterator j = anEntity.getFields().iterator();
-            while (j.hasNext()) {
-              String field = anEntity.getValue( (String) j.next());
-
-              if (field != null && regularExpression.isMatch(field.toLowerCase())) {
-                logger.debug("regexp match on " + filter.getExpression());
-                return true;
-              }
-            }
-          }
-          catch (Throwable t) {
-            logger.warn("error while checking entity with regexp " + filter.getExpression() + ": " + t.getMessage());
-          }
-        }
-      }
-
-      return false;
-    }
-  }
-
-  private void setCookie(HttpServletResponse aResponse) {
-    Random random = new Random();
-
-    Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));
-    cookie.setMaxAge(cookieMaxAge);
-    cookie.setPath("/");
-
-    if (aResponse!=null)
-      aResponse.addCookie(cookie);
-  }
-
-  private boolean checkCookie(List aCookies) {
-    if (getCookieOnBlock()) {
-      Iterator i = aCookies.iterator();
-
-      while (i.hasNext()) {
-        Cookie cookie = (Cookie) i.next();
-
-        if (cookie.getName().equals(cookieName)) {
-          logger.debug("cookie match");
-          return true;
-        }
-      }
-    }
-
-    return false;
-  }
-
-  public boolean checkRequest(Request aRequest, HttpServletResponse aResponse, String anId, boolean anIsComment) {
-    String address = "0.0.0.0";
-    String browser = "unknown";
-    List cookies = null;
-
-    HttpServletRequest request = null;
-
-    if (aRequest instanceof HTTPAdapters.HTTPParsedRequestAdapter) {
-      request = ((HTTPAdapters.HTTPParsedRequestAdapter) aRequest).getRequest();
-    }
-    else if (aRequest instanceof HTTPAdapters.HTTPRequestAdapter) {
-      request = ((HTTPAdapters.HTTPRequestAdapter) aRequest).getRequest();
-    }
-    if (request!=null) {
-      browser = (String) request.getHeader("User-Agent");
-      address = request.getRemoteAddr();
-      cookies = Arrays.asList(request.getCookies());
-    }
-
-    if (anIsComment)
-      logComment(address, anId , new Date(), browser);
-    else
-      logArticle(address, anId , new Date(), browser);
-
-    return checkCookie(cookies) || checkIpFilter(address);
-  }
-
-  public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {
-    try {
-      long time = System.currentTimeMillis();
-
-      MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(commentBlockAction);
-
-      if (checkRequest(aRequest, aResponse, aComment.getId(), true) || checkRegExpFilter(aComment)) {
-        logger.debug("performing operation " + operation.getName());
-        operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));
-        setCookie(aResponse);
-      }
-
-      logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");
-    }
-    catch (Throwable t) {
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      logger.error("Abuse.checkComment: " + t.toString());
-    }
-  }
-
-  public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {
-    try {
-      long time = System.currentTimeMillis();
-
-      MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = MirGlobal.localizer().adminInterface().simpleArticleOperationForName(articleBlockAction);
-
-      if (checkRequest(aRequest, aResponse, anArticle.getId(), false) || checkRegExpFilter(anArticle)) {
-        logger.debug("performing operation " + operation.getName());
-        operation.perform(null, MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));
-        setCookie(aResponse);
-      }
-
-      logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");
-    }
-    catch (Throwable t) {
-      t.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      logger.error("Abuse.checkArticle: " + t.toString());
-    }
-  }
-
-  public boolean getLogEnabled() {
-    return logEnabled;
-  }
-
-  public void setLogEnabled(boolean anEnabled) {
-    logEnabled = anEnabled;
-    truncateLog();
-  }
-
-  public int getLogSize() {
-    return logSize;
-  }
-
-  public void setLogSize(int aSize) {
-    logSize = aSize;
-    truncateLog();
-  }
-
-  public boolean getOpenPostingDisabled() {
-    return openPostingDisabled;
-  }
-
-  public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {
-    openPostingDisabled = anOpenPostingDisabled;
-  }
-
-  public boolean getOpenPostingPassword() {
-    return openPostingPassword;
-  }
-
-  public void setOpenPostingPassword(boolean anOpenPostingPassword) {
-    openPostingPassword = anOpenPostingPassword;
-  }
-
-  public boolean getCookieOnBlock() {
-    return cookieOnBlock;
-  }
-
-  public void setCookieOnBlock(boolean aCookieOnBlock) {
-    cookieOnBlock = aCookieOnBlock;
-  }
-
-  public String getArticleBlockAction() {
-    return articleBlockAction;
-  }
-
-  public void setArticleBlockAction(String anAction) {
-    articleBlockAction = anAction;
-  }
-
-  public String getCommentBlockAction() {
-    return commentBlockAction;
-  }
-
-  public void setCommentBlockAction(String anAction) {
-    commentBlockAction = anAction;
-  }
-
-
-  public List getLog() {
-    synchronized(log) {
-      List result = new Vector();
-
-      Iterator i = log.iterator();
-      while (i.hasNext()) {
-        LogEntry logEntry = (LogEntry) i.next();
-        Map entry = new HashMap();
-
-        entry.put("ip", logEntry.getIpNumber());
-        entry.put("id", logEntry.getId());
-        entry.put("timestamp", new DateToMapAdapter(logEntry.getTimeStamp()));
-        if (logEntry.getIsArticle())
-          entry.put("type", "content");
-        else
-          entry.put("type", "comment");
-        entry.put("browser", logEntry.getBrowserString());
-
-        result.add(entry);
-      }
-
-      return result;
-    }
-  }
-
-  public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {
-    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));
-  }
-
-  public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {
-    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));
-  }
-
-  public void load() {
-    try {
-      ExtendedProperties configuration = new ExtendedProperties();
-
-      try {
-        configuration = new ExtendedProperties(configFile);
-      }
-      catch (FileNotFoundException e) {
-      }
-
-      getFilterConfig(filters, "abuse.filter", configuration);
-
-      setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));
-      setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));
-      setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));
-      setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));
-      setLogSize(configuration.getInt("abuse.logSize", 10));
-      setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));
-      setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.toString());
-    }
-  }
-  public void save() {
-    try {
-      ExtendedProperties configuration = new ExtendedProperties();
-
-      setFilterConfig(filters, "abuse.filter", configuration);
-
-      configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled()?"1":"0");
-      configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword()?"1":"0");
-      configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock()?"1":"0");
-      configuration.addProperty("abuse.logEnabled", getLogEnabled()?"1":"0");
-      configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));
-      configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());
-      configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());
-
-      configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");
-    }
-    catch (Throwable t) {
-      throw new RuntimeException(t.toString());
-    }
-  }
-
-  public List getFilterTypes() {
-    List result = new Vector();
-
-    Map entry = new HashMap();
-    entry.put("resource", "ip");
-    entry.put("id", IP_FILTER_TYPE);
-    result.add(entry);
-
-    entry = new HashMap();
-    entry.put("resource", "regexp");
-    entry.put("id", REGEXP_FILTER_TYPE);
-    result.add(entry);
-
-    return result;
-  }
-
-  public List getArticleActions() {
-    try {
-      List result = new Vector();
-
-      Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();
-      while (i.hasNext()) {
-        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
-
-        Map action = new HashMap();
-        action.put("resource", operation.getName());
-        action.put("identifier", operation.getName());
-
-        result.add(action);
-      }
-
-      return result;
-    }
-    catch (Throwable t) {
-      throw new RuntimeException("can't get article actions");
-    }
-  }
-
-  public List getCommentActions() {
-    try {
-      List result = new Vector();
-
-      Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();
-      while (i.hasNext()) {
-        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
-
-        Map action = new HashMap();
-        action.put("resource", operation.getName());
-        action.put("identifier", operation.getName());
-
-        result.add(action);
-      }
-
-      return result;
-    }
-    catch (Throwable t) {
-      throw new RuntimeException("can't get comment actions");
-    }
-  }
-
-  public List getFilters() {
-    return getFiltersAsMaps(filters);
-  }
-
-  public void addFilter(String aType, String anExpression) {
-    addFilter(filters, aType, anExpression);
-  }
-
-  public void setFilter(String anIdentifier, String aType, String anExpression) {
-    setFilter(filters, anIdentifier, aType, anExpression);
-  }
-
-  public void deleteFilter(String anIdentifier) {
-    deleteFilter(filters, anIdentifier);
-  }
-
-  public void validateIpFilter(String anIdentifier, String anArticleAction, String aCommentAction) throws Exception {
-  }
-
-  private List getFiltersAsMaps(List aFilters) {
-    synchronized(aFilters) {
-      List result = new Vector();
-
-      Iterator i = aFilters.iterator();
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-        Map map = new HashMap();
-
-        map.put("id", filter.getId());
-        map.put("expression", filter.getExpression());
-        map.put("type", filter.getType());
-
-        result.add(map);
-      }
-      return result;
-    }
-  }
-
-  private void addFilter(List aFilters, String aType, String anExpression) {
-    Filter filter = new Filter();
-
-    filter.setId(generateId());
-    filter.setExpression(anExpression);
-    filter.setType(aType);
-
-    synchronized (aFilters) {
-      aFilters.add(filter);
-    }
-  }
-
-  private void setFilter(List aFilters, String anIdentifier, String aType, String anExpression) {
-    synchronized (aFilters) {
-      Filter filter = findFilter(aFilters, anIdentifier);
-
-      if (filter!=null) {
-        filter.setExpression(anExpression);
-        filter.setType(aType);
-      }
-    }
-  }
-
-  private Filter findFilter(List aFilters, String anIdentifier) {
-    synchronized (aFilters) {
-      Iterator i = aFilters.iterator();
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        if (filter.getId().equals(anIdentifier)) {
-          return filter;
-        }
-      }
-    }
-
-    return null;
-  }
-
-  private void deleteFilter(List aFilters, String anIdentifier) {
-    synchronized (aFilters) {
-      Filter filter = findFilter(aFilters, anIdentifier);
-
-      if (filter!=null) {
-        aFilters.remove(filter);
-      }
-    }
-  }
-
-  private String generateId() {
-    synchronized(this) {
-      maxIdentifier = maxIdentifier+1;
-
-      return Integer.toString(maxIdentifier);
-    }
-  }
-
-  private static class Filter {
-    private String identifier;
-    private String expression;
-    private String type;
-
-    public Filter() {
-      expression="";
-      type="";
-      identifier="";
-    }
-
-    public String getId() {
-      return identifier;
-    }
-
-    public void setId(String anId) {
-      identifier = anId;
-    }
-
-    public String getExpression() {
-      return expression;
-    }
-
-    public void setExpression(String anExpression) {
-      expression = anExpression;
-    }
-
-    public String getType() {
-      return type;
-    }
-
-    public void setType(String aType) {
-      type = aType;
-    }
-  }
-
-  private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
-    synchronized(aFilters) {
-      Iterator i = aFilters.iterator();
-
-      while (i.hasNext()) {
-        Filter filter = (Filter) i.next();
-
-        aConfiguration.addProperty(aConfigKey, filter.getType()+":"+filter.getExpression());
-      }
-    }
-  }
-
-  private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {
-    synchronized(aFilters) {
-      aFilters.clear();
-
-      Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).iterator();
-
-      while (i.hasNext()) {
-        String filter = (String) i.next();
-        List parts = StringRoutines.separateString(filter, ":");
-
-        if (parts.size()==2) {
-          addFilter( (String) parts.get(0), (String) parts.get(1));
-        }
-      }
-    }
-  }
-
-  private static class LogEntry {
-    private String ipNumber;
-    private String browserString;
-    private String id;
-    private Date timeStamp;
-    private boolean isArticle;
-
-    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {
-      ipNumber = anIpNumber;
-      browserString = aBrowserString;
-      id = anId;
-      isArticle = anIsArticle;
-      timeStamp=aTimeStamp;
-    }
-
-    public String getIpNumber() {
-      return ipNumber;
-    }
-
-    public String getBrowserString() {
-      return browserString;
-    }
-
-    public String getId() {
-      return id;
-    }
-
-    public Date getTimeStamp() {
-      return timeStamp;
-    }
-
-    public boolean getIsArticle() {
-      return isArticle;
-    }
-  }
-
-  private void truncateLog() {
-    synchronized(log) {
-      if (!logEnabled)
-        log.clear();
-      else {
-        while (log.size()>0 && log.size()>logSize) {
-          log.remove(0);
-        }
-      }
-    }
-  };
-
-  private void appendLog(LogEntry anEntry) {
-    synchronized (log) {
-      if (logEnabled) {
-        log.add(anEntry);
-        truncateLog();
-      }
-    }
-  }
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.global;\r
+\r
+import java.io.File;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.util.Arrays;\r
+import java.util.Date;\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Random;\r
+import java.util.Vector;\r
+import javax.servlet.http.Cookie;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.apache.commons.collections.ExtendedProperties;\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.session.Request;\r
+import mir.util.GeneratorFormatAdapters;\r
+import mir.util.StringRoutines;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.localizer.MirAdminInterfaceLocalizer;\r
+import mircoders.localizer.MirAntiAbuseFilterType;\r
+\r
+\r
+public class Abuse {\r
+  private List filterRules;\r
+  private Map filterTypes;\r
+  private List filterTypeIds;\r
+  private int maxIdentifier;\r
+  private LoggerWrapper logger;\r
+  private LoggerWrapper adminUsageLogger;\r
+  private int logSize;\r
+  private boolean logEnabled;\r
+  private boolean openPostingDisabled;\r
+  private boolean openPostingPassword;\r
+  private boolean cookieOnBlock;\r
+  private String articleBlockAction;\r
+  private String commentBlockAction;\r
+  private List log;\r
+  private String configFile = MirGlobal.config().getStringWithHome("Abuse.Config");\r
+\r
+  private MirPropertiesConfiguration configuration;\r
+\r
+  private static String cookieName=MirGlobal.config().getString("Abuse.CookieName");\r
+  private static int cookieMaxAge = 60*60*MirGlobal.config().getInt("Abuse.CookieMaxAge");\r
+\r
+  public Abuse() {\r
+    logger = new LoggerWrapper("Global.Abuse");\r
+    adminUsageLogger = new LoggerWrapper("AdminUsage");\r
+    filterRules = new Vector();\r
+    maxIdentifier = 0;\r
+    log = new Vector();\r
+\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (Throwable e) {\r
+      throw new RuntimeException("Can't get configuration: " + e.getMessage());\r
+    }\r
+\r
+    logSize = 100;\r
+    logEnabled = false;\r
+    articleBlockAction = "";\r
+    commentBlockAction = "";\r
+    openPostingPassword = false;\r
+    openPostingDisabled = false;\r
+    cookieOnBlock = false;\r
+\r
+    try {\r
+      filterTypes = new HashMap();\r
+      filterTypeIds = new Vector();\r
+\r
+      Iterator i = MirGlobal.localizer().openPostings().getAntiAbuseFilterTypes().iterator();\r
+\r
+      while (i.hasNext()) {\r
+        MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) i.next();\r
+        filterTypes.put(filterType.getName(), filterType);\r
+        filterTypeIds.add(filterType.getName());\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("Can't get filter types: " + t.getMessage());\r
+    }\r
+\r
+    load();\r
+  }\r
+\r
+  private void setCookie(HttpServletResponse aResponse) {\r
+    Random random = new Random();\r
+\r
+    Cookie cookie = new Cookie(cookieName, Integer.toString(random.nextInt(1000000000)));\r
+    cookie.setMaxAge(cookieMaxAge);\r
+    cookie.setPath("/");\r
+\r
+    if (aResponse!=null)\r
+      aResponse.addCookie(cookie);\r
+  }\r
+\r
+  private boolean checkCookie(List aCookies) {\r
+    if (getCookieOnBlock()) {\r
+      Iterator i = aCookies.iterator();\r
+\r
+      while (i.hasNext()) {\r
+        Cookie cookie = (Cookie) i.next();\r
+\r
+        if (cookie.getName().equals(cookieName)) {\r
+          logger.debug("cookie match");\r
+          return true;\r
+        }\r
+      }\r
+    }\r
+\r
+    return false;\r
+  }\r
+\r
+  FilterRule findMatchingFilter(Entity anEntity, Request aRequest) {\r
+    Iterator iterator = filterRules.iterator();\r
+\r
+    while (iterator.hasNext()) {\r
+      FilterRule rule = (FilterRule) iterator.next();\r
+\r
+      if (rule.test(anEntity, aRequest))\r
+        return rule;\r
+    }\r
+\r
+    return null;\r
+  }\r
+\r
+  public void checkComment(EntityComment aComment, Request aRequest, HttpServletResponse aResponse) {\r
+    logComment(aComment, aRequest);\r
+\r
+    try {\r
+      long time = System.currentTimeMillis();\r
+\r
+      FilterRule filterRule = findMatchingFilter(aComment, aRequest);\r
+\r
+      if (filterRule!=null) {\r
+        logger.debug("Match for " + filterRule.getType()+" rule '"+ filterRule.getExpression()+"'");\r
+        filterRule.setLastHit(new GregorianCalendar().getTime());\r
+        MirGlobal.performCommentOperation(null, aComment, filterRule.getCommentAction());\r
+        setCookie(aResponse);\r
+        save();\r
+      }\r
+\r
+      logger.info("checkComment: " + (System.currentTimeMillis()-time) + "ms");\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
+      logger.error("Abuse.checkComment: " + t.toString());\r
+    }\r
+  }\r
+\r
+  public void checkArticle(EntityContent anArticle, Request aRequest, HttpServletResponse aResponse) {\r
+    logArticle(anArticle, aRequest);\r
+\r
+    try {\r
+      long time = System.currentTimeMillis();\r
+\r
+      FilterRule filterRule = findMatchingFilter(anArticle, aRequest);\r
+\r
+      if (filterRule!=null) {\r
+        logger.debug("Match for " + filterRule.getType() + " rule '" + filterRule.getExpression()+"'");\r
+        filterRule.setLastHit(new GregorianCalendar().getTime());\r
+        MirGlobal.performArticleOperation(null, anArticle, filterRule.getArticleAction());\r
+        setCookie(aResponse);\r
+        save();\r
+      }\r
+\r
+      logger.info("checkArticle: " + (System.currentTimeMillis()-time) + "ms");\r
+    }\r
+    catch (Throwable t) {\r
+      t.printStackTrace(logger.asPrintWriter(logger.DEBUG_MESSAGE));\r
+      logger.error("Abuse.checkArticle: " + t.toString());\r
+    }\r
+  }\r
+\r
+  public boolean getLogEnabled() {\r
+    return logEnabled;\r
+  }\r
+\r
+  public void setLogEnabled(boolean anEnabled) {\r
+    if (!configuration.getString("Abuse.DisallowIPLogging", "0").equals("1"))\r
+      logEnabled = anEnabled;\r
+    truncateLog();\r
+  }\r
+\r
+  public int getLogSize() {\r
+    return logSize;\r
+  }\r
+\r
+  public void setLogSize(int aSize) {\r
+    logSize = aSize;\r
+    truncateLog();\r
+  }\r
+\r
+  public boolean getOpenPostingDisabled() {\r
+    return openPostingDisabled;\r
+  }\r
+\r
+  public void setOpenPostingDisabled(boolean anOpenPostingDisabled) {\r
+    openPostingDisabled = anOpenPostingDisabled;\r
+  }\r
+\r
+  public boolean getOpenPostingPassword() {\r
+    return openPostingPassword;\r
+  }\r
+\r
+  public void setOpenPostingPassword(boolean anOpenPostingPassword) {\r
+    openPostingPassword = anOpenPostingPassword;\r
+  }\r
+\r
+  public boolean getCookieOnBlock() {\r
+    return cookieOnBlock;\r
+  }\r
+\r
+  public void setCookieOnBlock(boolean aCookieOnBlock) {\r
+    cookieOnBlock = aCookieOnBlock;\r
+  }\r
+\r
+  public String getArticleBlockAction() {\r
+    return articleBlockAction;\r
+  }\r
+\r
+  public void setArticleBlockAction(String anAction) {\r
+    articleBlockAction = anAction;\r
+  }\r
+\r
+  public String getCommentBlockAction() {\r
+    return commentBlockAction;\r
+  }\r
+\r
+  public void setCommentBlockAction(String anAction) {\r
+    commentBlockAction = anAction;\r
+  }\r
+\r
+  public List getLog() {\r
+    synchronized(log) {\r
+      try {\r
+        List result = new Vector();\r
+\r
+        Iterator i = log.iterator();\r
+        while (i.hasNext()) {\r
+          LogEntry logEntry = (LogEntry) i.next();\r
+          Map entry = new HashMap();\r
+\r
+          entry.put("ip", logEntry.getIpNumber());\r
+          entry.put("id", logEntry.getId());\r
+          entry.put("timestamp", new GeneratorFormatAdapters.DateFormatAdapter(logEntry.getTimeStamp(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));\r
+          if (logEntry.getIsArticle())\r
+            entry.put("type", "content");\r
+          else\r
+            entry.put("type", "comment");\r
+          entry.put("browser", logEntry.getBrowserString());\r
+\r
+          result.add(entry);\r
+        }\r
+\r
+        return result;\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.toString());\r
+      }\r
+    }\r
+  }\r
+\r
+  public void logComment(Entity aComment, Request aRequest) {\r
+    String ipAddress = aRequest.getHeader("ip");\r
+    String id = aComment.getId();\r
+    String browser = aRequest.getHeader("User-Agent");\r
+\r
+    logComment(ipAddress, id, new Date(), browser);\r
+  }\r
+\r
+  public void logArticle(Entity anArticle, Request aRequest) {\r
+    String ipAddress = aRequest.getHeader("ip");\r
+    String id = anArticle.getId();\r
+    String browser = aRequest.getHeader("User-Agent");\r
+\r
+    logArticle(ipAddress, id, new Date(), browser);\r
+  }\r
+\r
+  public void logComment(String anIp, String anId, Date aTimeStamp, String aBrowser) {\r
+    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, false));\r
+  }\r
+\r
+  public void logArticle(String anIp, String anId, Date aTimeStamp, String aBrowser) {\r
+    appendLog(new LogEntry(aTimeStamp, anIp, aBrowser, anId, true));\r
+  }\r
+\r
+  public void load() {\r
+    synchronized (filterRules) {\r
+      try {\r
+        ExtendedProperties configuration = new ExtendedProperties();\r
+\r
+        try {\r
+          configuration = new ExtendedProperties(configFile);\r
+        }\r
+        catch (FileNotFoundException e) {\r
+        }\r
+\r
+        getFilterConfig(filterRules, "abuse.filter", configuration);\r
+\r
+        setOpenPostingDisabled(configuration.getString("abuse.openPostingDisabled", "0").equals("1"));\r
+        setOpenPostingPassword(configuration.getString("abuse.openPostingPassword", "0").equals("1"));\r
+        setCookieOnBlock(configuration.getString("abuse.cookieOnBlock", "0").equals("1"));\r
+        setLogEnabled(configuration.getString("abuse.logEnabled", "0").equals("1"));\r
+        setLogSize(configuration.getInt("abuse.logSize", 10));\r
+        setArticleBlockAction(configuration.getString("abuse.articleBlockAction", ""));\r
+        setCommentBlockAction(configuration.getString("abuse.commentBlockAction", ""));\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.toString());\r
+      }\r
+    }\r
+  }\r
+\r
+  public void save() {\r
+    synchronized (filterRules) {\r
+      try {\r
+        ExtendedProperties configuration = new ExtendedProperties();\r
+\r
+        setFilterConfig(filterRules, "abuse.filter", configuration);\r
+\r
+        configuration.addProperty("abuse.openPostingDisabled", getOpenPostingDisabled() ? "1" : "0");\r
+        configuration.addProperty("abuse.openPostingPassword", getOpenPostingPassword() ? "1" : "0");\r
+        configuration.addProperty("abuse.cookieOnBlock", getCookieOnBlock() ? "1" : "0");\r
+        configuration.addProperty("abuse.logEnabled", getLogEnabled() ? "1" : "0");\r
+        configuration.addProperty("abuse.logSize", Integer.toString(getLogSize()));\r
+        configuration.addProperty("abuse.articleBlockAction", getArticleBlockAction());\r
+        configuration.addProperty("abuse.commentBlockAction", getCommentBlockAction());\r
+\r
+        configuration.save(new FileOutputStream(new File(configFile)), "Anti abuse configuration");\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.toString());\r
+      }\r
+    }\r
+  }\r
+\r
+  public List getFilterTypes() {\r
+    try {\r
+      List result = new Vector();\r
+\r
+      Iterator i = filterTypeIds.iterator();\r
+      while (i.hasNext()) {\r
+        String id = (String) i.next();\r
+\r
+        Map action = new HashMap();\r
+        action.put("resource", id);\r
+        action.put("identifier", id);\r
+\r
+        result.add(action);\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("can't get article actions");\r
+    }\r
+  }\r
+\r
+  public List getArticleActions() {\r
+    try {\r
+      List result = new Vector();\r
+\r
+      Iterator i = MirGlobal.localizer().adminInterface().simpleArticleOperations().iterator();\r
+      while (i.hasNext()) {\r
+        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+\r
+        Map action = new HashMap();\r
+        action.put("resource", operation.getName());\r
+        action.put("identifier", operation.getName());\r
+\r
+        result.add(action);\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("can't get article actions");\r
+    }\r
+  }\r
+\r
+  public List getCommentActions() {\r
+    try {\r
+      List result = new Vector();\r
+\r
+      Iterator i = MirGlobal.localizer().adminInterface().simpleCommentOperations().iterator();\r
+      while (i.hasNext()) {\r
+        MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+\r
+        Map action = new HashMap();\r
+        action.put("resource", operation.getName());\r
+        action.put("identifier", operation.getName());\r
+\r
+        result.add(action);\r
+      }\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException("can't get comment actions");\r
+    }\r
+  }\r
+\r
+  public List getFilters() {\r
+    List result = new Vector();\r
+\r
+    synchronized(filterRules) {\r
+      Iterator i = filterRules.iterator();\r
+      while (i.hasNext()) {\r
+        FilterRule filter = (FilterRule) i.next();\r
+        result.add(filter.clone());\r
+      }\r
+      return result;\r
+    }\r
+  }\r
+\r
+  public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
+    return addFilter(aType, anExpression, aComments, aCommentAction, anArticleAction, null);\r
+  }\r
+\r
+  public String addFilter(String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aListHit) {\r
+    return addFilter(filterRules, aType, anExpression, aComments, aCommentAction, anArticleAction, aListHit);\r
+  }\r
+\r
+  public FilterRule getFilter(String anId) {\r
+    synchronized (filterRules) {\r
+      FilterRule result = (FilterRule) findFilter(filterRules, anId);\r
+      if (result==null)\r
+        return result;\r
+      else\r
+        return (FilterRule) result.clone();\r
+    }\r
+  }\r
+\r
+  public String setFilter(String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
+    return setFilter(filterRules, anIdentifier, aType, anExpression, aComments, aCommentAction, anArticleAction);\r
+  }\r
+\r
+  public void deleteFilter(String anIdentifier) {\r
+    deleteFilter(filterRules, anIdentifier);\r
+  }\r
+\r
+  private String addFilter(List aFilters, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction, Date aLastHit) {\r
+    MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);\r
+\r
+    if (type==null)\r
+      return "invalidtype";\r
+\r
+    if (!type.validate(anExpression)) {\r
+      return "invalidexpression";\r
+    }\r
+\r
+    FilterRule filter = new FilterRule();\r
+\r
+    filter.setId(generateId());\r
+    filter.setExpression(anExpression);\r
+    filter.setType(aType);\r
+    filter.setComments(aComments);\r
+    filter.setArticleAction(anArticleAction);\r
+    filter.setCommentAction(aCommentAction);\r
+    filter.setLastHit(aLastHit);\r
+\r
+    synchronized (aFilters) {\r
+      aFilters.add(filter);\r
+    }\r
+\r
+    return null;\r
+  }\r
+\r
+  private String setFilter(List aFilters, String anIdentifier, String aType, String anExpression, String aComments, String aCommentAction, String anArticleAction) {\r
+    MirAntiAbuseFilterType type = (MirAntiAbuseFilterType) filterTypes.get(aType);\r
+\r
+    if (type==null)\r
+      return "invalidtype";\r
+\r
+    if (!type.validate(anExpression)) {\r
+      return "invalidexpression";\r
+    }\r
+\r
+    synchronized (aFilters) {\r
+      FilterRule filter = findFilter(aFilters, anIdentifier);\r
+\r
+      if (filter!=null) {\r
+        filter.setExpression(anExpression);\r
+        filter.setType(aType);\r
+        filter.setCommentAction(aCommentAction);\r
+        filter.setArticleAction(anArticleAction);\r
+        filter.setComments(aComments);\r
+      }\r
+\r
+      return null;\r
+    }\r
+  }\r
+\r
+  private FilterRule findFilter(List aFilters, String anIdentifier) {\r
+    synchronized (aFilters) {\r
+      Iterator i = aFilters.iterator();\r
+      while (i.hasNext()) {\r
+        FilterRule filter = (FilterRule) i.next();\r
+\r
+        if (filter.getId().equals(anIdentifier)) {\r
+          return filter;\r
+        }\r
+      }\r
+    }\r
+\r
+    return null;\r
+  }\r
+\r
+  private void deleteFilter(List aFilters, String anIdentifier) {\r
+    synchronized (aFilters) {\r
+      FilterRule filter = findFilter(aFilters, anIdentifier);\r
+\r
+      if (filter!=null) {\r
+        aFilters.remove(filter);\r
+      }\r
+    }\r
+  }\r
+\r
+  private String generateId() {\r
+    synchronized(this) {\r
+      maxIdentifier = maxIdentifier+1;\r
+\r
+      return Integer.toString(maxIdentifier);\r
+    }\r
+  }\r
+\r
+  public class FilterRule {\r
+    private String identifier;\r
+    private String expression;\r
+    private String type;\r
+    private String comments;\r
+    private String articleAction;\r
+    private String commentAction;\r
+    private Date lastHit;\r
+\r
+    public FilterRule() {\r
+      expression = "";\r
+      type = "";\r
+      identifier = "";\r
+      comments = "";\r
+      articleAction = articleBlockAction;\r
+      commentAction = commentBlockAction;\r
+      lastHit = null;\r
+    }\r
+\r
+    public Date getLastHit() {\r
+      return lastHit;\r
+    }\r
+\r
+    public void setLastHit(Date aDate) {\r
+      lastHit = aDate;\r
+    }\r
+\r
+    public String getId() {\r
+      return identifier;\r
+    }\r
+\r
+    public void setId(String anId) {\r
+      identifier = anId;\r
+    }\r
+\r
+    public String getExpression() {\r
+      return expression;\r
+    }\r
+\r
+    public void setExpression(String anExpression) {\r
+      expression = anExpression;\r
+    }\r
+\r
+    public String getType() {\r
+      return type;\r
+    }\r
+\r
+    public void setType(String aType) {\r
+      type = aType;\r
+    }\r
+\r
+    public void setComments(String aComments) {\r
+      comments = aComments;\r
+    }\r
+\r
+    public String getComments() {\r
+      return comments;\r
+    }\r
+\r
+    public String getArticleAction() {\r
+      return articleAction;\r
+    }\r
+\r
+    public void setArticleAction(String anArticleAction) {\r
+      articleAction = anArticleAction;\r
+    }\r
+\r
+    public String getCommentAction() {\r
+      return commentAction;\r
+    }\r
+\r
+    public void setCommentAction(String aCommentAction) {\r
+      commentAction = aCommentAction;\r
+    }\r
+\r
+    public boolean test(Entity anEntity, Request aRequest) {\r
+      MirAntiAbuseFilterType filterType = (MirAntiAbuseFilterType) filterTypes.get(type);\r
+      try {\r
+        if (filterType != null)\r
+          return filterType.test(expression, anEntity, aRequest);\r
+      }\r
+      catch (Throwable t) {\r
+        logger.error("error while testing "+type+"-filter '"+expression+"'");\r
+      }\r
+\r
+      return false;\r
+    };\r
+\r
+    public Object clone() {\r
+      FilterRule result = new FilterRule();\r
+      result.setComments(getComments());\r
+      result.setExpression(getExpression());\r
+      result.setId(getId());\r
+      result.setType(getType());\r
+      result.setArticleAction(getArticleAction());\r
+      result.setCommentAction(getCommentAction());\r
+      result.setLastHit(getLastHit());\r
+\r
+      return result;\r
+    }\r
+  }\r
+\r
+  private void setFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
+    synchronized(aFilters) {\r
+      Iterator i = aFilters.iterator();\r
+\r
+      while (i.hasNext()) {\r
+        FilterRule filter = (FilterRule) i.next();\r
+\r
+        String filterconfig =\r
+            StringRoutines.replaceStringCharacters(filter.getType(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
+            StringRoutines.replaceStringCharacters(filter.getExpression(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
+            StringRoutines.replaceStringCharacters(filter.getArticleAction(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
+            StringRoutines.replaceStringCharacters(filter.getCommentAction(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"} ) + ":" +\r
+            StringRoutines.replaceStringCharacters(filter.getComments(), new char[] { '\\', ':'}, new String[] { "\\\\", "\\:"})  + ":";\r
+\r
+        if (filter.getLastHit()!=null)\r
+          filterconfig = filterconfig + filter.getLastHit().getTime();\r
+\r
+        aConfiguration.addProperty(aConfigKey, filterconfig);\r
+      }\r
+    }\r
+  }\r
+\r
+  private void getFilterConfig(List aFilters, String aConfigKey, ExtendedProperties aConfiguration) {\r
+    synchronized(aFilters) {\r
+      aFilters.clear();\r
+\r
+      if (aConfiguration.getStringArray(aConfigKey)!=null) {\r
+\r
+        Iterator i = Arrays.asList(aConfiguration.getStringArray(aConfigKey)).\r
+            iterator();\r
+\r
+        while (i.hasNext()) {\r
+          String filter = (String) i.next();\r
+          List parts = StringRoutines.splitStringWithEscape(filter, ':', '\\');\r
+          if (parts.size() == 2) {\r
+            parts.add(articleBlockAction);\r
+            parts.add(commentBlockAction);\r
+            parts.add("");\r
+            parts.add("");\r
+          }\r
+\r
+          if (parts.size() >= 5) {\r
+            Date lastHit = null;\r
+\r
+            if (parts.size()>=6) {\r
+              String lastHitString = (String) parts.get(5);\r
+\r
+              try {\r
+                lastHit = new Date(Long.parseLong(lastHitString));\r
+              }\r
+              catch (Throwable t) {\r
+              }\r
+            }\r
+\r
+            addFilter( (String) parts.get(0), (String) parts.get(1), (String) parts.get(4), (String) parts.get(3), (String) parts.get(2), lastHit);\r
+          }\r
+        }\r
+      }\r
+    }\r
+  }\r
+\r
+  private static class LogEntry {\r
+    private String ipNumber;\r
+    private String browserString;\r
+    private String id;\r
+    private Date timeStamp;\r
+    private boolean isArticle;\r
+\r
+    public LogEntry(Date aTimeStamp, String anIpNumber, String aBrowserString, String anId, boolean anIsArticle) {\r
+      ipNumber = anIpNumber;\r
+      browserString = aBrowserString;\r
+      id = anId;\r
+      isArticle = anIsArticle;\r
+      timeStamp=aTimeStamp;\r
+    }\r
+\r
+    public String getIpNumber() {\r
+      return ipNumber;\r
+    }\r
+\r
+    public String getBrowserString() {\r
+      return browserString;\r
+    }\r
+\r
+    public String getId() {\r
+      return id;\r
+    }\r
+\r
+    public Date getTimeStamp() {\r
+      return timeStamp;\r
+    }\r
+\r
+    public boolean getIsArticle() {\r
+      return isArticle;\r
+    }\r
+  }\r
+\r
+  private void truncateLog() {\r
+    synchronized(log) {\r
+      if (!logEnabled)\r
+        log.clear();\r
+      else {\r
+        while (log.size()>0 && log.size()>logSize) {\r
+          log.remove(0);\r
+        }\r
+      }\r
+    }\r
+  };\r
+\r
+  private void appendLog(LogEntry anEntry) {\r
+    synchronized (log) {\r
+      if (logEnabled) {\r
+        log.add(anEntry);\r
+        truncateLog();\r
+      }\r
+    }\r
+  }\r
+\r
+  public void logAdminUsage(EntityUsers aUser, String aDescription) {\r
+    try {\r
+      String user = "unknown (" + aUser.toString() +")";\r
+      if (user!=null)\r
+        user = aUser.getValue("login");\r
+      adminUsageLogger.info(user + ": " + aDescription);\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error("Error while logging admin usage ("+aUser.toString()+", "+aDescription+"): " +t.toString());\r
+    }\r
+  }\r
 }
\ No newline at end of file
index fe20e67..c62181b 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
 package mircoders.global;
 
+
+import java.util.Calendar;
 import java.util.Date;
 import java.util.GregorianCalendar;
 import java.util.HashMap;
@@ -38,15 +40,21 @@ import java.util.List;
 import java.util.Map;
 import java.util.Vector;
 
+import mir.log.LoggerWrapper;
+
 // important: objects passed as data must not be altered once put into a job
 
 public class JobQueue {
-  private Vector jobs;
-  private Vector finishedJobs;
-  private Map dataToJob;
-  private Map identifierToJob;
+  private Vector jobHandlers;
+  private Map identifierToJobHandler;
   private int nrJobs;
+  private int jobCleanupTreshold;
+  private JobQueueRunner queueRunner;
+  private Thread thread;
+  private LoggerWrapper logger;
+  private long lastCleanup;
 
+  public static final int STATUS_CREATED = -1;
   public static final int STATUS_PENDING = 0;
   public static final int STATUS_PROCESSING = 1;
   public static final int STATUS_PROCESSED = 2;
@@ -59,129 +67,145 @@ public class JobQueue {
 
   public static final int FINISHEDJOBS_LOGSIZE = 10;
 
-  public JobQueue() {
-    finishedJobs = new Vector();
-    jobs = new Vector();
-    dataToJob = new HashMap();
-    identifierToJob = new HashMap();
+  public JobQueue(LoggerWrapper aLogger) {
+    logger = aLogger;
+    jobHandlers = new Vector();
+    identifierToJobHandler = new HashMap();
     nrJobs = 0;
+    lastCleanup = 0;
+    jobCleanupTreshold = 900; // seconds
+    queueRunner = new JobQueueRunner(logger);
+    thread = new Thread(queueRunner);
+    thread.start();
   }
 
-  public String appendJob(Object aData) {
-    synchronized (jobs) {
-      Job job = new Job(aData, Integer.toString(nrJobs));
+  public String appendJob(Job aJob, String aDescription) {
+    try {
+      if (System.currentTimeMillis() - lastCleanup > 60000)
+        cleanupJobList();
+    }
+    catch (Throwable t) {
+      logger.error("error while cleaning up joblist: " + t.toString());
+    }
+
+    synchronized (jobHandlers) {
+      JobHandler jobHandler = new JobHandler(aJob, Integer.toString(nrJobs), aDescription);
       nrJobs++;
-      jobs.add(job);
-      dataToJob.put(aData, job);
-      identifierToJob.put(job.getIdentifier(), job);
-      return job.getIdentifier();
+      jobHandlers.add(jobHandler);
+      identifierToJobHandler.put(jobHandler.getIdentifier(), jobHandler);
+      jobHandler.setPending();
+
+      return jobHandler.getIdentifier();
     }
   }
 
-  public Object acquirePendingJob() {
-    synchronized (jobs) {
-      int priorityFound= 0;
-      Job jobFound;
+  public List getJobsInfo() {
+    List result = new Vector();
 
-      do {
-        jobFound = null;
-        Iterator i = jobs.iterator();
-        while (i.hasNext()) {
-          Job job = (Job) i.next();
+    synchronized (jobHandlers) {
+      Iterator i = jobHandlers.iterator();
 
-          if (job.isPending() && (jobFound==null || priorityFound<job.getPriority())) {
-            jobFound = job;
-            priorityFound = job.getPriority();
-          }
-        }
+      while (i.hasNext()) {
+        result.add(0, ((JobHandler) i.next()).getJobInfo());
       }
-      while (jobFound!=null && !jobFound.setProcessing());
-
-      if (jobFound!=null)
-        return jobFound.getData();
-      else
-        return null;
     }
-  }
 
-  private void finishJob(Job aJob) {
-    synchronized (jobs) {
-      identifierToJob.remove(aJob.identifier);
-      jobs.remove(aJob);
-      finishedJobs.insertElementAt(aJob, 0);
-      if (finishedJobs.size()>FINISHEDJOBS_LOGSIZE)
-        finishedJobs.remove(finishedJobs.size()-1);
-    }
+    return result;
   }
 
-  public void jobProcessed(Object aData) {
-    synchronized (jobs) {
-      Job job = (Job) dataToJob.get(aData);
+  private void cleanupJobList() {
+    List toRemove = new Vector();
+    synchronized (jobHandlers) {
+      Iterator i = jobHandlers.iterator();
 
-      if (job!=null) {
-        job.setProcessed();
-        finishJob(job);
-      }
-    }
-  }
+      Calendar tresholdCalendar = new GregorianCalendar();
+      tresholdCalendar.add(Calendar.SECOND, -jobCleanupTreshold);
+      Date treshold = tresholdCalendar.getTime();
 
-  public void jobAborted(Object aData) {
-    synchronized (jobs) {
-      Job job = (Job) dataToJob.get(aData);
+      while (i.hasNext()) {
+        JobHandler jobHandler = (JobHandler) i.next();
 
-      if (job!=null) {
-        job.setAborted();
-        finishJob(job);
+        synchronized (jobHandler) {
+          if (jobHandler.isFinished() && jobHandler.getLastChange().before(treshold)) {
+            toRemove.add(jobHandler);
+          }
+        }
       }
+
+      jobHandlers.removeAll(toRemove);
     }
+
+    lastCleanup = System.currentTimeMillis();
   }
 
-  public void cancelJob(Object aData) {
-    synchronized (jobs) {
-      Job job = (Job) dataToJob.get(aData);
+  private JobHandler acquirePendingJob() {
+    synchronized (jobHandlers) {
+      int priorityFound= 0;
+      JobHandler jobFound;
 
-      if (job!=null && job.setCancelled()) {
-        finishJob(job);
+      jobFound = null;
+      Iterator i = jobHandlers.iterator();
+      while (i.hasNext()) {
+        JobHandler job = (JobHandler) i.next();
+
+        if (job.isPending() && (jobFound==null || priorityFound<job.getPriority())) {
+          jobFound = job;
+          priorityFound = job.getPriority();
+        }
       }
-    }
-  }
 
-  public void makeJobListSnapshots(List aJobList, List aFinishedJobList) {
-    synchronized (jobs) {
-      aJobList.addAll(makeJobListSnapshot());
-      aFinishedJobList.addAll(makeFinishedJobListSnapshot());
+      return jobFound;
     }
   }
 
-  public List makeJobListSnapshot() {
-    synchronized (jobs) {
-      return (List) jobs.clone();
+  public void cancelJobs(List aJobs) {
+    synchronized (jobHandlers) {
+      Iterator i = aJobs.iterator();
+
+      while (i.hasNext()) {
+        ((JobHandler) identifierToJobHandler.get(i.next())).cancelOrAbortJob();
+      }
     }
   }
 
-  public List makeFinishedJobListSnapshot() {
-    synchronized (jobs) {
-      return (List) finishedJobs.clone();
-    }
+  public interface Job {
+    void abort();
+
+    /**
+     *
+     *
+     * @return <code>true</code> if terminated normally, <code>false</code> if aborted
+     */
+    boolean run();
   }
 
-  public class Job implements Cloneable {
-    private Object data;
-    private Date lastChange;
+  public static class JobInfo {
     private String identifier;
+    private Date lastChange;
     private int status;
+    private long runningTime;
     private int priority;
+    private String description;
 
-    public Job(Object aData, String anIdentifier, int aStatus, int aPriority, Date aLastChange) {
-      data = aData;
+    private JobInfo(String aDescription, int aStatus, Date aLastChange, String anIdentifier, long aRunningTime, int aPriority) {
+      description = aDescription;
+      lastChange = aLastChange;
       status = aStatus;
       identifier = anIdentifier;
       priority = aPriority;
-      lastChange = aLastChange;
+      runningTime = aRunningTime;
+    }
+
+    public String getDescription() {
+      return description;
+    }
+
+    public int getStatus() {
+      return status;
     }
 
-    public Job(Object aData, String anIdentifier, int aStatus, int aPriority) {
-      this(aData, anIdentifier, aStatus, aPriority, (new GregorianCalendar()).getTime());
+    public int getPriority() {
+      return priority;
     }
 
     public Date getLastChange() {
@@ -192,37 +216,109 @@ public class JobQueue {
       return identifier;
     }
 
-    public Job(Object aData, String anIdentifier) {
-      this(aData, anIdentifier, STATUS_PENDING, PRIORITY_NORMAL);
+    public long getRunningTime() {
+      return runningTime;
+    }
+  }
+
+  public class JobHandler {
+    private Job job;
+    private String identifier;
+    private String description;
+
+    private Date lastChange;
+    private long starttime;
+    private long endtime;
+    private int status;
+    private int priority;
+    private boolean hasRun;
+
+    public JobHandler(Job aJob, String anIdentifier, String aDescription, int aPriority) {
+      job = aJob;
+      description = aDescription;
+      identifier = anIdentifier;
+      priority = aPriority;
+      status = STATUS_CREATED;
+    }
+
+    public JobHandler(Job aJob, String anIdentifier, String aDescription) {
+      this(aJob, anIdentifier, aDescription, PRIORITY_NORMAL);
     }
 
-    public Object getData() {
-      return data;
+    public JobInfo getJobInfo() {
+      return new JobInfo(getDescription(), getStatus(), getLastChange(), getIdentifier(), getRunningTime(), priority);
     }
 
+    private void runJob() {
+      if (setProcessing()) {
+        if (job.run())
+          setProcessed();
+        else
+          setAborted();
+      }
+    };
+
+    private void cancelOrAbortJob() {
+      synchronized (this) {
+        if (isPending())
+          setCancelled();
+        if (isProcessing())
+          job.abort();
+      }
+    };
+
     public int getStatus() {
       synchronized(this) {
         return status;
       }
     }
 
+    public String getIdentifier() {
+      return identifier;
+    }
+
+    public String getDescription() {
+      return description;
+    }
+
+    public long getRunningTime() {
+      synchronized(this) {
+        long result = 0;
+
+        if (hasRun) {
+          if (isFinished())
+            result = endtime;
+          else
+            result = System.currentTimeMillis();
+
+          result = result - starttime;
+        }
+
+        return result;
+      }
+    }
+
     public int getPriority() {
       return priority;
     }
 
-    protected boolean setProcessing() {
+    private boolean setProcessing() {
       return setStatus(STATUS_PENDING, STATUS_PROCESSING);
     }
 
-    protected void setProcessed() {
+    private void setProcessed() {
       setStatus(STATUS_PROCESSING, STATUS_PROCESSED);
     }
 
-    protected void setAborted() {
+    private void setAborted() {
       setStatus(STATUS_PROCESSING, STATUS_ABORTED);
     }
 
-    protected boolean setCancelled() {
+    private void setPending() {
+      setStatus(STATUS_CREATED, STATUS_PENDING);
+    }
+
+    private boolean setCancelled() {
       return setStatus(STATUS_PENDING, STATUS_CANCELLED);
     }
 
@@ -250,11 +346,25 @@ public class JobQueue {
       return getStatus() == STATUS_PENDING;
     }
 
+    public Date getLastChange() {
+      synchronized (this) {
+        return lastChange;
+      }
+    }
+
     private boolean setStatus(int anOldStatus, int aNewStatus) {
       synchronized(this) {
         if (status == anOldStatus) {
           status = aNewStatus;
           lastChange = (new GregorianCalendar()).getTime();
+          if (isProcessing()) {
+            starttime = System.currentTimeMillis();
+            hasRun = true;
+          }
+
+          if (isFinished()) {
+            endtime = System.currentTimeMillis();
+          }
           return true;
         }
         else {
@@ -262,10 +372,37 @@ public class JobQueue {
         }
       }
     }
+  }
 
-    protected Object clone() {
-      synchronized(this) {
-        return new Job(data, identifier, status, priority, lastChange);
+  private class JobQueueRunner implements Runnable {
+    private LoggerWrapper logger;
+
+    public JobQueueRunner(LoggerWrapper aLogger) {
+      logger = aLogger;
+    }
+
+    public void run() {
+      logger.debug("starting JobQueueRunner");
+
+      try {
+        while (true) {
+          JobHandler job = acquirePendingJob();
+          if (job != null) {
+            logger.debug("  starting job ("+job.getIdentifier()+"): " +job.getDescription());
+            job.runJob();
+            logger.debug("  finished job ("+job.getIdentifier()+"): " +job.getDescription());
+          }
+          else {
+            try {
+              Thread.sleep(1500);
+            }
+            catch (InterruptedException e) {
+            }
+          }
+        }
+      }
+      finally {
+        logger.warn("JobQueueRunner terminated");
       }
     }
   }
index ea72306..59c61e1 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.global;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.misc.ConfigException;
-import mircoders.localizer.MirCachingLocalizerDecorator;
-import mircoders.localizer.MirLocalizer;
-
-public class MirGlobal {
-  static private MirPropertiesConfiguration configuration;
-  static private MirLocalizer localizer;
-  static private ProducerEngine producerEngine;
-  static private Abuse abuse;
-  static private MRUCache mruCache;
-
-  public static MirLocalizer localizer() {
-    String localizerClassName;
-    Class localizerClass;
-
-    if (localizer == null ) {
-      synchronized(MirGlobal.class) {
-        if (localizer == null ) {
-          localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");
-
-          try {
-            localizerClass = Class.forName(localizerClassName);
-          }
-          catch (Throwable t) {
-            throw new ConfigException("localizer class '" + localizerClassName + "' not found: " + t.toString());
-          }
-
-          if (!(MirLocalizer.class.isAssignableFrom(localizerClass)))
-            throw new ConfigException("localizer class '" + localizerClassName + "' is not assignable from MirLocalizer");
-
-          try {
-            localizer = new MirCachingLocalizerDecorator((MirLocalizer) localizerClass.newInstance());
-          }
-          catch (Throwable t) {
-            throw new ConfigException("localizer class '" + localizerClassName + "' cannot be instantiated: " + t.toString());
-          }
-        }
-      }
-    }
-
-    return localizer;
-  }
-
-  public static Abuse abuse() {
-    if (abuse==null) {
-      synchronized(MirGlobal.class) {
-        if (abuse==null)
-          abuse = new Abuse();
-      }
-    }
-
-    return abuse;
-  }
-
-  public static MirPropertiesConfiguration config() {
-    try {
-      return MirPropertiesConfiguration.instance();
-    }
-    catch (PropertiesConfigExc e) {
-      throw new RuntimeException(e.getMessage());
-    }
-  }
-
-  public static ProducerEngine producerEngine() {
-    if (producerEngine == null) {
-      producerEngine = new ProducerEngine();
-    }
-
-    return producerEngine;
-  }
-
-  public static MRUCache mruCache() {
-    synchronized(MirGlobal.class) {
-      if (mruCache == null) {
-       mruCache = new MRUCache();
-      }
-      return mruCache;
-    }
-  }
-}
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.global;\r
+\r
+import java.util.*;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;\r
+import mir.misc.ConfigException;\r
+import mircoders.localizer.MirCachingLocalizerDecorator;\r
+import mircoders.localizer.*;\r
+import mircoders.accesscontrol.*;\r
+import mircoders.entity.*;\r
+import mir.entity.adapter.*;\r
+\r
+public class MirGlobal {\r
+  static private MirPropertiesConfiguration configuration;\r
+  static private MirLocalizer localizer;\r
+  static private ProducerEngine producerEngine;\r
+  static private Abuse abuse;\r
+  static private MRUCache mruCache;\r
+  static private AccessControl accessControl;\r
+  static private Map articleOperations;\r
+  static private Map commentOperations;\r
+\r
+  public synchronized static MirLocalizer localizer() {\r
+    String localizerClassName;\r
+    Class localizerClass;\r
+\r
+    if (localizer == null ) {\r
+      localizerClassName = config().getString("Mir.Localizer", "mirlocal.localizer.basic.MirBasicLocalizer");\r
+\r
+      try {\r
+        localizerClass = Class.forName(localizerClassName);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new ConfigException("localizer class '" + localizerClassName + "' not found: " + t.toString());\r
+      }\r
+\r
+      if (!(MirLocalizer.class.isAssignableFrom(localizerClass)))\r
+        throw new ConfigException("localizer class '" + localizerClassName + "' is not assignable from MirLocalizer");\r
+\r
+      try {\r
+        localizer = new MirCachingLocalizerDecorator((MirLocalizer) localizerClass.newInstance());\r
+      }\r
+      catch (Throwable t) {\r
+        throw new ConfigException("localizer class '" + localizerClassName + "' cannot be instantiated: " + t.toString());\r
+      }\r
+    }\r
+\r
+    return localizer;\r
+  }\r
+\r
+  public static Abuse abuse() {\r
+    if (abuse==null) {\r
+      synchronized(MirGlobal.class) {\r
+        if (abuse==null)\r
+          abuse = new Abuse();\r
+      }\r
+    }\r
+\r
+    return abuse;\r
+  }\r
+\r
+  public static MirPropertiesConfiguration config() {\r
+    try {\r
+      return MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (PropertiesConfigExc e) {\r
+      throw new RuntimeException(e.getMessage());\r
+    }\r
+  }\r
+\r
+  public static ProducerEngine producerEngine() {\r
+    if (producerEngine == null) {\r
+      producerEngine = new ProducerEngine();\r
+    }\r
+\r
+    return producerEngine;\r
+  }\r
+\r
+  public static MRUCache mruCache() {\r
+    synchronized(MirGlobal.class) {\r
+      if (mruCache == null) {\r
+        mruCache = new MRUCache();\r
+      }\r
+      return mruCache;\r
+    }\r
+  }\r
+\r
+  public static synchronized AccessControl accessControl() {\r
+    if (accessControl == null) {\r
+      accessControl=new AccessControl();\r
+    }\r
+\r
+    return accessControl;\r
+  }\r
+\r
+  public static void performArticleOperation(EntityUsers aUser, EntityContent  anArticle, String anOperation) {\r
+    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getArticleOperationForName(anOperation);\r
+\r
+    try {\r
+      if (operation!=null)\r
+        operation.perform(\r
+            localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser),\r
+            localizer().dataModel().adapterModel().makeEntityAdapter("content", anArticle));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+\r
+  public static void performCommentOperation(EntityUsers aUser, EntityComment  aComment, String anOperation) {\r
+    MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = getCommentOperationForName(anOperation);\r
+\r
+    try {\r
+      if (operation!=null)\r
+        operation.perform(\r
+            localizer().dataModel().adapterModel().makeEntityAdapter("user", aUser),\r
+            localizer().dataModel().adapterModel().makeEntityAdapter("comment", aComment));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+\r
+  private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getArticleOperationForName(String aName) {\r
+    try {\r
+      if (articleOperations == null) {\r
+        articleOperations = new HashMap();\r
+        Iterator i = localizer().adminInterface().simpleArticleOperations().iterator();\r
+        while (i.hasNext()) {\r
+          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+          articleOperations.put(operation.getName(), operation);\r
+        }\r
+      }\r
+\r
+      return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) articleOperations.get(aName);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+\r
+  private synchronized static MirAdminInterfaceLocalizer.MirSimpleEntityOperation getCommentOperationForName(String aName) {\r
+    try {\r
+      if (commentOperations == null) {\r
+        commentOperations = new HashMap();\r
+        Iterator i = localizer().adminInterface().simpleCommentOperations().iterator();\r
+        while (i.hasNext()) {\r
+          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation = (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+          commentOperations.put(operation.getName(), operation);\r
+        }\r
+      }\r
+\r
+      return (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) commentOperations.get(aName);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+\r
+}\r
+\r
+\r
index 518fac8..6c6f282 100755 (executable)
@@ -40,7 +40,8 @@ import mir.log.LoggerToWriterAdapter;
 import mir.log.LoggerWrapper;
 import mir.producer.Producer;
 import mir.producer.ProducerFactory;
-import mir.util.DateToMapAdapter;
+import mir.util.*;
+import mir.config.*;
 import mir.util.StringRoutines;
 import multex.Exc;
 import multex.Failure;
@@ -48,22 +49,22 @@ import multex.Failure;
 public class ProducerEngine {
 //  private Map producers;
   private JobQueue producerJobQueue;
-  private Thread queueThread;
   private LoggerWrapper logger;
 
 
   protected ProducerEngine() {
-    producerJobQueue = new JobQueue();
     logger = new LoggerWrapper("Producer");
-
-    queueThread = new Thread(new ProducerJobQueueThread());
-    queueThread.start();
+    producerJobQueue = new JobQueue(new LoggerWrapper("Producer.Queue"));
   }
 
   public void addJob(String aProducerFactory, String aVerb) {
-    producerJobQueue.appendJob(new ProducerJob(aProducerFactory, aVerb));
+    producerJobQueue.appendJob(new ProducerJob(aProducerFactory, aVerb), aProducerFactory+"."+aVerb);
   }
 
+  public void cancelJobs(List aJobs) {
+    producerJobQueue.cancelJobs(aJobs);
+  };
+
   public void addTask(ProducerTask aTask) {
     addJob(aTask.getProducer(), aTask.getVerb());
   }
@@ -76,56 +77,61 @@ public class ProducerEngine {
     }
   }
 
-  private String convertStatus(JobQueue.Job aJob) {
-    if (aJob.hasBeenProcessed())
-      return "processed";
-    if (aJob.isProcessing())
-      return "processing";
-    if (aJob.isPending())
-      return "pending";
-    if (aJob.isCancelled())
-      return "cancelled";
-    if (aJob.hasBeenAborted())
-      return "aborted";
-
+  private String convertStatus(JobQueue.JobInfo aJob) {
+    switch (aJob.getStatus()) {
+      case JobQueue.STATUS_ABORTED:
+        return "aborted";
+      case JobQueue.STATUS_CANCELLED:
+        return "cancelled";
+      case JobQueue.STATUS_CREATED:
+        return "created";
+      case JobQueue.STATUS_PENDING:
+        return "pending";
+      case JobQueue.STATUS_PROCESSED:
+        return "processed";
+      case JobQueue.STATUS_PROCESSING:
+        return "processing";
+    }
     return "unknown";
   }
 
-  private Map convertJob(JobQueue.Job aJob) {
-    Map result = new HashMap();
-    ProducerJob producerJob = (ProducerJob) aJob.getData();
-
-    result.put("identifier", aJob.getIdentifier());
-    result.put("factory", producerJob.getFactoryName());
-    result.put("verb", producerJob.getVerb());
-    result.put("priority", new Integer(aJob.getPriority()));
-    result.put("status", convertStatus(aJob));
-    result.put("lastchange", new DateToMapAdapter(aJob.getLastChange()));
-
-    return result;
-  }
+  private Map convertJob(JobQueue.JobInfo aJob) {
+    try {
+      Map result = new HashMap();
+      result.put("identifier", aJob.getIdentifier());
+      result.put("description", aJob.getDescription());
+      result.put("priority", new Integer(aJob.getPriority()));
+      result.put("runningtime", new Double( (double) aJob.getRunningTime() / 1000));
+      result.put("status", convertStatus(aJob));
+      result.put("lastchange", new GeneratorFormatAdapters.DateFormatAdapter(aJob.getLastChange(), MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));
+      result.put("finished", new Boolean(
+          aJob.getStatus() == JobQueue.STATUS_PROCESSED ||
+          aJob.getStatus() == JobQueue.STATUS_CANCELLED ||
+          aJob.getStatus() == JobQueue.STATUS_ABORTED));
 
-  private void convertJobList(List aSourceJobList, List aDestination) {
-    Iterator i = aSourceJobList.iterator();
-
-    while (i.hasNext())
-      aDestination.add(convertJob((JobQueue.Job) i.next()));
+      return result;
+    }
+    catch (Throwable t) {
+      throw new RuntimeException(t.toString());
+    }
   }
 
-  public List getQueueStatus() {
+  private List convertJobInfoList(List aJobInfoList) {
     List result = new Vector();
-    List pendingJobs = new Vector();
-    List finishedJobs = new Vector();
 
-    producerJobQueue.makeJobListSnapshots(pendingJobs, finishedJobs);
+    Iterator i = aJobInfoList.iterator();
 
-    convertJobList(pendingJobs, result);
-    convertJobList(finishedJobs, result);
+    while (i.hasNext())
+      result.add(convertJob((JobQueue.JobInfo) i.next()));
 
     return result;
   }
 
-private class ProducerJob {
+  public List getQueueStatus() {
+    return convertJobInfoList(producerJobQueue.getJobsInfo());
+  }
+
+  private class ProducerJob implements JobQueue.Job {
     private String factoryName;
     private String verb;
     private Producer producer;
@@ -150,10 +156,11 @@ private class ProducerJob {
       }
     }
 
-    public void execute() {
+    public boolean run() {
       ProducerFactory factory;
       long startTime;
       long endTime;
+      boolean result = false;
       Map startingMap = new HashMap();
 
       startTime = System.currentTimeMillis();
@@ -169,7 +176,7 @@ private class ProducerJob {
             producer = factory.makeProducer(verb, startingMap);
           }
           if (producer!=null) {
-            producer.produce(logger);
+            result = producer.produce(logger);
           }
         }
       }
@@ -179,6 +186,8 @@ private class ProducerJob {
       }
       endTime = System.currentTimeMillis();
       logger.info("Done producing job: " + factoryName + "." + verb + ", time elapsed:" + (endTime-startTime) + " ms");
+
+      return result;
     }
 
     boolean isAborted() {
@@ -186,31 +195,6 @@ private class ProducerJob {
     }
   }
 
-  private class ProducerJobQueueThread implements Runnable {
-    public void run() {
-      logger.debug("starting ProducerJobQueueThread");
-
-      while (true) {
-        ProducerJob job = (ProducerJob) producerJobQueue.acquirePendingJob();
-        if (job!=null) {
-          job.execute();
-          if (job.isAborted())
-            producerJobQueue.jobAborted(job);
-          else
-            producerJobQueue.jobProcessed(job);
-        }
-        else
-        {
-          try {
-            Thread.sleep(1500);
-          }
-          catch (InterruptedException e) {
-          }
-        }
-      }
-    }
-  }
-
   public static class ProducerEngineExc extends Exc {
     public ProducerEngineExc(String aMessage) {
       super(aMessage);
index 25fc488..5e66c4b 100755 (executable)
@@ -71,14 +71,9 @@ public interface MirAdminInterfaceLocalizer {
 
   /**
    *
-   * @param aName
    * @return
    */
-  public MirSimpleEntityOperation simpleCommentOperationForName(String aName);
-
-
   public List simpleArticleOperations();
-  public MirSimpleEntityOperation simpleArticleOperationForName(String aName);
 
   public interface MirSimpleEntityOperation {
     public String getName();
diff --git a/source/mircoders/localizer/MirAntiAbuseFilterType.java b/source/mircoders/localizer/MirAntiAbuseFilterType.java
new file mode 100755 (executable)
index 0000000..d14ea32
--- /dev/null
@@ -0,0 +1,68 @@
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.localizer;\r
+\r
+import mir.entity.Entity;\r
+import mir.session.Request;\r
+\r
+/**\r
+ *\r
+ *\r
+ * <p>Title: Anti-abuse filter type</p>\r
+ * <p>Description: Interface to define filter types for the anti-abuse system\r
+ *  </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: Mir coders</p>\r
+ * @author Zapata\r
+ * @version 1.0\r
+ */\r
+\r
+public interface MirAntiAbuseFilterType {\r
+  /**\r
+   * The identifying name of the filter type. Must be unique.\r
+   *\r
+   * @return\r
+   */\r
+  public String getName();\r
+\r
+  /**\r
+   * Must return <code>true</code> if the expression is valid for this filter. <code>false</code> if not.\r
+   * @param anExpression\r
+   * @return\r
+   */\r
+  public boolean validate(String anExpression);\r
+\r
+  /**\r
+   * Must return <code>true</code> if the posting matches the filter.\r
+   * @param anExpression\r
+   * @return\r
+   */\r
+  public boolean test(String anExpression, Entity anEntity, Request aRequest);\r
+}
\ No newline at end of file
index 6670249..bec059e 100755 (executable)
@@ -1,76 +1,90 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.localizer;
-
-import mir.session.Request;
-import mir.session.Session;
-import mir.session.SessionHandler;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-
-public interface MirOpenPostingLocalizer {
-
-  /**
-   * Class to encapsulate a validation error
-   *
-   * <p>Title: </p>
-   * <p>Description: </p>
-   * <p>Copyright: Copyright (c) 2003</p>
-   * <p>Company: </p>
-   * @author not attributable
-   * @version 1.0
-   */
-
-  /**
-   *
-   * @param aRequest
-   * @param aSession
-   * @return
-   * @throws MirLocalizerExc
-   * @throws MirLocalizerFailure
-   */
-  public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;
-
-  /**
-   *
-   * @param aComment
-   * @throws MirLocalizerExc
-   * @throws MirLocalizerFailure
-   */
-  public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;
-
-  /**
-   *
-   * @param aContent
-   * @throws MirLocalizerExc
-   * @throws MirLocalizerFailure
-   */
-  public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.localizer;\r
+\r
+import java.util.List;\r
+\r
+import mir.session.Request;\r
+import mir.session.Session;\r
+import mir.session.SessionHandler;\r
+\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+\r
+public interface MirOpenPostingLocalizer {\r
+\r
+  /**\r
+   * Class to encapsulate a validation error\r
+   *\r
+   * <p>Title: </p>\r
+   * <p>Description: </p>\r
+   * <p>Copyright: Copyright (c) 2003</p>\r
+   * <p>Company: </p>\r
+   * @author not attributable\r
+   * @version 1.0\r
+   */\r
+\r
+  /**\r
+   *\r
+   * @param aRequest\r
+   * @param aSession\r
+   * @return\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+  public SessionHandler getOpenSessionHandler(Request aRequest, Session aSession) throws MirLocalizerExc, MirLocalizerFailure;\r
+\r
+  /**\r
+   *\r
+   * @param aComment\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+  public void afterCommentPosting(EntityComment aComment) throws MirLocalizerExc, MirLocalizerFailure;\r
+\r
+  /**\r
+   * This method will be called after an article is posted via the open posting interface.\r
+   *\r
+   * @param aContent\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+  public void afterContentPosting(EntityContent aContent) throws MirLocalizerExc, MirLocalizerFailure;\r
+\r
+  /**\r
+   *\r
+   *\r
+   * @return\r
+   * @throws MirLocalizerExc\r
+   * @throws MirLocalizerFailure\r
+   */\r
+\r
+  public List getAntiAbuseFilterTypes() throws MirLocalizerExc, MirLocalizerFailure;\r
+}\r
index 7196ea1..4ed7d6a 100755 (executable)
@@ -236,6 +236,33 @@ public class MirBasicAdminInterfaceLocalizer implements MirAdminInterfaceLocaliz
     }
   }
 
+  protected static class SetCommentFieldsOperation extends CommentModifyingOperation {
+    private Map values;
+
+    public SetCommentFieldsOperation(String aName, String aFields[], String aValues[]) throws MirLocalizerExc {
+      super(aName);
+
+      values = new HashMap();
+
+      for (int i=0; i<aFields.length; i++)
+        values.put(aFields[i], aValues[i]);
+    }
+
+    protected boolean isAvailable(EntityComment aComment) {
+      return true;
+    }
+
+    protected void performModification(EntityAdapter aUser, EntityComment aComment) throws StorageObjectFailure {
+      Iterator i = values.entrySet().iterator();
+
+      while (i.hasNext()) {
+        Map.Entry entry = (Map.Entry) i.next();
+        aComment.setValueForProperty((String) entry.getKey(), (String) entry.getValue());
+      }
+    }
+  }
+
+
   protected static class ModifyCommentFieldOperation extends CommentModifyingOperation {
     private String field;
     private String value;
diff --git a/source/mircoders/localizer/basic/MirBasicAntiAbuseFilterTypes.java b/source/mircoders/localizer/basic/MirBasicAntiAbuseFilterTypes.java
new file mode 100755 (executable)
index 0000000..e7ae73d
--- /dev/null
@@ -0,0 +1,180 @@
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.localizer.basic;\r
+\r
+import java.util.*;\r
+\r
+import gnu.regexp.*;\r
+\r
+import mir.entity.Entity;\r
+import mir.session.Request;\r
+import mir.util.InternetFunctions;\r
+import mircoders.localizer.MirAntiAbuseFilterType;\r
+\r
+\r
+/**\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class MirBasicAntiAbuseFilterTypes {\r
+  private MirBasicAntiAbuseFilterTypes() {\r
+  }\r
+\r
+  public static abstract class BasicFilterType implements MirAntiAbuseFilterType {\r
+    private String name;\r
+\r
+    public BasicFilterType(String aName) {\r
+      name = aName;\r
+    }\r
+\r
+    public String getName() {\r
+      return name;\r
+    }\r
+  }\r
+\r
+  /**\r
+   * A basic ip filter. Supports x.x.x.x, x.x.x.x/x and x.x.x.x/x.x.x.x expressions.\r
+   *\r
+   * <p>Title: </p>\r
+   * <p>Description: </p>\r
+   * <p>Copyright: Copyright (c) 2003</p>\r
+   * <p>Company: </p>\r
+   * @author not attributable\r
+   * @version 1.0\r
+   */\r
+\r
+  public static class IPFilter extends BasicFilterType {\r
+    public IPFilter(String aName) {\r
+      super(aName);\r
+    }\r
+\r
+    public boolean validate(String anExpression) {\r
+      try {\r
+        InternetFunctions.isIpAddressInNetwork("1.1.1.1", anExpression);\r
+        return true;\r
+      }\r
+      catch (Throwable t) {\r
+        return false;\r
+      }\r
+    };\r
+\r
+    public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
+      try {\r
+        return InternetFunctions.isIpAddressInNetwork(aRequest.getHeader("ip"), anExpression);\r
+      }\r
+      catch (Throwable t) {\r
+        return false;\r
+      }\r
+    };\r
+  }\r
+\r
+  /**\r
+   * A regular expression filter.\r
+   *\r
+   * <p>Title: </p>\r
+   * <p>Description: </p>\r
+   * <p>Copyright: Copyright (c) 2003</p>\r
+   * <p>Company: </p>\r
+   * @author not attributable\r
+   * @version 1.0\r
+   */\r
+\r
+  public static class RegularExpressionFilter extends BasicFilterType {\r
+    private boolean exactMatch;\r
+    private boolean caseSensitive;\r
+    private List selectedFields;\r
+\r
+    public RegularExpressionFilter(String aName) {\r
+      this(aName, false, false, null);\r
+    }\r
+\r
+    public RegularExpressionFilter(String aName, boolean aCaseSensitive, boolean anExactMatch, String[] aSelectedFields) {\r
+      super(aName);\r
+\r
+      caseSensitive = aCaseSensitive;\r
+      exactMatch = anExactMatch;\r
+      if (aSelectedFields==null)\r
+        selectedFields = null;\r
+      else\r
+        selectedFields = Arrays.asList(aSelectedFields);\r
+    }\r
+\r
+    public boolean validate(String anExpression) {\r
+      try {\r
+        new RE(anExpression);\r
+        return true;\r
+      }\r
+      catch (Throwable t) {\r
+        return false;\r
+      }\r
+    };\r
+\r
+    public boolean test(String anExpression, Entity anEntity, Request aRequest) {\r
+      try {\r
+        Iterator j;\r
+        int flags = 0;\r
+\r
+        if (caseSensitive)\r
+          flags |= RE.REG_ICASE;\r
+\r
+        RE regularExpression = new RE(anExpression, RE.REG_ICASE);\r
+\r
+        if (selectedFields!=null)\r
+          j = selectedFields.iterator();\r
+        else\r
+          j = anEntity.getFields().iterator();\r
+\r
+        while (j.hasNext()) {\r
+          String field = anEntity.getValue( (String) j.next());\r
+\r
+          if (exactMatch) {\r
+            if (field != null && regularExpression.isMatch(field)) {\r
+              return true;\r
+            }\r
+          }\r
+          else {\r
+            if (field != null && regularExpression.getMatch(field) != null) {\r
+              return true;\r
+            }\r
+          }\r
+        }\r
+      }\r
+      catch (Throwable t) {\r
+      }\r
+      return false;\r
+    }\r
+  }\r
+}
\ No newline at end of file
index 7a082a9..bcb42ff 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.localizer.basic;\r
+\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+\r
+import mir.entity.Entity;\r
+import mir.misc.StringUtil;\r
+import mir.session.Request;\r
+import mir.session.Response;\r
+import mir.session.Session;\r
+import mir.session.SessionExc;\r
+import mir.session.SessionFailure;\r
+import mir.session.UploadedFile;\r
+import mir.session.ValidationError;\r
+import mir.session.ValidationHelper;\r
+import mir.util.ExceptionFunctions;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.media.MediaUploadProcessor;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.module.*;\r
+import mircoders.storage.*;\r
+import mircoders.storage.DatabaseContent;\r
+import mircoders.storage.DatabaseContentToMedia;\r
+import mircoders.storage.DatabaseContentToTopics;\r
+\r
+/**\r
+ *\r
+ * <p>Title: Experimental session handler for article postings </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author Zapata\r
+ * @version 1.0\r
+ */\r
+\r
+public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {\r
+  protected ModuleContent contentModule = new ModuleContent(DatabaseContent.getInstance());\r
+  protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();\r
+  protected DatabaseContent contentDatabase = DatabaseContent.getInstance();\r
+\r
+  public MirBasicArticlePostingHandler() {\r
+    super();\r
+\r
+    setResponseGenerators(\r
+      configuration.getString("Localizer.OpenSession.article.EditTemplate"),\r
+      configuration.getString("Localizer.OpenSession.article.DupeTemplate"),\r
+      configuration.getString("Localizer.OpenSession.article.UnsupportedMediaTemplate"),\r
+      configuration.getString("Localizer.OpenSession.article.DoneTemplate"));\r
+  }\r
+\r
+  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {\r
+    super.initializeResponseData(aRequest, aSession, aResponse);\r
+\r
+    Iterator i = DatabaseContent.getInstance().getFields().iterator();\r
+    while (i.hasNext()) {\r
+      String field = (String) i.next();\r
+      aResponse.setResponseValue(field, aRequest.getParameter(field));\r
+    }\r
+    aResponse.setResponseValue("to_topic", aRequest.getParameters("to_topic"));\r
+  }\r
+\r
+  public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
+    super.validate(aResults, aRequest, aSession);\r
+\r
+    ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults);\r
+    ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults);\r
+    ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);\r
+    ValidationHelper.testFieldEntered(aRequest, "content_data", "validationerror.missing", aResults);\r
+  }\r
+\r
+  public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {\r
+    try {\r
+      anArticle.setValueForProperty("is_published", "1");\r
+      anArticle.setValueForProperty("is_produced", "0");\r
+      anArticle.setValueForProperty("date",\r
+                                    StringUtil.date2webdbDate(new GregorianCalendar()));\r
+      anArticle.setValueForProperty("is_html", "0");\r
+      anArticle.setValueForProperty("publish_path",\r
+                                    StringUtil.webdbDate2path(anArticle.\r
+          getValue("date")));\r
+      ModuleArticleType module = new ModuleArticleType(DatabaseArticleType.\r
+          getInstance());\r
+\r
+      anArticle.setValueForProperty("to_article_type",\r
+                                    module.articleTypeIdForName(configuration.\r
+          getString("Localizer.OpenSession.article.DefaultArticleType")));\r
+      anArticle.setValueForProperty("to_publisher", "1");\r
+    }\r
+    catch (Throwable t) {\r
+      throw new SessionFailure(t);\r
+    }\r
+  }\r
+\r
+  public void setArticleTopics(Request aRequest, Session aSession, EntityContent aContent) throws SessionExc, SessionFailure {\r
+    // topics:\r
+    List topics = aRequest.getParameters("to_topic");\r
+    if (topics.size() > 0) {\r
+      try {\r
+        DatabaseContentToTopics.getInstance().setTopics(aContent.getId(), topics);\r
+      }\r
+      catch (Throwable e) {\r
+        logger.error("setting content_x_topic failed");\r
+        throw new SessionFailure("MirBasicArticlePostingHandler: can't set topics: " + e.toString(), e);\r
+      }\r
+    }\r
+  }\r
+\r
+  public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
+    try {\r
+      String id;\r
+      Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
+\r
+      EntityContent article = (EntityContent) contentModule.createNew();\r
+      article.setValues(values);\r
+\r
+      finalizeArticle(aRequest, aSession, article);\r
+      id = article.insert();\r
+      if (id == null) {\r
+        logger.info("Duplicate article rejected");\r
+        throw new DuplicatePostingExc("Duplicate article rejected");\r
+      }\r
+      aSession.setAttribute("content", article);\r
+\r
+\r
+      setArticleTopics(aRequest, aSession, article);\r
+\r
+    }\r
+    catch (Throwable t) {\r
+      throw new SessionFailure(t);\r
+    }\r
+  }\r
+\r
+  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {\r
+    try {\r
+      Map values = new HashMap();\r
+      values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title"));\r
+      values.put("creator", aRequest.getParameter("creator"));\r
+      values.put("to_publisher", "0");\r
+      values.put("is_published", "1");\r
+      values.put("is_produced", "1");\r
+      Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);\r
+      mediaItem.update();\r
+      contentToMedia.addMedia(((EntityContent) aSession.getAttribute("content")).getId(), mediaItem.getId());\r
+    }\r
+    catch (Throwable t) {\r
+      throw new SessionFailure(t);\r
+    }\r
+  }\r
+\r
+  public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
+    EntityContent article = (EntityContent) aSession.getAttribute("content");\r
+\r
+    MirGlobal.abuse().checkArticle(article, aRequest, null);\r
+    try {\r
+      MirGlobal.localizer().openPostings().afterContentPosting(article);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new SessionFailure(t);\r
+    }\r
+    logger.info("article posted");\r
+  };\r
+\r
+}
 
-package mircoders.localizer.basic;
-
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.misc.StringUtil;
-import mir.session.Request;
-import mir.session.Response;
-import mir.session.Session;
-import mir.session.SessionExc;
-import mir.session.SessionFailure;
-import mir.session.UploadedFile;
-import mircoders.entity.EntityContent;
-import mircoders.global.MirGlobal;
-import mircoders.media.MediaUploadProcessor;
-import mircoders.module.ModuleContent;
-import mircoders.storage.DatabaseContent;
-import mircoders.storage.DatabaseContentToMedia;
-import mircoders.storage.DatabaseContentToTopics;
-
-/**
- *
- * <p>Title: Experimental session handler for article postings </p>
- * <p>Description: </p>
- * <p>Copyright: Copyright (c) 2003</p>
- * <p>Company: </p>
- * @author Zapata
- * @version 1.0
- */
-
-public class MirBasicArticlePostingHandler extends MirBasicPostingSessionHandler {
-  protected ModuleContent contentModule = new ModuleContent(DatabaseContent.getInstance());
-  protected DatabaseContentToMedia contentToMedia = DatabaseContentToMedia.getInstance();
-  protected DatabaseContent contentDatabase = DatabaseContent.getInstance();
-
-  public MirBasicArticlePostingHandler() {
-    super();
-
-    setResponseGenerators(
-      configuration.getString("Localizer.OpenSession.article.EditTemplate"),
-      configuration.getString("Localizer.OpenSession.article.DupeTemplate"),
-      configuration.getString("Localizer.OpenSession.article.UnsupportedMediaTemplate"),
-      configuration.getString("Localizer.OpenSession.article.DoneTemplate"));
-  }
-
-  protected void initializeResponseData(Request aRequest, Session aSession, Response aResponse) throws SessionExc, SessionFailure {
-    super.initializeResponseData(aRequest, aSession, aResponse);
-
-    Iterator i = DatabaseContent.getInstance().getFields().iterator();
-    while (i.hasNext()) {
-      String field = (String) i.next();
-      aResponse.setResponseValue(field, aRequest.getParameter(field));
-    }
-    aResponse.setResponseValue("to_topic", aRequest.getParameters("to_topic"));
-  }
-
-  public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
-    super.validate(aResults, aRequest, aSession);
-
-    testFieldEntered(aRequest, "title", "validationerror.missing", aResults);
-    testFieldEntered(aRequest, "description", "validationerror.missing", aResults);
-    testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);
-    testFieldEntered(aRequest, "content_data", "validationerror.missing", aResults);
-  }
-
-  public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
-    anArticle.setValueForProperty("is_published", "1");
-    anArticle.setValueForProperty("is_produced", "0");
-    anArticle.setValueForProperty("date", StringUtil.date2webdbDate(new GregorianCalendar()));
-    anArticle.setValueForProperty("is_html","0");
-    anArticle.setValueForProperty("publish_path", StringUtil.webdbDate2path(anArticle.getValue("date")));
-    anArticle.setValueForProperty("to_article_type", "1");
-    anArticle.setValueForProperty("to_publisher", "1");
-  }
-
-  public void setArticleTopics(Request aRequest, Session aSession, EntityContent aContent) throws SessionExc, SessionFailure {
-    // topics:
-    List topics = aRequest.getParameters("to_topic");
-    if (topics.size() > 0) {
-      try {
-        DatabaseContentToTopics.getInstance().setTopics(aContent.getId(), topics);
-      }
-      catch (Throwable e) {
-        logger.error("setting content_x_topic failed");
-        throw new SessionFailure("MirBasicArticlePostingHandler: can't set topics: " + e.toString(), e);
-      }
-    }
-  }
-
-  public void preProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
-    try {
-      String id;
-      Map values = getIntersectingValues(aRequest, DatabaseContent.getInstance());
-
-      EntityContent article = (EntityContent) contentModule.createNew();
-      article.setValues(values);
-
-      finalizeArticle(aRequest, aSession, article);
-      id = article.insert();
-      if (id == null) {
-        logger.info("Duplicate article rejected");
-        throw new DuplicatePostingExc("Duplicate article rejected");
-      }
-      aSession.setAttribute("content", article);
-
-
-      setArticleTopics(aRequest, aSession, article);
-
-    }
-    catch (Throwable t) {
-      throw new SessionFailure(t);
-    }
-  }
-
-  public void processUploadedFile(Request aRequest, Session aSession, UploadedFile aFile) throws SessionExc, SessionFailure {
-    try {
-      Map values = new HashMap();
-      values.put("title", aRequest.getParameter(aFile.getFieldName()+"_title"));
-      values.put("creator", aRequest.getParameter("creator"));
-      values.put("to_publisher", "0");
-      values.put("is_published", "1");
-      values.put("is_produced", "1");
-      Entity mediaItem = MediaUploadProcessor.processMediaUpload(aFile, values);
-      mediaItem.update();
-      contentToMedia.addMedia(((EntityContent) aSession.getAttribute("content")).getId(), mediaItem.getId());
-    }
-    catch (Throwable t) {
-      throw new SessionFailure(t);
-    }
-  }
-
-  public void postProcessRequest(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
-    EntityContent article = (EntityContent) aSession.getAttribute("content");
-
-    MirGlobal.abuse().checkArticle(article, aRequest, null);
-    try {
-      MirGlobal.localizer().openPostings().afterContentPosting(article);
-    }
-    catch (Throwable t) {
-      throw new SessionFailure(t);
-    }
-    logger.info("article posted");
-  };
-
-}
\ No newline at end of file
index 847fd8c..4a2cee7 100755 (executable)
@@ -1,62 +1,62 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.localizer.basic;
-
-import mir.session.*;
-import mircoders.entity.*;
-
-
-public class MirBasicChildArticlePostingHandler extends MirBasicArticlePostingHandler {
-  public MirBasicChildArticlePostingHandler() {
-    super();
-
-    setNormalResponseGenerator(configuration.getString("Localizer.OpenSession.article.EditTemplate"));
-  }
-
-  public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {
-    super.finalizeArticle(aRequest, aSession, anArticle);
-
-    anArticle.setValueForProperty("to_content", (String) aSession.getAttribute("to_content"));
-  }
-
-  protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
-    super.initializeSession(aRequest, aSession);
-
-    String parentId = aRequest.getParameter("to_content");
-    if (parentId==null)
-      throw new SessionExc("initializeSession: parent id not set!");
-
-    aSession.setAttribute("to_content", parentId);
-  };
-
-
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.localizer.basic;\r
+\r
+import mir.session.Request;\r
+import mir.session.Session;\r
+import mir.session.SessionExc;\r
+import mir.session.SessionFailure;\r
+import mircoders.entity.EntityContent;\r
+\r
+\r
+public class MirBasicChildArticlePostingHandler extends MirBasicArticlePostingHandler {\r
+  public MirBasicChildArticlePostingHandler() {\r
+    super();\r
+\r
+    setNormalResponseGenerator(configuration.getString("Localizer.OpenSession.article.EditTemplate"));\r
+  }\r
+\r
+  public void finalizeArticle(Request aRequest, Session aSession, EntityContent anArticle) throws SessionExc, SessionFailure {\r
+    super.finalizeArticle(aRequest, aSession, anArticle);\r
+\r
+    anArticle.setValueForProperty("to_content", (String) aSession.getAttribute("to_content"));\r
+  }\r
+\r
+  protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {\r
+    super.initializeSession(aRequest, aSession);\r
+\r
+    String parentId = aRequest.getParameter("to_content");\r
+    if (parentId==null)\r
+      throw new SessionExc("initializeSession: parent id not set!");\r
+\r
+    aSession.setAttribute("to_content", parentId);\r
+  };\r
 }
\ No newline at end of file
index 1e243b1..9dd59b9 100755 (executable)
@@ -41,6 +41,9 @@ import mir.session.Session;
 import mir.session.SessionExc;
 import mir.session.SessionFailure;
 import mir.session.UploadedFile;
+import mir.session.ValidationError;
+import mir.session.ValidationHelper;
+import mir.util.ExceptionFunctions;
 import mircoders.entity.EntityComment;
 import mircoders.global.MirGlobal;
 import mircoders.media.MediaUploadProcessor;
@@ -87,9 +90,9 @@ public class MirBasicCommentPostingHandler extends MirBasicPostingSessionHandler
   public void validate(List aResults, Request aRequest, Session aSession) throws SessionExc, SessionFailure {
     super.validate(aResults, aRequest, aSession);
 
-    testFieldEntered(aRequest, "title", "validationerror.missing", aResults);
-    testFieldEntered(aRequest, "description", "validationerror.missing", aResults);
-    testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);
+    ValidationHelper.testFieldEntered(aRequest, "title", "validationerror.missing", aResults);
+    ValidationHelper.testFieldEntered(aRequest, "description", "validationerror.missing", aResults);
+    ValidationHelper.testFieldEntered(aRequest, "creator", "validationerror.missing", aResults);
   }
 
   protected void initializeSession(Request aRequest, Session aSession) throws SessionExc, SessionFailure {
@@ -164,4 +167,4 @@ public class MirBasicCommentPostingHandler extends MirBasicPostingSessionHandler
       super(aMessage);
     }
   }
-}
\ No newline at end of file
+}
index f01b6eb..f96b394 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.localizer.basic;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.Entity;
-import mir.entity.adapter.EntityAdapter;
-import mir.entity.adapter.EntityAdapterDefinition;
-import mir.entity.adapter.EntityAdapterModel;
-import mir.log.LoggerWrapper;
-import mir.media.MediaHelper;
-import mir.media.MirMedia;
-import mir.util.ParameterExpander;
-import mir.util.RewindableIterator;
-import mircoders.entity.EntityUploadedMedia;
-import mircoders.global.MirGlobal;
-import mircoders.localizer.MirAdminInterfaceLocalizer;
-import mircoders.localizer.MirDataModelLocalizer;
-import mircoders.localizer.MirLocalizerExc;
-import mircoders.localizer.MirLocalizerFailure;
-import mircoders.storage.DatabaseArticleType;
-import mircoders.storage.DatabaseAudio;
-import mircoders.storage.DatabaseBreaking;
-import mircoders.storage.DatabaseComment;
-import mircoders.storage.DatabaseCommentStatus;
-import mircoders.storage.DatabaseContent;
-import mircoders.storage.DatabaseImageType;
-import mircoders.storage.DatabaseImages;
-import mircoders.storage.DatabaseLanguage;
-import mircoders.storage.DatabaseMedia;
-import mircoders.storage.DatabaseMediaType;
-import mircoders.storage.DatabaseMediafolder;
-import mircoders.storage.DatabaseMessages;
-import mircoders.storage.DatabaseOther;
-import mircoders.storage.DatabaseTopics;
-import mircoders.storage.DatabaseUploadedMedia;
-import mircoders.storage.DatabaseUsers;
-import mircoders.storage.DatabaseVideo;
-
-public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {
-  protected LoggerWrapper logger;
-  protected MirPropertiesConfiguration configuration;
-
-  public MirBasicDataModelLocalizer() throws MirLocalizerFailure, MirLocalizerExc {
-    logger = new LoggerWrapper("Localizer.DataModel");
-
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-    }
-    catch (Throwable e) {
-      throw new MirLocalizerFailure("Can't get configuration: " + e.getMessage(), e);
-    }
-  }
-
-  protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure, MirLocalizerExc {
-    try {
-      anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create");
-      anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange");
-      anEntityAdapterDefinition.addMirDateField("date", "date");
-      anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField());
-      anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField());
-      anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField());
-
-      anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'"));
-      anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField(""));
-
-      anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_images",  new ContentToMediaField( "image" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" ));
-      anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new ContentToMediaField( "uploadedMedia", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_images",  new ContentToMediaField( "image", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new ContentToMediaField( "audio", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new ContentToMediaField( "video", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new ContentToMediaField( "otherMedia", false));
-      anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField());
-
-      anEntityAdapterDefinition.addCalculatedField("article_type", new ContentToArticleTypeField());
-
-      anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));
-      anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data"));
-
-      anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField());
-      anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField());
-
-      anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Article.PublicUrl")));
-
-      anEntityAdapterDefinition.addCalculatedField("operations",
-          new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations()));
-    }
-    catch (Throwable t) {
-      throw new MirLocalizerFailure(t.getMessage(), t);
-    }
-  }
-
-  protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure {
-    try {
-      anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create");
-      anEntityAdapterDefinition.addCalculatedField("to_content", new CommentToContentField());
-      anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField());
-
-      anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new CommentToMediaField( "uploadedMedia" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_images",  new CommentToMediaField( "image" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_audio", new CommentToMediaField( "audio" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_video", new CommentToMediaField( "video" ));
-      anEntityAdapterDefinition.addCalculatedField("to_media_other", new CommentToMediaField( "otherMedia" ));
-      anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new CommentToMediaField( "uploadedMedia", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_images",  new CommentToMediaField( "image", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new CommentToMediaField( "audio", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new CommentToMediaField( "video", false));
-      anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new CommentToMediaField( "otherMedia", false));
-
-      anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Comment.PublicUrl")));
-
-      anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));
-      anEntityAdapterDefinition.addCalculatedField("operations",
-          new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleCommentOperations()));
-    }
-    catch (Throwable t) {
-      throw new MirLocalizerFailure(t.getMessage(), t);
-    }
-  }
-
-  public EntityAdapterModel adapterModel() throws MirLocalizerFailure, MirLocalizerExc {
-    EntityAdapterModel result = new EntityAdapterModel();
-
-    try {
-      EntityAdapterDefinition definition;
-
-      definition = new EntityAdapterDefinition();
-      constructContentAdapterDefinition( definition );
-      result.addMapping( "content", DatabaseContent.getInstance(), definition);
-
-      definition = new EntityAdapterDefinition();
-      constructCommentAdapterDefinition( definition );
-      result.addMapping( "comment", DatabaseComment.getInstance(), definition);
-
-      result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition());
-
-      definition = new EntityAdapterDefinition();
-      definition.addDBDateField("creationdate", "webdb_create");
-      result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition);
-
-      result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "internalMessage", DatabaseMessages.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "user", DatabaseUsers.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "media", DatabaseMedia.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "image", DatabaseImages.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "audio", DatabaseAudio.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "video", DatabaseVideo.getInstance(), new EntityAdapterDefinition());
-      result.addMapping( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition());
-    }
-    catch (Throwable t) {
-      throw new MirLocalizerFailure(t.getMessage(), t);
-    }
-
-    return result;
-  }
-
-  protected class CommentToContentField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getToOneRelation(
-                    "id="+anEntityAdapter.get("to_media"),
-                    "id",
-                    "content" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class CommentToStatusField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getToOneRelation(
-                    "id="+anEntityAdapter.get("to_comment_status"),
-                    "id",
-                    "commentStatus" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class EntityToSimpleOperationsField implements EntityAdapterDefinition.CalculatedField {
-    private List operations;
-
-    public EntityToSimpleOperationsField(List anOperations) {
-      operations = anOperations;
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        Iterator i = operations.iterator();
-        List availableOperations = new Vector();
-
-        while (i.hasNext()) {
-          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =
-            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();
-
-          if (operation.isAvailable(anEntityAdapter)) {
-            availableOperations.add(operation.getName());
-          }
-        };
-
-        return availableOperations;
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class FilteredField implements EntityAdapterDefinition.CalculatedField {
-    private String fieldName;
-
-    public FilteredField(String aFieldName) {
-      fieldName = aFieldName;
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        if (anEntityAdapter.get("is_html")!=null && anEntityAdapter.get("is_html").equals("1")) {
-          return MirGlobal.localizer().producerAssistant().filterHTMLText((String) anEntityAdapter.get(fieldName));
-        }
-        else {
-          return MirGlobal.localizer().producerAssistant().filterNonHTMLText((String) anEntityAdapter.get(fieldName));
-        }
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ExpandedField implements EntityAdapterDefinition.CalculatedField {
-    private String expression;
-
-    public ExpandedField(String anExpression) {
-      expression = anExpression;
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return ParameterExpander.expandExpression(anEntityAdapter, expression);
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class EvaluatedField implements EntityAdapterDefinition.CalculatedField {
-    private String expression;
-
-    public EvaluatedField(String anExpression) {
-      expression = anExpression;
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return ParameterExpander.evaluateExpression(anEntityAdapter, expression);
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        logger.debug("ContentToParentField.getValue");
-        return anEntityAdapter.getToOneRelation(
-                    "id="+anEntityAdapter.get("to_content"),
-                    "id",
-                    "content" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getRelation(
-                    "to_content="+anEntityAdapter.get("id"),
-                    "id",
-                    "content" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getToOneRelation(
-                    "id="+anEntityAdapter.get("to_language"),
-                    "id",
-                    "language" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToArticleTypeField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getToOneRelation(
-                    "id="+anEntityAdapter.get("to_article_type"),
-                    "id",
-                    "articleType" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getRelation(
-                    "to_media="+anEntityAdapter.get("id")+" and is_published='1'",
-                    "webdb_create",
-                    "comment" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return anEntityAdapter.getRelation(
-                    "exists (select * from content_x_topic where content_id="+anEntityAdapter.get("id")+" and topic_id=id)",
-                    "title",
-                    "topic" );
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField {
-    private String definition;
-    private boolean published;
-
-    public ContentToMediaField(String aDefinition, boolean anOnlyPublished) {
-      definition = aDefinition;
-      published = anOnlyPublished;
-    }
-
-    public ContentToMediaField(String aDefinition) {
-      this(aDefinition, true);
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        String condition = "exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)";
-        if (published)
-          condition = "is_published='t' and " + condition;
-        return anEntityAdapter.getRelation(
-           condition,
-          "id",
-          definition);
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class CommentToMediaField implements EntityAdapterDefinition.CalculatedField {
-    private String definition;
-    private boolean published;
-
-    public CommentToMediaField(String aDefinition, boolean anOnlyPublished) {
-      definition = aDefinition;
-      published = anOnlyPublished;
-    }
-
-    public CommentToMediaField(String aDefinition) {
-      this(aDefinition, true);
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        String condition = "exists (select * from comment_x_media where comment_id="+anEntityAdapter.get("id")+" and media_id=id)";
-        if (published)
-          condition = "is_published='t' and " + condition;
-        return anEntityAdapter.getRelation(
-           condition,
-          "id",
-          definition);
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-
-  protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField {
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      EntityAdapter media;
-      Entity mediaType;
-      RewindableIterator iterator;
-      Map result;
-      MirMedia mediaHandler;
-      String tinyIcon;
-      String iconAlt;
-
-      try {
-        iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media"));
-        iterator.rewind();
-
-        tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText");
-        iconAlt = "Text";
-
-        if (iterator.hasNext()) {
-          media = (EntityAdapter) iterator.next();
-
-          mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType();
-          mediaHandler = MediaHelper.getHandler( mediaType );
-
-          if (mediaHandler.isVideo()) {
-            tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo");
-            iconAlt = "Video";
-          }
-          else if (mediaHandler.isAudio()) {
-            tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio");
-            iconAlt = "Audio";
-          }
-          else if (mediaHandler.isImage()) {
-            tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage");
-            iconAlt = "Image";
-          }
-          else {
-            tinyIcon = mediaHandler.getTinyIconName();
-            iconAlt = mediaHandler.getIconAltName();
-          }
-
-        }
-      }
-      catch (Throwable t) {
-        logger.error("ContentToIconField: " +t.getMessage());
-        throw new RuntimeException(t.getMessage());
-      }
-
-      result = new HashMap();
-      result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon);
-      result.put("icon_alt", iconAlt);
-
-      return result;
-    }
-  }
-
-  protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField {
-    private String extraCondition;
-
-    public ContentCommentCountField(String anExtraCondition) {
-      super();
-
-      extraCondition = anExtraCondition;
-    }
-
-    public Object getValue(EntityAdapter anEntityAdapter) {
-      try {
-        return Integer.toString(
-            DatabaseComment.getInstance().getSize(
-                  "to_media="+anEntityAdapter.get("id")+" " + extraCondition));
-      }
-      catch (Throwable t) {
-        throw new RuntimeException(t.getMessage());
-      }
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.localizer.basic;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.entity.Entity;\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.entity.adapter.EntityAdapterDefinition;\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaHelper;\r
+import mir.media.MirMedia;\r
+import mir.util.ParameterExpander;\r
+import mir.util.RewindableIterator;\r
+import mir.util.StructuredContentParser;\r
+import mircoders.entity.EntityUploadedMedia;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.localizer.MirAdminInterfaceLocalizer;\r
+import mircoders.localizer.MirDataModelLocalizer;\r
+import mircoders.localizer.MirLocalizerExc;\r
+import mircoders.localizer.MirLocalizerFailure;\r
+import mircoders.storage.DatabaseArticleType;\r
+import mircoders.storage.DatabaseAudio;\r
+import mircoders.storage.DatabaseBreaking;\r
+import mircoders.storage.DatabaseComment;\r
+import mircoders.storage.DatabaseCommentStatus;\r
+import mircoders.storage.DatabaseContent;\r
+import mircoders.storage.DatabaseContentToMedia;\r
+import mircoders.storage.DatabaseContentToTopics;\r
+import mircoders.storage.DatabaseImageType;\r
+import mircoders.storage.DatabaseImages;\r
+import mircoders.storage.DatabaseLanguage;\r
+import mircoders.storage.DatabaseMediaType;\r
+import mircoders.storage.DatabaseMediafolder;\r
+import mircoders.storage.DatabaseMessages;\r
+import mircoders.storage.DatabaseOther;\r
+import mircoders.storage.DatabaseTopics;\r
+import mircoders.storage.DatabaseUploadedMedia;\r
+import mircoders.storage.DatabaseUsers;\r
+import mircoders.storage.DatabaseVideo;\r
+\r
+public class MirBasicDataModelLocalizer implements MirDataModelLocalizer {\r
+  protected LoggerWrapper logger;\r
+  protected MirPropertiesConfiguration configuration;\r
+\r
+  public MirBasicDataModelLocalizer() throws MirLocalizerFailure, MirLocalizerExc {\r
+    logger = new LoggerWrapper("Localizer.DataModel");\r
+\r
+    try {\r
+      configuration = MirPropertiesConfiguration.instance();\r
+    }\r
+    catch (Throwable e) {\r
+      throw new MirLocalizerFailure("Can't get configuration: " + e.getMessage(), e);\r
+    }\r
+  }\r
+\r
+  protected void constructContentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure, MirLocalizerExc {\r
+    try {\r
+      anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+      anEntityAdapterDefinition.addDBDateField("changedate", "webdb_lastchange", configuration.getString("Mir.DefaultTimezone"));\r
+      anEntityAdapterDefinition.addMirDateField("date", "date", configuration.getString("Mir.DefaultTimezone"));\r
+      anEntityAdapterDefinition.addCalculatedField("to_topics", new ContentToTopicsField());\r
+      anEntityAdapterDefinition.addCalculatedField("to_comments", new ContentToCommentsField());\r
+      anEntityAdapterDefinition.addCalculatedField("language", new ContentToLanguageField());\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("commentcount", new ContentCommentCountField(" and is_published='1'"));\r
+      anEntityAdapterDefinition.addCalculatedField("fullcommentcount", new ContentCommentCountField(""));\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new ContentToMediaField( "uploadedMedia" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_images",  new ContentToMediaField( "image" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_audio", new ContentToMediaField( "audio" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_video", new ContentToMediaField( "video" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_other", new ContentToMediaField( "otherMedia" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new ContentToMediaField( "uploadedMedia", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_images",  new ContentToMediaField( "image", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new ContentToMediaField( "audio", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new ContentToMediaField( "video", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new ContentToMediaField( "otherMedia", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_icon", new ContentToIconField());\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("article_type", new ContentToArticleTypeField());\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));\r
+      anEntityAdapterDefinition.addCalculatedField("content_data_parsed", new FilteredField("content_data"));\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("children", new ContentToChildrenField());\r
+      anEntityAdapterDefinition.addCalculatedField("parent", new ContentToParentField());\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Article.PublicUrl")));\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("operations",\r
+          new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleArticleOperations()));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new MirLocalizerFailure(t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+  protected void constructCommentAdapterDefinition(EntityAdapterDefinition anEntityAdapterDefinition) throws MirLocalizerFailure {\r
+    try {\r
+      anEntityAdapterDefinition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+      anEntityAdapterDefinition.addCalculatedField("to_content", new CommentToContentField());\r
+      anEntityAdapterDefinition.addCalculatedField("status", new CommentToStatusField());\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("to_uploaded_media", new CommentToMediaField( "uploadedMedia" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_images",  new CommentToMediaField( "image" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_audio", new CommentToMediaField( "audio" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_video", new CommentToMediaField( "video" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_media_other", new CommentToMediaField( "otherMedia" ));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_uploaded_media", new CommentToMediaField( "uploadedMedia", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_images",  new CommentToMediaField( "image", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_audio", new CommentToMediaField( "audio", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_video", new CommentToMediaField( "video", false));\r
+      anEntityAdapterDefinition.addCalculatedField("to_all_media_other", new CommentToMediaField( "otherMedia", false));\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("publicurl", new ExpandedField(configuration.getString("Comment.PublicUrl")));\r
+\r
+      anEntityAdapterDefinition.addCalculatedField("description_parsed", new FilteredField("description"));\r
+      anEntityAdapterDefinition.addCalculatedField("operations",\r
+          new EntityToSimpleOperationsField(MirGlobal.localizer().adminInterface().simpleCommentOperations()));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new MirLocalizerFailure(t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+  public EntityAdapterModel adapterModel() throws MirLocalizerFailure, MirLocalizerExc {\r
+    EntityAdapterModel result = new EntityAdapterModel();\r
+\r
+    try {\r
+      EntityAdapterDefinition definition;\r
+\r
+      definition = new EntityAdapterDefinition();\r
+      constructContentAdapterDefinition( definition );\r
+      result.addMapping( "content", DatabaseContent.getInstance(), definition);\r
+\r
+      definition = new EntityAdapterDefinition();\r
+      constructCommentAdapterDefinition( definition );\r
+      result.addMapping( "comment", DatabaseComment.getInstance(), definition);\r
+\r
+      result.addMapping( "articleType", DatabaseArticleType.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "commentStatus", DatabaseCommentStatus.getInstance(), new EntityAdapterDefinition());\r
+\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+      result.addMapping( "breakingNews", DatabaseBreaking.getInstance(), definition);\r
+\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addDBDateField("creationdate", "webdb_create", configuration.getString("Mir.DefaultTimezone"));\r
+      result.addMapping( "internalMessage", DatabaseMessages.getInstance(), definition);\r
+\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+      result.addMapping( "uploadedMedia", DatabaseUploadedMedia.getInstance(), definition);\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+      result.addMapping( "image", DatabaseImages.getInstance(), definition);\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+      result.addMapping( "audio", DatabaseAudio.getInstance(), definition);\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+      result.addMapping( "video", DatabaseVideo.getInstance(), definition);\r
+      definition = new EntityAdapterDefinition();\r
+      definition.addCalculatedField("mediafolder", new MediaToMediaFolderField());\r
+      result.addMapping( "otherMedia", DatabaseOther.getInstance(), definition);\r
+\r
+\r
+      result.addMapping( "mediaFolder", DatabaseMediafolder.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "imageType", DatabaseImageType.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "language", DatabaseLanguage.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "mediaType", DatabaseMediaType.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "topic", DatabaseTopics.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "user", DatabaseUsers.getInstance(), new EntityAdapterDefinition());\r
+      result.addMapping( "otherMedia", DatabaseOther.getInstance(), new EntityAdapterDefinition());\r
+\r
+      result.addMapping( "content_x_topic", DatabaseContentToTopics.getInstance(), new EntityAdapterDefinition());\r
+\r
+    }\r
+    catch (Throwable t) {\r
+      throw new MirLocalizerFailure(t.getMessage(), t);\r
+    }\r
+\r
+    return result;\r
+  }\r
+\r
+  protected class CommentToContentField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getToOneRelation(\r
+                    "id="+anEntityAdapter.get("to_media"),\r
+                    "id",\r
+                    "content" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class CommentToStatusField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getToOneRelation(\r
+                    "id="+anEntityAdapter.get("to_comment_status"),\r
+                    "id",\r
+                    "commentStatus" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class EntityToSimpleOperationsField implements EntityAdapterDefinition.CalculatedField {\r
+    private List operations;\r
+\r
+    public EntityToSimpleOperationsField(List anOperations) {\r
+      operations = anOperations;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        Iterator i = operations.iterator();\r
+        List availableOperations = new Vector();\r
+\r
+        while (i.hasNext()) {\r
+          MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation =\r
+            (MirAdminInterfaceLocalizer.MirSimpleEntityOperation) i.next();\r
+\r
+          if (operation.isAvailable(anEntityAdapter)) {\r
+            availableOperations.add(operation.getName());\r
+          }\r
+        };\r
+\r
+        return availableOperations;\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class FilteredField implements EntityAdapterDefinition.CalculatedField {\r
+    private String fieldName;\r
+\r
+    public FilteredField(String aFieldName) {\r
+      fieldName = aFieldName;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        if (anEntityAdapter.get("is_html")!=null && anEntityAdapter.get("is_html").equals("1")) {\r
+          return MirGlobal.localizer().producerAssistant().filterHTMLText((String) anEntityAdapter.get(fieldName));\r
+        }\r
+        else {\r
+          return MirGlobal.localizer().producerAssistant().filterNonHTMLText((String) anEntityAdapter.get(fieldName));\r
+        }\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class StructuredContentField implements EntityAdapterDefinition.CalculatedField {\r
+    private String expression;\r
+\r
+    public StructuredContentField(String anExpression) {\r
+      expression = anExpression;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return StructuredContentParser.parse(ParameterExpander.evaluateStringExpression(anEntityAdapter, expression));\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ExpandedField implements EntityAdapterDefinition.CalculatedField {\r
+    private String expression;\r
+\r
+    public ExpandedField(String anExpression) {\r
+      expression = anExpression;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return ParameterExpander.expandExpression(anEntityAdapter, expression);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class EvaluatedField implements EntityAdapterDefinition.CalculatedField {\r
+    private String expression;\r
+\r
+    public EvaluatedField(String anExpression) {\r
+      expression = anExpression;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return ParameterExpander.evaluateExpression(anEntityAdapter, expression);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToParentField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        logger.debug("ContentToParentField.getValue");\r
+        return anEntityAdapter.getToOneRelation(\r
+                    "id="+anEntityAdapter.get("to_content"),\r
+                    "id",\r
+                    "content" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToChildrenField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getRelation(\r
+                    "to_content="+anEntityAdapter.get("id"),\r
+                    "id",\r
+                    "content" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToLanguageField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getToOneRelation(\r
+                    "id="+anEntityAdapter.get("to_language"),\r
+                    "id",\r
+                    "language" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToArticleTypeField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getToOneRelation(\r
+                    "id="+anEntityAdapter.get("to_article_type"),\r
+                    "id",\r
+                    "articleType" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class MediaToMediaFolderField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getToOneRelation(\r
+                    "id="+anEntityAdapter.get("to_media_folder"),\r
+                    "id",\r
+                    "mediaFolder" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToCommentsField implements EntityAdapterDefinition.CalculatedField {\r
+    private String extracondition;\r
+    private String order;\r
+\r
+    public ContentToCommentsField() {\r
+      this ( " and is_published='1'", "webdb_create");\r
+    }\r
+\r
+    public ContentToCommentsField(String anExtraCondition, String anOrder) {\r
+      order = anOrder;\r
+      extracondition = anExtraCondition;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return anEntityAdapter.getRelation(\r
+                    "to_media="+anEntityAdapter.get("id")+" " + extracondition,\r
+                    order,\r
+                    "comment" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToTopicsField implements EntityAdapterDefinition.CalculatedField {\r
+    private String topicCondition;\r
+\r
+    public ContentToTopicsField() {\r
+      this(null);\r
+    }\r
+\r
+    public ContentToTopicsField(String aTopicCondition) {\r
+      topicCondition = aTopicCondition;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        String condition = "exists (select * from content_x_topic where content_id="+anEntityAdapter.get("id")+" and topic_id=id)";\r
+        if (topicCondition!=null && topicCondition.length()>0)\r
+          condition = "(" + topicCondition + ") and " + condition;\r
+\r
+        return anEntityAdapter.getRelation(\r
+                    condition,\r
+                    "title",\r
+                    "topic" );\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToMediaField implements EntityAdapterDefinition.CalculatedField {\r
+    private String definition;\r
+    private boolean published;\r
+\r
+    public ContentToMediaField(String aDefinition, boolean anOnlyPublished) {\r
+      definition = aDefinition;\r
+      published = anOnlyPublished;\r
+    }\r
+\r
+    public ContentToMediaField(String aDefinition) {\r
+      this(aDefinition, true);\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        String condition = "exists (select * from content_x_media where content_id="+anEntityAdapter.get("id")+" and media_id=id)";\r
+        if (published)\r
+          condition = "is_published='t' and " + condition;\r
+        return anEntityAdapter.getRelation(\r
+           condition,\r
+          "id",\r
+          definition);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class CommentToMediaField implements EntityAdapterDefinition.CalculatedField {\r
+    private String definition;\r
+    private boolean published;\r
+\r
+    public CommentToMediaField(String aDefinition, boolean anOnlyPublished) {\r
+      definition = aDefinition;\r
+      published = anOnlyPublished;\r
+    }\r
+\r
+    public CommentToMediaField(String aDefinition) {\r
+      this(aDefinition, true);\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        String condition = "exists (select * from comment_x_media where comment_id="+anEntityAdapter.get("id")+" and media_id=id)";\r
+        if (published)\r
+          condition = "is_published='t' and " + condition;\r
+        return anEntityAdapter.getRelation(\r
+           condition,\r
+          "id",\r
+          definition);\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentToIconField implements EntityAdapterDefinition.CalculatedField {\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      EntityAdapter media;\r
+      Entity mediaType;\r
+      RewindableIterator iterator;\r
+      Map result;\r
+      MirMedia mediaHandler;\r
+      String tinyIcon;\r
+      String iconAlt;\r
+\r
+      try {\r
+        iterator = (RewindableIterator) (anEntityAdapter.get("to_uploaded_media"));\r
+        iterator.rewind();\r
+\r
+        tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyText");\r
+        iconAlt = "Text";\r
+\r
+        if (iterator.hasNext()) {\r
+          media = (EntityAdapter) iterator.next();\r
+\r
+          mediaType = ((EntityUploadedMedia) (media.getEntity())).getMediaType();\r
+          mediaHandler = MediaHelper.getHandler( mediaType );\r
+\r
+          if (mediaHandler.isVideo()) {\r
+            tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyVideo");\r
+            iconAlt = "Video";\r
+          }\r
+          else if (mediaHandler.isAudio()) {\r
+            tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyAudio");\r
+            iconAlt = "Audio";\r
+          }\r
+          else if (mediaHandler.isImage()) {\r
+            tinyIcon = MirGlobal.config().getString("Producer.Icon.TinyImage");\r
+            iconAlt = "Image";\r
+          }\r
+          else {\r
+            tinyIcon = mediaHandler.getTinyIconName();\r
+            iconAlt = mediaHandler.getIconAltName();\r
+          }\r
+\r
+        }\r
+      }\r
+      catch (Throwable t) {\r
+        logger.error("ContentToIconField: " +t.getMessage());\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+\r
+      result = new HashMap();\r
+      result.put("tiny_icon", MirGlobal.config().getString("Producer.ImageRoot") + "/" + tinyIcon);\r
+      result.put("icon_alt", iconAlt);\r
+\r
+      return result;\r
+    }\r
+  }\r
+\r
+  protected class ContentCommentCountField implements EntityAdapterDefinition.CalculatedField {\r
+    private String extraCondition;\r
+\r
+    public ContentCommentCountField(String anExtraCondition) {\r
+      super();\r
+\r
+      extraCondition = anExtraCondition;\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        return Integer.toString(\r
+            DatabaseComment.getInstance().getSize(\r
+                  "to_media="+anEntityAdapter.get("id")+" " + extraCondition));\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+\r
+  protected class ContentMediaCountField implements EntityAdapterDefinition.CalculatedField {\r
+    private String table;\r
+    private boolean published;\r
+\r
+    public ContentMediaCountField(String aTable, boolean anOnlyPublished) {\r
+      table = aTable;\r
+      published = anOnlyPublished;\r
+    }\r
+\r
+    public ContentMediaCountField(String aTable) {\r
+      this(aTable, true);\r
+    }\r
+\r
+    public Object getValue(EntityAdapter anEntityAdapter) {\r
+      try {\r
+        String subQuery = "select * from "+table+" where id = media_id";\r
+        if (published)\r
+          subQuery = subQuery + " and is_published='t'";\r
+\r
+        return Integer.toString(\r
+            DatabaseContentToMedia.getInstance().getSize(\r
+                  "exists ("+subQuery+")"));\r
+      }\r
+      catch (Throwable t) {\r
+        throw new RuntimeException(t.getMessage());\r
+      }\r
+    }\r
+  }\r
+}\r
index ad8d238..9210a46 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.localizer.basic;
@@ -53,7 +53,7 @@ public class MirBasicLocalizer implements MirLocalizer {
     return new MirBasicOpenPostingLocalizer();
   }
 
-  public MirProducerAssistantLocalizer producerAssistant() {
+  public MirProducerAssistantLocalizer producerAssistant() throws MirLocalizerFailure, MirLocalizerExc {
     return new MirBasicProducerAssistantLocalizer();
   }
 
index 637f4ac..14ba032 100755 (executable)
@@ -29,7 +29,7 @@
  */
 package mircoders.localizer.basic;
 
-import java.util.List;
+import java.util.*;
 import java.util.Random;
 
 import mir.config.MirPropertiesConfiguration;
@@ -41,13 +41,15 @@ import mircoders.entity.EntityComment;
 import mircoders.entity.EntityContent;
 import mircoders.global.MirGlobal;
 import mircoders.global.ProducerEngine;
-import mircoders.localizer.MirLocalizerExc;
+import mircoders.localizer.*;
 import mircoders.localizer.MirLocalizerFailure;
 import mircoders.localizer.MirOpenPostingLocalizer;
 
 public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
   private List afterContentProducerTasks;
   private List afterCommentProducerTasks;
+  private List filterTypes;
+  private Map filterTypesMap;
   protected LoggerWrapper logger;
   protected MirPropertiesConfiguration configuration;
 
@@ -73,6 +75,12 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
 
       throw new MirLocalizerFailure(t);
     }
+
+    filterTypes = new Vector();
+    filterTypesMap = new HashMap();
+
+    addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.RegularExpressionFilter("regexp"));
+    addSimpleAntiAbuseFilterType(new MirBasicAntiAbuseFilterTypes.IPFilter("ip"));
   }
 
   public SessionHandler getOpenSessionHandler(String aSessionType) {
@@ -122,4 +130,18 @@ public class MirBasicOpenPostingLocalizer implements MirOpenPostingLocalizer {
     return returnString.substring(5);
   }
 
+  public List getAntiAbuseFilterTypes() {
+    return filterTypes;
+  }
+
+  public void removeSimpleAntiAbuseFilterType(String aName) {
+    filterTypes.remove(filterTypesMap.get(aName));
+    filterTypesMap.remove(aName);
+  }
+
+  public void addSimpleAntiAbuseFilterType(MirAntiAbuseFilterType aFilterType) {
+    removeSimpleAntiAbuseFilterType(aFilterType.getName());
+    filterTypesMap.put(aFilterType.getName(), aFilterType);
+    filterTypes.add(aFilterType);
+  }
 }
index 08a7f57..ed0a12d 100755 (executable)
@@ -29,7 +29,6 @@
  */
 package mircoders.localizer.basic;
 
-import java.util.Arrays;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -46,6 +45,8 @@ import mir.session.SessionExc;
 import mir.session.SessionFailure;
 import mir.session.SessionHandler;
 import mir.session.UploadedFile;
+import mir.session.ValidationError;
+import mir.session.ValidationHelper;
 import mir.storage.StorageObject;
 import mir.util.ExceptionFunctions;
 import mircoders.global.MirGlobal;
@@ -258,116 +259,6 @@ public abstract class MirBasicPostingSessionHandler implements SessionHandler {
     }
   }
 
-  /**
-   * Class that represents a validation error
-   *
-   * <p>Title: </p>
-   * <p>Description: </p>
-   * <p>Copyright: Copyright (c) 2003</p>
-   * <p>Company: </p>
-   * @author not attributable
-   * @version 1.0
-   */
-
-  public class ValidationError {
-    private String field;
-    private String message;
-    private List parameters;
-
-    public ValidationError(String aField, String aMessage) {
-      this (aField, aMessage, new String[] {});
-    }
-
-    public ValidationError(String aField, String aMessage, Object aParameter) {
-      this (aField, aMessage, new Object[] {aParameter});
-    }
-
-    public ValidationError(String aField, String aMessage, Object[] aParameters) {
-      field = aField;
-      message = aMessage;
-      parameters = Arrays.asList(aParameters);
-    }
-
-    public String getMessage() {
-      return message;
-    }
-
-    public String getField() {
-      return field;
-    }
-
-    public List getParameters() {
-      return parameters;
-    }
-  }
-
-  /**
-   * Convenience validation method to test wether a field has been filled in
-   *
-   * @param aRequest
-   * @param aFieldName
-   * @param anErrorMessageResource
-   * @param aValidationResults
-   * @return
-   */
-
-  protected boolean testFieldEntered(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
-    Object value = aRequest.getParameter(aFieldName);
-    if (value==null || !(value instanceof String) || ((String) value).trim().length()==0) {
-      aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
-      return false;
-    }
-    else
-      return true;
-  }
-
-  /**
-   * Convenience validation method to test wether a field is numeric
-
-   * @param aRequest
-   * @param aFieldName
-   * @param anErrorMessageResource
-   * @param aValidationResults
-   * @return
-   */
-
-  protected boolean testFieldIsNumeric(Request aRequest, String aFieldName, String anErrorMessageResource, List aValidationResults) {
-    Object value = aRequest.getParameter(aFieldName);
-    if (value!=null) {
-      try {
-        Integer.parseInt((String) value);
-        return true;
-      }
-      catch (Throwable t) {
-        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
-        return false;
-      }
-    }
-    return true;
-  }
-
-  /**
-   * Convenience validation method to test wether a field is numeric
-
-   * @param aRequest
-   * @param aFieldName
-   * @param anErrorMessageResource
-   * @param aValidationResults
-   * @return
-   */
-
-  protected boolean testFieldLength(Request aRequest, String aFieldName, int aMaxLength, String anErrorMessageResource, List aValidationResults) {
-    String value = aRequest.getParameter(aFieldName);
-
-    if (value!=null) {
-      if (value.length()>aMaxLength) {
-        aValidationResults.add(new ValidationError(aFieldName, anErrorMessageResource));
-        return false;
-      }
-      else return true;
-    }
-    return true;
-  }
 
   /**
    * Method to generate a one-time password
index 253ed1d..f3a8eaa 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.localizer.basic;
-
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.adapter.EntityAdapter;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.util.DateToMapAdapter;
-import mir.util.GeneratorExpressionFunctions;
-import mir.util.GeneratorHTMLFunctions;
-import mir.util.GeneratorIntegerFunctions;
-import mir.util.GeneratorListFunctions;
-import mir.util.GeneratorStringFunctions;
-import mircoders.global.MirGlobal;
-import mircoders.localizer.MirProducerAssistantLocalizer;
-
-public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {
-  protected LoggerWrapper logger;
-
-  public void initializeGenerationValueSet(Map aValueSet) {
-    try {
-      Iterator i;
-
-      Map configMap = new HashMap();
-      Map utilityMap = new HashMap();
-
-      logger = new LoggerWrapper("Localizer.ProducerAssistant");
-
-// obsolete:
-      configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));
-      configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));
-      configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));
-      configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));
-      configMap.put("docRoot", MirGlobal.config().getString("RootUri"));
-      configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");
-      configMap.put("now", new DateToMapAdapter( (new GregorianCalendar()).getTime()));
-      configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));
-      configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));
-      configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));
-      configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));
-      configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));
-      configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));
-
-// "new":
-      configMap.putAll(MirPropertiesConfiguration.instance().allSettings());
-
-      utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace());
-      utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction());
-      utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction());
-      utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction());
-      utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction());
-      utilityMap.put("subList", new GeneratorListFunctions.subListFunction());
-      utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction());
-      utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction());
-      utilityMap.put("evaluate", new GeneratorExpressionFunctions.evaluateExpressionFunction());
-
-      aValueSet.put("config", configMap);
-      aValueSet.put("utility", utilityMap);
-
-      aValueSet.put("languages",
-        new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));
-
-      aValueSet.put("topics",
-        new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
-
-      Map articleTypeMap = new HashMap();
-      articleTypeMap.put("openposting", "0");
-      articleTypeMap.put("newswire", "1");
-      articleTypeMap.put("feature", "2");
-      articleTypeMap.put("topicspecial", "3");
-      articleTypeMap.put("startspecial", "4");
-
-      i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");
-      while (i.hasNext()) {
-        EntityAdapter articleType = (EntityAdapter) i.next();
-
-        articleTypeMap.put(articleType.get("name"), articleType.get("id"));
-      }
-      aValueSet.put("articletype", articleTypeMap);
-
-      Map commentStatusMap = new HashMap();
-      i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");
-      while (i.hasNext()) {
-        EntityAdapter commentStatus = (EntityAdapter) i.next();
-
-        commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));
-      }
-      aValueSet.put("commentstatus", commentStatusMap);
-    }
-    catch (Throwable t) {
-      logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());
-      throw new RuntimeException(t.getMessage());
-    }
-
-  };
-
-  public String filterNonHTMLText(String aText) {
-    return StringUtil.createHTML(
-        StringUtil.removeHTMLTags(aText),
-        MirGlobal.config().getString("Producer.ImageRoot"),
-        MirGlobal.config().getString("Producer.MailLinkName"),
-        MirGlobal.config().getString("Producer.ExtLinkName"),
-        MirGlobal.config().getString("Producer.IntLinkName")
-    );
-  }
-
-  public String filterHTMLText(String aText) {
-    return StringUtil.deleteForbiddenTags(aText);
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.localizer.basic;\r
+\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.Map;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.util.GeneratorDateTimeFunctions;\r
+import mir.util.GeneratorExpressionFunctions;\r
+import mir.util.GeneratorFormatAdapters;\r
+import mir.util.GeneratorHTMLFunctions;\r
+import mir.util.GeneratorIntegerFunctions;\r
+import mir.util.GeneratorListFunctions;\r
+import mir.util.GeneratorRegularExpressionFunctions;\r
+import mir.util.GeneratorStringFunctions;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.localizer.MirLocalizerExc;\r
+import mircoders.localizer.MirLocalizerFailure;\r
+import mircoders.localizer.MirProducerAssistantLocalizer;\r
+\r
+public class MirBasicProducerAssistantLocalizer implements MirProducerAssistantLocalizer {\r
+  protected LoggerWrapper logger;\r
+\r
+  public void initializeGenerationValueSet(Map aValueSet) throws MirLocalizerExc, MirLocalizerFailure  {\r
+    try {\r
+      Iterator i;\r
+\r
+      Map configMap = new HashMap();\r
+      Map utilityMap = new HashMap();\r
+\r
+      logger = new LoggerWrapper("Localizer.ProducerAssistant");\r
+\r
+// obsolete:\r
+      configMap.put("producerDocRoot", MirGlobal.config().getString("Producer.DocRoot"));\r
+      configMap.put("storageRoot", MirGlobal.config().getString("Producer.StorageRoot"));\r
+      configMap.put("productionHost", MirGlobal.config().getString("Producer.ProductionHost"));\r
+      configMap.put("openAction", MirGlobal.config().getString("Producer.OpenAction"));\r
+      configMap.put("docRoot", MirGlobal.config().getString("RootUri"));\r
+      configMap.put("actionRoot", MirGlobal.config().getString("RootUri") + "/servlet/Mir");\r
+      configMap.put("now", new GeneratorFormatAdapters.DateFormatAdapter(new GregorianCalendar().getTime(), MirGlobal.config().getString("Mir.DefaultTimezone")));\r
+      configMap.put("videoHost", MirGlobal.config().getString("Producer.Video.Host"));\r
+      configMap.put("audioHost", MirGlobal.config().getString("Producer.Audio.Host"));\r
+      configMap.put("imageHost", MirGlobal.config().getString("Producer.Image.Host"));\r
+      configMap.put("imagePath", MirGlobal.config().getString("Producer.Image.Path"));\r
+      configMap.put("mirVersion", MirGlobal.config().getString("Mir.Version"));\r
+      configMap.put("defEncoding", MirGlobal.config().getString("Mir.DefaultEncoding"));\r
+\r
+// "new":\r
+      configMap.putAll(MirPropertiesConfiguration.instance().allSettings());\r
+\r
+      utilityMap.put("compressWhitespace", new freemarker.template.utility.CompressWhitespace());\r
+      utilityMap.put("encodeHTML", new GeneratorHTMLFunctions.encodeHTMLGeneratorFunction());\r
+      utilityMap.put("encodeXML", new GeneratorHTMLFunctions.encodeXMLGeneratorFunction());\r
+      utilityMap.put("encodeURI", new GeneratorHTMLFunctions.encodeURIGeneratorFunction());\r
+      utilityMap.put("subString", new GeneratorStringFunctions.subStringFunction());\r
+      utilityMap.put("subList", new GeneratorListFunctions.subListFunction());\r
+      utilityMap.put("isOdd", new GeneratorIntegerFunctions.isOddFunction());\r
+      utilityMap.put("increment", new GeneratorIntegerFunctions.incrementFunction());\r
+      utilityMap.put("evaluate", new GeneratorExpressionFunctions.evaluateExpressionFunction());\r
+      utilityMap.put("constructString", new GeneratorStringFunctions.constructStructuredStringFunction());\r
+      utilityMap.put("escapeJDBCString", new GeneratorStringFunctions.jdbcStringEscapeFunction());\r
+      utilityMap.put("regexpreplace", new GeneratorRegularExpressionFunctions.regularExpressionReplaceFunction());\r
+      utilityMap.put("datetime", new GeneratorDateTimeFunctions.DateTimeFunctions(\r
+          MirPropertiesConfiguration.instance().getString("Mir.DefaultTimezone")));\r
+\r
+      aValueSet.put("config", configMap);\r
+      aValueSet.put("utility", utilityMap);\r
+\r
+      aValueSet.put("languages",\r
+        new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "language"));\r
+\r
+      aValueSet.put("topics",\r
+        new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
+\r
+      Map articleTypeMap = new HashMap();\r
+      articleTypeMap.put("openposting", "0");\r
+      articleTypeMap.put("newswire", "1");\r
+      articleTypeMap.put("feature", "2");\r
+      articleTypeMap.put("topicspecial", "3");\r
+      articleTypeMap.put("startspecial", "4");\r
+\r
+      i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "articleType");\r
+      while (i.hasNext()) {\r
+        EntityAdapter articleType = (EntityAdapter) i.next();\r
+\r
+        articleTypeMap.put(articleType.get("name"), articleType.get("id"));\r
+      }\r
+      aValueSet.put("articletype", articleTypeMap);\r
+\r
+      Map commentStatusMap = new HashMap();\r
+      i = new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "commentStatus");\r
+      while (i.hasNext()) {\r
+        EntityAdapter commentStatus = (EntityAdapter) i.next();\r
+\r
+        commentStatusMap.put(commentStatus.get("name"), commentStatus.get("id"));\r
+      }\r
+      aValueSet.put("commentstatus", commentStatusMap);\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error("initializeGenerationValueSet: Exception while collecting comment statuses" + t.getMessage());\r
+      throw new RuntimeException(t.getMessage());\r
+    }\r
+\r
+  };\r
+\r
+  public String filterNonHTMLText(String aText) {\r
+\r
+    logger.debug("about to filter non HTML Text of length " + aText.length());\r
+    try {\r
+      String result =\r
+          StringUtil.createHTML(\r
+          StringUtil.removeHTMLTags(aText),\r
+          MirGlobal.config().getString("Producer.ImageRoot"),\r
+          MirGlobal.config().getString("Producer.MailLinkName"),\r
+          MirGlobal.config().getString("Producer.ExtLinkName"),\r
+          MirGlobal.config().getString("Producer.IntLinkName")\r
+          );\r
+      logger.debug("done filtering non-HTML text ");\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      logger.error("error while filtering non-HTML text: " + t.toString());\r
+\r
+      throw new RuntimeException(t.toString());\r
+    }\r
+  }\r
+\r
+  public String filterHTMLText(String aText) {\r
+    return StringUtil.deleteForbiddenTags(aText);\r
+  }\r
+}\r
index c839eab..01e1e9f 100755 (executable)
@@ -30,7 +30,7 @@
 
 package  mircoders.media;
 
-import mir.media.*;
+import mir.media.MirMedia;
 
 /**
  * Handles audio media, like mp3 and maybe it could also handle some other.
@@ -39,7 +39,7 @@ import mir.media.*;
  * @see mir.media.MediaHandlerGeneric
  * @see mir.media.MirMedia
  * @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerAudio.java,v 1.10 2003/06/15 22:59:21 idfx Exp $
+ * @version $Id: MediaHandlerAudio.java,v 1.11 2003/09/03 18:29:04 zapata Exp $
  */
 
 public class MediaHandlerAudio extends MediaHandlerGeneric implements MirMedia
index ecc7fe9..0661917 100755 (executable)
@@ -32,6 +32,8 @@ package  mircoders.media;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.InputStream;
+import java.util.List;
+import java.util.Vector;
 import javax.servlet.ServletContext;
 
 import freemarker.template.SimpleList;
@@ -64,7 +66,7 @@ import mir.misc.StringUtil;
  *
  * @see mir.media.MirMedia
  * @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerGeneric.java,v 1.21 2003/06/15 22:59:21 idfx Exp $
+ * @version $Id: MediaHandlerGeneric.java,v 1.22 2003/09/03 18:29:04 zapata Exp $
  */
 
 public class MediaHandlerGeneric implements MirMedia
@@ -79,7 +81,7 @@ public class MediaHandlerGeneric implements MirMedia
       try {
         configuration = MirPropertiesConfiguration.instance();
       }
-      catch (PropertiesConfigExc e) {
+      catch (MirPropertiesConfiguration.PropertiesConfigExc e) {
       }
       imageHost = configuration.getString("Producer.Image.Host");
       imageRoot = configuration.getString("Producer.ImageRoot");
@@ -178,9 +180,9 @@ public class MediaHandlerGeneric implements MirMedia
         return "Generic media";
     }
 
-    public SimpleList getURL(Entity ent, Entity mediaTypeEnt)
+    public List getURL(Entity ent, Entity mediaTypeEnt)
     {
-      SimpleList theList = new SimpleList();
+      List theList = new Vector();
       theList.add(ent);
       return theList;
     }
index 210ad37..babce6c 100755 (executable)
@@ -31,6 +31,7 @@ package mircoders.media;
 
 import java.io.File;
 import java.io.InputStream;
+import java.util.*;
 
 import mir.config.MirPropertiesConfiguration;
 import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
@@ -42,7 +43,6 @@ import mir.media.MirMedia;
 import mir.misc.FileUtil;
 import mir.misc.StringUtil;
 import mircoders.entity.EntityImages;
-import freemarker.template.SimpleList;
 
 /**
  * This class handles saving, fetching creating representations
@@ -58,7 +58,7 @@ import freemarker.template.SimpleList;
  *
  * @see mir.media.MirMedia
  * @author mh
- * @version $Id: MediaHandlerImages.java,v 1.23 2003/04/30 00:37:27 zapata Exp $
+ * @version $Id: MediaHandlerImages.java,v 1.24 2003/09/03 18:29:04 zapata Exp $
  */
 
 
@@ -161,8 +161,8 @@ public abstract class MediaHandlerImages implements MirMedia
     return in;
   }
 
-  public SimpleList getURL(Entity ent, Entity mediaTypeEnt) {
-    SimpleList theList = new SimpleList();
+  public List getURL(Entity ent, Entity mediaTypeEnt) {
+    List theList = new Vector();
     theList.add(ent);
     return theList;
   }
index 2d24e83..4d15ba9 100755 (executable)
@@ -40,6 +40,8 @@ import mir.log.LoggerWrapper;
 import mir.media.MediaExc;
 import mir.media.MediaFailure;
 import mir.misc.StringUtil;
+import mircoders.storage.DatabaseUploadedMedia;
+import mircoders.module.*;
 
 
 /**
@@ -109,6 +111,8 @@ public class MediaHandlerImagesExtern extends MediaHandlerGeneric
         anImageEntity.setValueForProperty("publish_path", filePath);
 
         anImageEntity.update();
+
+
       }
     }
     catch(Throwable t) {
index f69cec8..a1e5c1b 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mircoders.media;
-
-import java.io.StringReader;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.media.MediaExc;
-import mir.media.MediaFailure;
-import mir.media.MirMedia;
-import mir.misc.FileUtil;
-import mir.misc.StringUtil;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-
-/**
- * Please note: this media handler produces
- * 3 media files, the raw .mp3, a .m3u which is
- * contains the URL for the mp3 and a .pls which
- * contains the URL to the mp3 in shoutcast playlist
- * format. What's important is that the web server (of
- * the media host) must recognize the .m3u and .pls file
- * extensions and send the proper "audio/x-mpegurl"
- * and "audio/x-scpls" mime-types respectively.
- * If the web server is apache, it's easy, just
- * add:
- *
- * audio/x-mpegurl                 m3u
- * audio/x-scpl                    pls
- *
- * to the file pointed to by the "TypesConfig"
- * command in your apache config file. Or add
- * and equivalent AddType command to your httpd.conf.
- * Of course this assumes that the mod_mime is loaded.
- *
- * If the web server is not apache, then your on your own.
- *
- * @see mir.media.MirMedia
- * @author mh <mh@nadir.org>
- * @version $Id: MediaHandlerMp3.java,v 1.15 2003/04/21 12:42:48 idfx Exp $
- */
-
-public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia
-{
-  protected LoggerWrapper logger;
-
-  public MediaHandlerMp3() {
-    logger = new LoggerWrapper("Media.Audio.Mp3");
-  }
-
-  public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
-
-    // first check if the file exists
-    super.produce(ent, mediaTypeEnt);
-
-    String baseName = ent.getId();
-    String date = ent.getValue("date");
-    String datePath = StringUtil.webdbDate2path(date);
-    String mp3Pointer = getPublishHost() + ent.getValue("publish_path");
-    String mpegURLFile = baseName + ".m3u";
-    String playlistFile = baseName + ".pls";
-
-    try {
-      //write the "meta" files
-      //first the .m3u since it only contains one line
-      FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile,
-                     new StringReader(mp3Pointer), "US-ASCII");
-      //now the .pls file
-      FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile,
-                     new StringReader(mp3Pointer), "US-ASCII");
-    }
-    catch (Throwable e) {
-      logger.error("MediaHandlerMp3.produce: " + e.toString());
-
-      throw new MediaFailure(e);
-    }
-  }
-
-  public SimpleList getURL(Entity ent, Entity mediaTypeEnt) {
-    SimpleList theList = new SimpleList();
-
-    //String stringSize = ent.getValue("size");
-    //int size = Integer.parseInt(stringSize, 10)/1024;
-    theList.add(ent);
-
-    String basePath = StringUtil.regexpReplace(ent.getValue("publish_path"),
-                                               ".mp3$", "");
-
-    // @todo the texts ("title") below urgently need to be sanely localizaeble
-    // somehow
-    SimpleHash m3uHash = new SimpleHash();
-    m3uHash.put("publish_path", basePath + ".m3u");
-    m3uHash.put("publish_server", ent.getValue("publish_server"));
-    m3uHash.put("title", "stream URL");
-    theList.add(m3uHash);
-
-    SimpleHash plsHash = new SimpleHash();
-    plsHash.put("publish_path", basePath + ".pls");
-    plsHash.put("publish_server", ent.getValue("publish_server"));
-    plsHash.put("title", "playlist URL");
-    theList.add(plsHash);
-
-    return theList;
-
-  }
-
-  public String getDescr(Entity mediaType) {
-    return "mp3";
-  }
-}
-
-
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package  mircoders.media;\r
+\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaExc;\r
+import mir.media.MediaFailure;\r
+import mir.media.MirMedia;\r
+import mir.misc.FileUtil;\r
+import mir.misc.StringUtil;\r
+\r
+/**\r
+ * Please note: this media handler produces\r
+ * 3 media files, the raw .mp3, a .m3u which is\r
+ * contains the URL for the mp3 and a .pls which\r
+ * contains the URL to the mp3 in shoutcast playlist\r
+ * format. What's important is that the web server (of\r
+ * the media host) must recognize the .m3u and .pls file\r
+ * extensions and send the proper "audio/x-mpegurl"\r
+ * and "audio/x-scpls" mime-types respectively.\r
+ * If the web server is apache, it's easy, just\r
+ * add:\r
+ *\r
+ * audio/x-mpegurl                 m3u\r
+ * audio/x-scpl                    pls\r
+ *\r
+ * to the file pointed to by the "TypesConfig"\r
+ * command in your apache config file. Or add\r
+ * and equivalent AddType command to your httpd.conf.\r
+ * Of course this assumes that the mod_mime is loaded.\r
+ *\r
+ * If the web server is not apache, then your on your own.\r
+ *\r
+ * @see mir.media.MirMedia\r
+ * @author mh <mh@nadir.org>\r
+ * @version $Id: MediaHandlerMp3.java,v 1.16 2003/09/03 18:29:04 zapata Exp $\r
+ */\r
+\r
+public class MediaHandlerMp3 extends MediaHandlerAudio implements MirMedia\r
+{\r
+  protected LoggerWrapper logger;\r
+\r
+  public MediaHandlerMp3() {\r
+    logger = new LoggerWrapper("Media.Audio.Mp3");\r
+  }\r
+\r
+  public void produce(Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {\r
+\r
+    // first check if the file exists\r
+    super.produce(ent, mediaTypeEnt);\r
+\r
+    String baseName = ent.getId();\r
+    String date = ent.getValue("date");\r
+    String datePath = StringUtil.webdbDate2path(date);\r
+    String mp3Pointer = getPublishHost() + ent.getValue("publish_path");\r
+    String mpegURLFile = baseName + ".m3u";\r
+    String playlistFile = baseName + ".pls";\r
+\r
+    try {\r
+      //write the "meta" files\r
+      //first the .m3u since it only contains one line\r
+      FileUtil.write(getStoragePath() + "/" + datePath + "/" + mpegURLFile,\r
+                     new StringReader(mp3Pointer), "US-ASCII");\r
+      //now the .pls file\r
+      FileUtil.write(getStoragePath() + "/" + datePath + "/" + playlistFile,\r
+                     new StringReader(mp3Pointer), "US-ASCII");\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("MediaHandlerMp3.produce: " + e.toString());\r
+\r
+      throw new MediaFailure(e);\r
+    }\r
+  }\r
+\r
+  public List getURL(Entity ent, Entity mediaTypeEnt) {\r
+    List theList = new Vector();\r
+\r
+    //String stringSize = ent.getValue("size");\r
+    //int size = Integer.parseInt(stringSize, 10)/1024;\r
+    theList.add(ent);\r
+\r
+    String basePath = StringUtil.regexpReplace(ent.getValue("publish_path"),\r
+                                               ".mp3$", "");\r
+\r
+    // @todo the texts ("title") below urgently need to be sanely localizaeble\r
+    // somehow\r
+    Map m3uHash = new HashMap();\r
+    m3uHash.put("publish_path", basePath + ".m3u");\r
+    m3uHash.put("publish_server", ent.getValue("publish_server"));\r
+    m3uHash.put("title", "stream URL");\r
+    theList.add(m3uHash);\r
+\r
+    Map plsHash = new HashMap();\r
+    plsHash.put("publish_path", basePath + ".pls");\r
+    plsHash.put("publish_server", ent.getValue("publish_server"));\r
+    plsHash.put("title", "playlist URL");\r
+    theList.add(plsHash);\r
+\r
+    return theList;\r
+\r
+  }\r
+\r
+  public String getDescr(Entity mediaType) {\r
+    return "mp3";\r
+  }\r
+}\r
+\r
+\r
+\r
index 62dc5a2..0623106 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mircoders.media;
-
-import java.io.StringReader;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.media.MediaExc;
-import mir.media.MediaFailure;
-import mir.media.MirMedia;
-import mir.misc.FileUtil;
-import mir.misc.StringUtil;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-
-
-
-/**
- * Handles realAudio .it manages the ram file.
- *
- * 03.2002 - reworked Realmedia handling. -mh
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
- * @author john <john@manifestor.org>, mh <heckmann@hbe.ca>
- * @version $Id: MediaHandlerRealAudio.java,v 1.19 2003/04/21 12:42:48 idfx Exp $
- */
-
-
-public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia
-{
-  public MediaHandlerRealAudio() {
-    logger = new LoggerWrapper("Media.Audio.Real");
-  }
-
-  public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure {
-
-    // first see if the file exists
-    super.produce(ent, mediaTypeEnt);
-
-    String baseName = ent.getId();
-    String date = ent.getValue("date");
-    String datePath = StringUtil.webdbDate2path(date);
-    String rtspDir = configuration.getString("Producer.RealMedia.Path");
-    String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");
-
-    String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path");
-    String RealMediaFile = datePath+ent.getId()+".ram";
-    try {
-      //write an rm (ram?. -mh) file
-      FileUtil.write(super.getStoragePath()+"/"+RealMediaFile,
-                      new StringReader(RealMediaPointer), "US-ASCII");
-    }
-    catch (Throwable e) {
-      logger.error("MediaHandlerRealAudio.produce: " + e.toString());
-      throw new MediaFailure(e);
-    }
-  }
-
-  public SimpleList getURL(Entity ent, Entity mediaTypeEnt)
-  {
-    SimpleList theList = new SimpleList();
-
-    //String stringSize = ent.getValue("size");
-    //int size = Integer.parseInt(stringSize, 10)/1024;
-    theList.add(ent);
-
-    String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"),
-                                            ".ra$","");
-
-    // @todo the texts ("title") below urgently need to be sanely localizaeble
-    // somehow
-    SimpleHash ramHash = new SimpleHash();
-    ramHash.put("publish_path", basePath+".ram");
-    ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));
-    ramHash.put("title", "stream URL");
-    theList.add(ramHash);
-
-    return theList;
-  }
-
-  public String getStoragePath()
-  {
-    return configuration.getString("Producer.RealMedia.Path");
-  }
-
-  public String getDescr(Entity mediaType)
-  {
-    return "RealMedia";
-  }
-
-  public String getPublishHost()
-  {
-    return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));
-  }
-
-}
-
-
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package  mircoders.media;\r
+\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaExc;\r
+import mir.media.MediaFailure;\r
+import mir.media.MirMedia;\r
+import mir.misc.FileUtil;\r
+import mir.misc.StringUtil;\r
+\r
+\r
+\r
+/**\r
+ * Handles realAudio .it manages the ram file.\r
+ *\r
+ * 03.2002 - reworked Realmedia handling. -mh\r
+ *\r
+ * @see mir.media.MediaHandlerGeneric\r
+ * @see mir.media.MirMedia\r
+ * @author john <john@manifestor.org>, mh <heckmann@hbe.ca>\r
+ * @version $Id: MediaHandlerRealAudio.java,v 1.20 2003/09/03 18:29:04 zapata Exp $\r
+ */\r
+\r
+\r
+public class MediaHandlerRealAudio extends MediaHandlerAudio implements MirMedia\r
+{\r
+  public MediaHandlerRealAudio() {\r
+    logger = new LoggerWrapper("Media.Audio.Real");\r
+  }\r
+\r
+  public void produce (Entity ent, Entity mediaTypeEnt ) throws MediaExc, MediaFailure {\r
+\r
+    // first see if the file exists\r
+    super.produce(ent, mediaTypeEnt);\r
+\r
+    String baseName = ent.getId();\r
+    String date = ent.getValue("date");\r
+    String datePath = StringUtil.webdbDate2path(date);\r
+    String rtspDir = configuration.getString("Producer.RealMedia.Path");\r
+    String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");\r
+\r
+    String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path");\r
+    String RealMediaFile = datePath+ent.getId()+".ram";\r
+    try {\r
+      //write an rm (ram?. -mh) file\r
+      FileUtil.write(super.getStoragePath()+"/"+RealMediaFile,\r
+                      new StringReader(RealMediaPointer), "US-ASCII");\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("MediaHandlerRealAudio.produce: " + e.toString());\r
+      throw new MediaFailure(e);\r
+    }\r
+  }\r
+\r
+  public List getURL(Entity ent, Entity mediaTypeEnt)\r
+  {\r
+    List theList = new Vector();\r
+\r
+    //String stringSize = ent.getValue("size");\r
+    //int size = Integer.parseInt(stringSize, 10)/1024;\r
+    theList.add(ent);\r
+\r
+    String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"),\r
+                                            ".ra$","");\r
+\r
+    // @todo the texts ("title") below urgently need to be sanely localizaeble\r
+    // somehow\r
+    Map ramHash = new HashMap();\r
+    ramHash.put("publish_path", basePath+".ram");\r
+    ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));\r
+    ramHash.put("title", "stream URL");\r
+    theList.add(ramHash);\r
+\r
+    return theList;\r
+  }\r
+\r
+  public String getStoragePath()\r
+  {\r
+    return configuration.getString("Producer.RealMedia.Path");\r
+  }\r
+\r
+  public String getDescr(Entity mediaType)\r
+  {\r
+    return "RealMedia";\r
+  }\r
+\r
+  public String getPublishHost()\r
+  {\r
+    return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));\r
+  }\r
+\r
+}\r
+\r
+\r
+\r
index 947a905..5c702e8 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package  mircoders.media;
-
-import java.io.File;
-import java.io.StringReader;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.media.MediaExc;
-import mir.media.MediaFailure;
-import mir.media.MirMedia;
-import mir.misc.FileUtil;
-import mir.misc.StringUtil;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-
-
-
-/**
- * Handles realVideo .it manages the ram file.
- *
- * 03.2002 - reworked Realmedia handling. -mh
- *
- * @see mir.media.MediaHandlerGeneric
- * @see mir.media.MirMedia
- * @author john <john@manifestor.org>, mh <mh@nadir.org>
- * @version $Id: MediaHandlerRealVideo.java,v 1.19 2003/04/21 12:42:48 idfx Exp $
- */
-
-
-public class MediaHandlerRealVideo extends MediaHandlerVideo implements MirMedia
-{
-  protected LoggerWrapper logger;
-
-  public MediaHandlerRealVideo() {
-    logger = new LoggerWrapper("Media.Video.Real");
-  }
-
-  public void produce (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {
-    // first see if the file exists
-    super.produce(ent, mediaTypeEnt);
-
-    String baseName = ent.getId();
-    String date = ent.getValue("date");
-    String datePath = StringUtil.webdbDate2path(date);
-    String rtspDir = configuration.getString("Producer.RealMedia.Path");
-    String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");
-
-    String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path");
-    String RealMediaFile = datePath+ent.getId()+".ram";
-    try {
-      //write an rm (ram?. -mh) file
-      FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile,
-                      new StringReader(RealMediaPointer), "US-ASCII");
-    }
-    catch (Throwable e) {
-      logger.error("MediaHandlerRealVideo.produce: " + e.toString());
-
-      throw new MediaFailure(e);
-    }
-  }
-
-  public SimpleList getURL(Entity ent, Entity mediaTypeEnt) {
-    SimpleList theList = new SimpleList();
-
-    //String stringSize = ent.getValue("size");
-    //int size = Integer.parseInt(stringSize, 10)/1024;
-    theList.add(ent);
-
-    String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"),
-                                            ".rm$","");
-
-    // @todo the texts ("title") below urgently need to be sanely localizaeble
-    // somehow
-    SimpleHash ramHash = new SimpleHash();
-    ramHash.put("publish_path", basePath+".ram");
-    ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));
-    ramHash.put("title", "stream URL");
-    theList.add(ramHash);
-
-    return theList;
-
-  }
-
-  public String getStoragePath() {
-    return configuration.getString("Producer.RealMedia.Path");
-  }
-
-  public String getDescr(Entity mediaType) {
-    return "RealMedia";
-  }
-
-  public String getPublishHost() {
-    return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));
-  }
-
-}
-
-
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package  mircoders.media;\r
+\r
+import java.io.File;\r
+import java.io.StringReader;\r
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaExc;\r
+import mir.media.MediaFailure;\r
+import mir.media.MirMedia;\r
+import mir.misc.FileUtil;\r
+import mir.misc.StringUtil;\r
+\r
+\r
+\r
+/**\r
+ * Handles realVideo .it manages the ram file.\r
+ *\r
+ * 03.2002 - reworked Realmedia handling. -mh\r
+ *\r
+ * @see mir.media.MediaHandlerGeneric\r
+ * @see mir.media.MirMedia\r
+ * @author john <john@manifestor.org>, mh <mh@nadir.org>\r
+ * @version $Id: MediaHandlerRealVideo.java,v 1.20 2003/09/03 18:29:04 zapata Exp $\r
+ */\r
+\r
+\r
+public class MediaHandlerRealVideo extends MediaHandlerVideo implements MirMedia\r
+{\r
+  protected LoggerWrapper logger;\r
+\r
+  public MediaHandlerRealVideo() {\r
+    logger = new LoggerWrapper("Media.Video.Real");\r
+  }\r
+\r
+  public void produce (Entity ent, Entity mediaTypeEnt) throws MediaExc, MediaFailure {\r
+    // first see if the file exists\r
+    super.produce(ent, mediaTypeEnt);\r
+\r
+    String baseName = ent.getId();\r
+    String date = ent.getValue("date");\r
+    String datePath = StringUtil.webdbDate2path(date);\r
+    String rtspDir = configuration.getString("Producer.RealMedia.Path");\r
+    String rtspMediaHost = configuration.getString("Producer.RealMedia.Host");\r
+\r
+    String RealMediaPointer = rtspMediaHost+ent.getValue("publish_path");\r
+    String RealMediaFile = datePath+ent.getId()+".ram";\r
+    try {\r
+      //write an rm (ram?. -mh) file\r
+      FileUtil.write(super.getStoragePath()+File.separator+RealMediaFile,\r
+                      new StringReader(RealMediaPointer), "US-ASCII");\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("MediaHandlerRealVideo.produce: " + e.toString());\r
+\r
+      throw new MediaFailure(e);\r
+    }\r
+  }\r
+\r
+  public List getURL(Entity ent, Entity mediaTypeEnt) {\r
+    List theList = new Vector();\r
+\r
+    //String stringSize = ent.getValue("size");\r
+    //int size = Integer.parseInt(stringSize, 10)/1024;\r
+    theList.add(ent);\r
+\r
+    String basePath=StringUtil.regexpReplace(ent.getValue("publish_path"),\r
+                                            ".rm$","");\r
+\r
+    // @todo the texts ("title") below urgently need to be sanely localizaeble\r
+    // somehow\r
+    Map ramHash = new HashMap();\r
+    ramHash.put("publish_path", basePath+".ram");\r
+    ramHash.put("publish_server", configuration.getString("Producer.Media.Host"));\r
+    ramHash.put("title", "stream URL");\r
+    theList.add(ramHash);\r
+\r
+    return theList;\r
+\r
+  }\r
+\r
+  public String getStoragePath() {\r
+    return configuration.getString("Producer.RealMedia.Path");\r
+  }\r
+\r
+  public String getDescr(Entity mediaType) {\r
+    return "RealMedia";\r
+  }\r
+\r
+  public String getPublishHost() {\r
+    return StringUtil.removeSlash(configuration.getString("Producer.RealMedia.Host"));\r
+  }\r
+\r
+}\r
+\r
+\r
+\r
index 13f4d7f..9e52a29 100755 (executable)
  */
 package mircoders.module;
 
-import mir.log.LoggerWrapper;
-import mir.module.*;
-import mir.util.*;
-import mir.storage.StorageObject;
+import mir.log.LoggerWrapper;\r
+import mir.module.AbstractModule;\r
+import mir.module.ModuleExc;\r
+import mir.module.ModuleFailure;\r
+import mir.storage.StorageObject;\r
+import mir.util.JDBCStringRoutines;
 
 public class ModuleArticleType extends AbstractModule {
   static LoggerWrapper logger = new LoggerWrapper("Module.ArticleType");
index 9055e9e..b936159 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.module;
 
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.module.AbstractModule;
-import mir.module.ModuleExc;
-import mir.module.ModuleFailure;
-import mir.storage.StorageObject;
-import mircoders.storage.DatabaseComment;
+import java.util.Map;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.module.AbstractModule;\r
+import mir.module.ModuleExc;\r
+import mir.module.ModuleFailure;\r
+import mir.storage.StorageObject;\r
 import mircoders.storage.DatabaseContent;
-import freemarker.template.SimpleList;
 
 
 /*
@@ -58,15 +56,6 @@ public class ModuleComment extends AbstractModule
     this.theStorage = theStorage;
   }
 
-  public SimpleList getCommentAsSimpleList() throws ModuleExc, ModuleFailure {
-    try {
-      return ((DatabaseComment)theStorage).getPopupData();
-    }
-    catch (Throwable e) {
-      throw new ModuleFailure(e);
-    }
-  }
-
   public void deleteById (String anId) throws ModuleExc, ModuleFailure {
     try {
       Entity theEntity = theStorage.selectById((String)anId);
index 317ff24..b6d5dad 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
+
 package mircoders.module;
 
 import java.util.List;
@@ -72,7 +72,7 @@ public class ModuleMediaType extends AbstractModule {
       throw new UnsupportedMimeTypeExc("Unsupported mimetype: " + aMimeType, aMimeType);
     }
 
-    return (Entity) mediaTypes.get(0);
+    return (Entity) mediaTypes.elementAt(0);
   }
 
   public static class MimeTypeExc extends ModuleExc {
index 562a8b6..98b25b1 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.module;
@@ -44,15 +44,12 @@ import mir.module.ModuleExc;
 import mir.module.ModuleFailure;
 import mir.storage.StorageObject;
 import mircoders.storage.DatabaseMediafolder;
-import freemarker.template.SimpleList;
 
 
 public class ModuleMediafolder extends AbstractModule
 {
   static LoggerWrapper logger = new LoggerWrapper("Module.Mediafolder");
 
-// Kontruktor
-
   public ModuleMediafolder(StorageObject aStorage)
   {
     if (aStorage == null)
@@ -60,17 +57,4 @@ public class ModuleMediafolder extends AbstractModule
 
     theStorage = aStorage;
   }
-
-// Methoden
-
-  public SimpleList getPopupData() throws ModuleExc, ModuleFailure {
-    try {
-      return ((DatabaseMediafolder)theStorage).getPopupData();
-    }
-    catch (Throwable e) {
-      throw new ModuleFailure(e);
-    }
-  }
-
-
 }
index cd8a781..d868ab6 100755 (executable)
@@ -39,14 +39,6 @@ import mir.module.ModuleExc;
 import mir.module.ModuleFailure;
 import mir.storage.StorageObject;
 import mircoders.storage.DatabaseTopics;
-import freemarker.template.SimpleList;
-
-/*
- *  ThemenModule -
- *
- *
- * @author RK
- */
 
 public class ModuleTopics extends AbstractModule {
 
@@ -56,15 +48,6 @@ public class ModuleTopics extends AbstractModule {
     this.theStorage = theStorage;
   }
 
-  public SimpleList getTopicsAsSimpleList() throws ModuleExc, ModuleFailure {
-    try {
-      return ((DatabaseTopics) theStorage).getPopupData();
-    }
-    catch (Throwable e) {
-      throw new ModuleFailure(e);
-    }
-  }
-
   /**
    *  Method getTopicList
    *
index 6a89ec9..7c0f304 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -94,6 +94,15 @@ public class ModuleUsers extends AbstractModule
     }
   }
 
+  public boolean checkUserPassword(EntityUsers aUser, String aPassword) throws ModuleExc, ModuleFailure {
+    try {
+      return aUser.getValue("password").equals(MirGlobal.localizer().adminInterface().makePasswordDigest(aPassword));
+    }
+    catch (Throwable t) {
+      throw new ModuleFailure(t);
+    }
+  }
+
   private Map digestPassword(Map aValues) throws ModuleExc, ModuleFailure {
     Map result = aValues;
 
index 2176f34..b3d5f62 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.pdf;
 
-import gnu.regexp.RE;
-import gnu.regexp.REException;
-
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.net.MalformedURLException;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.config.MirPropertiesConfiguration.PropertiesConfigExc;
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityImages;
-import mircoders.storage.DatabaseContentToMedia;
+import java.util.*;
 
 import com.lowagie.text.BadElementException;
 import com.lowagie.text.Document;
@@ -58,8 +48,19 @@ import com.lowagie.text.pdf.ColumnText;
 import com.lowagie.text.pdf.PdfContentByte;
 import com.lowagie.text.pdf.PdfTemplate;
 import com.lowagie.text.pdf.PdfWriter;
+import gnu.regexp.RE;
+import gnu.regexp.REException;
+import gnu.regexp.REMatch;
+import gnu.regexp.REMatchEnumeration;
 
-
+import mir.config.MirPropertiesConfiguration;
+import mir.entity.*;
+import mir.log.LoggerWrapper;
+import mir.misc.StringUtil;
+import mir.util.DateTimeFunctions;
+import mircoders.entity.EntityContent;
+import mircoders.entity.EntityImages;
+import mircoders.storage.*;
 
 public class PDFGenerator{
 
@@ -78,18 +79,18 @@ public class PDFGenerator{
   public float rightEdge;
   public float leftEdge;
 
-  public int    maxImageHeight;   
-  public int    maxImageWidth;    
+  public int    maxImageHeight;
+  public int    maxImageWidth;
   protected LoggerWrapper logger;
 
-  public int indexFontSize; 
-  public int indexLineHeight; 
-  public int indexFontFamily; 
+  public int indexFontSize;
+  public int indexLineHeight;
+  public int indexFontFamily;
 
   public float footerHeight;
   public String footerText;
-  public int footerFontSize; 
-  public int footerFontFamily; 
+  public int footerFontSize;
+  public int footerFontFamily;
 
   public int metaHeight;
   public int metaFontSize;
@@ -118,7 +119,7 @@ public class PDFGenerator{
     try {
       configuration = MirPropertiesConfiguration.instance();
     }
-    catch (PropertiesConfigExc e) {
+    catch (MirPropertiesConfiguration.PropertiesConfigExc e) {
       throw new RuntimeException("Can't get configuration: " + e.getMessage());
     }
     localImageDir=configuration.getString("Producer.Image.Path");
@@ -127,40 +128,40 @@ public class PDFGenerator{
       indexFontSize   = Integer.parseInt(configuration.getString("PDF.Index.FontSize"));
       indexLineHeight = Integer.parseInt(configuration.getString("PDF.Index.LineHeight"));
       indexFontFamily = getFontByName(configuration.getString("PDF.Index.FontFamily"));
-      
+
       footerText = configuration.getString("PDF.Footer.String");
       footerFontSize   = Integer.parseInt(configuration.getString("PDF.Footer.FontSize"));
       footerFontFamily = getFontByName(configuration.getString("PDF.Footer.FontFamily"));
       footerHeight = Integer.parseInt(configuration.getString("PDF.Footer.Height"));;
-      
+
       metaFontSize   = Integer.parseInt(configuration.getString("PDF.Meta.FontSize"));
       metaFontFamily = getFontByName(configuration.getString("PDF.Meta.FontFamily"));
       metaHeight = Integer.parseInt(configuration.getString("PDF.Meta.Height"));;
-      
+
       descriptionFontSize   = Integer.parseInt(configuration.getString("PDF.Description.FontSize"));
       descriptionLineHeight = Integer.parseInt(configuration.getString("PDF.Description.LineHeight"));
       descriptionFontFamily = getFontByName(configuration.getString("PDF.Description.FontFamily"));
-      
+
       contentFontSize   = Integer.parseInt(configuration.getString("PDF.Content.FontSize"));
       contentLineHeight = Integer.parseInt(configuration.getString("PDF.Content.LineHeight"));
       contentFontFamily = getFontByName(configuration.getString("PDF.Content.FontFamily"));
-      
+
       sourceFontSize   = Integer.parseInt(configuration.getString("PDF.Source.FontSize"));
       sourceLineHeight = Integer.parseInt(configuration.getString("PDF.Source.LineHeight"));
       sourceFontFamily = getFontByName(configuration.getString("PDF.Source.FontFamily"));
-      
+
       bigImageCaptionFontSize   = Integer.parseInt(configuration.getString("PDF.BigImageCaption.FontSize"));
       bigImageCaptionFontFamily = getFontByName(configuration.getString("PDF.BigImageCaption.FontFamily"));
-    
+
     }
     catch (NumberFormatException e){
       e.printStackTrace();
     }
 
     // step 1: make a document
-    
+
     String pageSize = configuration.getString("PDF.Pagesize");
-    
+
     if (pageSize.equals("LETTER")){
       document = new Document(PageSize.LETTER);
       pageWidth = 612;
@@ -174,35 +175,35 @@ public class PDFGenerator{
 
     maxImageHeight    = 250;
     maxImageWidth     = 250;
-        
-   
+
+
     verticalMargin = 20;
     horizontalMargin = 20;
-    
 
-    
+
+
     topEdge=pageHeight-verticalMargin;
     bottomEdge=verticalMargin;
     rightEdge=pageWidth-horizontalMargin;
     leftEdge=horizontalMargin;
-    
+
     currentYPosition=topEdge;
     currentPage = 1;
-    
+
     String headerText = configuration.getString("PDF.Title.String");
-    
+
     try{
       writer = PdfWriter.getInstance(document, out);
       cb = writer.getDirectContent();
-      
-      document.open();      
+
+      document.open();
       addHeader(headerText);
     }
     catch(DocumentException de) {
       logger.error(de.getMessage());
     }
   }
-  
+
   public void stop(){
     addFooter();
     document.close();
@@ -212,27 +213,47 @@ public class PDFGenerator{
     int titleFontSize=Integer.parseInt(configuration.getString("PDF.Title.FontSize"));
     int titleLineHeight=Integer.parseInt(configuration.getString("PDF.Title.LineHeight"));
     String titleFontFamily=configuration.getString("PDF.Title.FontFamily");
-    
+    String headerImage=configuration.getString("PDF.Header.Image");
+    int headerImageHeight = Integer.parseInt(configuration.getString("PDF.Header.ImageHeight"));
+
     try {
-           
-      ColumnText ct = new ColumnText(cb);   
-      //add a basic header
-      ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize,Font.BOLD)));
-      float[] rightCol = {rightEdge,topEdge,rightEdge,topEdge-titleLineHeight};
-      float[] leftCol = {leftEdge,topEdge,leftEdge,topEdge-titleLineHeight};
-      ct.setColumns(leftCol,rightCol);
-      ct.setYLine(topEdge);
-      ct.setAlignment(Element.ALIGN_CENTER);
-      ct.go();
-      
-      currentYPosition = currentYPosition - titleLineHeight;
-      
+      if ((! headerImage.equals("")) && headerImageHeight != 0){
+  PdfTemplate template = cb.createTemplate(rightEdge-horizontalMargin,headerImageHeight);
+
+  float toYPosition=currentYPosition - headerImageHeight;
+  Image theImage = Image.getInstance(headerImage);
+  theImage.setAbsolutePosition(0,0);
+  //   theImage.scaleAbsolute(img_width,img_height);
+  template.addImage(theImage);
+
+
+  cb.addTemplate(template,leftEdge,toYPosition);
+  currentYPosition = toYPosition;
+      }
+      if (! headerText.equals("")){
+  ColumnText ct = new ColumnText(cb);
+  //add a basic header
+  ct.addText(new Phrase(headerText, new Font(getFontByName(titleFontFamily), titleFontSize,Font.BOLD)));
+  float[] rightCol = {rightEdge,currentYPosition,rightEdge,currentYPosition-titleLineHeight};
+  float[] leftCol = {leftEdge,currentYPosition,leftEdge,currentYPosition-titleLineHeight};
+  ct.setColumns(leftCol,rightCol);
+  ct.setYLine(currentYPosition);
+  ct.setAlignment(Element.ALIGN_CENTER);
+  ct.go();
+
+  currentYPosition = currentYPosition - titleLineHeight;
+      }
     }
     catch(DocumentException de) {
       logger.error(de.getMessage());
     }
+    catch(MalformedURLException de) {
+      logger.error(de.getMessage());
+    }
+    catch(IOException de) {
+      logger.error(de.getMessage());
+    }
   }
-
   public void addIndexItem(EntityContent entityContent){
     try {
 
@@ -255,7 +276,7 @@ public class PDFGenerator{
     catch(DocumentException de) {
       logger.error(de.getMessage());
     }
-    
+
 
 
   }
@@ -288,9 +309,9 @@ public class PDFGenerator{
     cb.lineTo(leftEdge, currentYPosition-5);
     cb.stroke();
     currentYPosition = currentYPosition - 10;
-    
+
   }
-  
+
   public void addFooter(){
     try{
     ColumnText fct = new ColumnText(cb);
@@ -300,10 +321,10 @@ public class PDFGenerator{
     cb.stroke();
     float[] leftFooterCols = {leftEdge,bottomEdge+footerHeight-1,leftEdge,bottomEdge};
     float[] rightFooterCols = {rightEdge,bottomEdge+footerHeight-1,rightEdge,bottomEdge};
-    
+
     Paragraph footerP=new Paragraph(footerText,new Font(footerFontFamily,footerFontSize));
     fct.addText(footerP);
-    
+
     fct.setColumns(leftFooterCols,rightFooterCols);
     fct.setYLine(bottomEdge+footerHeight-1);
     fct.setAlignment(Element.ALIGN_JUSTIFIED);
@@ -326,7 +347,7 @@ public class PDFGenerator{
     try{
       //add a footer
       addFooter();
-      document.newPage();   
+      document.newPage();
       currentPage++;
       currentYPosition=topEdge;
     }
@@ -334,9 +355,9 @@ public class PDFGenerator{
       logger.error(de.getMessage());
     }
   }
-  
+
   public void addArticleSeparator(){
-    // make a line 
+    // make a line
     if (! enoughY(10)){
       newPage();
     }
@@ -349,45 +370,45 @@ public class PDFGenerator{
 
   public void addArticleMetaInfo(ColumnText ct,String theTitle,String theCreator,String theDate){
       //see if we have room for the author and title
-    
+
     if (! enoughY(metaHeight)){
-       newPage();
+  newPage();
       }
-    
+
     Paragraph titleP=new Paragraph(theTitle+"\n",new Font(metaFontFamily,metaFontSize,Font.BOLD));
     Paragraph whowhenP=new Paragraph(theCreator + "  " + theDate ,new Font(metaFontFamily,metaFontSize));
     ct.addText(titleP);
     ct.addText(whowhenP);
-    
+
     ct.setYLine(currentYPosition);
     ct.setAlignment(Element.ALIGN_LEFT);
-    
+
     float toYPosition = currentYPosition - metaHeight;
     float[] leftHeadCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
     float[] rightHeadCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
-    
+
     ct.setColumns(leftHeadCols,rightHeadCols);
-    try { 
+    try {
       ct.go();
       currentYPosition = toYPosition;
     }
     catch(DocumentException de) {
       logger.error(de.getMessage());
     }
-    
+
   }
 
   public void addArticleDescription(ColumnText ct,String theDescription){
     // Now we add the description, one line at a time, the ct should be empty at this point
-    
-    
+
+
     Paragraph descP=new Paragraph(theDescription,new Font(descriptionFontFamily,descriptionFontSize,Font.BOLD));
     ct.addText(descP);
-    
+
     // every article has a description, so we can assume that:
     int status = ColumnText.NO_MORE_COLUMN;
-    
-    int brake=1000; 
+
+    int brake=1000;
     while ((status & ColumnText.NO_MORE_TEXT) == 0 && brake >0){
       //there is still text left in the description.
       status = addTextLine(ct,descriptionLineHeight,Element.ALIGN_JUSTIFIED,leftEdge,rightEdge);
@@ -396,16 +417,16 @@ public class PDFGenerator{
     if (brake == 0)
       logger.error("runaway description...try increasing the line height or decreasing the font size");
   }
-  public void addArticleContent(ColumnText ct,String theContent,EntityList images){
+
+  public void addArticleContent(ColumnText ct,String theContent,Iterator images){
     //let's go ahead and add in all the body text
     Paragraph contentP=new Paragraph(theContent,new Font(contentFontFamily,contentFontSize));
     ct.addText(contentP);
-    
+
     int contentLinesBeforeImages=3;
     //and assume we have at least one line of text in the content
     int status = ColumnText.NO_MORE_COLUMN;
-    
+
     // let's add a little bit of text, like a couple of lines
     int x = 0;
     while (((status & ColumnText.NO_MORE_TEXT) == 0) && x<contentLinesBeforeImages){
@@ -415,166 +436,166 @@ public class PDFGenerator{
 
     boolean addImageOnLeft = true; //we will alternate within articles
     while (images.hasNext()){
-      
+
       EntityImages currentImage=(EntityImages) images.next();
       float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();
       float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();
       if (img_height>maxImageHeight){
-       img_width=(new Float((new Float(img_width*(maxImageHeight/img_height))).intValue())).floatValue();
-       img_height=maxImageHeight;
+  img_width=(new Float((new Float(img_width*(maxImageHeight/img_height))).intValue())).floatValue();
+  img_height=maxImageHeight;
       }
       if (img_width>maxImageWidth){
-       img_height=(new Float((new Float(img_height*(maxImageWidth/img_width))).intValue())).floatValue();
-       img_width=maxImageWidth;
+  img_height=(new Float((new Float(img_height*(maxImageWidth/img_width))).intValue())).floatValue();
+  img_width=maxImageWidth;
       }
 
       String img_title=currentImage.getValue("title");
       String img_path=currentImage.getValue("publish_path");
-      
-      if ((status & ColumnText.NO_MORE_TEXT) == 0){ 
-       // there is still text, so add an image which will have text wrapped around it, then add the text which 
-       // will be on the left or the right of the image
-       
-       float templateMinimumHeight = img_height+20;
-       float templateWidth = img_width+10;
-       float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
-       
-       PdfTemplate template = cb.createTemplate(templateWidth,templateHeight); 
-       
-       
-       //here we need a page check
-       if (! enoughY((new Float(templateHeight)).intValue())){
-         //ok, well just fill text to the bottom then
-         float toYPosition = bottomEdge+footerHeight;
-         float[] leftBottomCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
-         float[] rightBottomCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
-         ct.setColumns(leftBottomCols,rightBottomCols);
-         ct.setYLine(currentYPosition);
-         ct.setAlignment(Element.ALIGN_JUSTIFIED);
-         try{ 
-           status=ct.go();
-         }
-         catch(DocumentException de) {
-           logger.error(de.getMessage());
-         }
-         newPage();
-       }
-       
-       float toYPosition=currentYPosition - templateHeight;
-
-       try {
-         Image theImage = Image.getInstance(localImageDir+img_path);
-         theImage.scaleAbsolute(img_width,img_height);
-         theImage.setAbsolutePosition(5,13); 
-         
-         template.addImage(theImage);
-         template.beginText();
-         BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
-         template.setFontAndSize(bf, 8);
-         template.setTextMatrix(5, 3);
-         template.showText(img_title);
-         template.endText();
-       }
-       catch(BadElementException de) {
-         logger.error(de.getMessage());
-       }
-       catch(DocumentException de) {
-         logger.error(de.getMessage());
-       }
-       catch (MalformedURLException de){
-        logger.error(de.getMessage());
-       }
-       catch (IOException de){
-         logger.error(de.getMessage());
-       }
-
-       
-       float leftImageTextEdge=leftEdge;
-       float rightImageTextEdge=rightEdge;
-       
-       
-       if (addImageOnLeft){
-         cb.addTemplate(template,leftEdge,toYPosition);
-         leftImageTextEdge=leftEdge+templateWidth+5;
-         addImageOnLeft = false;
-       }           
-       else {
-         cb.addTemplate(template,rightEdge-templateWidth,toYPosition);
-         rightImageTextEdge = rightEdge-templateWidth-5;
-         addImageOnLeft = true;
-       }
-
-       logger.debug("adding template at " + leftEdge + "," + toYPosition);
-       
-       //and fill some text while we are at it
-       
-       float[] leftBottomCols = {leftImageTextEdge,currentYPosition,leftImageTextEdge,toYPosition};
-       float[] rightBottomCols = {rightImageTextEdge,currentYPosition,rightImageTextEdge,toYPosition};
-       ct.setColumns(leftBottomCols,rightBottomCols);
-       ct.setYLine(currentYPosition);
-       ct.setAlignment(Element.ALIGN_JUSTIFIED);
-       try{ 
-       status=ct.go();
-       currentYPosition=toYPosition;
-       }
-       catch(DocumentException de) {
-         logger.error(de.getMessage());
-       }
-       
-       
+
+      if ((status & ColumnText.NO_MORE_TEXT) == 0){
+  // there is still text, so add an image which will have text wrapped around it, then add the text which
+  // will be on the left or the right of the image
+
+  float templateMinimumHeight = img_height+20;
+  float templateWidth = img_width+10;
+  float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
+
+  PdfTemplate template = cb.createTemplate(templateWidth,templateHeight);
+
+
+  //here we need a page check
+  if (! enoughY((new Float(templateHeight)).intValue())){
+    //ok, well just fill text to the bottom then
+    float toYPosition = bottomEdge+footerHeight;
+    float[] leftBottomCols = {leftEdge,currentYPosition,leftEdge,toYPosition};
+    float[] rightBottomCols = {rightEdge,currentYPosition,rightEdge,toYPosition};
+    ct.setColumns(leftBottomCols,rightBottomCols);
+    ct.setYLine(currentYPosition);
+    ct.setAlignment(Element.ALIGN_JUSTIFIED);
+    try{
+      status=ct.go();
+    }
+    catch(DocumentException de) {
+      logger.error(de.getMessage());
+    }
+    newPage();
+  }
+
+  float toYPosition=currentYPosition - templateHeight;
+
+  try {
+    Image theImage = Image.getInstance(localImageDir+img_path);
+    theImage.scaleAbsolute(img_width,img_height);
+    theImage.setAbsolutePosition(5,13);
+
+    template.addImage(theImage);
+    template.beginText();
+    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
+    template.setFontAndSize(bf, 8);
+    template.setTextMatrix(5, 3);
+    template.showText(img_title);
+    template.endText();
+  }
+  catch(BadElementException de) {
+    logger.error(de.getMessage());
+  }
+  catch(DocumentException de) {
+    logger.error(de.getMessage());
+  }
+  catch (MalformedURLException de){
+   logger.error(de.getMessage());
+  }
+  catch (IOException de){
+    logger.error(de.getMessage());
+  }
+
+
+  float leftImageTextEdge=leftEdge;
+  float rightImageTextEdge=rightEdge;
+
+
+  if (addImageOnLeft){
+    cb.addTemplate(template,leftEdge,toYPosition);
+    leftImageTextEdge=leftEdge+templateWidth+5;
+    addImageOnLeft = false;
+  }
+  else {
+    cb.addTemplate(template,rightEdge-templateWidth,toYPosition);
+    rightImageTextEdge = rightEdge-templateWidth-5;
+    addImageOnLeft = true;
+  }
+
+  logger.debug("adding template at " + leftEdge + "," + toYPosition);
+
+  //and fill some text while we are at it
+
+  float[] leftBottomCols = {leftImageTextEdge,currentYPosition,leftImageTextEdge,toYPosition};
+  float[] rightBottomCols = {rightImageTextEdge,currentYPosition,rightImageTextEdge,toYPosition};
+  ct.setColumns(leftBottomCols,rightBottomCols);
+  ct.setYLine(currentYPosition);
+  ct.setAlignment(Element.ALIGN_JUSTIFIED);
+  try{
+  status=ct.go();
+  currentYPosition=toYPosition;
+  }
+  catch(DocumentException de) {
+    logger.error(de.getMessage());
+  }
+
+
       }
-      else { 
-       //add an image on the left with a big caption to the right
-       currentYPosition = currentYPosition - 10;
-       float templateMinimumHeight = img_height;
-       float templateWidth = img_width;
-       float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
-       PdfTemplate template = cb.createTemplate(templateWidth,templateHeight); 
-       if (! enoughY((new Float(templateHeight)).intValue())){
-         newPage();
-       }
-       float toYPosition=currentYPosition - templateHeight;
-       try{ 
-         Image theImage = Image.getInstance(localImageDir+img_path);
-         theImage.setAbsolutePosition(0,13); 
-         theImage.scaleAbsolute(img_width,img_height);
-         template.addImage(theImage);
-       }
-       catch(BadElementException de) {
-         logger.error(de.getMessage());
-       }
-       catch(DocumentException de) {
-         logger.error(de.getMessage());
-       }
-       catch(MalformedURLException de) {
-         logger.error(de.getMessage());
-       }
-       catch(IOException de) {
-         logger.error(de.getMessage());
-       }
-
-       cb.addTemplate(template,leftEdge,toYPosition);
-         
-       // add a big caption
-       ColumnText cct = new ColumnText(cb);   
-       float[] leftCaptionCols = {leftEdge+templateWidth+5,currentYPosition-5,leftEdge+templateWidth+5,toYPosition};
-       float[] rightCaptionCols = {rightEdge,currentYPosition-5,rightEdge,toYPosition};
-       
-       Paragraph captionP=new Paragraph(img_title,new Font(bigImageCaptionFontFamily,bigImageCaptionFontSize,Font.BOLD));
-       cct.addText(captionP);
-       cct.setColumns(leftCaptionCols,rightCaptionCols);
-       cct.setYLine(currentYPosition-5);
-       cct.setAlignment(Element.ALIGN_LEFT);
-       try{
-         cct.go();
-         currentYPosition=toYPosition;
-       }
-       catch(DocumentException de) {
-         logger.error(de.getMessage());
-       }
+      else {
+  //add an image on the left with a big caption to the right
+  currentYPosition = currentYPosition - 10;
+  float templateMinimumHeight = img_height;
+  float templateWidth = img_width;
+  float templateHeight = templateMinimumHeight+contentLineHeight-(templateMinimumHeight % contentLineHeight);
+  PdfTemplate template = cb.createTemplate(templateWidth,templateHeight);
+  if (! enoughY((new Float(templateHeight)).intValue())){
+    newPage();
+  }
+  float toYPosition=currentYPosition - templateHeight;
+  try{
+    Image theImage = Image.getInstance(localImageDir+img_path);
+    theImage.setAbsolutePosition(0,13);
+    theImage.scaleAbsolute(img_width,img_height);
+    template.addImage(theImage);
+  }
+  catch(BadElementException de) {
+    logger.error(de.getMessage());
+  }
+  catch(DocumentException de) {
+    logger.error(de.getMessage());
+  }
+  catch(MalformedURLException de) {
+    logger.error(de.getMessage());
+  }
+  catch(IOException de) {
+    logger.error(de.getMessage());
+  }
+
+  cb.addTemplate(template,leftEdge,toYPosition);
+
+  // add a big caption
+  ColumnText cct = new ColumnText(cb);
+  float[] leftCaptionCols = {leftEdge+templateWidth+5,currentYPosition-5,leftEdge+templateWidth+5,toYPosition};
+  float[] rightCaptionCols = {rightEdge,currentYPosition-5,rightEdge,toYPosition};
+
+  Paragraph captionP=new Paragraph(img_title,new Font(bigImageCaptionFontFamily,bigImageCaptionFontSize,Font.BOLD));
+  cct.addText(captionP);
+  cct.setColumns(leftCaptionCols,rightCaptionCols);
+  cct.setYLine(currentYPosition-5);
+  cct.setAlignment(Element.ALIGN_LEFT);
+  try{
+    cct.go();
+    currentYPosition=toYPosition;
+  }
+  catch(DocumentException de) {
+    logger.error(de.getMessage());
+  }
       }
     }
-    
+
     //add the rest of the text which might be left
     int brake = 10000;
     while ((status & ColumnText.NO_MORE_TEXT) == 0  && brake > 0){
@@ -595,67 +616,140 @@ public class PDFGenerator{
   private boolean enoughY(int heightOfBlockToAdd){
     if ((currentYPosition - heightOfBlockToAdd - footerHeight) < bottomEdge )
       return false;
-    else 
+    else
       return true;
   }
-  
-  
+
+
   public void add(EntityContent entityContent){
     logger.error("adding a content Entity");
-    
+
     /*
      * initialize
      * separate
      * meta info
      * description
-     * content  
+     * content
      * --image with text
      * --normal text
      * --image without text
      * source
     */
-    
-    EntityList images=DatabaseContentToMedia.getInstance().getImages(entityContent);
+
+   Iterator images = new EntityBrowser(
+      DatabaseImages.getInstance(),
+       "exists (select * from content_x_media where content_id=" + entityContent.getId() + " and media_id=id)",
+       "id desc", 30, -1, 0);
+
+    String isHTML  = entityContent.getValue("is_html");
     String theTitle = entityContent.getValue("title");
     String theCreator = entityContent.getValue("creator");
-    String theDate = entityContent.getValue("webdb_create_formatted");
+    String theDate = DateTimeFunctions.advancedDateFormat(
+        configuration.getString("RDF.Meta.DateFormat"),
+        StringUtil.convertMirInternalDateToDate(entityContent.getValue("webdb_create")),
+        configuration.getString("Mir.DefaultTimezone"));
+
+
     String theDescriptionRaw = entityContent.getValue("description");
     String theContentRaw = entityContent.getValue("content_data");
     String theSource =  configuration.getString("Producer.ProductionHost") + "/" + configuration.getString("StandardLanguage") + entityContent.getValue("publish_path") + entityContent.getValue("id") + ".shtml";
 
 
-    
+
     String theContent = "";
     String theDescription = "";
-    
-    try { 
-      RE re1 = new RE("\r?\n\r?\n");
-      String theContent1 = re1.substituteAll(theContentRaw,"BREAKHERE");
-      String theDescription1 = re1.substituteAll(theDescriptionRaw,"BREAKHERE");
-      
-      RE re2 = new RE("\r?\n");
-      String theContent2 = re2.substituteAll(theContent1," ");
-      String theDescription2 = re2.substituteAll(theDescription1," ");
-      
-      RE re3 = new RE("BREAKHERE");
-      theContent = "    " + re3.substituteAll(theContent2,"\n    ");
-      theDescription = re3.substituteAll(theDescription2,"\n    ");
 
+    if (isHTML.equals("1")){
+
+
+
+      try {
+  RE nobackslashr = new RE("\r");
+  theContent= nobackslashr.substituteAll(theContentRaw,"");
+
+  RE HxTag = new RE("</?h[1-6][^>]*>",RE.REG_ICASE);
+  theContent = HxTag.substituteAll(theContent,"\n\n");
+
+  RE ListItemTag = new RE("<li[^>]*>",RE.REG_ICASE);
+  theContent = ListItemTag.substituteAll(theContent,"\n * ");
+
+  RE ListTag = new RE("<(u|o)l[^>]*>",RE.REG_ICASE);
+  theContent = ListTag.substituteAll(theContent,"\n");
+
+  RE DivTag = new RE("</?div[^>]*>",RE.REG_ICASE);
+  theContent= DivTag.substituteAll(theContent,"\n");
+
+  RE PTag = new RE("<(p|P)([:space:]+[^>]*)?>");
+  theContent= PTag.substituteAll(theContent,"\n    ");
+
+  RE PTagClose = new RE("</(p|P)([:space:]+[^>]*)?>");
+  theContent= PTagClose.substituteAll(theContent,"\n");
+
+  RE BRTag = new RE("<(br|BR)([:space:]+[^>]*)?>");
+  theContent= BRTag.substituteAll(theContent,"\n");
+
+  RE ATagAll = new RE("<a[^>]*href=(?:\"|\')([^#\"\'][^\'\"]+)(?:\"|\')[^>]*>(.*?)</a>",RE.REG_ICASE);
+  REMatchEnumeration atags= ATagAll.getMatchEnumeration(theContent);
+  String theContentCopy=theContent;
+  while (atags.hasMoreMatches()){
+    REMatch atag = atags.nextMatch();
+    String atagString=atag.toString();
+    String atagStringHref=atag.toString(1);
+    String atagStringText=atag.toString(2);
+    int begin=theContentCopy.indexOf(atagString);
+    theContentCopy=theContentCopy.substring(0,begin) + atagStringText + " ["+ atagStringHref + "] " + theContentCopy.substring(begin+atagString.length());
+  }
+  theContent=theContentCopy;
+
+  RE noTags = new RE("<[^>]*>");
+  theContent= noTags.substituteAll(theContent," ");
+
+  theContent=mir.util.Translate.decode(theContent);
+
+  RE re1 = new RE("\r?\n\r?\n");
+  String theDescription1 = re1.substituteAll(theDescriptionRaw,"BREAKHERE");
+
+  RE re2 = new RE("\r?\n");
+  String theDescription2 = re2.substituteAll(theDescription1," ");
+
+  RE re3 = new RE("BREAKHERE");
+  theDescription = re3.substituteAll(theDescription2,"\n    ");
+
+
+      }
+      catch(REException ree){
+  logger.error(ree.getMessage());
+      }
     }
-    catch(REException ree){
-      logger.error(ree.getMessage());
-    }
+    else {
+      try {
+  RE re1 = new RE("\r?\n\r?\n");
+  String theContent1 = re1.substituteAll(theContentRaw,"BREAKHERE");
+  String theDescription1 = re1.substituteAll(theDescriptionRaw,"BREAKHERE");
 
+  RE re2 = new RE("\r?\n");
+  String theContent2 = re2.substituteAll(theContent1," ");
+  String theDescription2 = re2.substituteAll(theDescription1," ");
+
+  RE re3 = new RE("BREAKHERE");
+  theContent = "    " + re3.substituteAll(theContent2,"\n    ");
+  theDescription = re3.substituteAll(theDescription2,"\n    ");
+
+      }
+      catch(REException ree){
+  logger.error(ree.getMessage());
+      }
+    }
 
     addArticleSeparator();
-    
+
     ColumnText ct = new ColumnText(cb);
-    
+
     addArticleMetaInfo(ct,theTitle,theCreator,theDate);
     addArticleDescription(ct,theDescription);
     addArticleContent(ct,theContent,images);
     addArticleSource(ct,theSource);
-      
+
   }
 
   public int getFontByName(String fontName) {
@@ -664,20 +758,20 @@ public class PDFGenerator{
       theFont = Font.HELVETICA;
     }
     else {
-      if (fontName.equalsIgnoreCase("courier")) { 
-       theFont = Font.COURIER;
+      if (fontName.equalsIgnoreCase("courier")) {
+  theFont = Font.COURIER;
       }
       else {
-       if (fontName.equalsIgnoreCase("times")) { 
-         theFont = Font.TIMES_ROMAN;
-       }
-       else {
-         logger.error("using helvetica because I can't get font for name: "+fontName);
-         theFont = Font.HELVETICA;
-       }
+  if (fontName.equalsIgnoreCase("times")) {
+    theFont = Font.TIMES_ROMAN;
+  }
+  else {
+    logger.error("using helvetica because I can't get font for name: "+fontName);
+    theFont = Font.HELVETICA;
+  }
       }
     }
-    
+
     return theFont;
 
   }
index 61e0155..3f78883 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.producer;
@@ -80,7 +80,7 @@ public class ContentModifyingProducerNode implements ProducerNode {
       entity.setValueForProperty(fieldName, value);
       entity.update();
 
-      aLogger.info("  Modified content " + entity.get("id") + ": " + fieldName + " = " + value );
+      aLogger.info("  Modified content " + entity.getId() + ": " + fieldName + " = " + value );
     }
     catch (Throwable t) {
       aLogger.error("Error while modifying content: " + t.getMessage());
index 8fc3f5b..b4208a7 100755 (executable)
  */
 package mircoders.producer;
 
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
+import java.util.Date;
 import java.util.Map;
 
 import mir.entity.Entity;
@@ -120,9 +124,38 @@ public class IndexingProducerNode implements ProducerNode {
       //this initialization should go somewhere global like an xml file....
       (new KeywordSearchTerm("id", "", "id", "", "id")).index(theDoc, entity);
 
+      String textValue = entity.getValue("webdb_create");
+      Calendar calendar = GregorianCalendar.getInstance();
+      int year;
+      int month;
+      int day;
+      int hours;
+      int minutes;
+      Date date;
+      String formattedDate="";
+
+      if (textValue!=null) {
+        try {
+          year = Integer.parseInt(textValue.substring(0,4));
+          month = Integer.parseInt(textValue.substring(5,7));
+          day = Integer.parseInt(textValue.substring(8,10));
+         hours = Integer.parseInt(textValue.substring(11,13));
+          minutes = Integer.parseInt(textValue.substring(14,16));
+
+          calendar.set(year, month-1, day, hours, minutes);
+          date = calendar.getTime();
+         SimpleDateFormat formatter = new SimpleDateFormat ("yyyy.MM.dd hh:mm");
+         formattedDate=formatter.format(date);
+        }
+       catch (Throwable t){
+         aLogger.error("Error while generating content date to index: " + t.getMessage());
+         t.printStackTrace(aLogger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
+       }
+      }
       (new KeywordSearchTerm("webdb_create_formatted", "search_date",
         "webdb_create_formatted", "webdb_create_formatted",
-        "webdb_create_formatted")).index(theDoc, entity);
+        "webdb_create_formatted")).indexValue(theDoc,formattedDate);
+     
 
       (new UnIndexedSearchTerm("", "", "", "where", "where")).indexValue(theDoc,
         StringUtil.webdbDate2path(entity.getValue("date")) +
index 86ad9a9..77fd4c6 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.producer;
-
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-import mir.entity.Entity;
-import mir.entity.EntityList;
-import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerToWriterAdapter;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.producer.ProducerFailure;
-import mir.producer.ProducerNode;
-import mir.util.CachingRewindableIterator;
-import mir.util.HTMLRoutines;
-import mir.util.ParameterExpander;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityImages;
-import mircoders.storage.DatabaseContentToMedia;
-
-//because images are returned as a template model!(maybe not needed after all!)
-//import freemarker.template.*;
-
-
-public class PDFPreFormattingProducerNode implements ProducerNode {
-  private String contentKey;
-  private int numLinesBetweenImages;
-  private float contentAreaWidthCM;
-  private float characterWidthCM;
-  private float pixelWidthCM;
-  private float lineHeightCM;
-
-  public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {
-    contentKey = aContentKey;
-    numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();
-    contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();
-    characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();
-    pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();
-    lineHeightCM=(new Float(aLineHeightCM)).floatValue();
-
-    //    float characterWidthCM = 0.17F;
-    //float contentAreaWidthCM = 16;
-    //float pixelWidthCM = .03F;
-    //float lineHeightCM = .5F;
-  }
-
-  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {
-    Object data;
-    Entity entity;
-
-    try {
-      data = ParameterExpander.findValueForKey( aValueMap, contentKey );
-
-      if (! (data instanceof EntityAdapter)) {
-        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);
-      }
-
-      entity = ((EntityAdapter) data).getEntity();
-      if (! (entity instanceof EntityContent)) {
-        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);
-      }
-
-      int currentPosition = 0;
-
-      //int numLinesBetweenImages=3;
-
-
-
-
-      int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();
-
-      boolean outOfText = false;
-
-      ArrayList brokenUpContent = new ArrayList();
-
-
-      EntityList images=DatabaseContentToMedia.getInstance().getImages((EntityContent)entity);
-      String theContent = ((EntityContent) entity).getValue("content_data");
-      //remove pesky characters
-      theContent = HTMLRoutines.encodeXML(theContent);
-      //put in the <BR> tags so we can turn them to empty blocks
-      theContent = StringUtil.convertNewline2Break(theContent);
-
-      if (images == null){
-          Map row = new HashMap();
-          row.put("text",theContent);
-          row.put("hasImage","0");
-          brokenUpContent.add(row);
-      }
-      if (images != null){
-          //need to add checks for out of content!
-          Map row0 = new HashMap();
-          if (numCharsInAnImagelessRow>(theContent).length()){
-              row0.put("text",theContent);
-              outOfText = true;
-          }
-          else {
-              //break on words so we don't split html entities
-              int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);
-              row0.put("text",theContent.substring(0,lastSpaceAt));
-              currentPosition=lastSpaceAt;
-          }
-          row0.put("hasImage","0");
-          brokenUpContent.add(row0);
-          aLogger.debug("CP1 is "+ currentPosition);
-          while(images.hasNext()){
-              Map row1 = new HashMap();
-              Map row2 = new HashMap();
-              EntityImages currentImage=(EntityImages) images.next();
-              float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();
-              float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();
-
-              //oversize images must be shrunk
-              if (img_width>250){
-                  img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();
-                  img_width=250.0F;
-              }
-
-
-              //calculate how much text goes in the column(use 8 pixels to pad the column)
-              float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);
-              float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int
-              //add one line for image description
-              int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();
-
-              row1.put("text_widthCM",Float.toString(text_widthCM));
-
-              row1.put("img_title",currentImage.getValue("title"));
-
-              row1.put("img_width",Float.toString(img_width));
-              row1.put("img_height",Float.toString(img_height));
-
-              aLogger.debug("img_width " +Float.toString(img_width));
-              aLogger.debug("img_height "+Float.toString(img_height));
-
-              row1.put("img_src",currentImage.getValue("publish_path"));
-              row1.put("hasImage","1");
-              if (! outOfText){
-                  try {
-                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);
-                      row1.put("text",theContent.substring(currentPosition,lastSpaceAt));
-                      currentPosition=lastSpaceAt;
-                  }
-                  catch (IndexOutOfBoundsException e){
-                      row1.put("text",theContent.substring(currentPosition));
-                      outOfText = true;
-                          }
-              }
-              aLogger.debug("CP2 is "+ currentPosition);
-              brokenUpContent.add(row1);
-
-              if (! outOfText){
-                  try {
-                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);
-                      row2.put("text",theContent.substring(currentPosition,lastSpaceAt));
-                      currentPosition=lastSpaceAt;
-                  }
-                  catch (IndexOutOfBoundsException e){
-                      row2.put("text",theContent.substring(currentPosition));
-                      outOfText = true;
-                          }
-              }
-              row2.put("hasImage","0");
-              brokenUpContent.add(row2);
-
-              aLogger.debug("CP3 is "+ currentPosition);
-          }
-          Map row3 = new HashMap();
-          if (! outOfText){
-              row3.put("text",theContent.substring(currentPosition));
-              row3.put("hasImage","0");
-              brokenUpContent.add(row3);
-          }
-
-      }
-
-
-
-
-
-      ParameterExpander.setValueForKey(
-                                       aValueMap,
-                                       "data.formatted_content",
-                                       new CachingRewindableIterator(brokenUpContent.iterator())
-                                       );
-
-
-    }
-    catch (Throwable t) {
-      aLogger.error("Error while formatting content for PDF: " + t.getMessage());
-      t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));
-    }
-  }
-}
-
-
-
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.producer;\r
+\r
+import java.io.PrintWriter;\r
+import java.util.ArrayList;\r
+import java.util.HashMap;\r
+import java.util.*;\r
+\r
+import mir.entity.*;\r
+import mir.entity.EntityList;\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.log.LoggerToWriterAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.producer.ProducerFailure;\r
+import mir.producer.ProducerNode;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.HTMLRoutines;\r
+import mir.util.ParameterExpander;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityImages;\r
+import mircoders.storage.*;\r
+\r
+\r
+public class PDFPreFormattingProducerNode implements ProducerNode {\r
+  private String contentKey;\r
+  private int numLinesBetweenImages;\r
+  private float contentAreaWidthCM;\r
+  private float characterWidthCM;\r
+  private float pixelWidthCM;\r
+  private float lineHeightCM;\r
+\r
+  public PDFPreFormattingProducerNode(String aContentKey,String someNumLinesBetweenImages,String aContentAreaWidthCM,String aCharacterWidthCM,String aPixelWidthCM,String aLineHeightCM) {\r
+    contentKey = aContentKey;\r
+    numLinesBetweenImages=(new Integer(someNumLinesBetweenImages)).intValue();\r
+    contentAreaWidthCM=(new Float(aContentAreaWidthCM)).floatValue();\r
+    characterWidthCM=(new Float(aCharacterWidthCM)).floatValue();\r
+    pixelWidthCM=(new Float(aPixelWidthCM)).floatValue();\r
+    lineHeightCM=(new Float(aLineHeightCM)).floatValue();\r
+\r
+    //    float characterWidthCM = 0.17F;\r
+    //float contentAreaWidthCM = 16;\r
+    //float pixelWidthCM = .03F;\r
+    //float lineHeightCM = .5F;\r
+  }\r
+\r
+  public void produce(Map aValueMap, String aVerb, LoggerWrapper aLogger) throws ProducerFailure {\r
+    Object data;\r
+    Entity entity;\r
+\r
+    try {\r
+      data = ParameterExpander.findValueForKey( aValueMap, contentKey );\r
+\r
+      if (! (data instanceof EntityAdapter)) {\r
+        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not an EntityAdapter, but an " + data.getClass().getName(), null);\r
+      }\r
+\r
+      entity = ((EntityAdapter) data).getEntity();\r
+      if (! (entity instanceof EntityContent)) {\r
+        throw new ProducerFailure("PDFPreFormattingProducerNode: value of '"+contentKey+"' is not a content EntityAdapter, but a " + entity.getClass().getName() + " adapter", null);\r
+      }\r
+\r
+      int currentPosition = 0;\r
+\r
+      //int numLinesBetweenImages=3;\r
+\r
+\r
+\r
+\r
+      int numCharsInAnImagelessRow = (new Float(numLinesBetweenImages * (contentAreaWidthCM/characterWidthCM))).intValue();\r
+\r
+      boolean outOfText = false;\r
+\r
+      ArrayList brokenUpContent = new ArrayList();\r
+\r
+      Iterator images = new EntityBrowser(\r
+         DatabaseImages.getInstance(),\r
+          "exists (select * from content_x_media where content_id=" + entity.getId() + " and media_id=id)",\r
+          "id desc", 30, -1, 0);\r
+\r
+      String theContent = ((EntityContent) entity).getValue("content_data");\r
+      //remove pesky characters\r
+      theContent = HTMLRoutines.encodeXML(theContent);\r
+      //put in the <BR> tags so we can turn them to empty blocks\r
+      theContent = StringUtil.convertNewline2Break(theContent);\r
+\r
+      if (images == null){\r
+          Map row = new HashMap();\r
+          row.put("text",theContent);\r
+          row.put("hasImage","0");\r
+          brokenUpContent.add(row);\r
+      }\r
+      if (images != null){\r
+          //need to add checks for out of content!\r
+          Map row0 = new HashMap();\r
+          if (numCharsInAnImagelessRow>(theContent).length()){\r
+              row0.put("text",theContent);\r
+              outOfText = true;\r
+          }\r
+          else {\r
+              //break on words so we don't split html entities\r
+              int lastSpaceAt = theContent.lastIndexOf(" ",numCharsInAnImagelessRow);\r
+              row0.put("text",theContent.substring(0,lastSpaceAt));\r
+              currentPosition=lastSpaceAt;\r
+          }\r
+          row0.put("hasImage","0");\r
+          brokenUpContent.add(row0);\r
+          aLogger.debug("CP1 is "+ currentPosition);\r
+          while(images.hasNext()){\r
+              Map row1 = new HashMap();\r
+              Map row2 = new HashMap();\r
+              EntityImages currentImage=(EntityImages) images.next();\r
+              float img_width=(new Float(currentImage.getValue("img_width"))).floatValue();\r
+              float img_height=(new Float(currentImage.getValue("img_height"))).floatValue();\r
+\r
+              //oversize images must be shrunk\r
+              if (img_width>250){\r
+                  img_height=(new Float((new Float(img_height*(250.0F/img_width))).intValue())).floatValue();\r
+                  img_width=250.0F;\r
+              }\r
+\r
+\r
+              //calculate how much text goes in the column(use 8 pixels to pad the column)\r
+              float text_widthCM = contentAreaWidthCM-((img_width+8)*pixelWidthCM);\r
+              float number_of_lines = img_height*pixelWidthCM/lineHeightCM; //don't worry we will make it an int\r
+              //add one line for image description\r
+              int text_amount= (new Float((text_widthCM/characterWidthCM)*(number_of_lines+1))).intValue();\r
+\r
+              row1.put("text_widthCM",Float.toString(text_widthCM));\r
+\r
+              row1.put("img_title",currentImage.getValue("title"));\r
+\r
+              row1.put("img_width",Float.toString(img_width));\r
+              row1.put("img_height",Float.toString(img_height));\r
+\r
+              aLogger.debug("img_width " +Float.toString(img_width));\r
+              aLogger.debug("img_height "+Float.toString(img_height));\r
+\r
+              row1.put("img_src",currentImage.getValue("publish_path"));\r
+              row1.put("hasImage","1");\r
+              if (! outOfText){\r
+                  try {\r
+                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+text_amount);\r
+                      row1.put("text",theContent.substring(currentPosition,lastSpaceAt));\r
+                      currentPosition=lastSpaceAt;\r
+                  }\r
+                  catch (IndexOutOfBoundsException e){\r
+                      row1.put("text",theContent.substring(currentPosition));\r
+                      outOfText = true;\r
+                          }\r
+              }\r
+              aLogger.debug("CP2 is "+ currentPosition);\r
+              brokenUpContent.add(row1);\r
+\r
+              if (! outOfText){\r
+                  try {\r
+                      int lastSpaceAt = theContent.lastIndexOf(" ",currentPosition+numCharsInAnImagelessRow);\r
+                      row2.put("text",theContent.substring(currentPosition,lastSpaceAt));\r
+                      currentPosition=lastSpaceAt;\r
+                  }\r
+                  catch (IndexOutOfBoundsException e){\r
+                      row2.put("text",theContent.substring(currentPosition));\r
+                      outOfText = true;\r
+                          }\r
+              }\r
+              row2.put("hasImage","0");\r
+              brokenUpContent.add(row2);\r
+\r
+              aLogger.debug("CP3 is "+ currentPosition);\r
+          }\r
+          Map row3 = new HashMap();\r
+          if (! outOfText){\r
+              row3.put("text",theContent.substring(currentPosition));\r
+              row3.put("hasImage","0");\r
+              brokenUpContent.add(row3);\r
+          }\r
+\r
+      }\r
+\r
+\r
+\r
+\r
+\r
+      ParameterExpander.setValueForKey(\r
+                                       aValueMap,\r
+                                       "data.formatted_content",\r
+                                       new CachingRewindableIterator(brokenUpContent.iterator())\r
+                                       );\r
+\r
+\r
+    }\r
+    catch (Throwable t) {\r
+      aLogger.error("Error while formatting content for PDF: " + t.getMessage());\r
+      t.printStackTrace(new PrintWriter(new LoggerToWriterAdapter(aLogger, LoggerWrapper.DEBUG_MESSAGE)));\r
+    }\r
+  }\r
+}\r
+\r
+\r
+\r
+\r
diff --git a/source/mircoders/search/TopicMatrixSearchTerm.java b/source/mircoders/search/TopicMatrixSearchTerm.java
new file mode 100755 (executable)
index 0000000..e9fcf34
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (C) 2001, 2002, 2003 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License, 
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
+ * (or with modified versions of the above that use the same license as the above), 
+ * and distribute linked combinations including the two.  You must obey the 
+ * GNU General Public License in all respects for all of the code used other than 
+ * the above mentioned libraries.  If you modify this file, you may extend this 
+ * exception to your version of the file, but you are not obligated to do so.  
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package mircoders.search;
+
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import mir.entity.Entity;
+import mir.entity.EntityList;
+import mir.storage.StorageObjectFailure;
+import mircoders.entity.EntityContent;
+import mircoders.storage.DatabaseContentToTopics;
+
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+
+
+public class TopicMatrixSearchTerm extends SearchTerm{
+
+
+  public static String matchField       = "topic";
+  public static String paramName        = "search_topicmatrix"; 
+
+  public void index(Document doc, Entity entity) throws StorageObjectFailure{
+    EntityList topics = DatabaseContentToTopics.getInstance().getTopics((EntityContent) entity);
+    if (topics != null && topics.size()>0){
+      for(int k=0;k<topics.size();k++){
+        doc.add(Field.UnStored(matchField,(topics.elementAt(k)).getValue("title")));
+      }
+    }
+  }
+
+  public String makeTerm(HttpServletRequest req){
+    String queryTerm = "";
+    for (int x=0;x<10;x++){
+      String[] values = req.getParameterValues("search_topicmatrix_"+Integer.toString(x));
+      
+      if (values != null && values.length > 0){
+       String subqueryTerm = "(";
+         for (int i=0;i<values.length;i++){
+           subqueryTerm = subqueryTerm + " " + matchField + ":" + "\"" + values[i] + "\"";
+         }
+       subqueryTerm = subqueryTerm + ")";
+       queryTerm = queryTerm + " +" + subqueryTerm;
+      }
+    }
+    if (queryTerm.equals("")){
+      return null;
+    }
+    else {
+      return "( "+queryTerm+ " )";
+    }
+
+  }
+
+  public void returnMeta(Map result,Document doc){
+    return;
+  }
+
+
+}
+
+
index 7836c12..5ed322c 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.servlet;
-
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.struts.util.MessageResources;
-
-
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.generator.Generator;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.util.CachingRewindableIterator;
-import mir.util.ResourceBundleGeneratorFunction;
-import mircoders.global.MirGlobal;
-
-
-public class ServletHelper {
-  static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");
-
-
-  public static Map makeGenerationData(HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc {
-    return makeGenerationData(aResponse, aLocales, "bundles.adminlocal", "bundles.admin");
-  }
-
-  public static Map makeGenerationData(HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc {
-    return makeGenerationData(aResponse, aLocales, aBundle, aBundle);
-  }
-
-  public static Map makeGenerationData(HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc {
-
-    try {
-      Map result = new HashMap();
-
-      MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result);
-
-      // ML: hackish
-      ((Map) result.get("config")).put("actionRoot",
-             aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir"));
-
-      result.put("returnurl", null);
-
-      Object languages =
-          new CachingRewindableIterator(
-            new EntityIteratorAdapter( "", "id", 30,
-               MirGlobal.localizer().dataModel().adapterModel(), "language"));
-      Object topics =
-          new CachingRewindableIterator(
-            new EntityIteratorAdapter("", "id", 30,
-               MirGlobal.localizer().dataModel().adapterModel(), "topic"));
-
-      Object articleTypes =
-          new CachingRewindableIterator(
-            new EntityIteratorAdapter( "", "id", 30,
-               MirGlobal.localizer().dataModel().adapterModel(), "articleType"));
-
-      Object commentStatuses =
-          new CachingRewindableIterator(
-            new EntityIteratorAdapter( "", "id", 30,
-               MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"));
-
-      result.put("commentstatuses", commentStatuses);
-      result.put("articletypes", articleTypes);
-      result.put("languages", languages);
-      result.put("topics", topics);
-
-      result.put( "lang",
-          new ResourceBundleGeneratorFunction( aLocales,
-             new MessageResources[] { MessageResources.getMessageResources(aBundle),
-                                   MessageResources.getMessageResources(aDefaultBundle)}));
-
-      return result;
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {
-    Generator generator;
-
-    try {
-      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);
-
-      generator.generate(aWriter, aGenerationData, logger);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-
-  public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {
-    Generator generator;
-
-    try {
-      generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);
-
-      generator.generate(aWriter, aGenerationData, logger);
-    }
-    catch (Throwable t) {
-      throw new ServletModuleFailure(t);
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.servlet;\r
+\r
+import java.io.PrintWriter;\r
+import java.util.HashMap;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.apache.struts.util.MessageResources;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.entity.adapter.*;\r
+import mir.generator.Generator;\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.ResourceBundleGeneratorFunction;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.global.MirGlobal;\r
+\r
+\r
+public class ServletHelper {\r
+  static LoggerWrapper logger = new LoggerWrapper("ServletModule.Helper");\r
+\r
+\r
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales) throws ServletModuleExc {\r
+    return makeGenerationData(aRequest, aResponse, aLocales, "bundles.adminlocal", "bundles.admin");\r
+  }\r
+\r
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle) throws ServletModuleExc {\r
+    return makeGenerationData(aRequest, aResponse, aLocales, aBundle, aBundle);\r
+  }\r
+\r
+  public static Map makeGenerationData(HttpServletRequest aRequest, HttpServletResponse aResponse, Locale[] aLocales, String aBundle, String aDefaultBundle) throws ServletModuleExc {\r
+\r
+    try {\r
+      Map result = new HashMap();\r
+\r
+      MirGlobal.localizer().producerAssistant().initializeGenerationValueSet(result);\r
+\r
+      // ML: hackish\r
+      ((Map) result.get("config")).put("actionRoot",\r
+             aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/Mir"));\r
+\r
+      result.put("returnurl", null);\r
+      result.put("login_user", getUserAdapter(aRequest));\r
+\r
+      Object languages =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter( "", "id", 30,\r
+               MirGlobal.localizer().dataModel().adapterModel(), "language"));\r
+\r
+      Object topics =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter("", "id", 30,\r
+               MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
+\r
+      Object articleTypes =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter( "", "id", 30,\r
+               MirGlobal.localizer().dataModel().adapterModel(), "articleType"));\r
+\r
+      Object commentStatuses =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter( "", "id", 30,\r
+               MirGlobal.localizer().dataModel().adapterModel(), "commentStatus"));\r
+\r
+      result.put("commentstatuses", commentStatuses);\r
+      result.put("articletypes", articleTypes);\r
+      result.put("languages", languages);\r
+      result.put("topics", topics);\r
+\r
+      result.put( "lang",\r
+          new ResourceBundleGeneratorFunction( aLocales,\r
+             new MessageResources[] { MessageResources.getMessageResources(aBundle),\r
+                MessageResources.getMessageResources(aDefaultBundle)}));\r
+\r
+      return result;\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public static void generateResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {\r
+    logger.debug("generator used: " + aGenerator);\r
+\r
+    Generator generator;\r
+\r
+    try {\r
+      generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator(aGenerator);\r
+\r
+      generator.generate(aWriter, aGenerationData, logger);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public static void generateOpenPostingResponse(PrintWriter aWriter, Map aGenerationData, String aGenerator) throws ServletModuleExc {\r
+    Generator generator;\r
+\r
+    try {\r
+      generator = MirGlobal.localizer().generators().makeOpenPostingGeneratorLibrary().makeGenerator(aGenerator);\r
+\r
+      generator.generate(aWriter, aGenerationData, logger);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public static void redirect(HttpServletResponse aResponse, String aQuery) throws ServletModuleExc, ServletModuleFailure {\r
+    try {\r
+      aResponse.sendRedirect(aResponse.encodeRedirectURL(MirPropertiesConfiguration.instance().getString("RootUri") + "/servlet/Mir?"+aQuery));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure("ServletModule.redirect: " +t.getMessage(), t);\r
+    }\r
+  }\r
+\r
+  public static void redirect(HttpServletResponse aResponse, String aModule, String aMethod) throws ServletModuleExc, ServletModuleFailure {\r
+    redirect(aResponse, "module="+aModule+"&do="+aMethod);\r
+  }\r
+\r
+  public static void setUser(HttpServletRequest aRequest, EntityUsers aUser) {\r
+    if (aUser!=null)\r
+      aRequest.getSession().setAttribute("login.uid", aUser);\r
+    else\r
+      aRequest.getSession().removeAttribute("login.uid");\r
+  }\r
+\r
+  public static EntityUsers getUser(HttpServletRequest aRequest) {\r
+    return (EntityUsers) aRequest.getSession().getAttribute("login.uid");\r
+  }\r
+\r
+  public static EntityAdapter getUserAdapter(HttpServletRequest aRequest) {\r
+    try {\r
+      return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter( "user", (EntityUsers) aRequest.getSession().getAttribute("login.uid"));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure (t);\r
+    }\r
+  }\r
+\r
+  public static String getUserName(HttpServletRequest aRequest) {\r
+    EntityUsers user = getUser(aRequest);\r
+\r
+    if (user!=null)\r
+      return user.getValue("login");\r
+    else\r
+      return "nobody";\r
+  }\r
+}\r
index af691d6..6c0fb93 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mir.util.HTTPRequestParser;
-import mir.util.URLBuilder;
-import mircoders.global.MirGlobal;
-
-public class ServletModuleAbuse extends ServletModule {
-  private static ServletModuleAbuse instance = new ServletModuleAbuse();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleAbuse() {
-    logger = new LoggerWrapper("ServletModule.Abuse");
-    defaultAction = "showsettings";
-  }
-
-  public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String type=requestParser.getParameterWithDefault("type", "");
-    String id=requestParser.getParameterWithDefault("id", "");
-    String expression=requestParser.getParameterWithDefault("expression", "");
-
-    if (id.equals("")) {
-      MirGlobal.abuse().addFilter(type, expression);
-    }
-    else {
-      MirGlobal.abuse().setFilter(id, type, expression);
-    }
-
-    MirGlobal.abuse().save();
-
-    showfilters(aRequest, aResponse);
-  }
-
-  public void deletefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String id=requestParser.getParameterWithDefault("id", "");
-    MirGlobal.abuse().deleteFilter(id);
-
-    MirGlobal.abuse().save();
-
-    showfilters(aRequest, aResponse);
-  }
-
-  public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-
-      urlBuilder.setValue("module", "Abuse");
-      urlBuilder.setValue("do", "showfilters");
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      responseData.put("filters", MirGlobal.abuse().getFilters());
-      responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.filters.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-  public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-
-      urlBuilder.setValue("module", "Abuse");
-      urlBuilder.setValue("do", "showsettings");
-
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());
-      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());
-
-      responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled()));
-      responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword()));
-      responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled()));
-      responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize()));
-      responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock()));
-      responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction());
-      responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    try {
-      HTTPRequestParser parser = new HTTPRequestParser(aRequest);
-
-      MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1"));
-      MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1"));
-      MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1"));
-
-      try {
-        MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize()));
-      }
-      catch (Throwable t) {
-      }
-
-      MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1"));
-
-      MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction"));
-      MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction"));
-
-      MirGlobal.abuse().save();
-
-      showsettings(aRequest, aResponse);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-    int count;
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-      urlBuilder.setValue("module", "Abuse");
-      urlBuilder.setValue("do", "showlog");
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      responseData.put("log", MirGlobal.abuse().getLog());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "abuse.log.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.URLBuilder;\r
+import mircoders.global.Abuse;\r
+import mircoders.global.MirGlobal;\r
+\r
+public class ServletModuleAbuse extends ServletModule {\r
+  private static ServletModuleAbuse instance = new ServletModuleAbuse();\r
+  private String editFilterTemplate;\r
+  private String listFiltersTemplate;\r
+  private String mainTemplate;\r
+  private String viewLogTemplate;\r
+\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleAbuse() {\r
+    logger = new LoggerWrapper("ServletModule.Abuse");\r
+    defaultAction = "showsettings";\r
+\r
+    editFilterTemplate = configuration.getString("ServletModule.Abuse.EditFilter.Template");\r
+    listFiltersTemplate = configuration.getString("ServletModule.Abuse.ListFilters.Template");\r
+    viewLogTemplate = configuration.getString("ServletModule.Abuse.ViewLog.Template");\r
+    mainTemplate = configuration.getString("ServletModule.Abuse.Main.Template");\r
+  }\r
+\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    String id=requestParser.getParameterWithDefault("id", "");\r
+\r
+    if (id.equals("")) {\r
+      editfilter(aRequest, aResponse, "", "", "", "", "", "", "");\r
+    }\r
+    else {\r
+      Abuse.FilterRule filter = MirGlobal.abuse().getFilter(id);\r
+      if (filter==null)\r
+        throw new ServletModuleExc("Filter not found");\r
+\r
+      editfilter(aRequest, aResponse, filter.getId(), filter.getType(), filter.getExpression(), filter.getComments(), filter.getCommentAction(), filter.getArticleAction(), "");\r
+    }\r
+  }\r
+\r
+  public void editfilter(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+        String anId, String aType, String anExpression, String aComments,\r
+        String aCommentAction, String anArticleAction, String anErrorMessage) throws ServletModuleExc {\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      responseData.put("id", anId);\r
+      responseData.put("type", aType);\r
+      responseData.put("expression", anExpression);\r
+      responseData.put("comments", aComments);\r
+      responseData.put("articleaction", anArticleAction);\r
+      responseData.put("commentaction", aCommentAction);\r
+      responseData.put("errormessage", anErrorMessage);\r
+\r
+      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());\r
+      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());\r
+      responseData.put("filtertypes", MirGlobal.abuse().getFilterTypes());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editFilterTemplate);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void updatefilter(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String type=requestParser.getParameterWithDefault("type", "");\r
+    String id=requestParser.getParameterWithDefault("id", "");\r
+    String expression=requestParser.getParameterWithDefault("expression", "");\r
+    String commentaction=requestParser.getParameterWithDefault("commentaction", "");\r
+    String articleaction=requestParser.getParameterWithDefault("articleaction", "");\r
+    String comments=requestParser.getParameterWithDefault("comments", "");\r
+\r
+    String errorMessage;\r
+\r
+    String userName = ServletHelper.getUserName(aRequest);\r
+\r
+    if (id.equals("")) {\r
+      errorMessage = MirGlobal.abuse().addFilter(type, expression,comments, commentaction, articleaction);\r
+    }\r
+    else {\r
+      errorMessage = MirGlobal.abuse().setFilter(id, type, expression, comments, commentaction, articleaction);\r
+    }\r
+\r
+    if (errorMessage!=null) {\r
+      editfilter(aRequest, aResponse, id, type, expression, comments, commentaction, articleaction, errorMessage);\r
+    }\r
+    else {\r
+      MirGlobal.abuse().save();\r
+      showfilters(aRequest, aResponse);\r
+    }\r
+  }\r
+\r
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String id=requestParser.getParameterWithDefault("id", "");\r
+    MirGlobal.abuse().deleteFilter(id);\r
+\r
+    MirGlobal.abuse().save();\r
+\r
+    showfilters(aRequest, aResponse);\r
+  }\r
+\r
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    editfilter(aRequest, aResponse, "", "", "", "", "", "", "");\r
+  }\r
+  public void showfilters(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      urlBuilder.setValue("module", "Abuse");\r
+      urlBuilder.setValue("do", "showfilters");\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      responseData.put("filters", MirGlobal.abuse().getFilters());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listFiltersTemplate);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void showsettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      urlBuilder.setValue("module", "Abuse");\r
+      urlBuilder.setValue("do", "showsettings");\r
+\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      responseData.put("articleactions", MirGlobal.abuse().getArticleActions());\r
+      responseData.put("commentactions", MirGlobal.abuse().getCommentActions());\r
+\r
+      responseData.put("disableop", new Boolean(MirGlobal.abuse().getOpenPostingDisabled()));\r
+      responseData.put("passwordop", new Boolean(MirGlobal.abuse().getOpenPostingPassword()));\r
+      responseData.put("logenabled", new Boolean(MirGlobal.abuse().getLogEnabled()));\r
+      responseData.put("logsize", Integer.toString(MirGlobal.abuse().getLogSize()));\r
+      responseData.put("usecookies", new Boolean(MirGlobal.abuse().getCookieOnBlock()));\r
+      responseData.put("articleaction", MirGlobal.abuse().getArticleBlockAction());\r
+      responseData.put("commentaction", MirGlobal.abuse().getCommentBlockAction());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, mainTemplate);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void savesettings(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    try {\r
+      HTTPRequestParser parser = new HTTPRequestParser(aRequest);\r
+\r
+      MirGlobal.abuse().setOpenPostingDisabled(parser.getParameterWithDefault("disableop", "").equals("1"));\r
+      MirGlobal.abuse().setOpenPostingPassword(parser.getParameterWithDefault("passwordop", "").equals("1"));\r
+      MirGlobal.abuse().setLogEnabled(parser.getParameterWithDefault("logenabled", "").equals("1"));\r
+\r
+      try {\r
+        MirGlobal.abuse().setLogSize(parser.getIntegerWithDefault("logsize", MirGlobal.abuse().getLogSize()));\r
+      }\r
+      catch (Throwable t) {\r
+      }\r
+\r
+      MirGlobal.abuse().setCookieOnBlock(parser.getParameterWithDefault("usecookies", "").equals("1"));\r
+\r
+      MirGlobal.abuse().setArticleBlockAction(parser.getParameter("articleaction"));\r
+      MirGlobal.abuse().setCommentBlockAction(parser.getParameter("commentaction"));\r
+\r
+      MirGlobal.abuse().save();\r
+\r
+      showsettings(aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void showlog(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      urlBuilder.setValue("module", "Abuse");\r
+      urlBuilder.setValue("do", "showlog");\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      responseData.put("log", MirGlobal.abuse().getLog());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, viewLogTemplate);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
 }
\ No newline at end of file
index 4b591e9..ec85a08 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.servlet;
-
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mir.util.URLBuilder;
-
-public class ServletModuleAdmin extends ServletModule
-{
-  private static ServletModuleAdmin instance = new ServletModuleAdmin();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleAdmin() {
-    logger = new LoggerWrapper("ServletModule.Admin");
-    defaultAction = "showSuperUserMenu";
-  }
-
-  public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) {
-    URLBuilder urlBuilder = new URLBuilder();
-    int count;
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-      urlBuilder.setValue("module", "Admin");
-      urlBuilder.setValue("do", "superusermenu");
-
-      responseData.put("thisurl" , urlBuilder.getQuery());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.servlet;\r
+\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.URLBuilder;\r
+import mircoders.global.MirGlobal;\r
+\r
+public class ServletModuleAdmin extends ServletModule\r
+{\r
+  private static ServletModuleAdmin instance = new ServletModuleAdmin();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleAdmin() {\r
+    logger = new LoggerWrapper("ServletModule.Admin");\r
+    defaultAction = "start";\r
+  }\r
+\r
+  public void superusermenu(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      urlBuilder.setValue("module", "Admin");\r
+      urlBuilder.setValue("do", "superusermenu");\r
+\r
+      responseData.put("thisurl" , urlBuilder.getQuery());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "superusermenu.template");\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void start(HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    String startTemplate = configuration.getString("Mir.StartTemplate");\r
+    String sessionUrl = aResponse.encodeURL("");\r
+\r
+    try {\r
+      Map mergeData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)}\r
+          , "bundles.admin", "bundles.adminlocal");\r
+      mergeData.put("messages",\r
+                    new CachingRewindableIterator(\r
+          new EntityIteratorAdapter("", "webdb_create desc", 10,\r
+                                    MirGlobal.localizer().dataModel().adapterModel(), "internalMessage", 10, 0)));\r
+\r
+      mergeData.put("fileeditentries", ( (ServletModuleFileEdit) ServletModuleFileEdit.getInstance()).getEntries());\r
+      mergeData.put("administeroperations", ( (ServletModuleLocalizer) ServletModuleLocalizer.getInstance()).getAdministerOperations());\r
+\r
+      mergeData.put("searchvalue", null);\r
+      mergeData.put("searchfield", null);\r
+      mergeData.put("searchispublished", null);\r
+      mergeData.put("searcharticletype", null);\r
+      mergeData.put("searchorder", null);\r
+      mergeData.put("selectarticleurl", null);\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), mergeData, startTemplate);\r
+    }\r
+    catch (Exception e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+}\r
index 826d4f8..63de8b3 100755 (executable)
@@ -1,56 +1,64 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.servlet;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mircoders.module.ModuleArticleType;
-import mircoders.storage.DatabaseArticleType;
-
-public class ServletModuleArticleType extends ServletModule
-{
-  private static ServletModuleArticleType instance = new ServletModuleArticleType();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleArticleType() {
-    logger = new LoggerWrapper("ServletModule.ArticleType");
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-      templateListString = configuration.getString("ServletModule.ArticleType.ListTemplate");
-      templateObjektString = configuration.getString("ServletModule.ArticleType.EditTemplate");
-      templateConfirmString = configuration.getString("ServletModule.ArticleType.ConfirmTemplate");
-      mainModule = new ModuleArticleType(DatabaseArticleType.getInstance());
-    }
-    catch (Exception e) {
-      logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.servlet;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleArticleType;\r
+import mircoders.storage.DatabaseArticleType;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+public class ServletModuleArticleType extends ServletModule\r
+{\r
+  private static ServletModuleArticleType instance = new ServletModuleArticleType();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleArticleType() {\r
+    logger = new LoggerWrapper("ServletModule.ArticleType");\r
+\r
+    try {\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+      definition = "articleType";\r
+      mainModule = new ModuleArticleType(DatabaseArticleType.getInstance());\r
+    }\r
+    catch (Exception e) {\r
+      logger.error("Initialization of ServletModuleArticleType failed!: " + e.getMessage());\r
+    }\r
+  }\r
+}\r
index 91a4646..a35f177 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.servlet;
@@ -34,6 +34,7 @@ import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseAudio;
+import mircoders.global.*;
 
 /*
  *
@@ -42,10 +43,6 @@ import mircoders.storage.DatabaseAudio;
  */
 
 public class ServletModuleAudio extends ServletModuleUploadedMedia {
-
-  //private static DatabaseRights dbRights;
-
-  // Singelton / Contructor
   private static ServletModuleAudio instance = new ServletModuleAudio();
 
   public static ServletModule getInstance() {
@@ -54,15 +51,15 @@ public class ServletModuleAudio extends ServletModuleUploadedMedia {
 
   private ServletModuleAudio() {
     logger = new LoggerWrapper("ServletModule.Audio");
+
+    moduleName = "Audio";
+
     try {
-      configuration = MirPropertiesConfiguration.instance();
-      templateListString = configuration.getString("ServletModule.Audio.ListTemplate");
-      templateObjektString = configuration.getString("ServletModule.Audio.ObjektTemplate");
-      templateConfirmString = configuration.getString("ServletModule.Audio.ConfirmTemplate");
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "audio";
       mainModule = new ModuleUploadedMedia(DatabaseAudio.getInstance());
-      //dbRights = DatabaseRights.getInstance();
     }
-    catch (Exception e) {
+    catch (Throwable e) {
       logger.error("servletmodule audio could not be initialized: " + e.getMessage());
     }
   }
index 536d6da..ca65981 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.net.URLEncoder;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleFailure;
-import mircoders.module.ModuleBreaking;
-import mircoders.storage.DatabaseBreaking;
-import freemarker.template.SimpleHash;
-
-/*
- *  ServletModuleBreaking -
- *  Authentified Navigation for Breaking News
- *
- *
- */
-
-public class ServletModuleBreaking extends ServletModule
-{
-
-// Singelton / Kontruktor
-
-  private static ServletModuleBreaking instance = new ServletModuleBreaking();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleBreaking() {
-    logger = new LoggerWrapper("ServletModule.Breaking");
-    try {
-                        configuration = MirPropertiesConfiguration.instance();
-
-      templateListString = configuration.getString("ServletModule.Breaking.ListTemplate");
-      templateObjektString = configuration.getString("ServletModule.Breaking.ObjektTemplate");
-      templateConfirmString = configuration.getString("ServletModule.Breaking.ConfirmTemplate");
-
-      DatabaseBreaking dbb = DatabaseBreaking.getInstance();
-      mainModule = new ModuleBreaking(dbb);
-    }
-    catch (Exception e) {
-      logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage());
-    }
-  }
-
-  public void list(HttpServletRequest req, HttpServletResponse res)
-  {
-    logger.debug("-- breaking: list");
-// fetch and deliver
-    try {
-      SimpleHash mergeData = new SimpleHash();
-      String offset = req.getParameter("offset");
-      if (offset==null || offset.equals("")) offset="0";
-      mergeData.put("offset",offset);
-      EntityList theList = mainModule.getByWhereClause(null, "webdb_create desc", (new Integer(offset)).intValue());
-      mergeData.put("contentlist",theList);
-      if(theList.getOrder()!=null) {
-        mergeData.put("order", theList.getOrder());
-        mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
-      }
-      mergeData.put("count", (new Integer(theList.getCount())).toString());
-      mergeData.put("from", (new Integer(theList.getFrom())).toString());
-      mergeData.put("to", (new Integer(theList.getTo())).toString());
-      if (theList.hasNextBatch())
-        mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
-      if (theList.hasPrevBatch())
-        mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
-
-// raus damit
-      HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req));
-    }
-    catch (Exception e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleBreaking;\r
+import mircoders.storage.DatabaseBreaking;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class ServletModuleBreaking extends ServletModule\r
+{\r
+  private static ServletModuleBreaking instance = new ServletModuleBreaking();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleBreaking() {\r
+    logger = new LoggerWrapper("ServletModule.Breaking");\r
+\r
+    try {\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+      definition = "breakingNews";\r
+      mainModule = new ModuleBreaking(DatabaseBreaking.getInstance());\r
+    }\r
+    catch (Exception e) {\r
+      logger.error("Initialisation of ServletModuleBreaking failed!: " + e.getMessage());\r
+    }\r
+  }\r
+}\r
index 2704343..251c37c 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.servlet.ServletModuleUserExc;
-import mir.util.CachingRewindableIterator;
-import mir.util.HTTPRequestParser;
-import mir.util.JDBCStringRoutines;
-import mir.util.SQLQueryBuilder;
-import mir.util.URLBuilder;
-import mircoders.entity.EntityComment;
-import mircoders.global.MirGlobal;
-import mircoders.module.ModuleComment;
-import mircoders.module.ModuleContent;
-import mircoders.storage.DatabaseComment;
-import mircoders.storage.DatabaseContent;
-
-/*
- *  ServletModuleComment - controls navigation for Comments
- *
- *
- *  @author RK
- */
-
-public class ServletModuleComment extends ServletModule
-{
-  private ModuleContent     moduleContent;
-
-  private static ServletModuleComment instance = new ServletModuleComment();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleComment() {
-    logger = new LoggerWrapper("ServletModule.Comment");
-    try {
-      configuration = MirPropertiesConfiguration.instance();
-      templateListString = configuration.getString("ServletModule.Comment.ListTemplate");
-      templateObjektString = configuration.getString("ServletModule.Comment.ObjektTemplate");
-      templateConfirmString = configuration.getString("ServletModule.Comment.ConfirmTemplate");
-
-      mainModule = new ModuleComment(DatabaseComment.getInstance());
-      moduleContent = new ModuleContent(DatabaseContent.getInstance());
-    }
-    catch (Exception e) {
-      logger.error("servletmodule comment could not be initialized:" + e.getMessage());
-    }
-  }
-
-  public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {
-    if (!configuration.getString("Mir.Localizer.Admin.AllowDeleteArticle", "0").equals("1"))
-      throw new ServletModuleExc("Operation not permitted");
-
-    super.delete(req, res);
-  }
-
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String idParam = req.getParameter("id");
-
-    if (idParam == null)
-      throw new ServletModuleExc("Invalid call: id not supplied ");
-
-    showComment(idParam, req, res);
-  }
-
-  public void showComment(String anId, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});
-      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
-      Map comment;
-      URLBuilder urlBuilder = new URLBuilder();
-
-      urlBuilder.setValue("module", "Comment");
-      urlBuilder.setValue("do", "edit");
-      urlBuilder.setValue("id", anId);
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
-
-      if (anId != null) {
-        responseData.put("new", Boolean.FALSE);
-        comment = model.makeEntityAdapter("comment", mainModule.getById(anId));
-      }
-      else {
-        List fields = DatabaseComment.getInstance().getFields();
-        responseData.put("new", Boolean.TRUE);
-        comment = new HashMap();
-        Iterator i = fields.iterator();
-        while (i.hasNext()) {
-          comment.put(i.next(), null);
-        }
-
-//        MirGlobal.localizer().adminInterface().initializeArticle(article);
-      }
-      responseData.put("comment", comment);
-
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String  mediaIdParam = req.getParameter("mid");
-    String  commentId = req.getParameter("commentid");
-
-    if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");
-
-    try {
-      EntityComment comment = (EntityComment) mainModule.getById(commentId);
-      comment.attach(mediaIdParam);
-    }
-    catch(Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-
-    showComment(commentId, req, res);
-  }
-
-  public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String  commentId = req.getParameter("commentid");
-    String  midParam = req.getParameter("mid");
-    if (commentId == null)
-      throw new ServletModuleExc("smod comment :: dettach :: commentid missing");
-    if (midParam == null)
-      throw new ServletModuleExc("smod comment :: dettach :: mid missing");
-
-    try {
-      EntityComment comment = (EntityComment)mainModule.getById(commentId);
-      comment.dettach(commentId, midParam);
-    }
-    catch(Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-
-    showComment(commentId, req, res);
-  }
-
-
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String where = requestParser.getParameter("where");
-    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
-    int offset = requestParser.getIntegerWithDefault("offset", 0);
-
-    returnCommentList(aRequest, aResponse, where, order, offset);
-  }
-
-  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
-
-    String queryField = "";
-    String searchField = requestParser.getParameter("searchfield");
-    String searchText = requestParser.getParameter("searchtext");
-    String searchIsPublished = requestParser.getParameter("searchispublished");
-    String searchStatus = requestParser.getParameter("searchstatus");
-    String searchOrder = requestParser.getParameter("searchorder");
-
-    if (searchIsPublished.equals("0")) {
-      queryBuilder.appendAndCondition("is_published='f'");
-    }
-    else if (searchIsPublished.equals("1")) {
-      queryBuilder.appendAndCondition("is_published='t'");
-    }
-
-    if (searchText.length()>0) {
-        queryBuilder.appendAndCondition(
-          "lower("+ searchField + ") like " +
-          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");
-    }
-
-    if (searchStatus.length()>0) {
-      queryBuilder.appendAndCondition("to_comment_status="+Integer.parseInt(searchStatus));
-    }
-
-    if (searchOrder.length()>0) {
-      if (searchOrder.equals("datedesc"))
-        queryBuilder.appendAscendingOrder("webdb_create");
-      else if (searchOrder.equals("dateasc"))
-        queryBuilder.appendDescendingOrder("webdb_create");
-      else if (searchOrder.equals("articletitle"))
-        queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)");
-      else if (searchOrder.equals("creator"))
-        queryBuilder.appendDescendingOrder("creator");
-    }
-
-    returnCommentList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);
-  }
-
-  public void articlecomments(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String articleIdString = req.getParameter("articleid");
-    int articleId;
-
-    try {
-      articleId  = Integer.parseInt(articleIdString);
-
-      returnCommentList( req, res, "to_media="+articleId, "webdb_create desc", 0);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void returnCommentList(HttpServletRequest aRequest, HttpServletResponse aResponse,
-     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {
-
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    URLBuilder urlBuilder = new URLBuilder();
-    EntityAdapterModel model;
-    int nrCommentsPerPage = 20;
-    int count;
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-      model = MirGlobal.localizer().dataModel().adapterModel();
-
-      Object commentList =
-          new CachingRewindableIterator(
-            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrCommentsPerPage,
-              MirGlobal.localizer().dataModel().adapterModel(), "comment", nrCommentsPerPage, anOffset)
-      );
-
-      responseData.put("nexturl", null);
-      responseData.put("prevurl", null);
-
-      count=mainModule.getSize(aWhereClause);
-
-      urlBuilder.setValue("module", "Comment");
-      urlBuilder.setValue("do", "list");
-      urlBuilder.setValue("where", aWhereClause);
-      urlBuilder.setValue("order", anOrderByClause);
-
-      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
-      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));
-      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
-      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));
-      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
-
-      responseData.put("searchfield", requestParser.getParameter("searchfield"));
-      responseData.put("searchtext", requestParser.getParameter("searchtext"));
-      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
-      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));
-      responseData.put("searchorder", requestParser.getParameter("searchorder"));
-
-      urlBuilder.setValue("offset", anOffset);
-      responseData.put("offset" , new Integer(anOffset).toString());
-      responseData.put("thisurl" , urlBuilder.getQuery());
-
-      if (count>=anOffset+nrCommentsPerPage) {
-        urlBuilder.setValue("offset", anOffset + nrCommentsPerPage);
-        responseData.put("nexturl" , urlBuilder.getQuery());
-      }
-
-      if (anOffset>0) {
-        urlBuilder.setValue("offset", Math.max(anOffset - nrCommentsPerPage, 0));
-        responseData.put("prevurl" , urlBuilder.getQuery());
-      }
-
-      responseData.put("comments", commentList);
-      responseData.put("from" , Integer.toString(anOffset+1));
-      responseData.put("count", Integer.toString(count));
-      responseData.put("to", Integer.toString(Math.min(anOffset+nrCommentsPerPage, count)));
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "commentlist.template");
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-}
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.servlet.ServletModuleUserExc;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.JDBCStringRoutines;\r
+import mir.util.SQLQueryBuilder;\r
+import mir.util.URLBuilder;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleComment;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.storage.DatabaseComment;\r
+import mircoders.storage.DatabaseContent;\r
+\r
+/*\r
+ *  ServletModuleComment - controls navigation for Comments\r
+ *\r
+ *\r
+ *  @author the mir-coders\r
+ */\r
+\r
+public class ServletModuleComment extends ServletModule\r
+{\r
+  private ModuleContent  moduleContent;\r
+\r
+  private static ServletModuleComment instance = new ServletModuleComment();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleComment() {\r
+    logger = new LoggerWrapper("ServletModule.Comment");\r
+    try {\r
+      mainModule = new ModuleComment(DatabaseComment.getInstance());\r
+      moduleContent = new ModuleContent(DatabaseContent.getInstance());\r
+    }\r
+    catch (Exception e) {\r
+      logger.error("servletmodule comment could not be initialized:" + e.getMessage());\r
+    }\r
+  }\r
+\r
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure {\r
+    try {\r
+      MirGlobal.accessControl().general().assertMayDeleteComments(ServletHelper.getUser(aRequest));\r
+\r
+      super.delete(aRequest, aResponse);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String idParam = aRequest.getParameter("id");\r
+\r
+    if (idParam == null)\r
+      throw new ServletModuleExc("Invalid call: id not supplied ");\r
+\r
+    showComment(idParam, aRequest, aResponse);\r
+  }\r
+\r
+  public void showComment(String anId, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
+      Map comment;\r
+      URLBuilder urlBuilder = new URLBuilder();\r
+\r
+      urlBuilder.setValue("module", "Comment");\r
+      urlBuilder.setValue("do", "edit");\r
+      urlBuilder.setValue("id", anId);\r
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+\r
+      if (anId != null) {\r
+        responseData.put("new", Boolean.FALSE);\r
+        comment = model.makeEntityAdapter("comment", mainModule.getById(anId));\r
+      }\r
+      else {\r
+        List fields = DatabaseComment.getInstance().getFields();\r
+        responseData.put("new", Boolean.TRUE);\r
+        comment = new HashMap();\r
+        Iterator i = fields.iterator();\r
+        while (i.hasNext()) {\r
+          comment.put(i.next(), null);\r
+        }\r
+      }\r
+      responseData.put("comment", comment);\r
+\r
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String  mediaIdParam = aRequest.getParameter("mid");\r
+    String  commentId = aRequest.getParameter("commentid");\r
+\r
+    if (commentId == null || mediaIdParam==null) throw new ServletModuleExc("smod comment :: attach :: commentid/mid missing");\r
+\r
+    try {\r
+      EntityComment comment = (EntityComment) mainModule.getById(commentId);\r
+      comment.attach(mediaIdParam);\r
+    }\r
+    catch(Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+\r
+    showComment(commentId, aRequest, aResponse);\r
+  }\r
+\r
+  public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String  commentId = aRequest.getParameter("commentid");\r
+    String  midParam = aRequest.getParameter("mid");\r
+    if (commentId == null)\r
+      throw new ServletModuleExc("smod comment :: dettach :: commentid missing");\r
+    if (midParam == null)\r
+      throw new ServletModuleExc("smod comment :: dettach :: mid missing");\r
+\r
+    try {\r
+      EntityComment comment = (EntityComment)mainModule.getById(commentId);\r
+      comment.dettach(commentId, midParam);\r
+    }\r
+    catch(Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+\r
+    showComment(commentId, aRequest, aResponse);\r
+  }\r
+\r
+\r
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String where = requestParser.getParameter("where");\r
+    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");\r
+    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
+\r
+    returnCommentList(aRequest, aResponse, where, order, offset);\r
+  }\r
+\r
+  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
+\r
+    String queryField = "";\r
+    String searchField = requestParser.getParameter("searchfield");\r
+    String searchText = requestParser.getParameter("searchtext");\r
+    String searchIsPublished = requestParser.getParameter("searchispublished");\r
+    String searchStatus = requestParser.getParameter("searchstatus");\r
+    String searchOrder = requestParser.getParameter("searchorder");\r
+\r
+    if (searchIsPublished.equals("0")) {\r
+      queryBuilder.appendAndCondition("is_published='f'");\r
+    }\r
+    else if (searchIsPublished.equals("1")) {\r
+      queryBuilder.appendAndCondition("is_published='t'");\r
+    }\r
+\r
+    if (searchText.length()>0) {\r
+        queryBuilder.appendAndCondition(\r
+          "lower("+ searchField + ") like " +\r
+          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");\r
+    }\r
+\r
+    if (searchStatus.length()>0) {\r
+      queryBuilder.appendAndCondition("to_comment_status="+Integer.parseInt(searchStatus));\r
+    }\r
+\r
+    if (searchOrder.length()>0) {\r
+      if (searchOrder.equals("datedesc"))\r
+        queryBuilder.appendAscendingOrder("webdb_create");\r
+      else if (searchOrder.equals("dateasc"))\r
+        queryBuilder.appendDescendingOrder("webdb_create");\r
+      else if (searchOrder.equals("articletitle"))\r
+        queryBuilder.appendAscendingOrder("(select content.title from content where content.id = comment.to_media)");\r
+      else if (searchOrder.equals("creator"))\r
+        queryBuilder.appendDescendingOrder("creator");\r
+    }\r
+\r
+    returnCommentList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0);\r
+  }\r
+\r
+  public void articlecomments(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String articleIdString = aRequest.getParameter("articleid");\r
+    int articleId;\r
+\r
+    try {\r
+      articleId  = Integer.parseInt(articleIdString);\r
+\r
+      returnCommentList( aRequest, aResponse, "to_media="+articleId, "webdb_create desc", 0);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void returnCommentList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+     String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
+\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    EntityAdapterModel model;\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+\r
+      Object commentList =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,\r
+              MirGlobal.localizer().dataModel().adapterModel(), "comment", nrEntitiesPerListPage, anOffset)\r
+      );\r
+\r
+      responseData.put("nexturl", null);\r
+      responseData.put("prevurl", null);\r
+\r
+      count=mainModule.getSize(aWhereClause);\r
+\r
+      urlBuilder.setValue("module", "Comment");\r
+      urlBuilder.setValue("do", "list");\r
+      urlBuilder.setValue("where", aWhereClause);\r
+      urlBuilder.setValue("order", anOrderByClause);\r
+\r
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
+      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));\r
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
+      urlBuilder.setValue("searchstatus", requestParser.getParameter("searchstatus"));\r
+      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
+\r
+      responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
+      responseData.put("searchtext", requestParser.getParameter("searchtext"));\r
+      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
+      responseData.put("searchstatus", requestParser.getParameter("searchstatus"));\r
+      responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
+\r
+      urlBuilder.setValue("offset", anOffset);\r
+      responseData.put("offset" , new Integer(anOffset).toString());\r
+      responseData.put("thisurl" , urlBuilder.getQuery());\r
+\r
+      if (count>=anOffset+nrEntitiesPerListPage) {\r
+        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);\r
+        responseData.put("nexturl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      if (anOffset>0) {\r
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
+        responseData.put("prevurl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      responseData.put("comments", commentList);\r
+      responseData.put("from" , Integer.toString(anOffset+1));\r
+      responseData.put("count", Integer.toString(count));\r
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+      String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+      String idParam = aRequest.getParameter("id");\r
+      if (idParam == null)\r
+        throw new ServletModuleExc("Wrong call: (id) is missing");\r
+\r
+      Map withValues = getIntersectingValues(aRequest, DatabaseComment.getInstance());\r
+\r
+      String content_id = aRequest.getParameter("id");\r
+\r
+      if (!withValues.containsKey("is_published"))\r
+        withValues.put("is_published","0");\r
+      if (!withValues.containsKey("is_html"))\r
+        withValues.put("is_html","0");\r
+\r
+      String webdbCreate = (String) withValues.get("webdb_create");\r
+      if (webdbCreate==null || webdbCreate.trim().length()==0)\r
+        withValues.remove("webdb_create");\r
+\r
+      String id = mainModule.set(withValues);\r
+\r
+      if (returnUrl!=null){\r
+        redirect(aResponse, returnUrl);\r
+      }\r
+      else\r
+        showComment(idParam, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+}
\ No newline at end of file
index 2f13787..7696fee 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.servlet;
@@ -34,6 +34,8 @@ import mir.log.LoggerWrapper;
 import mir.servlet.ServletModule;
 import mircoders.module.ModuleCommentStatus;
 import mircoders.storage.DatabaseCommentStatus;
+import mircoders.global.*;
+
 
 public class ServletModuleCommentStatus extends ServletModule
 {
@@ -44,13 +46,11 @@ public class ServletModuleCommentStatus extends ServletModule
     logger = new LoggerWrapper("ServletModule.CommentStatus");
 
     try {
-      configuration = MirPropertiesConfiguration.instance();
-      templateListString = configuration.getString("ServletModule.CommentStatus.ListTemplate");
-      templateObjektString = configuration.getString("ServletModule.CommentStatus.EditTemplate");
-      templateConfirmString = configuration.getString("ServletModule.CommentStatus.ConfirmTemplate");
-
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "commentStatus";
       mainModule = new ModuleCommentStatus(DatabaseCommentStatus.getInstance());
-    } catch (Exception e) {
+    }
+    catch (Throwable e) {
       logger.error("Initialization of ServletModuleCommentStatus failed!: " + e.getMessage());
     }
   }
index 2730972..c9d6586 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.util.GregorianCalendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.entity.adapter.EntityAdapterModel;
-import mir.entity.adapter.EntityIteratorAdapter;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.util.CachingRewindableIterator;
-import mir.util.HTTPRequestParser;
-import mir.util.JDBCStringRoutines;
-import mir.util.SQLQueryBuilder;
-import mir.util.URLBuilder;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityUsers;
-import mircoders.global.MirGlobal;
-import mircoders.module.ModuleContent;
-import mircoders.search.IndexUtil;
-import mircoders.storage.DatabaseComment;
-import mircoders.storage.DatabaseContent;
-import mircoders.storage.DatabaseContentToMedia;
-import mircoders.storage.DatabaseContentToTopics;
-
-import org.apache.lucene.index.IndexReader;
-
-import freemarker.template.SimpleHash;
-
-/*
- *  ServletModuleContent -
- *  deliver html for the article admin form.
- *
- * @version $Id: ServletModuleContent.java,v 1.52 2003/05/08 02:43:42 zapata Exp $
- * @author rk, mir-coders
- *
- */
-
-public class ServletModuleContent extends ServletModule
-{
-  private String editTemplate = configuration.getString("ServletModule.Content.ObjektTemplate");;
-  private String listTemplate = configuration.getString("ServletModule.Content.ListTemplate");
-
-  private static ServletModuleContent instance = new ServletModuleContent();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleContent() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Content");
-    try {
-
-      templateListString = configuration.getString("ServletModule.Content.ListTemplate");
-      templateObjektString = configuration.getString("ServletModule.Content.ObjektTemplate");
-      templateConfirmString = configuration.getString("ServletModule.Content.ConfirmTemplate");
-
-      mainModule = new ModuleContent(DatabaseContent.getInstance());
-    }
-    catch (Throwable e) {
-      logger.fatal("ServletModuleContent could not be initialized: " + e.toString());
-    }
-  }
-
-  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-    String where = requestParser.getParameter("where");
-    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");
-    int offset = requestParser.getIntegerWithDefault("offset", 0);
-    String selectArticleUrl = requestParser.getParameter("selectarticleurl");
-
-    returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl);
-  }
-
-  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      SQLQueryBuilder queryBuilder = new SQLQueryBuilder();
-      String searchField = requestParser.getParameterWithDefault("searchfield", "");
-      String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();
-      String searchOrder = requestParser.getParameterWithDefault("searchorder", "");
-      String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");
-      String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");
-      String selectArticleUrl = requestParser.getParameter("selectarticleurl");
-
-      if (searchValue.length()>0) {
-        if (searchField.equals("id"))
-          queryBuilder.appendAndCondition(
-            "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");
-        else if (searchField.equals("contents"))
-          queryBuilder.appendAndCondition(
-            "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+
-            " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");
-        else
-          queryBuilder.appendAndCondition(
-            "lower("+ searchField + ") like " +
-            "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");
-      }
-
-      if (searchispublished.length()>0) {
-        if (searchispublished.equals("0"))
-          queryBuilder.appendAndCondition("is_published='f'");
-        else
-          queryBuilder.appendAndCondition("is_published='t'");
-      }
-
-      if (searchArticleType.length()>0) {
-        queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));
-      }
-
-      if (searchOrder.length()>0) {
-        if (searchOrder.equals("datedesc"))
-          queryBuilder.appendAscendingOrder("webdb_create");
-        else if (searchOrder.equals("dateasc"))
-          queryBuilder.appendDescendingOrder("webdb_create");
-        else if (searchOrder.equals("title"))
-          queryBuilder.appendDescendingOrder("title");
-        else if (searchOrder.equals("creator"))
-          queryBuilder.appendDescendingOrder("creator");
-      }
-
-      returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    _showObject(null, req, res);
-  }
-
-
-  public void insert(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-//theLog.printDebugInfo(":: content :: trying to insert");
-    try {
-      EntityUsers   user = _getUser(req);
-      Map withValues = getIntersectingValues(req, DatabaseContent.getInstance());
-
-      String now = StringUtil.date2webdbDate(new GregorianCalendar());
-      withValues.put("date", now);
-      withValues.put("publish_path", StringUtil.webdbDate2path(now));
-      withValues.put("to_publisher", user.getId());
-      withValues.put("is_produced", "0");
-      if (!withValues.containsKey("is_published"))
-        withValues.put("is_published","0");
-      if (!withValues.containsKey("is_html"))
-        withValues.put("is_html","0");
-
-      String id = mainModule.add(withValues);
-      List topics;
-
-      DatabaseContentToTopics.getInstance().setTopics(id, req.getParameterValues("to_topic"));
-
-      _showObject(id, req, res);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void delete(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    if (!configuration.getString("Mir.Localizer.Admin.AllowDeleteArticle", "0").equals("1"))
-      throw new ServletModuleExc("Operation not permitted");
-
-    EntityUsers   user = _getUser(req);
-
-    String idParam = req.getParameter("id");
-    if (idParam == null) throw new ServletModuleExc("Invalid call: id missing");
-
-    String confirmParam = req.getParameter("confirm");
-    String cancelParam = req.getParameter("cancel");
-
-    logger.info("where = " + req.getParameter("where"));
-
-    if (confirmParam == null && cancelParam == null) {
-
-      SimpleHash mergeData = new SimpleHash();
-      mergeData.put("module", "Content");
-      mergeData.put("infoString", "Content: " + idParam);
-      mergeData.put("id", idParam);
-      mergeData.put("where", req.getParameter("where"));
-      mergeData.put("order", req.getParameter("order"));
-      mergeData.put("offset", req.getParameter("offset"));
-      deliver(req, res, mergeData, templateConfirmString);
-    }
-    else {
-      if (confirmParam!= null && !confirmParam.equals("")) {
-        try {
-          mainModule.deleteById(idParam);
-
-          /** @todo the following two should be implied in
-           *  DatabaseContent */
-          DatabaseContentToTopics.getInstance().deleteByContentId(idParam);
-          DatabaseComment.getInstance().deleteByContentId(idParam);
-          DatabaseContentToMedia.getInstance().deleteByContentId(idParam);
-
-
-          //delete from lucene index, if any
-          String index = configuration.getString("IndexPath");
-          if (IndexReader.indexExists(index)){
-            IndexUtil.unindexID(idParam,index);
-          }
-
-        }
-        catch (Throwable e) {
-          throw new ServletModuleFailure(e);
-        }
-        list(req,res);
-      }
-      else {
-        // Datensatz anzeigen
-        _showObject(idParam, req, res);
-      }
-    }
-  }
-
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String idParam = req.getParameter("id");
-    if (idParam == null)
-      throw new ServletModuleExc("Invalid call: id not supplied ");
-    _showObject(idParam, req, res);
-  }
-
-// methods for attaching media file
-  public void attach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String  mediaIdParam = req.getParameter("mid");
-    String  articleId = req.getParameter("articleid");
-
-    if (articleId == null || mediaIdParam==null)
-      throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");
-
-    try {
-      EntityContent entContent = (EntityContent) mainModule.getById(articleId);
-      entContent.attach(mediaIdParam);
-    }
-    catch(Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-
-    _showObject(articleId, req, res);
-  }
-
-  public void dettach(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String  articleId = req.getParameter("articleid");
-    String  midParam = req.getParameter("mid");
-    if (articleId == null)
-      throw new ServletModuleExc("smod content :: dettach :: articleid missing");
-    if (midParam == null)
-      throw new ServletModuleExc("smod content :: dettach :: mid missing");
-
-    try {
-      EntityContent entContent = (EntityContent)mainModule.getById(articleId);
-      entContent.dettach(articleId, midParam);
-    }
-    catch(Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-
-    _showObject(articleId, req, res);
-  }
-
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-      String returnUrl = requestParser.getParameter("returnurl");
-
-      String idParam = aRequest.getParameter("id");
-      if (idParam == null)
-        throw new ServletModuleExc("Wrong call: (id) is missing");
-
-      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());
-
-      String content_id = aRequest.getParameter("id");
-
-      withValues.put("is_produced", "0");
-      if (!withValues.containsKey("is_published"))
-        withValues.put("is_published","0");
-      if (!withValues.containsKey("is_html"))
-        withValues.put("is_html","0");
-
-      String id = mainModule.set(withValues);
-      DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));
-
-      String whereParam = aRequest.getParameter("where");
-      String orderParam = aRequest.getParameter("order");
-
-      if (returnUrl!=null){
-        redirect(aResponse, returnUrl);
-      }
-      else
-        _showObject(idParam, aRequest, aResponse);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-  /**
-   * HelperMethod shows the basic article editing form.
-   *
-   * if the "id" parameter is null, it means show an empty form to add a new
-   * article.
-   *
-   * @param id
-   * @param aRequest
-   * @param aResponse
-   * @throws ServletModuleExc
-   */
-  public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();
-      Map article;
-      URLBuilder urlBuilder = new URLBuilder();
-
-      urlBuilder.setValue("module", "Content");
-      urlBuilder.setValue("do", "edit");
-      urlBuilder.setValue("id", id);
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
-
-      if (id!=null) {
-        responseData.put("new", Boolean.FALSE);
-        article = model.makeEntityAdapter("content", mainModule.getById(id));
-      }
-      else {
-        List fields = DatabaseContent.getInstance().getFields();
-        responseData.put("new", Boolean.TRUE);
-        article = new HashMap();
-        Iterator i = fields.iterator();
-        while (i.hasNext()) {
-          article.put(i.next(), null);
-        }
-
-        article.put("to_topics", null);
-
-        MirGlobal.localizer().adminInterface().initializeArticle(article);
-      }
-      responseData.put("article", article);
-
-      responseData.put("topics",
-          new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"),
-          20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));
-
-
-
-      responseData.put("returnurl", requestParser.getParameter("returnurl"));
-      responseData.put("thisurl", urlBuilder.getQuery());
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editTemplate);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void returnArticleList(
-       HttpServletRequest aRequest,
-       HttpServletResponse aResponse,
-       String aWhereClause,
-       String anOrderByClause,
-       int anOffset,
-       String aSelectArticleUrl) throws ServletModuleExc {
-
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    URLBuilder urlBuilder = new URLBuilder();
-    EntityAdapterModel model;
-    int nrArticlesPerPage = 20;
-    int count;
-
-    try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
-      model = MirGlobal.localizer().dataModel().adapterModel();
-
-      Object articleList =
-          new CachingRewindableIterator(
-            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrArticlesPerPage,
-               MirGlobal.localizer().dataModel().adapterModel(), "content", nrArticlesPerPage, anOffset)
-      );
-
-      responseData.put("nexturl", null);
-      responseData.put("prevurl", null);
-
-      count=mainModule.getSize(aWhereClause);
-
-      urlBuilder.setValue("module", "Content");
-      urlBuilder.setValue("do", "list");
-      urlBuilder.setValue("where", aWhereClause);
-      urlBuilder.setValue("order", anOrderByClause);
-
-
-      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));
-      urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));
-      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));
-      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));
-      urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));
-      urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);
-
-      responseData.put("searchfield", requestParser.getParameter("searchfield"));
-      responseData.put("searchvalue", requestParser.getParameter("searchvalue"));
-      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));
-      responseData.put("searchorder", requestParser.getParameter("searchorder"));
-      responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));
-      responseData.put("selectarticleurl", aSelectArticleUrl);
-
-      urlBuilder.setValue("offset", anOffset);
-      responseData.put("offset" , new Integer(anOffset).toString());
-      responseData.put("thisurl" , urlBuilder.getQuery());
-
-      if (count>=anOffset+nrArticlesPerPage) {
-        urlBuilder.setValue("offset", (anOffset + nrArticlesPerPage));
-        responseData.put("nexturl" , urlBuilder.getQuery());
-      }
-
-      if (anOffset>0) {
-        urlBuilder.setValue("offset", Math.max(anOffset - nrArticlesPerPage, 0));
-        responseData.put("prevurl" , urlBuilder.getQuery());
-      }
-
-      responseData.put("articles", articleList);
-
-      responseData.put("from" , Integer.toString(anOffset+1));
-      responseData.put("count", Integer.toString(count));
-      responseData.put("to", Integer.toString(Math.min(anOffset+nrArticlesPerPage, count)));
-      responseData.put("offset" , Integer.toString(anOffset));
-      responseData.put("order", anOrderByClause);
-      responseData.put("where" , aWhereClause);
-
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listTemplate);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      URLBuilder urlBuilder = new URLBuilder();
-
-      urlBuilder.setValue("module", "Content");
-      urlBuilder.setValue("do", "setparent");
-      urlBuilder.setValue("childid", requestParser.getParameter("id"));
-      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));
-
-      returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      String articleId = requestParser.getParameter("article_id");
-
-      if (articleId == null)
-        throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");
-
-      returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    String articleId = aRequest.getParameter("childid");
-    String parentId  = aRequest.getParameter("id");
-    String returnUrl = aRequest.getParameter("returnurl");
-
-    try {
-      EntityContent article = (EntityContent) mainModule.getById(articleId);
-      article.setValueForProperty("to_content", parentId);
-      article.setProduced(false);
-      article.update();
-    }
-    catch(Throwable e) {
-      logger.error("ServletModuleContent.setparent: " + e.getMessage());
-      throw new ServletModuleFailure(e);
-    }
-
-    redirect(aResponse, returnUrl);
-  }
-
-  public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
-  {
-    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-    String articleId = requestParser.getParameter("id");
-    String returnUrl = requestParser.getParameter("returnurl");
-
-    try {
-      EntityContent article = (EntityContent) mainModule.getById(articleId);
-      article.setValueForProperty("to_content", "");
-      article.setProduced(false);
-      article.update();
-    }
-    catch(Throwable e) {
-      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));
-      logger.error("ServletModuleContent.clearparent: " + e.getMessage());
-
-      throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);
-    }
-
-    redirect(aResponse, returnUrl);
-  }
-
-  private EntityUsers _getUser(HttpServletRequest req)
-  {
-    HttpSession session=req.getSession(false);
-
-    return (EntityUsers)session.getAttribute("login.uid");
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.util.GregorianCalendar;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.JDBCStringRoutines;\r
+import mir.util.SQLQueryBuilder;\r
+import mir.util.URLBuilder;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.storage.DatabaseContent;\r
+import mircoders.storage.DatabaseContentToTopics;\r
+\r
+/*\r
+ *  ServletModuleContent -\r
+ *  deliver html for the article admin form.\r
+ *\r
+ * @version $Id: ServletModuleContent.java,v 1.53 2003/09/03 18:29:05 zapata Exp $\r
+ * @author rk, mir-coders\r
+ *\r
+ */\r
+\r
+public class ServletModuleContent extends ServletModule\r
+{\r
+  private static ServletModuleContent instance = new ServletModuleContent();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleContent() {\r
+    super();\r
+\r
+    logger = new LoggerWrapper("ServletModule.Content");\r
+\r
+    try {\r
+      mainModule = new ModuleContent(DatabaseContent.getInstance());\r
+    }\r
+    catch (Throwable e) {\r
+      logger.fatal("ServletModuleContent could not be initialized: " + e.toString());\r
+    }\r
+  }\r
+\r
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    String where = requestParser.getParameter("where");\r
+    String order = requestParser.getParameterWithDefault("order", "webdb_create desc");\r
+    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
+    String selectArticleUrl = requestParser.getParameter("selectarticleurl");\r
+\r
+    returnArticleList(aRequest, aResponse, where, order, offset, selectArticleUrl);\r
+  }\r
+\r
+  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleFailure {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
+      String searchField = requestParser.getParameterWithDefault("searchfield", "");\r
+      String searchValue = requestParser.getParameterWithDefault("searchvalue", "").trim();\r
+      String searchOrder = requestParser.getParameterWithDefault("searchorder", "");\r
+      String searchispublished = requestParser.getParameterWithDefault("searchispublished", "");\r
+      String searchArticleType = requestParser.getParameterWithDefault("searcharticletype", "");\r
+      String selectArticleUrl = requestParser.getParameter("selectarticleurl");\r
+\r
+      if (searchValue.length()>0) {\r
+        if (searchField.equals("id"))\r
+          queryBuilder.appendAndCondition(\r
+            "id='"+JDBCStringRoutines.escapeStringLiteral(searchValue)+"'");\r
+        else if (searchField.equals("contents"))\r
+          queryBuilder.appendAndCondition(\r
+            "(lower(content_data) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')"+\r
+            " or (lower(description) like " + "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%')");\r
+        else\r
+          queryBuilder.appendAndCondition(\r
+            "lower("+ searchField + ") like " +\r
+            "'%" + JDBCStringRoutines.escapeStringLiteral(searchValue.toLowerCase()) + "%'");\r
+      }\r
+\r
+      if (searchispublished.length()>0) {\r
+        if (searchispublished.equals("0"))\r
+          queryBuilder.appendAndCondition("is_published='f'");\r
+        else\r
+          queryBuilder.appendAndCondition("is_published='t'");\r
+      }\r
+\r
+      if (searchArticleType.length()>0) {\r
+        queryBuilder.appendAndCondition("to_article_type="+Integer.parseInt(searchArticleType));\r
+      }\r
+\r
+      if (searchOrder.length()>0) {\r
+        if (searchOrder.equals("datedesc"))\r
+          queryBuilder.appendDescendingOrder("webdb_create");\r
+        else if (searchOrder.equals("dateasc"))\r
+          queryBuilder.appendAscendingOrder("webdb_create");\r
+        else if (searchOrder.equals("title"))\r
+          queryBuilder.appendAscendingOrder("title");\r
+        else if (searchOrder.equals("creator"))\r
+          queryBuilder.appendAscendingOrder("creator");\r
+      }\r
+\r
+      returnArticleList(aRequest, aResponse, queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), 0, selectArticleUrl);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    _showObject(null, aRequest, aResponse);\r
+  }\r
+\r
+\r
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+//theLog.printDebugInfo(":: content :: trying to insert");\r
+    try {\r
+      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
+\r
+      String now = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      withValues.put("date", now);\r
+      withValues.put("publish_path", StringUtil.webdbDate2path(now));\r
+      withValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());\r
+      withValues.put("is_produced", "0");\r
+      if (!withValues.containsKey("is_published"))\r
+        withValues.put("is_published","0");\r
+      if (!withValues.containsKey("is_html"))\r
+        withValues.put("is_html","0");\r
+\r
+      String webdbCreate = (String) withValues.get("webdb_create");\r
+      if (webdbCreate==null || webdbCreate.trim().length()==0)\r
+        withValues.remove("webdb_create");\r
+\r
+      String id = mainModule.add(withValues);\r
+      List topics;\r
+\r
+      DatabaseContentToTopics.getInstance().setTopics(id, aRequest.getParameterValues("to_topic"));\r
+\r
+      _showObject(id, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String idParam = aRequest.getParameter("id");\r
+    if (idParam == null)\r
+      throw new ServletModuleExc("Invalid call: id not supplied ");\r
+    _showObject(idParam, aRequest, aResponse);\r
+  }\r
+\r
+// methods for attaching media file\r
+  public void attach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String  mediaIdParam = aRequest.getParameter("mid");\r
+    String  articleId = aRequest.getParameter("articleid");\r
+\r
+    if (articleId == null || mediaIdParam==null)\r
+      throw new ServletModuleExc("smod content :: attach :: articleid/mid missing");\r
+\r
+    try {\r
+      EntityContent entContent = (EntityContent) mainModule.getById(articleId);\r
+      entContent.attach(mediaIdParam);\r
+    }\r
+    catch(Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+\r
+    _showObject(articleId, aRequest, aResponse);\r
+  }\r
+\r
+  public void dettach(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String  articleId = aRequest.getParameter("articleid");\r
+    String  midParam = aRequest.getParameter("mid");\r
+    if (articleId == null)\r
+      throw new ServletModuleExc("smod content :: dettach :: articleid missing");\r
+    if (midParam == null)\r
+      throw new ServletModuleExc("smod content :: dettach :: mid missing");\r
+\r
+    try {\r
+      EntityContent entContent = (EntityContent)mainModule.getById(articleId);\r
+      entContent.dettach(articleId, midParam);\r
+    }\r
+    catch(Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+\r
+    _showObject(articleId, aRequest, aResponse);\r
+  }\r
+\r
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+      String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+      String idParam = aRequest.getParameter("id");\r
+      if (idParam == null)\r
+        throw new ServletModuleExc("Wrong call: (id) is missing");\r
+\r
+      Map withValues = getIntersectingValues(aRequest, DatabaseContent.getInstance());\r
+\r
+      String content_id = aRequest.getParameter("id");\r
+\r
+      withValues.put("is_produced", "0");\r
+      if (!withValues.containsKey("is_published"))\r
+        withValues.put("is_published","0");\r
+      if (!withValues.containsKey("is_html"))\r
+        withValues.put("is_html","0");\r
+\r
+      String webdbCreate = (String) withValues.get("webdb_create");\r
+      if (webdbCreate==null || webdbCreate.trim().length()==0)\r
+        withValues.remove("webdb_create");\r
+\r
+      String id = mainModule.set(withValues);\r
+      DatabaseContentToTopics.getInstance().setTopics(aRequest.getParameter("id"), aRequest.getParameterValues("to_topic"));\r
+\r
+      if (returnUrl!=null && !returnUrl.equals("")){\r
+        redirect(aResponse, returnUrl);\r
+      }\r
+      else\r
+        _showObject(idParam, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+\r
+  /**\r
+   * HelperMethod shows the basic article editing form.\r
+   *\r
+   * if the "id" parameter is null, it means show an empty form to add a new\r
+   * article.\r
+   *\r
+   * @param id\r
+   * @param aRequest\r
+   * @param aResponse\r
+   * @throws ServletModuleExc\r
+   */\r
+  public void _showObject(String id, HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
+      Map article;\r
+      URLBuilder urlBuilder = new URLBuilder();\r
+\r
+      urlBuilder.setValue("module", "Content");\r
+      urlBuilder.setValue("do", "edit");\r
+      urlBuilder.setValue("id", id);\r
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+\r
+      if (id!=null) {\r
+        responseData.put("new", Boolean.FALSE);\r
+        article = model.makeEntityAdapter("content", mainModule.getById(id));\r
+      }\r
+      else {\r
+        List fields = DatabaseContent.getInstance().getFields();\r
+        responseData.put("new", Boolean.TRUE);\r
+        article = new HashMap();\r
+        Iterator i = fields.iterator();\r
+        while (i.hasNext()) {\r
+          article.put(i.next(), null);\r
+        }\r
+\r
+        article.put("to_topics", null);\r
+\r
+        MirGlobal.localizer().adminInterface().initializeArticle(article);\r
+      }\r
+      responseData.put("article", article);\r
+\r
+      responseData.put("topics",\r
+          new EntityIteratorAdapter("", configuration.getString("Mir.Localizer.Admin.TopicListOrder"),\r
+          20, MirGlobal.localizer().dataModel().adapterModel(), "topic"));\r
+\r
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void returnArticleList(\r
+       HttpServletRequest aRequest,\r
+       HttpServletResponse aResponse,\r
+       String aWhereClause,\r
+       String anOrderByClause,\r
+       int anOffset,\r
+       String aSelectArticleUrl) throws ServletModuleExc {\r
+\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    EntityAdapterModel model;\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+\r
+      Object articleList =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter( aWhereClause, anOrderByClause, nrEntitiesPerListPage,\r
+               MirGlobal.localizer().dataModel().adapterModel(), "content", nrEntitiesPerListPage, anOffset)\r
+      );\r
+\r
+      responseData.put("nexturl", null);\r
+      responseData.put("prevurl", null);\r
+\r
+      count=mainModule.getSize(aWhereClause);\r
+\r
+      urlBuilder.setValue("module", "Content");\r
+      urlBuilder.setValue("do", "list");\r
+      urlBuilder.setValue("where", aWhereClause);\r
+      urlBuilder.setValue("order", anOrderByClause);\r
+\r
+\r
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
+      urlBuilder.setValue("searchvalue", requestParser.getParameter("searchvalue"));\r
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
+      urlBuilder.setValue("searchorder", requestParser.getParameter("searchorder"));\r
+      urlBuilder.setValue("searcharticletype", requestParser.getParameter("searcharticletype"));\r
+      urlBuilder.setValue("selectarticleurl", aSelectArticleUrl);\r
+\r
+      responseData.put("searchfield", requestParser.getParameter("searchfield"));\r
+      responseData.put("searchvalue", requestParser.getParameter("searchvalue"));\r
+      responseData.put("searchispublished", requestParser.getParameter("searchispublished"));\r
+      responseData.put("searchorder", requestParser.getParameter("searchorder"));\r
+      responseData.put("searcharticletype", requestParser.getParameter("searcharticletype"));\r
+      responseData.put("selectarticleurl", aSelectArticleUrl);\r
+\r
+      urlBuilder.setValue("offset", anOffset);\r
+      responseData.put("offset" , new Integer(anOffset).toString());\r
+      responseData.put("thisurl" , urlBuilder.getQuery());\r
+\r
+      if (count>=anOffset+nrEntitiesPerListPage) {\r
+        urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));\r
+        responseData.put("nexturl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      if (anOffset>0) {\r
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
+        responseData.put("prevurl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      responseData.put("articles", articleList);\r
+\r
+      responseData.put("from" , Integer.toString(anOffset+1));\r
+      responseData.put("count", Integer.toString(count));\r
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
+      responseData.put("offset" , Integer.toString(anOffset));\r
+      responseData.put("order", anOrderByClause);\r
+      responseData.put("where" , aWhereClause);\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void selectparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      URLBuilder urlBuilder = new URLBuilder();\r
+\r
+      urlBuilder.setValue("module", "Content");\r
+      urlBuilder.setValue("do", "setparent");\r
+      urlBuilder.setValue("childid", requestParser.getParameter("id"));\r
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+\r
+      returnArticleList(aRequest, aResponse, "", "", 0, urlBuilder.getQuery());\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void listchildren(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      String articleId = requestParser.getParameter("article_id");\r
+\r
+      if (articleId == null)\r
+        throw new ServletModuleExc("ServletModuleContent.listchildren: article_id not set!");\r
+\r
+      returnArticleList(aRequest, aResponse, "to_content = " + articleId, "", 0, null);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void setparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    String articleId = aRequest.getParameter("childid");\r
+    String parentId  = aRequest.getParameter("id");\r
+    String returnUrl = aRequest.getParameter("returnurl");\r
+\r
+    try {\r
+      EntityContent article = (EntityContent) mainModule.getById(articleId);\r
+      article.setValueForProperty("to_content", parentId);\r
+      article.setProduced(false);\r
+      article.update();\r
+    }\r
+    catch(Throwable e) {\r
+      logger.error("ServletModuleContent.setparent: " + e.getMessage());\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+\r
+    redirect(aResponse, returnUrl);\r
+  }\r
+\r
+  public void clearparent(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    String articleId = requestParser.getParameter("id");\r
+    String returnUrl = requestParser.getParameter("returnurl");\r
+\r
+    try {\r
+      EntityContent article = (EntityContent) mainModule.getById(articleId);\r
+      article.setValueForProperty("to_content", "");\r
+      article.setProduced(false);\r
+      article.update();\r
+    }\r
+    catch(Throwable e) {\r
+      e.printStackTrace(logger.asPrintWriter(LoggerWrapper.DEBUG_MESSAGE));\r
+      logger.error("ServletModuleContent.clearparent: " + e.getMessage());\r
+\r
+      throw new ServletModuleFailure("ServletModuleContent.clearparent: " + e.getMessage(), e);\r
+    }\r
+\r
+    redirect(aResponse, returnUrl);\r
+  }\r
+}\r
index 3b4ca3b..92ff9c7 100755 (executable)
@@ -59,7 +59,7 @@ import mir.util.URLBuilder;
  *  in the config file.
  *
  * @author $Author: zapata $
- * @version $Revision: 1.13 $ $Date: 2003/05/08 02:43:42 $
+ * @version $Revision: 1.14 $ $Date: 2003/09/03 18:29:05 $
  *
  */
 
@@ -137,10 +137,6 @@ public class ServletModuleFileEdit extends ServletModule
     }
 
     dirFilter = new FileFunctions.DirectoryFilter();
-
-    templateListString =configuration.getString("ServletModule.FileEdit.ListTemplate");
-    templateObjektString =configuration.getString("ServletModule.FileEdit.ObjektTemplate");
-    templateConfirmString =configuration.getString("ServletModule.FileEdit.ConfirmTemplate");
   }
 
   public List getEntries() {
@@ -228,7 +224,7 @@ public class ServletModuleFileEdit extends ServletModule
   public void listSubDirectory(FileEditDirectory aDirectory, String aSubDirectory, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc
   {
     try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
       File dir = new File(aDirectory.getRootDirectory(), aSubDirectory);
 
       if (!validateDirectory(aDirectory, dir) || !dir.isDirectory()) {
@@ -255,7 +251,7 @@ public class ServletModuleFileEdit extends ServletModule
       responseData.put("subdirectory", aSubDirectory);
       responseData.put("entry", aDirectory.getName());
 
-      ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateListString);
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);
     }
     catch (Throwable e) {
       throw new ServletModuleFailure(e);
@@ -271,7 +267,7 @@ public class ServletModuleFileEdit extends ServletModule
         listSubDirectory(aDirectory, "", aRequest, aResponse);
       }
       else {
-        Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+        Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
         URLBuilder urlBuilder = new URLBuilder();
 
         urlBuilder.setValue("module", "FileEdit");
@@ -295,7 +291,7 @@ public class ServletModuleFileEdit extends ServletModule
         responseData.put("subdirectory", aSubDirectory);
         responseData.put("returnurl", urlBuilder.getQuery());
 
-        ServletHelper.generateResponse(aResponse.getWriter(), responseData, templateObjektString);
+        ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);
       }
     }
     catch (Throwable e) {
index f1d8002..6ae6d20 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.servlet;
 
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.storage.StorageObjectFailure;
-import mircoders.module.ModuleContent;
+import java.util.Iterator;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.storage.StorageObjectFailure;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.JDBCStringRoutines;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleContent;\r
 import mircoders.storage.DatabaseContent;
-import freemarker.template.SimpleHash;
 
 /*
  *  ServletModuleHidden - output of so called "censored" articles
@@ -52,15 +57,14 @@ import freemarker.template.SimpleHash;
 
 public class ServletModuleHidden extends ServletModule
 {
-
-// Singelton / Kontruktor
   private static ServletModuleHidden instance = new ServletModuleHidden();
   public static ServletModule getInstance() { return instance; }
 
   private ServletModuleHidden() {
     super();
+
     logger = new LoggerWrapper("ServletModule.Hidden");
-    templateListString = configuration.getString("ServletModule.Hidden.ListTemplate");
+
     try {
       mainModule = new ModuleContent(DatabaseContent.getInstance());
     }
@@ -73,47 +77,29 @@ public class ServletModuleHidden extends ServletModule
   public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
   {
 // determine parameter
-    SimpleHash mergeData = new SimpleHash();
-    String query_year = req.getParameter("year");
-    String query_month = req.getParameter("month");
-    String order = "webdb_create";
+    HTTPRequestParser requestParser = new HTTPRequestParser(req);
+    Map responseData = ServletHelper.makeGenerationData(req, res, new Locale[] { getLocale(req), getFallbackLocale(req)});
 
-// form sql statement
-    String whereClause = "is_published=false AND webdb_create LIKE '"+
-                         query_year+"-"+query_month+"%'";
+    String query_year = requestParser.getParameter("year");
+    String query_month = requestParser.getParameter("month");
 
-    logger.debug("ServletModuleHidden.list: whereclause: " + whereClause);
-
-// fetch and deliver
     try {
+      if ((query_year!=null && !query_year.equals("")) && (query_month!=null && !query_month.equals(""))) {
+        String whereClause = "is_published=false AND webdb_create LIKE "+
+            "'"+JDBCStringRoutines.escapeStringLiteral(query_year)+"-"+JDBCStringRoutines.escapeStringLiteral(query_month)+"%'";
 
-      if ((query_year!=null && !query_year.equals(""))
-          && (query_month!=null && !query_month.equals(""))) {
-        EntityList theList = mainModule.getByWhereClause(whereClause, order, -1);
-        if (theList!=null && theList.size()>0) {
-
-//make articleHash for comment
-          StringBuffer buf= new StringBuffer("id in (");boolean first=true;
-          for(int i=0;i<theList.size();i++) {
-            if (first==false) buf.append(",");
-            first=false;
-            buf.append(theList.elementAt(i).getValue("to_media"));
-          }
-          buf.append(")");
-          SimpleHash articleHash =
-              HTMLTemplateProcessor.makeSimpleHash(
-              mainModule.getByWhereClause(buf.toString(),-1));
-          mergeData.put("articleHash", articleHash);
+        Iterator articleList =
+            new CachingRewindableIterator(
+              new EntityIteratorAdapter( whereClause, "webdb_create", 100,
+                 MirGlobal.localizer().dataModel().adapterModel(), "content", -1, 0)
+        );
 
-// send the year and month for use in the list template
-          mergeData.put("year", query_year);
-          mergeData.put("month", query_month);
-// get comment
-          mergeData.put("contentlist",theList);
-        }
+        responseData.put("year", query_year);
+        responseData.put("month", query_month);
+        responseData.put("articles", articleList);
       }
-// raus damit
-      HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req));
+
+      ServletHelper.generateResponse(res.getWriter(), responseData, listGenerator);
     }
     catch (Throwable e) {
       throw new ServletModuleFailure(e);
index 1e1c9ec..ca90691 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.servlet;
@@ -34,11 +34,12 @@ import mir.servlet.ServletModule;
 import mir.storage.StorageObjectFailure;
 import mircoders.module.ModuleImages;
 import mircoders.storage.DatabaseImages;
+import mircoders.global.*;
 
 /*
  *  ServletModuleImages -
  *
- * @version $Id: ServletModuleImages.java,v 1.26 2003/04/21 12:42:51 idfx Exp $
+ * @version $Id: ServletModuleImages.java,v 1.27 2003/09/03 18:29:05 zapata Exp $
  * @author RK, the mir-coders group
  */
 
@@ -52,14 +53,14 @@ public class ServletModuleImages extends ServletModuleUploadedMedia
   private ServletModuleImages() {
     super();
     logger = new LoggerWrapper("ServletModule.Images");
-    templateListString = configuration.getString("ServletModule.Images.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Images.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Images.ConfirmTemplate");
+    moduleName = "Images";
 
     try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "image";
       mainModule = new ModuleImages(DatabaseImages.getInstance());
     }
-    catch (StorageObjectFailure e) {
+    catch (Throwable e) {
       logger.error("Initialization of ServletModuleImages failed!: " + e.getMessage());
     }
   }
index 724d73f..d6526cd 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 package mircoders.servlet;
@@ -34,6 +34,7 @@ import mir.servlet.ServletModule;
 import mir.storage.StorageObjectFailure;
 import mircoders.module.ModuleLanguage;
 import mircoders.storage.DatabaseLanguage;
+import mircoders.global.*;
 
 /*
  *  ServletModuleLanguage -
@@ -52,14 +53,12 @@ public class ServletModuleLanguage extends ServletModule
     super();
     logger = new LoggerWrapper("ServletModule.Language");
 
-    templateListString = configuration.getString("ServletModule.Language.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Language.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Language.ConfirmTemplate");
-
     try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "language";
       mainModule = new ModuleLanguage(DatabaseLanguage.getInstance());
     }
-    catch (StorageObjectFailure e) {
+    catch (Throwable e) {
       logger.error("Initialization of ServletModuleLanguage failed: " + e.getMessage());
     }
   }
index 119e626..26c3e4b 100755 (executable)
  */
 package mircoders.servlet;
 
-import java.util.*;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.entity.adapter.EntityAdapter;
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.util.*;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityUsers;
-import mircoders.global.MirGlobal;
-import mircoders.localizer.MirAdminInterfaceLocalizer;
-import mircoders.module.ModuleComment;
-import mircoders.module.ModuleContent;
-import mircoders.storage.DatabaseComment;
+import java.util.HashMap;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.util.StringRoutines;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.localizer.MirAdminInterfaceLocalizer;\r
+import mircoders.module.ModuleComment;\r
+import mircoders.module.ModuleContent;\r
+import mircoders.storage.DatabaseComment;\r
 import mircoders.storage.DatabaseContent;
 
 public class ServletModuleLocalizer extends ServletModule {
@@ -96,18 +96,7 @@ public class ServletModuleLocalizer extends ServletModule {
 
   }
 
-  private EntityAdapter getActiveUser(HttpServletRequest aRequest) throws ServletModuleExc {
-    try {
-      HttpSession session = aRequest.getSession(false);
-      return MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter
-          ("user", (EntityUsers) session.getAttribute("login.uid"));
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure("ServletModuleLocalizer.getActiveUser: " + e.getMessage(), e);
-    }
-  }
-
-  public void performCommentOperation(EntityAdapter aUser, String anId, String anOperation) {
+  public void performCommentOperation(EntityUsers aUser, String anId, String anOperation) {
     MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation;
     EntityAdapter comment;
     EntityComment entity;
@@ -116,9 +105,7 @@ public class ServletModuleLocalizer extends ServletModule {
       entity = (EntityComment) commentModule.getById(anId);
 
       if (entity != null) {
-        comment = MirGlobal.localizer().dataModel().adapterModel().makeEntityAdapter("comment", entity);
-        operation = MirGlobal.localizer().adminInterface().simpleCommentOperationForName(anOperation);
-        operation.perform(aUser, comment);
+        MirGlobal.performCommentOperation(aUser, entity, anOperation);
         logger.info("Operation " + anOperation + " successfully performed on comment " + anId);
       }
       else {
@@ -135,7 +122,7 @@ public class ServletModuleLocalizer extends ServletModule {
     String operationString = aRequest.getParameter("operation");
     String returnUrlString = aRequest.getParameter("returnurl");
 
-    performCommentOperation(getActiveUser(aRequest), commentIdString, operationString);
+    performCommentOperation(ServletHelper.getUser(aRequest), commentIdString, operationString);
 
     redirect(aResponse, returnUrlString);
   }
@@ -145,19 +132,21 @@ public class ServletModuleLocalizer extends ServletModule {
 
     String[] operations = aRequest.getParameterValues("operation");
 
-    for (int i=0; i<operations.length; i++) {
-      if (operations[i].length()>0) {
-        List parts = StringRoutines.splitString(operations[i], ";");
+    if (operations!=null) {
+      for (int i = 0; i < operations.length; i++) {
+        if (operations[i].length() > 0) {
+          List parts = StringRoutines.splitString(operations[i], ";");
 
-        if (parts.size() != 2) {
-          logger.error("commentoperationbatch: operation string invalid: " +
-                       operations[i]);
-        }
-        else {
-          String commentIdString = (String) parts.get(0);
-          String operationString = (String) parts.get(1);
+          if (parts.size() != 2) {
+            logger.error("commentoperationbatch: operation string invalid: " +
+                         operations[i]);
+          }
+          else {
+            String commentIdString = (String) parts.get(0);
+            String operationString = (String) parts.get(1);
 
-          performCommentOperation(getActiveUser(aRequest), commentIdString, operationString);
+            performCommentOperation(ServletHelper.getUser(aRequest), commentIdString, operationString);
+          }
         }
       }
     }
@@ -165,7 +154,7 @@ public class ServletModuleLocalizer extends ServletModule {
     redirect(aResponse, returnUrlString);
   }
 
-  public void performArticleOperation(EntityAdapter aUser, String anId, String anOperation) {
+  public void performArticleOperation(EntityUsers aUser, String anId, String anOperation) {
     MirAdminInterfaceLocalizer.MirSimpleEntityOperation operation;
     EntityAdapter article;
     EntityContent entity;
@@ -174,11 +163,7 @@ public class ServletModuleLocalizer extends ServletModule {
       entity = (EntityContent) contentModule.getById(anId);
 
       if (entity != null) {
-        article = MirGlobal.localizer().dataModel().adapterModel().
-            makeEntityAdapter("content", entity);
-        operation = MirGlobal.localizer().adminInterface().
-            simpleArticleOperationForName(anOperation);
-        operation.perform(aUser, article);
+        MirGlobal.performArticleOperation(aUser, entity, anOperation);
         logger.info("Operation " + anOperation + " successfully performed on article " + anId);
       }
       else {
@@ -195,7 +180,7 @@ public class ServletModuleLocalizer extends ServletModule {
     String operationString = aRequest.getParameter("operation");
     String returnUrlString = aRequest.getParameter("returnurl");
 
-    performArticleOperation(getActiveUser(aRequest), articleIdString, operationString);
+    performArticleOperation(ServletHelper.getUser(aRequest), articleIdString, operationString);
     redirect(aResponse, returnUrlString);
   }
 
@@ -204,18 +189,21 @@ public class ServletModuleLocalizer extends ServletModule {
 
     String[] operations = aRequest.getParameterValues("operation");
 
-    for (int i=0; i<operations.length; i++) {
-      if (operations[i].length()>0) {
-        List parts = StringRoutines.splitString(operations[i], ";");
+    if (operations!=null) {
 
-        if (parts.size() != 2) {
-          logger.error("articleoperationbatch: operation string invalid: " + operations[i]);
-        }
-        else {
-          String articleIdString = (String) parts.get(0);
-          String operationString = (String) parts.get(1);
+      for (int i = 0; i < operations.length; i++) {
+        if (operations[i].length() > 0) {
+          List parts = StringRoutines.splitString(operations[i], ";");
 
-          performArticleOperation(getActiveUser(aRequest), articleIdString, operationString);
+          if (parts.size() != 2) {
+            logger.error("articleoperationbatch: operation string invalid: " + operations[i]);
+          }
+          else {
+            String articleIdString = (String) parts.get(0);
+            String operationString = (String) parts.get(1);
+
+            performArticleOperation(ServletHelper.getUser(aRequest), articleIdString, operationString);
+          }
         }
       }
     }
index ac35350..bb33dd2 100755 (executable)
@@ -1,85 +1,68 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.servlet;
-
-/**
- * Title:        Mir
- * Description:
- * @author       rk
- * @version      02
- */
-
-import java.util.GregorianCalendar;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.servlet.ServletModule;
-import mir.storage.StorageObjectFailure;
-import mircoders.module.ModuleMediafolder;
-import mircoders.storage.DatabaseMediafolder;
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleScalar;
-
-
-public class ServletModuleMediafolder extends ServletModule
-{
-  public static ServletModule getInstance() { return instance; }
-  private static ServletModuleMediafolder instance = new ServletModuleMediafolder();
-
-  private ServletModuleMediafolder() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Mediafolder");
-
-    templateListString = configuration.getString("ServletModule.Mediafolder.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Mediafolder.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Mediafolder.ConfirmTemplate");
-
-    try {
-      mainModule = new ModuleMediafolder(DatabaseMediafolder.getInstance());
-    }
-    catch (StorageObjectFailure e) {
-      logger.error("Failed to initialize ServletModuleMediafolder: " + e.getMessage());
-    }
-  }
-
-  public void add(HttpServletRequest req, HttpServletResponse res)
-  {
-    SimpleHash mergeData = new SimpleHash();
-    mergeData.put("new", "1");
-    String now = StringUtil.date2webdbDate(new GregorianCalendar());
-// date auf now
-    mergeData.put("date", new SimpleScalar(now));
-    deliver(req, res, mergeData, templateObjektString);
-  }
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.servlet;\r
+\r
+/**\r
+ *\r
+ */\r
+\r
+import java.util.GregorianCalendar;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.servlet.ServletModule;\r
+import mir.storage.StorageObjectFailure;\r
+import mircoders.module.ModuleMediafolder;\r
+import mircoders.storage.DatabaseMediafolder;\r
+\r
+public class ServletModuleMediafolder extends ServletModule\r
+{\r
+  public static ServletModule getInstance() { return instance; }\r
+  private static ServletModuleMediafolder instance = new ServletModuleMediafolder();\r
+\r
+  private ServletModuleMediafolder() {\r
+    super();\r
+    logger = new LoggerWrapper("ServletModule.Mediafolder");\r
+\r
+    try {\r
+      mainModule = new ModuleMediafolder(DatabaseMediafolder.getInstance());\r
+    }\r
+    catch (StorageObjectFailure e) {\r
+      logger.error("Failed to initialize ServletModuleMediafolder: " + e.getMessage());\r
+    }\r
+  }\r
+\r
+  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    aNewObject.put("date", StringUtil.date2webdbDate(new GregorianCalendar()));\r
+  }\r
 }
\ No newline at end of file
index efd1e6b..a8ec504 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.servlet;
-
-import java.net.URLEncoder;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.misc.HTMLTemplateProcessor;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.storage.StorageObjectFailure;
-import mircoders.module.ModuleMessage;
-import mircoders.storage.DatabaseMessages;
-import freemarker.template.SimpleHash;
-
-/**
- * Title:       ServletModuleMessage
- * Description:
- * Copyright:   Copyright (c) 2001-2002
- * Company:     mir-coders
- * @author
- * @version 1.0
- */
-
-
-public class ServletModuleMessage extends ServletModule
-{
-
-  // Singelton / Kontruktor
-
-  private static ServletModuleMessage instance = new ServletModuleMessage();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleMessage() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Messages");
-
-    templateListString = configuration.getString("ServletModule.Messages.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Messages.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Messages.ConfirmTemplate");
-
-    try {
-      mainModule = new ModuleMessage(DatabaseMessages.getInstance());
-    }
-    catch (StorageObjectFailure e) {
-      logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());
-
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-// fetch and deliver
-    try {
-      SimpleHash mergeData = new SimpleHash();
-      String offset = req.getParameter("offset");
-      if (offset==null || offset.equals("")) offset="0";
-      mergeData.put("offset",offset);
-      EntityList theList = mainModule.getByWhereClause(null, "webdb_create desc", (new Integer(offset)).intValue());
-      mergeData.put("contentlist",theList);
-      if(theList.getOrder()!=null) {
-        mergeData.put("order", theList.getOrder());
-        mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
-      }
-      mergeData.put("count", (new Integer(theList.getCount())).toString());
-      mergeData.put("from", (new Integer(theList.getFrom())).toString());
-      mergeData.put("to", (new Integer(theList.getTo())).toString());
-      if (theList.hasNextBatch())
-        mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
-      if (theList.hasPrevBatch())
-        mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
-
-      HTMLTemplateProcessor.process(res, templateListString, mergeData, res.getWriter(), getLocale(req), getFallbackLocale(req));
-
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.servlet;\r
+\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleFailure;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleMessage;\r
+import mircoders.storage.DatabaseMessages;\r
+\r
+/**\r
+ * Title:       ServletModuleMessage\r
+ * Description:\r
+ * Copyright:   Copyright (c) 2001-2002\r
+ * Company:     mir-coders\r
+ * @author\r
+ * @version 1.0\r
+ */\r
+\r
+\r
+public class ServletModuleMessage extends ServletModule\r
+{\r
+  private static ServletModuleMessage instance = new ServletModuleMessage();\r
+  public static ServletModule getInstance() { return instance; }\r
+\r
+  private ServletModuleMessage() {\r
+    super();\r
+    logger = new LoggerWrapper("ServletModule.Messages");\r
+\r
+    try {\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+      definition = "internalMessage";\r
+      mainModule = new ModuleMessage(DatabaseMessages.getInstance());\r
+    }\r
+    catch (Throwable e) {\r
+      logger.error("initialization of ServletModuleMessage failed!: " + e.getMessage());\r
+\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  protected void initializeNewObject(Map aNewObject, HttpServletRequest aRequest, HttpServletResponse aResponse) {\r
+    aNewObject.put("creator", ServletHelper.getUserName(aRequest));\r
+  }\r
+}\r
index eef87c9..3742181 100755 (executable)
@@ -102,6 +102,7 @@ import mircoders.search.ImagesSearchTerm;
 import mircoders.search.KeywordSearchTerm;
 import mircoders.search.TextSearchTerm;
 import mircoders.search.TopicSearchTerm;
+import mircoders.search.TopicMatrixSearchTerm;
 import mircoders.search.UnIndexedSearchTerm;
 import mircoders.search.VideoSearchTerm;
 import mircoders.storage.DatabaseComment;
@@ -119,7 +120,7 @@ import mircoders.storage.DatabaseTopics;
  *    open-postings to the newswire
  *
  * @author mir-coders group
- * @version $Id: ServletModuleOpenIndy.java,v 1.89 2003/05/08 02:43:42 zapata Exp $
+ * @version $Id: ServletModuleOpenIndy.java,v 1.90 2003/09/03 18:29:05 zapata Exp $
  *
  */
 
@@ -353,7 +354,7 @@ public class ServletModuleOpenIndy extends ServletModule
 
       Map extraInfo = new HashMap();
       extraInfo.put("languagePopUpData", DatabaseLanguage.getInstance().getPopupData());
-      extraInfo.put("themenPopupData", topicsModule.getTopicsAsSimpleList());
+      extraInfo.put("themenPopupData", DatabaseTopics.getInstance().getPopupData());
 
       extraInfo.put("topics", topicsModule.getTopicsList());
       deliver(req, res, mergeData, extraInfo, postingFormTemplate);
@@ -523,6 +524,35 @@ public class ServletModuleOpenIndy extends ServletModule
   private static final String SESSION_REQUEST_KEY="sessionid";
 
   /**
+   * Selects the language for the response.
+   *
+   * @param session
+   * @param aRequest
+   */
+
+  protected Locale getResponseLocale(HttpSession aSession, HttpServletRequest aRequest) {
+    String requestLanguage = aRequest.getParameter("language");
+    String sessionLanguage = (String) aSession.getAttribute("language");
+    String acceptLanguage = aRequest.getLocale().getLanguage();
+    String defaultLanguage = configuration.getString("Mir.Login.DefaultLanguage", "en");
+
+    String language = requestLanguage;
+
+    if (language==null)
+      language = sessionLanguage;
+
+    if (language==null)
+      language = acceptLanguage;
+
+    if (language==null)
+      language = defaultLanguage;
+
+    aSession.setAttribute("language", language);
+
+    return new Locale(language, "");
+  }
+
+  /**
    * Dispatch method for open sessions: a flexible extensible and customizable way
    *   for open access. Can be used for postings, but also for lots of other stuff.
    *
@@ -550,10 +580,10 @@ public class ServletModuleOpenIndy extends ServletModule
       Session session = new HTTPAdapters.HTTPSessionAdapter(aRequest.getSession());
 
       SimpleResponse response = new SimpleResponse(
-          ServletHelper.makeGenerationData(aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)},
+          ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getResponseLocale(aRequest.getSession(), aRequest), getFallbackLocale(aRequest)},
              "bundles.open"));
 
-      response.setResponseValue("actionURL", aResponse.encodeURL(HttpUtils.getRequestURL(aRequest).toString())+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
+      response.setResponseValue("actionURL", aResponse.encodeURL(MirGlobal.config().getString("RootUri") + "/servlet/OpenMir")+"?"+SESSION_REQUEST_KEY+"="+aRequest.getSession().getId());
 
       SessionHandler handler = MirGlobal.localizer().openPostings().getOpenSessionHandler(request, session);
 
@@ -583,6 +613,7 @@ public class ServletModuleOpenIndy extends ServletModule
     String to = req.getParameter("mail_to");
     String from = req.getParameter("mail_from");
     String from_name = req.getParameter("mail_from_name");
+    String from_ip = req.getRemoteAddr();
     String comment = req.getParameter("mail_comment");
     String mail_language = req.getParameter("mail_language");
 
@@ -616,8 +647,8 @@ public class ServletModuleOpenIndy extends ServletModule
       String theEmailText;
 
       if (MirGlobal.mruCache().hasObject(theCacheKey)){
-  logger.info("fetching email text for article "+aid+" from cache");
-  theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
+        logger.info("fetching email text for article "+aid+" from cache");
+        theEmailText = (String) MirGlobal.mruCache().getObject(theCacheKey);
       }
       else {
         EntityContent contentEnt;
@@ -641,7 +672,7 @@ public class ServletModuleOpenIndy extends ServletModule
 
 
       // add some headers
-      content = "To: " + to + "\nReply-To: "+ from + "\n" + content;
+      content = "To: " + to + "\nReply-To: "+ from + "\nX-Originating-IP: "+ from_ip + "\n" + content;
       // put in the comment where it should go
       if (comment != null) {
         String commentTextToInsert = "\n\nAttached comment from " + from_name + ":\n" + comment;
@@ -727,6 +758,7 @@ public class ServletModuleOpenIndy extends ServletModule
       TextSearchTerm descriptionTerm = new TextSearchTerm("description", "search_content", "description", "description", "description");
       ContentSearchTerm contentTerm = new ContentSearchTerm("content_data", "search_content", "content", "", "");
       TopicSearchTerm topicTerm = new TopicSearchTerm();
+      TopicMatrixSearchTerm topicMatrixTerm = new TopicMatrixSearchTerm();
       ImagesSearchTerm imagesTerm = new ImagesSearchTerm();
       AudioSearchTerm audioTerm = new AudioSearchTerm();
       VideoSearchTerm videoTerm = new VideoSearchTerm();
@@ -741,7 +773,7 @@ public class ServletModuleOpenIndy extends ServletModule
       }
 
       try {
-        mergeData.put("topics", topicsModule.getTopicsAsSimpleList());
+        mergeData.put("topics", DatabaseTopics.getInstance().getPopupData());
       }
       catch (Throwable e) {
         logger.debug("Can't get topics: " + e.toString());
@@ -791,6 +823,11 @@ public class ServletModuleOpenIndy extends ServletModule
             queryString = queryString + " +" + topicFragment;
           }
 
+          String topicMatrixFragment = topicMatrixTerm.makeTerm(req);
+          if (topicMatrixFragment != null) {
+            queryString = queryString + " +" + topicMatrixFragment;
+          }
+
           String imagesFragment = imagesTerm.makeTerm(req);
           if (imagesFragment != null) {
             queryString = queryString + " +" + imagesFragment;
@@ -1089,7 +1126,7 @@ public class ServletModuleOpenIndy extends ServletModule
   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator)
       throws ServletModuleFailure {
     try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)}, "bundles.open");
       responseData.put("data", aData);
       responseData.put("extra", anExtra);
 
@@ -1109,7 +1146,7 @@ public class ServletModuleOpenIndy extends ServletModule
   public void deliver(PrintWriter anOutputWriter, HttpServletRequest aRequest, HttpServletResponse aResponse, Map aData, Map anExtra, String aGenerator,String aLocaleString)
       throws ServletModuleFailure {
     try {
-      Map responseData = ServletHelper.makeGenerationData(aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { new Locale(aLocaleString,""), getFallbackLocale(aRequest)}, "bundles.open");
       responseData.put("data", aData);
       responseData.put("extra", anExtra);
 
index 23f71ea..0940696 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -35,15 +35,19 @@ import mir.servlet.ServletModule;
 import mir.storage.StorageObjectFailure;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseOther;
+import mircoders.global.*;
 
-/*
- *
+/**
  *
- * @author br1
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author the mir coders
+ * @version 1.0
  */
 
 public class ServletModuleOtherMedia extends ServletModuleUploadedMedia {
-  // Singelton / Contructor
   private static ServletModuleOtherMedia instance = new ServletModuleOtherMedia();
 
   public static ServletModule getInstance() {
@@ -53,15 +57,14 @@ public class ServletModuleOtherMedia extends ServletModuleUploadedMedia {
   private ServletModuleOtherMedia() {
     super();
     logger = new LoggerWrapper("ServletModule.OtherMedia");
+    moduleName = "OtherMedia";
 
-    templateListString = configuration.getString("ServletModule.OtherMedia.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.OtherMedia.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.OtherMedia.ConfirmTemplate");
     try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "otherMedia";
       mainModule = new ModuleUploadedMedia(DatabaseOther.getInstance());
-      //dbRights = DatabaseRights.getInstance();
     }
-    catch (StorageObjectFailure e) {
+    catch (Throwable e) {
       logger.error("servletmodule otherMedia could not be initialized: " + e.getMessage());
     }
   }
index 69be3b5..26af533 100755 (executable)
@@ -36,20 +36,20 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Vector;
-
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.apache.struts.util.MessageResources;
+
 import mir.generator.Generator;
 import mir.log.LoggerWrapper;
 import mir.producer.ProducerFactory;
 import mir.servlet.ServletModule;
 import mir.servlet.ServletModuleFailure;
+import mir.util.HTTPRequestParser;
 import mir.util.ResourceBundleGeneratorFunction;
 import mircoders.global.MirGlobal;
 
-import org.apache.struts.util.MessageResources;
-
 public class ServletModuleProducer extends ServletModule
 {
   private static ServletModuleProducer instance = new ServletModuleProducer();
@@ -79,14 +79,15 @@ public class ServletModuleProducer extends ServletModule
     defaultAction="showProducerQueueStatus";
   }
 
-  public void showMessage(PrintWriter aWriter, Locale aLocale, String aMessage, String anArgument1, String anArgument2) {
+  public void showMessage(HttpServletRequest aRequest, HttpServletResponse aResponse, String aMessage, String anArgument1, String anArgument2) {
     Map responseData;
     try {
-      responseData = new HashMap();
+      responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
       responseData.put("message", aMessage);
       responseData.put("argument1", anArgument1);
       responseData.put("argument2", anArgument2);
-      generateResponse("infomessage.template", aWriter, responseData, aLocale);
+
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "infomessage.template");
     }
     catch (Throwable t) {
       throw new ServletModuleFailure(t);
@@ -104,7 +105,7 @@ public class ServletModuleProducer extends ServletModule
     try {
       generator = MirGlobal.localizer().generators().makeAdminGeneratorLibrary().makeGenerator("producerqueue.template");
 
-      generationData = ServletHelper.makeGenerationData(aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
+      generationData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});
       generationData.put( "thisurl", "module=Producer&do=showProducerQueueStatus");
 
       producersData = new Vector();
@@ -139,7 +140,7 @@ public class ServletModuleProducer extends ServletModule
     }
   }
 
-  public void produce(HttpServletRequest req, HttpServletResponse res) {
+  public void produce(HttpServletRequest aRequest, HttpServletResponse aResponse) {
     /*
      * This method will only be called by external scripts (e.g. from cron jobs).
      * The output therefore is very simple.
@@ -147,11 +148,11 @@ public class ServletModuleProducer extends ServletModule
      */
 
     try {
-      PrintWriter out = res.getWriter();
+      PrintWriter out = aResponse.getWriter();
 
-      if (req.getParameter("producer")!=null) {
-        String producerParam = req.getParameter("producer");
-        String verbParam = req.getParameter("verb");
+      if (aRequest.getParameter("producer")!=null) {
+        String producerParam = aRequest.getParameter("producer");
+        String verbParam = aRequest.getParameter("verb");
 
         MirGlobal.producerEngine().addJob(producerParam, verbParam);
         out.println("job added");
@@ -165,7 +166,7 @@ public class ServletModuleProducer extends ServletModule
   public void produceAllNew(HttpServletRequest aRequest, HttpServletResponse aResponse) {
     try {
       MirGlobal.localizer().producers().produceAllNew();
-      showMessage(aResponse.getWriter(), getLocale(aRequest), "produceAllNewAddedToQueue", "", "");
+      showMessage(aRequest, aResponse, "produceAllNewAddedToQueue", "", "");
     }
     catch (Throwable t) {
       throw new ServletModuleFailure(t);
@@ -180,7 +181,7 @@ public class ServletModuleProducer extends ServletModule
 
         MirGlobal.producerEngine().addJob(producerParam, verbParam);
 
-        showProducerQueueStatus(aRequest, aResponse);
+        ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus");
       }
     }
     catch (Throwable t) {
@@ -188,7 +189,16 @@ public class ServletModuleProducer extends ServletModule
     }
   }
 
-  public void cancelAbortJob(HttpServletRequest aRequest, HttpServletResponse aResponse)  {
-    // ML: to be coded
+  public void cancel(HttpServletRequest aRequest, HttpServletResponse aResponse)  {
+    try {
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
+      List jobs = new Vector(requestParser.getParameterList("jobid"));
+
+      MirGlobal.producerEngine().cancelJobs(jobs);
+      ServletHelper.redirect(aResponse, "Producer", "showProducerQueueStatus");
+    }
+    catch (Throwable t) {
+      throw new ServletModuleFailure(t);
+    }
   }
 }
index d2a3916..63fdd7c 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -35,18 +35,20 @@ import mir.servlet.ServletModule;
 import mir.storage.StorageObjectFailure;
 import mircoders.module.ModuleTopics;
 import mircoders.storage.DatabaseTopics;
+import mircoders.global.*;
 
-/*
- *  ServletModuleTopics
- *
+/**
  *
- *
- * @author RK
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
  */
 
 public class ServletModuleTopics extends ServletModule
 {
-// Singelton / Constructor
   private static ServletModuleTopics instance = new ServletModuleTopics();
   public static ServletModule getInstance() { return instance; }
 
@@ -54,14 +56,12 @@ public class ServletModuleTopics extends ServletModule
     super();
     logger = new LoggerWrapper("ServletModule.Topics");
 
-    templateListString = configuration.getString("ServletModule.Themen.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Themen.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Themen.ConfirmTemplate");
-
     try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "topic";
       mainModule = new ModuleTopics(DatabaseTopics.getInstance());
     }
-    catch (StorageObjectFailure e) {
+    catch (Throwable e) {
       logger.error("Initialization of ServletModuleTopics failed!: " + e.getMessage());
     }
   }
index ba34a63..6dddfa7 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.io.InputStream;
-import java.net.URLEncoder;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletOutputStream;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import mir.config.MirPropertiesConfiguration;
-import mir.entity.Entity;
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.media.MediaHelper;
-import mir.media.MirMedia;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.servlet.ServletModuleUserExc;
-import mir.session.UploadedFile;
-import mir.util.ExceptionFunctions;
-import mir.util.HTTPParsedRequest;
-import mircoders.entity.EntityComment;
-import mircoders.entity.EntityContent;
-import mircoders.entity.EntityUploadedMedia;
-import mircoders.entity.EntityUsers;
-import mircoders.media.MediaUploadProcessor;
-import mircoders.module.*;
-import mircoders.storage.DatabaseComment;
-import mircoders.storage.DatabaseContent;
-import mircoders.storage.DatabaseMediafolder;
-
-import org.apache.commons.fileupload.FileItem;
-
-import freemarker.template.SimpleHash;
-import freemarker.template.SimpleList;
-
-/*
- *  ServletModuleBilder -
- *  liefert HTML fuer Bilder
- *
- * @version $Id: ServletModuleUploadedMedia.java,v 1.28 2003/04/29 02:36:51 zapata Exp $
- * @author RK, the mir-coders group
- */
-
-public abstract class ServletModuleUploadedMedia
-        extends mir.servlet.ServletModule {
-
-  //private static DatabaseRights dbRights;
-
-  public static ServletModule getInstance() {
-    return null;
-  }
-
-  public ServletModuleUploadedMedia() {
-    super();
-    logger = new LoggerWrapper("ServletModule.UploadedMedia");
-  }
-
-  public void insert(HttpServletRequest req, HttpServletResponse res)
-          throws ServletModuleExc, ServletModuleUserExc {
-    try {
-      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(req,
-          configuration.getString("Mir.DefaultEncoding"),
-          configuration.getInt("MaxMediaUploadSize")*1024,
-          configuration.getString("TempDir"));
-
-      EntityUsers user = _getUser(req);
-      Map mediaValues = new HashMap();
-
-      mediaValues.put("to_publisher", _getUser(req).getId());
-
-      Iterator i = mainModule.getStorageObject().getFields().iterator();
-      while (i.hasNext()) {
-        String field = (String) i.next();
-        String value = parsedRequest.getParameter(field);
-        if (value!=null)
-          mediaValues.put(field, value);
-      }
-
-      List mediaList = new Vector();
-
-      i = parsedRequest.getFiles().iterator();
-      while (i.hasNext()) {
-        UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());
-
-        String suffix = file.getFieldName().substring(5);
-        mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));
-
-        mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));
-      }
-
-      String articleid = parsedRequest.getParameter("articleid");
-      String commentid = parsedRequest.getParameter("commentid");
-
-      if (articleid!=null) {
-        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);
-
-        i=mediaList.iterator();
-
-        while (i.hasNext()) {
-          entContent.attach(((EntityUploadedMedia) i.next()).getId());
-        }
-
-        ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, req, res);
-
-        return;
-      }
-
-      if (commentid!=null) {
-        EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid);
-
-        i=mediaList.iterator();
-
-        while (i.hasNext()) {
-          comment.attach( ( (EntityUploadedMedia) i.next()).getId());
-        }
-
-        ((ServletModuleComment) ServletModuleComment.getInstance()).showComment(commentid, req, res);
-
-        return;
-      }
-
-      SimpleHash mergeData = new SimpleHash();
-      SimpleHash popups = new SimpleHash();
-      mergeData.put("contentlist", mir.generator.FreemarkerGenerator.makeAdapter(mediaList));
-
-      mergeData.put("count", Integer.toString(mediaList.size()));
-      mergeData.put("from", "1");
-      mergeData.put("to", Integer.toString(mediaList.size()));
-
-      //fetch the popups
-      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
-      // raus damit
-      deliver(req, res, mergeData, popups, templateListString);
-    }
-    catch (Throwable t) {
-      Throwable cause = ExceptionFunctions.traceCauseException(t);
-
-      if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {
-        throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});
-      }
-      throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);
-    }
-  }
-
-  public void update(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-
-    try {
-      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(req,
-          configuration.getString("Mir.DefaultEncoding"),
-          configuration.getInt("MaxMediaUploadSize")*1024,
-          configuration.getString("TempDir"));
-      EntityUsers user = _getUser(req);
-      Map mediaValues = new HashMap();
-
-      Iterator i = mainModule.getStorageObject().getFields().iterator();
-      while (i.hasNext()) {
-        String field = (String) i.next();
-        String value = parsedRequest.getParameter(field);
-        if (value!=null)
-          mediaValues.put(field, value);
-      }
-
-      mediaValues.put("to_publisher", user.getId());
-      mediaValues.put("is_produced", "0");
-      if (!mediaValues.containsKey("is_published"))
-        mediaValues.put("is_published", "0");
-
-      String id = mainModule.set(mediaValues);
-      logger.debug("update: media ID = " + id);
-      _edit(id, req, res);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure("upload -- exception " + e.toString(), e);
-    }
-
-  }
-
-
-  public void list(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    // Parameter auswerten
-    SimpleHash mergeData = new SimpleHash();
-    SimpleHash popups = new SimpleHash();
-
-    String query_text = req.getParameter("query_text");
-    mergeData.put("query_text", query_text);
-    if (query_text != null) mergeData.put("query_text_encoded", URLEncoder.encode(query_text));
-    String query_field = req.getParameter("query_field");
-    mergeData.put("query_field", query_field);
-    String query_is_published = req.getParameter("query_is_published");
-    mergeData.put("query_is_published", query_is_published);
-    String query_media_folder = req.getParameter("query_media_folder");
-    mergeData.put("query_media_folder", query_media_folder);
-    String offset = req.getParameter("offset");
-    if (offset == null || offset.equals("")) offset = "0";
-    mergeData.put("offset", offset);
-
-    String order = req.getParameter("order");
-    if (order == null || order.equals("")) order = "webdb_lastchange desc";
-
-    // if in connection mode to content
-    mergeData.put("articleid", req.getParameter("articleid"));
-    mergeData.put("commentid", req.getParameter("commentid"));
-
-
-    // sql basteln
-    String whereClause = "";
-    boolean isFirst = true;
-    if (query_text != null && !query_text.equalsIgnoreCase("")) {
-      whereClause += "lower(" + query_field + ") like lower('%" + query_text + "%')";
-      isFirst = false;
-    }
-    if (query_is_published != null && !query_is_published.equals("")) {
-      if (isFirst == false) whereClause += " and ";
-      whereClause += "is_published='" + query_is_published + "'";
-      isFirst = false;
-    }
-    if (query_media_folder != null && !query_media_folder.equals("")) {
-      if (isFirst == false) whereClause += " and ";
-      whereClause += "to_media_folder='" + query_media_folder + "'";
-    }
-    //theLog.printDebugInfo("sql-whereclause: " + whereClause + " order: " + order + " offset: " + offset);
-
-    // fetch and deliver
-    try {
-      if (query_text != null || query_is_published != null || query_media_folder != null) {
-        EntityList theList = mainModule.getByWhereClause(whereClause, order, (new Integer(offset)).intValue(), 10);
-        if (theList != null) {
-          mergeData.put("contentlist", theList);
-          if (theList.getOrder() != null) {
-            mergeData.put("order", theList.getOrder());
-            mergeData.put("order_encoded", URLEncoder.encode(theList.getOrder()));
-          }
-          mergeData.put("count", (new Integer(theList.getCount())).toString());
-          mergeData.put("from", (new Integer(theList.getFrom())).toString());
-          mergeData.put("to", (new Integer(theList.getTo())).toString());
-          if (theList.hasNextBatch())
-            mergeData.put("next", (new Integer(theList.getNextBatch())).toString());
-          if (theList.hasPrevBatch())
-            mergeData.put("prev", (new Integer(theList.getPrevBatch())).toString());
-        }
-      }
-      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
-
-      deliver(req, res, mergeData, popups, templateListString);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-  public void add(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    try {
-      SimpleHash mergeData = new SimpleHash();
-      SimpleHash popups = new SimpleHash();
-      String maxMedia = MirPropertiesConfiguration.instance().getString("ServletModule.OpenIndy.MaxMediaUploadItems");
-      String numOfMedia = req.getParameter("medianum");
-
-      mergeData.put("new", "1");
-      mergeData.put("articleid", req.getParameter("articleid"));
-      mergeData.put("commentid", req.getParameter("commentid"));
-
-      popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
-
-      if (numOfMedia==null || numOfMedia.equals("")) {
-        numOfMedia="1";
-      }
-      else if(Integer.parseInt(numOfMedia) > Integer.parseInt(maxMedia)) {
-        numOfMedia = maxMedia;
-      }
-
-      int mediaNum = Integer.parseInt(numOfMedia);
-      SimpleList mediaFields = new SimpleList();
-      for(int i =0; i<mediaNum;i++){
-        Integer mNum = new Integer(i+1);
-        mediaFields.add(mNum.toString());
-      }
-      mergeData.put("medianum",numOfMedia);
-      mergeData.put("mediafields",mediaFields);
-      deliver(req, res, mergeData, popups, templateObjektString);
-    }
-    catch (Exception e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    String idParam = req.getParameter("id");
-    _edit(idParam, req, res);
-  }
-
-  private void _edit(String idParam, HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    if (idParam != null && !idParam.equals("")) {
-      try {
-        SimpleHash popups = new SimpleHash();
-        popups.put("mediafolderPopupData", DatabaseMediafolder.getInstance().getPopupData());
-        deliver(req, res, mainModule.getById(idParam), popups,
-                templateObjektString);
-      }
-      catch (Throwable e) {
-        throw new ServletModuleFailure(e);
-      }
-    }
-    else {
-      throw new ServletModuleExc("ServletmoduleUploadedMedia :: _edit without id");
-    }
-  }
-
-
-  /** @todo should be in ServletModule.java */
-  private EntityUsers _getUser(HttpServletRequest req) {
-    HttpSession session = req.getSession(false);
-    return (EntityUsers) session.getAttribute("login.uid");
-  }
-
-  public void getMedia(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc {
-    String idParam = req.getParameter("id");
-    if (idParam!=null && !idParam.equals("")) {
-      try {
-        EntityUploadedMedia ent = (EntityUploadedMedia)mainModule.getById(idParam);
-        Entity mediaType = ent.getMediaType();
-        MirMedia mediaHandler;
-
-        ServletContext ctx = MirPropertiesConfiguration.getContext();
-        String fName = ent.getId()+"."+mediaType.getValue("name");
-
-        mediaHandler = MediaHelper.getHandler(mediaType);
-        InputStream in = mediaHandler.getMedia(ent, mediaType);
-
-        res.setContentType(ctx.getMimeType(fName));
-        //important that before calling this res.getWriter was not called first
-        ServletOutputStream out = res.getOutputStream();
-
-        int read ;
-        byte[] buf = new byte[8 * 1024];
-        while((read = in.read(buf)) != -1) {
-          out.write(buf, 0, read);
-        }
-        in.close();
-        out.close();
-      }
-      catch (Throwable e) {
-        throw new ServletModuleFailure(e);
-      }
-    }
-    else logger.error("id not specified.");
-    // no exception allowed
-  }
-
-  public void getIcon(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String idParam = req.getParameter("id");
-    if (idParam!=null && !idParam.equals("")) {
-      try {
-        EntityUploadedMedia ent = (EntityUploadedMedia) mainModule.getById(idParam);
-        Entity mediaType = ent.getMediaType();
-        MirMedia mediaHandler;
-
-        mediaHandler = MediaHelper.getHandler(mediaType);
-        InputStream in = mediaHandler.getIcon(ent);
-
-        if (in==null)
-          throw new ServletModuleExc("no icon available");
-
-        res.setContentType(mediaHandler.getIconMimeType(ent, mediaType));
-        //important that before calling this res.getWriter was not called first
-        ServletOutputStream out = res.getOutputStream();
-
-        int read ;
-        byte[] buf = new byte[8 * 1024];
-        while((read = in.read(buf)) != -1) {
-          out.write(buf, 0, read);
-        }
-        in.close();
-        out.close();
-      }
-
-      catch (Throwable e) {
-        throw new ServletModuleFailure(e);
-      }
-    }
-    else logger.error("getIcon: id not specified.");
-    // no exception allowed
-  }
-
-}
-
-
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.io.InputStream;\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+import javax.servlet.ServletContext;\r
+import javax.servlet.ServletOutputStream;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import org.apache.commons.fileupload.FileItem;\r
+import mir.config.MirPropertiesConfiguration;\r
+import mir.entity.Entity;\r
+import mir.entity.adapter.EntityAdapter;\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.media.MediaHelper;\r
+import mir.media.MirMedia;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.servlet.ServletModuleUserExc;\r
+import mir.session.UploadedFile;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.ExceptionFunctions;\r
+import mir.util.HTTPParsedRequest;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.JDBCStringRoutines;\r
+import mir.util.SQLQueryBuilder;\r
+import mir.util.URLBuilder;\r
+import mircoders.entity.EntityComment;\r
+import mircoders.entity.EntityContent;\r
+import mircoders.entity.EntityUploadedMedia;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.media.MediaUploadProcessor;\r
+import mircoders.module.ModuleMediaType;\r
+import mircoders.storage.DatabaseComment;\r
+import mircoders.storage.DatabaseContent;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author the mir coders\r
+ * @version 1.0\r
+ */\r
+\r
+public abstract class ServletModuleUploadedMedia extends ServletModule {\r
+  protected String moduleName = "UploadedMedia";\r
+\r
+  public static ServletModule getInstance() {\r
+    return null;\r
+  }\r
+\r
+  public ServletModuleUploadedMedia() {\r
+    super();\r
+\r
+    definition = "uploadedMedia";\r
+    logger = new LoggerWrapper("ServletModule.UploadedMedia");\r
+    try {\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+          throws ServletModuleExc, ServletModuleUserExc {\r
+    try {\r
+      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,\r
+          configuration.getString("Mir.DefaultEncoding"),\r
+          configuration.getInt("MaxMediaUploadSize")*1024,\r
+          configuration.getString("TempDir"));\r
+\r
+      Map mediaValues = new HashMap();\r
+\r
+      mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());\r
+\r
+      Iterator i = mainModule.getStorageObject().getFields().iterator();\r
+      while (i.hasNext()) {\r
+        String field = (String) i.next();\r
+        String value = parsedRequest.getParameter(field);\r
+        if (value!=null)\r
+          mediaValues.put(field, value);\r
+      }\r
+\r
+      List mediaList = new Vector();\r
+\r
+      i = parsedRequest.getFiles().iterator();\r
+      while (i.hasNext()) {\r
+        UploadedFile file = new mir.session.CommonsUploadedFileAdapter((FileItem) i.next());\r
+\r
+        String suffix = file.getFieldName().substring(5);\r
+        mediaValues.put("title", parsedRequest.getParameter("media_title" + suffix));\r
+\r
+        mediaList.add(MediaUploadProcessor.processMediaUpload(file, mediaValues));\r
+      }\r
+\r
+      String articleid = parsedRequest.getParameter("articleid");\r
+      String commentid = parsedRequest.getParameter("commentid");\r
+\r
+      if (articleid!=null) {\r
+        EntityContent entContent = (EntityContent) DatabaseContent.getInstance().selectById(articleid);\r
+\r
+        i=mediaList.iterator();\r
+\r
+        while (i.hasNext()) {\r
+          entContent.attach(((EntityUploadedMedia) i.next()).getId());\r
+        }\r
+\r
+        ((ServletModuleContent) ServletModuleContent.getInstance())._showObject(articleid, aRequest, aResponse);\r
+\r
+        return;\r
+      }\r
+\r
+      if (commentid!=null) {\r
+        EntityComment comment = (EntityComment) DatabaseComment.getInstance().selectById(commentid);\r
+\r
+        i=mediaList.iterator();\r
+\r
+        while (i.hasNext()) {\r
+          comment.attach( ( (EntityUploadedMedia) i.next()).getId());\r
+        }\r
+\r
+        ((ServletModuleComment) ServletModuleComment.getInstance()).showComment(commentid, aRequest, aResponse);\r
+\r
+        return;\r
+      }\r
+\r
+      returnUploadedMediaList(aRequest, aResponse, mediaList, 1, mediaList.size(), mediaList.size(), "", null, null);\r
+    }\r
+    catch (Throwable t) {\r
+      Throwable cause = ExceptionFunctions.traceCauseException(t);\r
+\r
+      if (cause instanceof ModuleMediaType.UnsupportedMimeTypeExc) {\r
+        throw new ServletModuleUserExc("media.error.unsupportedformat", new String[] {});\r
+      }\r
+      throw new ServletModuleFailure("ServletModuleUploadedMedia.insert: " + t.toString(), t);\r
+    }\r
+  }\r
+\r
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+\r
+    try {\r
+      HTTPParsedRequest parsedRequest = new HTTPParsedRequest(aRequest,\r
+          configuration.getString("Mir.DefaultEncoding"),\r
+          configuration.getInt("MaxMediaUploadSize")*1024,\r
+          configuration.getString("TempDir"));\r
+      Map mediaValues = new HashMap();\r
+\r
+      Iterator i = mainModule.getStorageObject().getFields().iterator();\r
+      while (i.hasNext()) {\r
+        String field = (String) i.next();\r
+        String value = parsedRequest.getParameter(field);\r
+        if (value!=null)\r
+          mediaValues.put(field, value);\r
+      }\r
+\r
+      mediaValues.put("to_publisher", ServletHelper.getUser(aRequest).getId());\r
+      mediaValues.put("is_produced", "0");\r
+      if (!mediaValues.containsKey("is_published"))\r
+        mediaValues.put("is_published", "0");\r
+\r
+      String id = mainModule.set(mediaValues);\r
+      logger.debug("update: media ID = " + id);\r
+\r
+      editUploadedMediaObject(id, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure("upload -- exception " + e.toString(), e);\r
+    }\r
+\r
+  }\r
+\r
+  public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+                                      Object aList, int aFrom, int aTo, int aCount,\r
+                                      String aThisUrl, String aNextUrl, String aPreviousUrl) throws ServletModuleExc {\r
+\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      responseData.put("searchfield", requestParser.getParameterWithDefault("searchfield", ""));\r
+      responseData.put("searchtext", requestParser.getParameterWithDefault("searchtext", ""));\r
+      responseData.put("searchispublished", requestParser.getParameterWithDefault("searchispublished", ""));\r
+      responseData.put("searchmediafolder", requestParser.getParameterWithDefault("searchmediafolder", ""));\r
+      responseData.put("articleid", requestParser.getParameter("articleid"));\r
+      responseData.put("commentid", requestParser.getParameter("commentid"));\r
+\r
+      responseData.put("thisurl", aThisUrl);\r
+      responseData.put("nexturl", aNextUrl);\r
+      responseData.put("prevurl", aPreviousUrl);\r
+\r
+      responseData.put("from", Integer.toString(aFrom));\r
+      responseData.put("count", Integer.toString(aCount));\r
+      responseData.put("to", Integer.toString(aTo));\r
+\r
+      responseData.put("medialist", aList);\r
+\r
+      addExtraData(responseData);\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public void returnUploadedMediaList(HttpServletRequest aRequest, HttpServletResponse aResponse,\r
+                                      String aWhereClause, String anOrderByClause, int anOffset) throws ServletModuleExc {\r
+\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    EntityAdapterModel model;\r
+    String nextPageUrl = null;\r
+    String previousPageUrl = null;\r
+    String thisUrl = null;\r
+\r
+    int count;\r
+\r
+    try {\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+\r
+      Object mediaList =\r
+          new CachingRewindableIterator(\r
+          new EntityIteratorAdapter(aWhereClause, anOrderByClause, nrEntitiesPerListPage,\r
+                   model, definition, nrEntitiesPerListPage, anOffset)\r
+          );\r
+\r
+      count = mainModule.getSize(aWhereClause);\r
+\r
+      urlBuilder.setValue("module", moduleName);\r
+      urlBuilder.setValue("do", "list");\r
+      urlBuilder.setValue("where", aWhereClause);\r
+      urlBuilder.setValue("order", anOrderByClause);\r
+\r
+      urlBuilder.setValue("articleid", requestParser.getParameter("articleid"));\r
+      urlBuilder.setValue("commentid", requestParser.getParameter("commentid"));\r
+      urlBuilder.setValue("searchfield", requestParser.getParameter("searchfield"));\r
+      urlBuilder.setValue("searchtext", requestParser.getParameter("searchtext"));\r
+      urlBuilder.setValue("searchispublished", requestParser.getParameter("searchispublished"));\r
+      urlBuilder.setValue("searchmediafolder", requestParser.getParameter("searchmediafolder"));\r
+      urlBuilder.setValue("where", aWhereClause);\r
+      urlBuilder.setValue("order", anOrderByClause);\r
+\r
+      urlBuilder.setValue("offset", anOffset);\r
+      thisUrl = urlBuilder.getQuery();\r
+\r
+      if (count >= anOffset + nrEntitiesPerListPage) {\r
+        urlBuilder.setValue("offset", anOffset + nrEntitiesPerListPage);\r
+        nextPageUrl = urlBuilder.getQuery();\r
+      }\r
+\r
+      if (anOffset > 0) {\r
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
+        previousPageUrl = urlBuilder.getQuery();\r
+      }\r
+\r
+      returnUploadedMediaList(aRequest, aResponse, mediaList,\r
+              anOffset+1, anOffset+nrEntitiesPerListPage, count, thisUrl,\r
+              nextPageUrl, previousPageUrl);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void search(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    SQLQueryBuilder queryBuilder = new SQLQueryBuilder();\r
+\r
+    String queryField = "";\r
+    String searchField = requestParser.getParameter("searchfield");\r
+    String searchText = requestParser.getParameter("searchtext");\r
+    String searchIsPublished = requestParser.getParameter("searchispublished");\r
+    String searchMediaFolder = requestParser.getParameter("searchmediafolder");\r
+\r
+    queryBuilder.appendDescendingOrder("webdb_create");\r
+\r
+    if (searchIsPublished!=null)\r
+      if (searchIsPublished.equals("0")) {\r
+        queryBuilder.appendAndCondition("is_published='f'");\r
+      }\r
+      else if (searchIsPublished.equals("1")) {\r
+        queryBuilder.appendAndCondition("is_published='t'");\r
+      }\r
+\r
+    if (searchField!=null && searchText!=null && searchText.length()>0) {\r
+        queryBuilder.appendAndCondition(\r
+          "lower(" + searchField + ") like " +\r
+          "'%" + JDBCStringRoutines.escapeStringLiteral(searchText.toLowerCase()) + "%'");\r
+    }\r
+\r
+    if (searchMediaFolder!=null && searchMediaFolder.length()>0) {\r
+      queryBuilder.appendAndCondition("to_media_folder="+Integer.parseInt(searchMediaFolder));\r
+    }\r
+\r
+    returnUploadedMediaList(aRequest, aResponse,\r
+            queryBuilder.getWhereClause(), queryBuilder.getOrderByClause(), requestParser.getIntegerWithDefault("offset", 0));\r
+  }\r
+\r
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    returnUploadedMediaList(aRequest, aResponse,\r
+       requestParser.getParameterWithDefault("where", ""),\r
+       requestParser.getParameterWithDefault("order", "webdb_create desc"),\r
+       requestParser.getIntegerWithDefault("offset", 0));\r
+  }\r
+\r
+\r
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
+\r
+      int nrMedia = requestParser.getIntegerWithDefault("nrmedia", 1);\r
+      int maxNrMedia=configuration.getInt("ServletModule.OpenIndy.MaxMediaUploadItems", 20);\r
+\r
+      List fields = mainModule.getStorageObject().getFields();\r
+      Map media = new HashMap();\r
+      Iterator i = fields.iterator();\r
+      while (i.hasNext()) {\r
+        media.put(i.next(), null);\r
+      }\r
+      media.put("to_media_folder", new Integer(7));\r
+      responseData.put("uploadedmedia", media);\r
+\r
+      responseData.put("new", Boolean.TRUE);\r
+      responseData.put("articleid", requestParser.getParameter("articleid"));\r
+      responseData.put("commentid", requestParser.getParameter("commentid"));\r
+      responseData.put("returnurl", null);\r
+\r
+      if (nrMedia<=0)\r
+        nrMedia=1;\r
+      if (nrMedia>maxNrMedia)\r
+        nrMedia=maxNrMedia;\r
+\r
+      List mediaFields = new Vector();\r
+      for (int j=0; j<nrMedia; j++)\r
+        mediaFields.add(new Integer(j));\r
+\r
+      responseData.put("nrmedia", new Integer(nrMedia));\r
+      responseData.put("mediafields", mediaFields);\r
+\r
+      responseData.put("edittemplate", editGenerator);\r
+      responseData.put("module", moduleName);\r
+\r
+      addExtraData(responseData);\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, "uploadedmedia.template");\r
+    }\r
+    catch (Exception e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    editUploadedMediaObject(aRequest.getParameter("id"), aRequest, aResponse);\r
+  }\r
+\r
+  private void editUploadedMediaObject(String idParam, HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    if (idParam != null && !idParam.equals("")) {\r
+      try {\r
+        Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] {getLocale(aRequest), getFallbackLocale(aRequest)});\r
+        EntityAdapter object =\r
+            model.makeEntityAdapter(definition, mainModule.getById(idParam));\r
+        responseData.put("uploadedmedia", object);\r
+        responseData.put("new", Boolean.FALSE);\r
+        responseData.put("articleid", null);\r
+        responseData.put("commentid", null);\r
+        responseData.put("returnurl", null);\r
+\r
+        responseData.put("edittemplate", editGenerator);\r
+        responseData.put("module", moduleName);\r
+\r
+        addExtraData(responseData);\r
+\r
+        ServletHelper.generateResponse(aResponse.getWriter(), responseData, "uploadedmedia.template");\r
+      }\r
+      catch (Throwable e) {\r
+        throw new ServletModuleFailure(e);\r
+      }\r
+    }\r
+    else {\r
+      throw new ServletModuleExc("ServletmoduleUploadedMedia :: editUploadedMediaObject without id");\r
+    }\r
+  }\r
+\r
+  public void getMedia(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc {\r
+    String idParam = aRequest.getParameter("id");\r
+    if (idParam!=null && !idParam.equals("")) {\r
+      try {\r
+        EntityUploadedMedia ent = (EntityUploadedMedia)mainModule.getById(idParam);\r
+        Entity mediaType = ent.getMediaType();\r
+        MirMedia mediaHandler;\r
+\r
+        ServletContext ctx = MirPropertiesConfiguration.getContext();\r
+        String fName = ent.getId()+"."+mediaType.getValue("name");\r
+\r
+        mediaHandler = MediaHelper.getHandler(mediaType);\r
+        InputStream in = mediaHandler.getMedia(ent, mediaType);\r
+\r
+        aResponse.setContentType(ctx.getMimeType(fName));\r
+        //important that before calling this aResponse.getWriter was not called first\r
+        ServletOutputStream out = aResponse.getOutputStream();\r
+\r
+        int read ;\r
+        byte[] buf = new byte[8 * 1024];\r
+        while((read = in.read(buf)) != -1) {\r
+          out.write(buf, 0, read);\r
+        }\r
+        in.close();\r
+        out.close();\r
+      }\r
+      catch (Throwable e) {\r
+        throw new ServletModuleFailure(e);\r
+      }\r
+    }\r
+    else logger.error("id not specified.");\r
+    // no exception allowed\r
+  }\r
+\r
+  public void getIcon(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String idParam = aRequest.getParameter("id");\r
+    if (idParam!=null && !idParam.equals("")) {\r
+      try {\r
+        EntityUploadedMedia ent = (EntityUploadedMedia) mainModule.getById(idParam);\r
+        Entity mediaType = ent.getMediaType();\r
+        MirMedia mediaHandler;\r
+\r
+        mediaHandler = MediaHelper.getHandler(mediaType);\r
+        InputStream in = mediaHandler.getIcon(ent);\r
+\r
+        if (in==null)\r
+          throw new ServletModuleExc("no icon available");\r
+\r
+        aResponse.setContentType(mediaHandler.getIconMimeType(ent, mediaType));\r
+        //important that before calling this aResponse.getWriter was not called first\r
+        ServletOutputStream out = aResponse.getOutputStream();\r
+\r
+        int read ;\r
+        byte[] buf = new byte[8 * 1024];\r
+        while((read = in.read(buf)) != -1) {\r
+          out.write(buf, 0, read);\r
+        }\r
+        in.close();\r
+        out.close();\r
+      }\r
+\r
+      catch (Throwable e) {\r
+        logger.error("getIcon: " + e.toString());\r
+      }\r
+    }\r
+    else logger.error("getIcon: id not specified.");\r
+    // no exception allowed\r
+  }\r
+\r
+  protected void addExtraData(Map aTarget) throws ServletModuleExc, ServletModuleFailure {\r
+    try {\r
+      aTarget.put("mediafolders",\r
+                  new EntityIteratorAdapter("", "", 20, MirGlobal.localizer().dataModel().adapterModel(), "mediaFolder"));\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+}
\ No newline at end of file
index 1d6e2e0..25e824c 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.servlet;
-
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import mir.log.LoggerWrapper;
-import mir.servlet.ServletModule;
-import mir.servlet.ServletModuleExc;
-import mir.servlet.ServletModuleFailure;
-import mir.servlet.ServletModuleUserExc;
-import mir.storage.StorageObjectFailure;
-import mir.util.HTTPRequestParser;
-import mircoders.module.ModuleUsers;
-import mircoders.storage.DatabaseUsers;
-import freemarker.template.SimpleHash;
-
-/*
- *  ServletModuleUsers -
- *  liefert HTML fuer Users
- *
- *
- * @author RK
- */
-
-public class ServletModuleUsers extends ServletModule
-{
-  private static ServletModuleUsers instance = new ServletModuleUsers();
-  public static ServletModule getInstance() { return instance; }
-
-  private ServletModuleUsers() {
-    super();
-    logger = new LoggerWrapper("ServletModule.Users");
-
-    templateListString = configuration.getString("ServletModule.Users.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Users.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Users.ConfirmTemplate");
-
-    try {
-      mainModule = new ModuleUsers(DatabaseUsers.getInstance());
-    }
-    catch (StorageObjectFailure e) {
-      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());
-    }
-  }
-
-  public void edit(HttpServletRequest req, HttpServletResponse res) throws ServletModuleExc
-  {
-    String idParam = req.getParameter("id");
-
-    if (idParam == null)
-      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");
-
-    try {
-      deliver(req, res, mainModule.getById(idParam), templateObjektString);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void add(HttpServletRequest req, HttpServletResponse res)
-      throws ServletModuleExc
-  {
-    try {
-      SimpleHash mergeData = new SimpleHash();
-      mergeData.put("new", "1");
-      deliver(req, res, mergeData, templateObjektString);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public String checkPassword(HTTPRequestParser aRequestParser) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    if ( (aRequestParser.getParameter("newpassword") != null &&
-          aRequestParser.getParameter("newpassword").length() > 0) ||
-        (aRequestParser.getParameter("newpassword2") != null &&
-         aRequestParser.getParameter("newpassword2").length() > 0)
-        ) {
-      String newPassword = aRequestParser.getParameterWithDefault("newpassword", "");
-      String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", "");
-
-      if (newPassword.length() == 0 || newPassword2.length() == 0) {
-        throw new ServletModuleUserExc("user.error.missingpasswords", new String[] {});
-      }
-
-      if (!newPassword.equals(newPassword2)) {
-        throw new ServletModuleUserExc("user.error.passwordmismatch", new String[] {});
-      }
-
-      return newPassword;
-    }
-    else
-      return null;
-  }
-
-  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)
-      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
-
-      String newPassword=checkPassword(requestParser);
-      if (newPassword!=null)
-        withValues.put("password", newPassword);
-      else
-        throw new ServletModuleUserExc("user.error.missingpassword", new String[] {});
-
-      String id = mainModule.add(withValues);
-      if (requestParser.hasParameter("returnurl"))
-        redirect(aResponse, requestParser.getParameter("returnurl"));
-      else
-        list(aRequest, aResponse);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure
-  {
-    try {
-      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);
-
-      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());
-
-      String newPassword=checkPassword(requestParser);
-      if (newPassword!=null)
-        withValues.put("password", newPassword);
-
-      mainModule.set(withValues);
-
-      if (requestParser.hasParameter("returnurl"))
-        redirect(aResponse, requestParser.getParameter("returnurl"));
-      else
-        list(aRequest, aResponse);
-    }
-    catch (Throwable e) {
-      throw new ServletModuleFailure(e);
-    }
-  }
-
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.servlet;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Locale;\r
+import java.util.Map;\r
+import javax.servlet.http.HttpServletRequest;\r
+import javax.servlet.http.HttpServletResponse;\r
+\r
+import mir.entity.adapter.EntityAdapterModel;\r
+import mir.entity.adapter.EntityIteratorAdapter;\r
+import mir.log.LoggerWrapper;\r
+import mir.servlet.ServletModule;\r
+import mir.servlet.ServletModuleExc;\r
+import mir.servlet.ServletModuleFailure;\r
+import mir.servlet.ServletModuleUserExc;\r
+import mir.storage.StorageObjectFailure;\r
+import mir.util.CachingRewindableIterator;\r
+import mir.util.HTTPRequestParser;\r
+import mir.util.URLBuilder;\r
+import mircoders.entity.EntityUsers;\r
+import mircoders.global.MirGlobal;\r
+import mircoders.module.ModuleUsers;\r
+import mircoders.storage.DatabaseUsers;\r
+import mircoders.global.*;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+public class ServletModuleUsers extends ServletModule\r
+{\r
+  private static ServletModuleUsers instance = new ServletModuleUsers();\r
+  public static ServletModule getInstance() { return instance; }\r
+  protected ModuleUsers usersModule;\r
+\r
+  private ServletModuleUsers() {\r
+    super();\r
+    logger = new LoggerWrapper("ServletModule.Users");\r
+\r
+    try {\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+      definition = "user";\r
+      usersModule = new ModuleUsers(DatabaseUsers.getInstance());\r
+      mainModule = usersModule;\r
+    }\r
+    catch (Throwable e) {\r
+      logger.debug("initialization of ServletModuleUsers failed!: " + e.getMessage());\r
+    }\r
+  }\r
+\r
+  public void edit(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String idParam = aRequest.getParameter("id");\r
+\r
+    if (idParam == null)\r
+      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");\r
+\r
+    try {\r
+      EntityUsers user = (EntityUsers) mainModule.getById(idParam);\r
+      MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user);\r
+\r
+      showUser(idParam, false, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void add(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc\r
+  {\r
+    try {\r
+      MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest));\r
+\r
+      showUser(null, false, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public String validatePassword(EntityUsers aUser, HTTPRequestParser aRequestParser) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    if ( (aRequestParser.getParameter("newpassword") != null &&\r
+          aRequestParser.getParameter("newpassword").length() > 0) ||\r
+        (aRequestParser.getParameter("newpassword2") != null &&\r
+         aRequestParser.getParameter("newpassword2").length() > 0)\r
+        ) {\r
+      String newPassword = aRequestParser.getParameterWithDefault("newpassword", "");\r
+      String newPassword2 = aRequestParser.getParameterWithDefault("newpassword2", "");\r
+      String oldPassword = aRequestParser.getParameterWithDefault("oldpassword", "");\r
+\r
+      try {\r
+        if (!usersModule.checkUserPassword(aUser, oldPassword)) {\r
+          throw new ServletModuleUserExc("user.error.incorrectpassword", new String[] {});\r
+        }\r
+      }\r
+      catch (Throwable t) {\r
+        throw new ServletModuleFailure(t);\r
+      }\r
+\r
+\r
+      if (newPassword.length() == 0 || newPassword2.length() == 0) {\r
+        throw new ServletModuleUserExc("user.error.missingpasswords", new String[] {});\r
+      }\r
+\r
+      if (!newPassword.equals(newPassword2)) {\r
+        throw new ServletModuleUserExc("user.error.passwordmismatch", new String[] {});\r
+      }\r
+\r
+      return newPassword;\r
+    }\r
+    else\r
+      return null;\r
+  }\r
+\r
+  public void insert(HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    try {\r
+      MirGlobal.accessControl().user().assertMayAddUsers(ServletHelper.getUser(aRequest));\r
+\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
+\r
+      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);\r
+      if (newPassword!=null)\r
+        withValues.put("password", newPassword);\r
+      else\r
+        throw new ServletModuleUserExc("user.error.missingpassword", new String[] {});\r
+\r
+      String id = mainModule.add(withValues);\r
+      if (requestParser.hasParameter("returnurl"))\r
+        redirect(aResponse, requestParser.getParameter("returnurl"));\r
+      else\r
+        list(aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void update(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      EntityUsers user = (EntityUsers) mainModule.getById(requestParser.getParameter("id"));\r
+      MirGlobal.accessControl().user().assertMayEditUser(ServletHelper.getUser(aRequest), user);\r
+\r
+      Map withValues = getIntersectingValues(aRequest, mainModule.getStorageObject());\r
+      if (!withValues.containsKey("is_admin"))\r
+        withValues.put("is_admin","0");\r
+\r
+      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);\r
+      if (newPassword!=null)\r
+        withValues.put("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword));\r
+\r
+      mainModule.set(withValues);\r
+\r
+      if (requestParser.hasParameter("returnurl"))\r
+        redirect(aResponse, requestParser.getParameter("returnurl"));\r
+      else\r
+        list(aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void updatepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc, ServletModuleUserExc, ServletModuleFailure\r
+  {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      EntityUsers user = (EntityUsers) mainModule.getById(requestParser.getParameter("id"));\r
+      MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user);\r
+\r
+      String newPassword=validatePassword(ServletHelper.getUser(aRequest), requestParser);\r
+      if (newPassword!=null) {\r
+        user.setValueForProperty("password", MirGlobal.localizer().adminInterface().makePasswordDigest(newPassword));\r
+        user.update();\r
+\r
+        // hackish: to make sure the cached logged in user is up-to-date:\r
+        ServletHelper.setUser(aRequest, (EntityUsers) mainModule.getById(ServletHelper.getUser(aRequest).getId()));\r
+      }\r
+\r
+      if (requestParser.hasParameter("returnurl"))\r
+        redirect(aResponse, requestParser.getParameter("returnurl"));\r
+      else\r
+        redirect(aResponse, "");\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void list(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+\r
+    int offset = requestParser.getIntegerWithDefault("offset", 0);\r
+\r
+    returnUserList(aRequest, aResponse, offset);\r
+  }\r
+\r
+  public void returnUserList(\r
+       HttpServletRequest aRequest,\r
+       HttpServletResponse aResponse,\r
+       int anOffset) throws ServletModuleExc {\r
+\r
+// ML: to be deleted, support for 3 extra vars to be added\r
+\r
+    HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+    URLBuilder urlBuilder = new URLBuilder();\r
+    EntityAdapterModel model;\r
+    int count;\r
+\r
+    try {\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      model = MirGlobal.localizer().dataModel().adapterModel();\r
+\r
+      Object userList =\r
+          new CachingRewindableIterator(\r
+            new EntityIteratorAdapter( "", "login", nrEntitiesPerListPage,\r
+               MirGlobal.localizer().dataModel().adapterModel(), "user", nrEntitiesPerListPage, anOffset)\r
+      );\r
+\r
+      responseData.put("nexturl", null);\r
+      responseData.put("prevurl", null);\r
+\r
+      count=mainModule.getSize("");\r
+\r
+      urlBuilder.setValue("module", "Users");\r
+      urlBuilder.setValue("do", "list");\r
+\r
+      urlBuilder.setValue("offset", anOffset);\r
+      responseData.put("offset" , new Integer(anOffset).toString());\r
+      responseData.put("thisurl" , urlBuilder.getQuery());\r
+\r
+      if (count>=anOffset+nrEntitiesPerListPage) {\r
+        urlBuilder.setValue("offset", (anOffset + nrEntitiesPerListPage));\r
+        responseData.put("nexturl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      if (anOffset>0) {\r
+        urlBuilder.setValue("offset", Math.max(anOffset - nrEntitiesPerListPage, 0));\r
+        responseData.put("prevurl" , urlBuilder.getQuery());\r
+      }\r
+\r
+      responseData.put("users", userList);\r
+      responseData.put("mayDeleteUsers", new Boolean(MirGlobal.accessControl().user().mayDeleteUsers(ServletHelper.getUser(aRequest))));\r
+      responseData.put("mayAddUsers", new Boolean(MirGlobal.accessControl().user().mayAddUsers(ServletHelper.getUser(aRequest))));\r
+      responseData.put("mayEditUsers", new Boolean(MirGlobal.accessControl().user().mayEditUsers(ServletHelper.getUser(aRequest))));\r
+\r
+      responseData.put("from" , Integer.toString(anOffset+1));\r
+      responseData.put("count", Integer.toString(count));\r
+      responseData.put("to", Integer.toString(Math.min(anOffset+nrEntitiesPerListPage, count)));\r
+      responseData.put("offset" , Integer.toString(anOffset));\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, listGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void showUser(String anId, boolean anOnlyPassword, HttpServletRequest aRequest, HttpServletResponse aResponse)\r
+      throws ServletModuleExc {\r
+    try {\r
+      HTTPRequestParser requestParser = new HTTPRequestParser(aRequest);\r
+      Map responseData = ServletHelper.makeGenerationData(aRequest, aResponse, new Locale[] { getLocale(aRequest), getFallbackLocale(aRequest)});\r
+      EntityAdapterModel model = MirGlobal.localizer().dataModel().adapterModel();\r
+      Map user;\r
+      URLBuilder urlBuilder = new URLBuilder();\r
+\r
+      urlBuilder.setValue("module", "Users");\r
+      if (anOnlyPassword)\r
+        urlBuilder.setValue("do", "changepassword");\r
+      else\r
+        urlBuilder.setValue("do", "edit");\r
+      urlBuilder.setValue("id", anId);\r
+      urlBuilder.setValue("returnurl", requestParser.getParameter("returnurl"));\r
+\r
+      if (anId!=null) {\r
+        responseData.put("new", Boolean.FALSE);\r
+        user = model.makeEntityAdapter("user", mainModule.getById(anId));\r
+      }\r
+      else {\r
+        List fields = DatabaseUsers.getInstance().getFields();\r
+        responseData.put("new", Boolean.TRUE);\r
+        user = new HashMap();\r
+        Iterator i = fields.iterator();\r
+        while (i.hasNext()) {\r
+          user.put(i.next(), null);\r
+        }\r
+\r
+        MirGlobal.localizer().adminInterface().initializeArticle(user);\r
+      }\r
+      responseData.put("user", user);\r
+      responseData.put("passwordonly", new Boolean(anOnlyPassword));\r
+\r
+      responseData.put("returnurl", requestParser.getParameter("returnurl"));\r
+      responseData.put("thisurl", urlBuilder.getQuery());\r
+\r
+      ServletHelper.generateResponse(aResponse.getWriter(), responseData, editGenerator);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+\r
+  public void delete(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleUserExc, ServletModuleExc, ServletModuleFailure {\r
+    try {\r
+      EntityUsers user = (EntityUsers) mainModule.getById(aRequest.getParameter("id"));\r
+\r
+      MirGlobal.accessControl().user().assertMayDeleteUser(ServletHelper.getUser(aRequest), user);\r
+\r
+      super.delete(aRequest, aResponse);\r
+    }\r
+    catch (Throwable t) {\r
+      throw new ServletModuleFailure(t);\r
+    }\r
+  }\r
+\r
+  public void changepassword(HttpServletRequest aRequest, HttpServletResponse aResponse) throws ServletModuleExc\r
+  {\r
+    String idParam = aRequest.getParameter("id");\r
+\r
+    if (idParam == null)\r
+      throw new ServletModuleExc("ServletModuleUser.edit: invalid call: (id) not specified");\r
+\r
+    try {\r
+      EntityUsers user = (EntityUsers) mainModule.getById(idParam);\r
+      MirGlobal.accessControl().user().assertMayChangeUserPassword(ServletHelper.getUser(aRequest), user);\r
+\r
+      showUser(idParam, true, aRequest, aResponse);\r
+    }\r
+    catch (Throwable e) {\r
+      throw new ServletModuleFailure(e);\r
+    }\r
+  }\r
+}\r
+\r
index d206247..2499be3 100755 (executable)
  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  *
  * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License, 
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library 
- * (or with modified versions of the above that use the same license as the above), 
- * and distribute linked combinations including the two.  You must obey the 
- * GNU General Public License in all respects for all of the code used other than 
- * the above mentioned libraries.  If you modify this file, you may extend this 
- * exception to your version of the file, but you are not obligated to do so.  
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
  * If you do not wish to do so, delete this exception statement from your version.
  */
 
@@ -35,38 +35,38 @@ import mir.servlet.ServletModule;
 import mir.storage.StorageObjectFailure;
 import mircoders.module.ModuleUploadedMedia;
 import mircoders.storage.DatabaseVideo;
+import mircoders.global.*;
 
-/*
- *
+/**
  *
- * @author br1
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
  */
 
 public class ServletModuleVideo extends ServletModuleUploadedMedia {
-
-  //private static DatabaseRights dbRights;
-
-  // Singelton / Contructor
   private static ServletModuleVideo instance = new ServletModuleVideo();
 
   public static ServletModule getInstance() {
     return instance;
   }
 
-
   private ServletModuleVideo() {
     super();
     logger = new LoggerWrapper("ServletModule.Video");
-    templateListString = configuration.getString("ServletModule.Video.ListTemplate");
-    templateObjektString = configuration.getString("ServletModule.Video.ObjektTemplate");
-    templateConfirmString = configuration.getString("ServletModule.Video.ConfirmTemplate");
+
+    moduleName = "Video";
+
     try {
+      model = MirGlobal.localizer().dataModel().adapterModel();
+      definition = "video";
       mainModule = new ModuleUploadedMedia(DatabaseVideo.getInstance());
-      //dbRights = DatabaseRights.getInstance();
     }
-    catch (StorageObjectFailure e) {
+    catch (Throwable e) {
       logger.error("servletmodule video could not be initialized: " + e.getMessage());
     }
   }
-}
-
+}
\ No newline at end of file
index 9ba7abc..d6ed182 100755 (executable)
@@ -39,17 +39,17 @@ package mircoders.storage;
  * @version 1.0
  */
 
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
+import java.util.List;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
 
 public class DatabaseArticleType extends Database implements StorageObject{
 
   private static DatabaseArticleType instance;
-  private static SimpleList articletypePopupData;
+  private static List articletypePopupData;
 
   public synchronized static DatabaseArticleType getInstance() throws StorageObjectFailure {
     if (instance == null) {
@@ -65,7 +65,4 @@ public class DatabaseArticleType extends Database implements StorageObject{
     this.theTable = "article_type";
   }
 
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", false);
-  }
 }
index bed4e44..24d6b06 100755 (executable)
@@ -1,90 +1,84 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.storage;
-
-import java.util.GregorianCalendar;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-public class DatabaseAudio extends Database implements StorageObject{
-
-  private static DatabaseAudio instance;
-  private static SimpleList publisherPopupData;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseAudio getInstance() {
-    if (instance == null) {
-      instance = new DatabaseAudio();
-    }
-    return instance;
-  }
-
-  private DatabaseAudio() throws StorageObjectFailure {
-    super();
-    logger = new LoggerWrapper("Database.Audio");
-
-    hasTimestamp = true;
-    theTable = "audio";
-    theCoreTable = "media";
-    theEntityClass = mircoders.entity.EntityAudio.class;
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("title", true);
-  }
-
-  public void update(Entity theEntity) throws StorageObjectFailure {
-    String date = theEntity.getValue("date");
-    if (date == null) {
-      date = StringUtil.date2webdbDate(new GregorianCalendar());
-      theEntity.setValueForProperty("date", date);
-    }
-
-    super.update(theEntity);
-  }
-
-  public String insert(Entity theEntity) throws StorageObjectFailure {
-    String date = theEntity.getValue("date");
-    if (date == null) {
-      date = StringUtil.date2webdbDate(new GregorianCalendar());
-      theEntity.setValueForProperty("date", date);
-    }
-    return super.insert(theEntity);
-  }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.storage;\r
+\r
+import java.util.GregorianCalendar;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+public class DatabaseAudio extends Database implements StorageObject{\r
+\r
+  private static DatabaseAudio instance;\r
+\r
+  // the following *has* to be sychronized cause this static method\r
+  // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+  // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+  public synchronized static DatabaseAudio getInstance() {\r
+    if (instance == null) {\r
+      instance = new DatabaseAudio();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseAudio() throws StorageObjectFailure {\r
+    super();\r
+    logger = new LoggerWrapper("Database.Audio");\r
+\r
+    hasTimestamp = true;\r
+    theTable = "audio";\r
+    theCoreTable = "media";\r
+    theEntityClass = mircoders.entity.EntityAudio.class;\r
+  }\r
+\r
+  public void update(Entity theEntity) throws StorageObjectFailure {\r
+    String date = theEntity.getValue("date");\r
+    if (date == null) {\r
+      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      theEntity.setValueForProperty("date", date);\r
+    }\r
+\r
+    super.update(theEntity);\r
+  }\r
+\r
+  public String insert(Entity theEntity) throws StorageObjectFailure {\r
+    String date = theEntity.getValue("date");\r
+    if (date == null) {\r
+      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      theEntity.setValueForProperty("date", date);\r
+    }\r
+    return super.insert(theEntity);\r
+  }\r
+\r
+}\r
index 3151c99..56f3e33 100755 (executable)
 
 package mircoders.storage;
 
-import java.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
+import java.sql.Connection;\r
+import java.sql.SQLException;\r
+import java.sql.Statement;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
  * <b>This class implements the access to the comment-table for the
@@ -67,10 +66,6 @@ public class DatabaseComment extends Database implements StorageObject{
     this.theEntityClass = mircoders.entity.EntityComment.class;
   }
 
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("title", true);
-  }
-
   public boolean deleteByContentId(String id) throws StorageObjectFailure {
     Statement stmt = null;
     Connection con = null;
index c2f5cc8..7cd02d8 100755 (executable)
@@ -39,11 +39,10 @@ package mircoders.storage;
  * @version 1.0
  */
 
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 
 public class DatabaseCommentStatus extends Database implements StorageObject{
@@ -64,8 +63,4 @@ public class DatabaseCommentStatus extends Database implements StorageObject{
     theTable = "comment_status";
     logger = new LoggerWrapper("Database.CommentStatus");
   }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", false);
-  }
 }
\ No newline at end of file
index 9868d6b..1767ef7 100755 (executable)
 
 package mircoders.storage;
 
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityComment;
+import java.sql.Connection;\r
+import java.sql.ResultSet;\r
+import java.sql.Statement;\r
+\r
+import mir.entity.EntityList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectExc;\r
+import mir.storage.StorageObjectFailure;\r
+import mircoders.entity.EntityComment;\r
 import mircoders.entity.EntityUploadedMedia;
 
 /**
  * <b>implements abstract DB connection to the comment_x_media SQL table
  *
  * @author RK, mir-coders group
- * @version $Id: DatabaseCommentToMedia.java,v 1.3 2003/05/03 00:21:22 zapata Exp $
+ * @version $Id: DatabaseCommentToMedia.java,v 1.4 2003/09/03 18:29:05 zapata Exp $
  *
  */
 
@@ -72,33 +72,6 @@ public class DatabaseCommentToMedia extends Database implements StorageObject{
     theEntityClass = mir.entity.GenericEntity.class;
   }
 
-  /**
-   * get all the media-files belonging to a comment entity
-   *
-   */
-  public EntityList getMedia(EntityComment comment) throws StorageObjectFailure {
-    EntityList returnList = null;
-    if (comment != null) {
-      // get all to_topic from media_x_topic
-      String id = comment.getId();
-      String subselect = "id in (select media_id from " + theTable +
-          " where comment_id=" + id + ")";
-
-      try {
-        // media should stay in uploaded order. this is especially important
-        // for photo stories which require a specific chronologic order.
-        // this is why we have the the second parameter "id"
-        returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect,
-            "id", -1);
-      }
-      catch (Throwable e) {
-        logger.debug("-- get media failed " + e.toString());
-        throw new StorageObjectFailure("-- get media failed ", e);
-      }
-    }
-    return returnList;
-  }
-
   public boolean hasMedia(EntityComment comment) throws StorageObjectFailure,
       StorageObjectExc {
     if (comment != null) {
index a5fc5a4..b28c5e0 100755 (executable)
 
 package mircoders.storage;
 
-import java.sql.Connection;
-import java.sql.Statement;
-
-import mir.entity.EntityList;
-import mir.entity.EntityRelation;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
+import java.sql.Connection;\r
+import java.sql.Statement;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
 import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
 
 /**
  * <b>this class implements the access to the content-table</b>
@@ -50,7 +47,6 @@ import mircoders.entity.EntityContent;
 public class DatabaseContent extends Database implements StorageObject {
 
   private static DatabaseContent      instance;
-  private static EntityRelation       relationComments;
 
   // Contructors / Singleton
 
@@ -72,8 +68,6 @@ public class DatabaseContent extends Database implements StorageObject {
     theCoreTable="media";
     logger = new LoggerWrapper("Database.Content");
 
-    relationComments =
-        new EntityRelation("id", "to_media", DatabaseComment.getInstance(), EntityRelation.TO_MANY);
     theEntityClass = mircoders.entity.EntityContent.class;
   }
 
@@ -102,14 +96,6 @@ public class DatabaseContent extends Database implements StorageObject {
   }
 
   /**
-   * returns the comments that belong to the article (via entityrelation)
-   * where db-flag is_published is true
-   */
-  public EntityList getComments(EntityContent entC) throws StorageObjectFailure {
-    return relationComments.getMany(entC,"webdb_create","is_published='1'");
-  }
-
-  /**
    *
    * @param id
    * @return
@@ -119,8 +105,10 @@ public class DatabaseContent extends Database implements StorageObject {
   public boolean delete(String id) throws StorageObjectFailure
   {
     DatabaseComment.getInstance().deleteByContentId(id);
-    super.delete(id);
-    return true;
+    DatabaseContentToTopics.getInstance().deleteByContentId(id);
+    DatabaseContentToMedia.getInstance().deleteByContentId(id);
+
+    return super.delete(id);
   }
 
 }
index 8cb8a56..ce7572a 100755 (executable)
 
 package mircoders.storage;
 
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
+import java.sql.Connection;\r
+import java.sql.ResultSet;\r
+import java.sql.Statement;\r
+\r
+import mir.entity.EntityList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectExc;\r
+import mir.storage.StorageObjectFailure;\r
+import mircoders.entity.EntityContent;\r
 import mircoders.entity.EntityUploadedMedia;
 
 /**
  * <b>implements abstract DB connection to the content_x_media SQL table
  *
  * @author RK, mir-coders group
- * @version $Id: DatabaseContentToMedia.java,v 1.19 2003/05/03 00:21:22 zapata Exp $
+ * @version $Id: DatabaseContentToMedia.java,v 1.20 2003/09/03 18:29:05 zapata Exp $
  *
  */
 
@@ -72,33 +72,6 @@ public class DatabaseContentToMedia extends Database implements StorageObject{
     theEntityClass = mir.entity.GenericEntity.class;
   }
 
-  /**
-   * get all the media-files belonging to a content entity
-   *
-   */
-  public EntityList getMedia(EntityContent content) throws StorageObjectFailure {
-    EntityList returnList = null;
-    if (content != null) {
-      // get all to_topic from media_x_topic
-      String id = content.getId();
-      String subselect = "id in (select media_id from " + theTable +
-          " where content_id=" + id + ")";
-
-      try {
-        // media should stay in uploaded order. this is especially important
-        // for photo stories which require a specific chronologic order.
-        // this is why we have the the second parameter "id"
-        returnList = DatabaseMedia.getInstance().selectByWhereClause(subselect,
-            "id", -1);
-      }
-      catch (Throwable e) {
-        logger.debug("-- get media failed " + e.toString());
-        throw new StorageObjectFailure("-- get media failed ", e);
-      }
-    }
-    return returnList;
-  }
-
   public boolean hasMedia(EntityContent content) throws StorageObjectFailure,
       StorageObjectExc {
     if (content != null) {
index 7475e90..4a696e4 100755 (executable)
 
 package mircoders.storage;
 
-import java.sql.Connection;
-import java.sql.ResultSet;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Vector;
-
-import mir.entity.EntityList;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import mircoders.entity.EntityContent;
+import java.sql.Connection;\r
+import java.sql.ResultSet;\r
+import java.sql.Statement;\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Vector;\r
+\r
+import mir.entity.EntityList;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+import mircoders.entity.EntityContent;\r
 import mircoders.entity.EntityTopics;
 
 /**
index f857d70..bbf37db 100755 (executable)
 
 package mircoders.storage;
 
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
 import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
  * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
@@ -45,7 +43,6 @@ import freemarker.template.SimpleList;
 public class DatabaseImageColor extends Database implements StorageObject{
 
   private static DatabaseImageColor instance;
-  private static SimpleList publisherPopupData;
 
   // the following *has* to be sychronized cause this static method
   // could get preemted and we could end up with 2 instances of DatabaseFoo..
@@ -64,7 +61,4 @@ public class DatabaseImageColor extends Database implements StorageObject{
     theTable = "img_color";
   }
 
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", true);
-  }
 }
index 310987d..26f2a8d 100755 (executable)
 
 package mircoders.storage;
 
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
 import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
  * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
@@ -45,7 +43,6 @@ import freemarker.template.SimpleList;
 public class DatabaseImageFormat extends Database implements StorageObject{
 
   private static DatabaseImageFormat instance;
-  private static SimpleList publisherPopupData;
 
   // the following *has* to be sychronized cause this static method
   // could get preemted and we could end up with 2 instances of DatabaseFoo..
@@ -63,9 +60,4 @@ public class DatabaseImageFormat extends Database implements StorageObject{
     hasTimestamp = false;
     theTable = "img_format";
   }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", true);
-  }
-
 }
index 1fac5a3..641f903 100755 (executable)
 
 package mircoders.storage;
 
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
 import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
  * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
@@ -45,7 +43,6 @@ import freemarker.template.SimpleList;
 public class DatabaseImageLayout extends Database implements StorageObject{
 
   private static DatabaseImageLayout instance;
-  private static SimpleList publisherPopupData;
 
   // the following *has* to be sychronized cause this static method
   // could get preemted and we could end up with 2 instances of DatabaseFoo..
@@ -64,9 +61,4 @@ public class DatabaseImageLayout extends Database implements StorageObject{
     hasTimestamp = false;
     theTable = "img_layout";
   }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", true);
-  }
-
 }
index 377f1f7..a924eb5 100755 (executable)
@@ -1,69 +1,63 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.storage;
-
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseImageType extends Database implements StorageObject{
-  private static DatabaseImageType instance;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseImageType getInstance() {
-    if (instance == null) {
-      instance = new DatabaseImageType();
-    }
-    return instance;
-  }
-
-  private DatabaseImageType() {
-    super();
-    logger = new LoggerWrapper("Database.ImageType");
-
-    hasTimestamp = false;
-    theTable = "img_type";
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", true);
-  }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.storage;\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class DatabaseImageType extends Database implements StorageObject{\r
+  private static DatabaseImageType instance;\r
+\r
+  public synchronized static DatabaseImageType getInstance() {\r
+    if (instance == null) {\r
+      instance = new DatabaseImageType();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseImageType() {\r
+    super();\r
+    logger = new LoggerWrapper("Database.ImageType");\r
+\r
+    hasTimestamp = false;\r
+    theTable = "img_type";\r
+  }\r
+}\r
index d525df4..681fbaa 100755 (executable)
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.storage;
-
-import java.util.GregorianCalendar;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseImages extends Database implements StorageObject{
-
-  private static DatabaseImages instance;
-  private static SimpleList publisherPopupData;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseImages getInstance() {
-    if (instance == null) {
-      instance = new DatabaseImages();
-    }
-    return instance;
-  }
-
-  private DatabaseImages() {
-    super();
-
-    logger = new LoggerWrapper("Database.Images");
-
-    hasTimestamp = true;
-    theTable = "images";
-    theCoreTable = "media";
-    theEntityClass = mircoders.entity.EntityImages.class;
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("title", true);
-  }
-
-  public void update(Entity theEntity) throws StorageObjectFailure {
-    String date = theEntity.getValue("date");
-    if (date == null) {
-      date = StringUtil.date2webdbDate(new GregorianCalendar());
-      theEntity.setValueForProperty("date", date);
-    }
-
-    super.update(theEntity);
-  }
-
-  public String insert(Entity theEntity) throws StorageObjectFailure {
-    String date = theEntity.getValue("date");
-
-    if (date == null) {
-      date = StringUtil.date2webdbDate(new GregorianCalendar());
-      theEntity.setValueForProperty("date", date);
-    }
-
-    return super.insert(theEntity);
-  }
-
-  // initialisierungen aus den statischen Tabellen
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.util.GregorianCalendar;\r
+import java.util.List;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle\r
+ *\r
+ *\r
+ */\r
+\r
+public class DatabaseImages extends Database implements StorageObject{\r
+\r
+  private static DatabaseImages instance;\r
+\r
+  public synchronized static DatabaseImages getInstance() {\r
+    if (instance == null) {\r
+      instance = new DatabaseImages();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseImages() {\r
+    super();\r
+\r
+    logger = new LoggerWrapper("Database.Images");\r
+\r
+    hasTimestamp = true;\r
+    theTable = "images";\r
+    theCoreTable = "media";\r
+    theEntityClass = mircoders.entity.EntityImages.class;\r
+  }\r
+\r
+  public void update(Entity theEntity) throws StorageObjectFailure {\r
+    String date = theEntity.getValue("date");\r
+    if (date == null) {\r
+      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      theEntity.setValueForProperty("date", date);\r
+    }\r
+\r
+    super.update(theEntity);\r
+  }\r
+\r
+  public String insert(Entity theEntity) throws StorageObjectFailure {\r
+    String date = theEntity.getValue("date");\r
+\r
+    if (date == null) {\r
+      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      theEntity.setValueForProperty("date", date);\r
+    }\r
+\r
+    return super.insert(theEntity);\r
+  }\r
+}\r
index e0b15bc..a1ed74d 100755 (executable)
@@ -1,79 +1,93 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.storage;
-
-/**
- * Title: DatabaseLanguage
- * Description:
- * Copyright:    Copyright (c) 2001
- * Company:      Indymedia
- * @author
- * @version 1.0
- */
-
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-
-public class DatabaseLanguage extends Database implements StorageObject{
-
-  private static DatabaseLanguage instance;
-  private static SimpleList languagePopupData;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseLanguage getInstance() throws
-      StorageObjectFailure {
-    if (instance == null) {
-      instance = new DatabaseLanguage();
-    }
-    return instance;
-  }
-
-  private DatabaseLanguage() throws StorageObjectFailure {
-    super();
-    logger = new LoggerWrapper("Database.Language");
-
-    this.hasTimestamp = false;
-    this.theTable = "language";
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    SimpleList pData = null;
-    pData = getPopupData("name", false);
-
-    return pData;
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+/**\r
+ * Title: DatabaseLanguage\r
+ * Description:\r
+ * Copyright:    Copyright (c) 2001\r
+ * Company:      Indymedia\r
+ * @author\r
+ * @version 1.0\r
+ */\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityBrowser;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+\r
+public class DatabaseLanguage extends Database implements StorageObject{\r
+  private static DatabaseLanguage instance;\r
+\r
+  // the following *has* to be sychronized cause this static method\r
+  // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+  // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+  public synchronized static DatabaseLanguage getInstance() throws\r
+      StorageObjectFailure {\r
+    if (instance == null) {\r
+      instance = new DatabaseLanguage();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseLanguage() throws StorageObjectFailure {\r
+    super();\r
+    logger = new LoggerWrapper("Database.Language");\r
+\r
+    this.hasTimestamp = false;\r
+    this.theTable = "language";\r
+  }\r
+\r
+  public List getPopupData() throws StorageObjectFailure {\r
+    List result = new Vector();\r
+    Iterator i = new EntityBrowser(this, "", "name", 100, -1, 0);\r
+\r
+    while (i.hasNext()) {\r
+      Entity e = (Entity) i.next();\r
+      Map entry = new HashMap();\r
+      entry.put("key", e.getId());\r
+      entry.put("value", e.getValue("name"));\r
+\r
+      result.add(entry);\r
+    }\r
+\r
+    return result;\r
+  }\r
+}\r
diff --git a/source/mircoders/storage/DatabaseMedia.java b/source/mircoders/storage/DatabaseMedia.java
deleted file mode 100755 (executable)
index ed653a5..0000000
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.storage;
-
-import mir.entity.Entity;
-import mir.entity.EntityRelation;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectExc;
-import mir.storage.StorageObjectFailure;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseMedia extends Database implements StorageObject{
-
-  private static DatabaseMedia instance;
-  private static EntityRelation         relationMediaType;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseMedia getInstance() {
-    if (instance == null) {
-      instance = new DatabaseMedia();
-    }
-    return instance;
-  }
-
-  private DatabaseMedia() {
-    super();
-
-    logger = new LoggerWrapper("Database.Media");
-
-    hasTimestamp = false;
-    theTable="media";
-    relationMediaType =
-        new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE);
-    theEntityClass = mircoders.entity.EntityMedia.class;
-  }
-
-  // methods
-
-
-  /**
-   * returns the comments that belong to the article (via entityrelation)
-   * where db-flag is_published is true
-   */
-  public Entity getMediaType(Entity ent) throws StorageObjectFailure, StorageObjectExc {
-    try {
-      return relationMediaType.getOne(ent);
-    }
-    catch (Throwable e) {
-      logger.error("failed to get media_type: " + e.getMessage());
-      throw new StorageObjectFailure("DatabaseMedia.getMediaType :" + e.getMessage(),e);
-    }
-  }
-
-}
index 398acb2..cd2cf1a 100755 (executable)
@@ -42,12 +42,8 @@ import mir.storage.StorageObjectFailure;
  */
 
 public class DatabaseMediaType extends Database implements StorageObject{
-
   private static DatabaseMediaType instance;
 
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
   public synchronized static DatabaseMediaType getInstance() {
     if (instance == null) {
       instance = new DatabaseMediaType();
index 01be686..aaccbe4 100755 (executable)
@@ -1,77 +1,59 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.storage;
-
-/**
- * Title:        Mir
- * Description:  Ihre Beschreibung
- * Copyright:    Copyright (c) 1999
- * Company:
- * @author
- * @version
- */
-
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-
-
-public class DatabaseMediafolder extends Database implements StorageObject{
-
-  private static DatabaseMediafolder instance;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseMediafolder getInstance() {
-    if (instance == null) {
-      instance = new DatabaseMediafolder();
-    }
-    return instance;
-  }
-
-  private DatabaseMediafolder() {
-    super();
-
-    logger = new LoggerWrapper("Database.Mediafolder");
-
-    hasTimestamp = false;
-    theTable="media_folder";
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name",true);
-  }
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+/**\r
+ *\r
+ */\r
+\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+\r
+public class DatabaseMediafolder extends Database implements StorageObject{\r
+  private static DatabaseMediafolder instance;\r
+\r
+  public synchronized static DatabaseMediafolder getInstance() {\r
+    if (instance == null) {\r
+      instance = new DatabaseMediafolder();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseMediafolder() {\r
+    super();\r
+\r
+    logger = new LoggerWrapper("Database.Mediafolder");\r
+\r
+    hasTimestamp = false;\r
+    theTable="media_folder";\r
+  }\r
+}\r
index 22f4875..712f542 100755 (executable)
@@ -1,98 +1,97 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-package mircoders.storage;
-
-
-import java.util.GregorianCalendar;
-
-import mir.entity.Entity;
-import mir.log.LoggerWrapper;
-import mir.misc.StringUtil;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseOther extends Database implements StorageObject{
-  private static DatabaseOther instance;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseOther getInstance() {
-    if (instance == null) {
-      instance = new DatabaseOther();
-    }
-    return instance;
-  }
-
-  private DatabaseOther() {
-    super();
-
-    logger = new LoggerWrapper("Database.OtherMedia");
-
-    hasTimestamp = true;
-    theTable = "other_media";
-    theCoreTable = "media";
-    theEntityClass = mircoders.entity.EntityOther.class;
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("title", true);
-  }
-
-  public void update(Entity theEntity) throws StorageObjectFailure {
-    String date = theEntity.getValue("date");
-    if (date == null) {
-      date = StringUtil.date2webdbDate(new GregorianCalendar());
-      theEntity.setValueForProperty("date", date);
-    }
-
-    super.update(theEntity);
-  }
-
-  public String insert(Entity theEntity) throws StorageObjectFailure {
-    String date = theEntity.getValue("date");
-    if (date == null) {
-      date = StringUtil.date2webdbDate(new GregorianCalendar());
-      theEntity.setValueForProperty("date", date);
-    }
-    return super.insert(theEntity);
-  }
-
-  // initialisierungen aus den statischen Tabellen
-
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+package mircoders.storage;\r
+\r
+\r
+import java.util.GregorianCalendar;\r
+\r
+import mir.entity.Entity;\r
+import mir.log.LoggerWrapper;\r
+import mir.misc.StringUtil;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class DatabaseOther extends Database implements StorageObject{\r
+  private static DatabaseOther instance;\r
+\r
+  // the following *has* to be sychronized cause this static method\r
+  // could get preemted and we could end up with 2 instances of DatabaseFoo..\r
+  // see the "Singletons with needles and thread" article at JavaWorld -mh\r
+  public synchronized static DatabaseOther getInstance() {\r
+    if (instance == null) {\r
+      instance = new DatabaseOther();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseOther() {\r
+    super();\r
+\r
+    logger = new LoggerWrapper("Database.OtherMedia");\r
+\r
+    hasTimestamp = true;\r
+    theTable = "other_media";\r
+    theCoreTable = "media";\r
+    theEntityClass = mircoders.entity.EntityOther.class;\r
+  }\r
+\r
+  public void update(Entity theEntity) throws StorageObjectFailure {\r
+    String date = theEntity.getValue("date");\r
+    if (date == null) {\r
+      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      theEntity.setValueForProperty("date", date);\r
+    }\r
+\r
+    super.update(theEntity);\r
+  }\r
+\r
+  public String insert(Entity theEntity) throws StorageObjectFailure {\r
+    String date = theEntity.getValue("date");\r
+    if (date == null) {\r
+      date = StringUtil.date2webdbDate(new GregorianCalendar());\r
+      theEntity.setValueForProperty("date", date);\r
+    }\r
+    return super.insert(theEntity);\r
+  }\r
+\r
+  // initialisierungen aus den statischen Tabellen\r
+\r
+}\r
index 11914a8..5bdbd08 100755 (executable)
@@ -34,20 +34,20 @@ import mir.log.LoggerWrapper;
 import mir.storage.Database;
 import mir.storage.StorageObject;
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
  *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
  */
 
 public class DatabaseRights extends Database implements StorageObject{
   private static DatabaseRights instance;
 
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
   public synchronized static DatabaseRights getInstance() {
     if (instance == null) {
       instance = new DatabaseRights();
@@ -63,9 +63,4 @@ public class DatabaseRights extends Database implements StorageObject{
     hasTimestamp = false;
     theTable = "rights";
   }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("name", true);
-  }
-
 }
index 2b502cb..95f5df8 100755 (executable)
@@ -1,72 +1,91 @@
-/*
- * Copyright (C) 2001, 2002 The Mir-coders group
- *
- * This file is part of Mir.
- *
- * Mir is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * Mir is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with Mir; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
- *
- * In addition, as a special exception, The Mir-coders gives permission to link
- * the code of this program with  any library licensed under the Apache Software License,
- * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
- * (or with modified versions of the above that use the same license as the above),
- * and distribute linked combinations including the two.  You must obey the
- * GNU General Public License in all respects for all of the code used other than
- * the above mentioned libraries.  If you modify this file, you may extend this
- * exception to your version of the file, but you are not obligated to do so.
- * If you do not wish to do so, delete this exception statement from your version.
- */
-
-package mircoders.storage;
-
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
-import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
-
-/**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
- *
- */
-
-public class DatabaseTopics extends Database implements StorageObject{
-
-  private static DatabaseTopics instance;
-
-  // the following *has* to be sychronized cause this static method
-  // could get preemted and we could end up with 2 instances of DatabaseFoo..
-  // see the "Singletons with needles and thread" article at JavaWorld -mh
-  public synchronized static DatabaseTopics getInstance() {
-    if (instance == null) {
-      instance = new DatabaseTopics();
-    }
-    return instance;
-  }
-
-  private DatabaseTopics() throws StorageObjectFailure {
-    super();
-
-    logger = new LoggerWrapper("Database.Topics");
-
-    hasTimestamp = false;
-    theTable = "topic";
-    theEntityClass = mircoders.entity.EntityTopics.class;
-  }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("title", true);
-  }
-}
+/*\r
+ * Copyright (C) 2001, 2002 The Mir-coders group\r
+ *\r
+ * This file is part of Mir.\r
+ *\r
+ * Mir is free software; you can redistribute it and/or modify\r
+ * it under the terms of the GNU General Public License as published by\r
+ * the Free Software Foundation; either version 2 of the License, or\r
+ * (at your option) any later version.\r
+ *\r
+ * Mir is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU General Public License for more details.\r
+ *\r
+ * You should have received a copy of the GNU General Public License\r
+ * along with Mir; if not, write to the Free Software\r
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA\r
+ *\r
+ * In addition, as a special exception, The Mir-coders gives permission to link\r
+ * the code of this program with  any library licensed under the Apache Software License,\r
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library\r
+ * (or with modified versions of the above that use the same license as the above),\r
+ * and distribute linked combinations including the two.  You must obey the\r
+ * GNU General Public License in all respects for all of the code used other than\r
+ * the above mentioned libraries.  If you modify this file, you may extend this\r
+ * exception to your version of the file, but you are not obligated to do so.\r
+ * If you do not wish to do so, delete this exception statement from your version.\r
+ */\r
+\r
+package mircoders.storage;\r
+\r
+import java.util.HashMap;\r
+import java.util.Iterator;\r
+import java.util.List;\r
+import java.util.Map;\r
+import java.util.Vector;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityBrowser;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
+import mir.storage.StorageObjectFailure;\r
+\r
+/**\r
+ *\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class DatabaseTopics extends Database implements StorageObject{\r
+  private static DatabaseTopics instance;\r
+\r
+  public synchronized static DatabaseTopics getInstance() {\r
+    if (instance == null) {\r
+      instance = new DatabaseTopics();\r
+    }\r
+    return instance;\r
+  }\r
+\r
+  private DatabaseTopics() throws StorageObjectFailure {\r
+    super();\r
+\r
+    logger = new LoggerWrapper("Database.Topics");\r
+\r
+    hasTimestamp = false;\r
+    theTable = "topic";\r
+    theEntityClass = mircoders.entity.EntityTopics.class;\r
+  }\r
+\r
+  public List getPopupData() throws StorageObjectFailure {\r
+    List result = new Vector();\r
+    Iterator i = new EntityBrowser(this, "", "title", 100, -1, 0);\r
+\r
+    while (i.hasNext()) {\r
+      Entity e = (Entity) i.next();\r
+      Map entry = new HashMap();\r
+      entry.put("key", e.getId());\r
+      entry.put("value", e.getValue("title"));\r
+\r
+      result.add(entry);\r
+    }\r
+\r
+    return result;\r
+  }\r
+}\r
index 0e077ed..8c2000f 100755 (executable)
 
 package mircoders.storage;
 
-import mir.entity.Entity;
-import mir.entity.EntityRelation;
-import mir.log.LoggerWrapper;
-import mir.storage.Database;
-import mir.storage.StorageObject;
+import java.util.Iterator;\r
+\r
+import mir.entity.Entity;\r
+import mir.entity.EntityBrowser;\r
+import mir.log.LoggerWrapper;\r
+import mir.storage.Database;\r
+import mir.storage.StorageObject;\r
 import mir.storage.StorageObjectFailure;
 
 public class DatabaseUploadedMedia extends Database implements StorageObject {
   private static DatabaseUploadedMedia  instance;
-  private static EntityRelation         relationMediaType;
 
   public synchronized static DatabaseUploadedMedia getInstance() {
     if (instance == null ) {
@@ -56,7 +57,6 @@ public class DatabaseUploadedMedia extends Database implements StorageObject {
 
     theTable="uploaded_media";
     theCoreTable="media";
-    relationMediaType = new EntityRelation("to_media_type", "id", DatabaseMediaType.getInstance(), EntityRelation.TO_ONE);
     theEntityClass = mircoders.entity.EntityUploadedMedia.class;
   }
 
@@ -68,7 +68,9 @@ public class DatabaseUploadedMedia extends Database implements StorageObject {
   public Entity getMediaType(Entity ent) throws StorageObjectFailure {
     Entity type=null;
     try {
-      type = relationMediaType.getOne(ent);
+      Iterator i = new EntityBrowser(DatabaseMediaType.getInstance(), ent.getValue("to_media_type") + " = id" , "id", 1);
+      if (i.hasNext())
+        type = (Entity) i.next();
     }
     catch (Throwable t) {
       logger.error("DatabaseUploadedMedia :: failed to get media_type: " + t.getMessage());
index 89e1ae6..29dddac 100755 (executable)
@@ -34,12 +34,15 @@ import mir.log.LoggerWrapper;
 import mir.storage.Database;
 import mir.storage.StorageObject;
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
  *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
  */
 
 public class DatabaseUsers extends Database implements StorageObject{
@@ -65,8 +68,4 @@ public class DatabaseUsers extends Database implements StorageObject{
     theTable = "webdb_users";
     theEntityClass = mircoders.entity.EntityUsers.class;
   }
-
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("login", true);
-  }
 }
index a51d5b1..5f2b138 100755 (executable)
@@ -30,7 +30,7 @@
 
 package mircoders.storage;
 
-import java.util.GregorianCalendar;
+import java.util.*;
 
 import mir.entity.Entity;
 import mir.log.LoggerWrapper;
@@ -38,18 +38,20 @@ import mir.misc.StringUtil;
 import mir.storage.Database;
 import mir.storage.StorageObject;
 import mir.storage.StorageObjectFailure;
-import freemarker.template.SimpleList;
 
 /**
- * <b>Diese Klasse implementiert die Datenbankverbindung zur MetaObjekt-Tabelle
- *
  *
+ * <p>Title: </p>
+ * <p>Description: </p>
+ * <p>Copyright: Copyright (c) 2003</p>
+ * <p>Company: </p>
+ * @author not attributable
+ * @version 1.0
  */
 
 public class DatabaseVideo extends Database implements StorageObject{
 
   private static DatabaseVideo instance;
-  private static SimpleList publisherPopupData;
 
   // the following *has* to be sychronized cause this static method
   // could get preemted and we could end up with 2 instances of DatabaseFoo..
@@ -72,10 +74,6 @@ public class DatabaseVideo extends Database implements StorageObject{
     theEntityClass = mircoders.entity.EntityVideo.class;
   }
 
-  public SimpleList getPopupData() throws StorageObjectFailure {
-    return getPopupData("title", true);
-  }
-
   public void update(Entity theEntity) throws StorageObjectFailure {
     String date = theEntity.getValue("date");
     if (date == null) {
diff --git a/source/tool/ConfigTool.java b/source/tool/ConfigTool.java
new file mode 100755 (executable)
index 0000000..c6e1619
--- /dev/null
@@ -0,0 +1,96 @@
+package tool;\r
+\r
+import java.security.MessageDigest;\r
+import java.util.TimeZone;\r
+\r
+import gnu.regexp.RE;\r
+import mir.util.StringRoutines;\r
+\r
+/**\r
+ * <p>Title: </p>\r
+ * <p>Description: </p>\r
+ * <p>Copyright: Copyright (c) 2003</p>\r
+ * <p>Company: </p>\r
+ * @author not attributable\r
+ * @version 1.0\r
+ */\r
+\r
+public class ConfigTool {\r
+  public ConfigTool() {\r
+  }\r
+\r
+  public static void timezone(String aSpecification) {\r
+    try {\r
+      RE specification = new RE(aSpecification);\r
+      String[] timeZoneIds = TimeZone.getAvailableIDs();\r
+\r
+      System.out.println("ID\tOffset\tDST?\tName");\r
+      for (int i=0; i<timeZoneIds.length; i++) {\r
+        if (specification.isMatch(timeZoneIds[i])) {\r
+          TimeZone timeZone = TimeZone.getTimeZone(timeZoneIds[i]);\r
+          long offset = timeZone.getRawOffset()/(1000*60);\r
+          String sign = "";\r
+          if (offset<0) {\r
+            offset=-offset;\r
+            sign = "-";\r
+          }\r
+\r
+          System.out.println(timeZone.getID() + "\t" + sign + offset/60 + ":" + StringRoutines.padStringLeft(Long.toString(offset%60),2,'0')+"\t"+(timeZone.useDaylightTime()?"yes":"no")+"\t"+ timeZone.getDisplayName());\r
+        }\r
+      }\r
+    }\r
+    catch (Throwable t) {\r
+      System.err.println(t.toString());\r
+    }\r
+  }\r
+\r
+  public static void digest(String aDigest, String aData) {\r
+    try {\r
+      MessageDigest messageDigest = MessageDigest.getInstance(aDigest);\r
+\r
+      System.out.println(StringRoutines.convertToHex(messageDigest.digest(aData.getBytes("UTF-8"))));\r
+    }\r
+    catch (Throwable t) {\r
+      System.err.println(t.toString());\r
+    }\r
+  }\r
+\r
+  public static void main(String[] anArguments) {\r
+    String command = "help";\r
+\r
+    if (anArguments.length >= 1) {\r
+      command = anArguments[0];\r
+\r
+      if (command.equals("timezone")) {\r
+        if (anArguments.length<=2) {\r
+          if (anArguments.length==2)\r
+            timezone(anArguments[1]);\r
+          else\r
+            timezone(".*");\r
+        }\r
+\r
+        return;\r
+      }\r
+      else if (command.equals("digest")) {\r
+        if (anArguments.length == 3) {\r
+          digest(anArguments[1], anArguments[2]);\r
+\r
+          return;\r
+        }\r
+      }\r
+    }\r
+\r
+\r
+\r
+    System.out.println("Usage:");\r
+\r
+    System.out.println("  ConfigTool timezone [regexp]");\r
+    System.out.println("");\r
+    System.out.println("      Shows the available timezones");\r
+    System.out.println("");\r
+    System.out.println("  BundleTool digest <digestname> <string>");\r
+    System.out.println("");\r
+    System.out.println("      Calculates the digest of a string.");\r
+    System.out.println("");\r
+  }\r
+}
\ No newline at end of file
diff --git a/templates/admin/EDITFUNCTIONS.template b/templates/admin/EDITFUNCTIONS.template
new file mode 100755 (executable)
index 0000000..d9830b9
--- /dev/null
@@ -0,0 +1,126 @@
+<include "SETTINGS.template">\r
+\r
+<function EditStart(aHiddenFields, aHiddenValues)>\r
+    <form action="${config.actionRoot}" method="post">
+        <assign index="0">\r
+        <list aHiddenFields as i>\r
+          <input type="hidden" name="${i}" value="${utility.encodeHTML(aHiddenValues[index])}">\r
+          <assign index=utility.increment(index)>
+        </list>\r
+      <table border="0">
+</function>
+\r
+<function EditEnd()>\r
+      </table>\r
+    </form>\r
+</function>\r
+\r
+<function EditFieldStart(aLabel, aHint, aLabelClass, aValueClass)>\r
+  <tr>
+    <td align="right" class="${aLabelClass}">
+      <b>${aLabel}:</b>
+      <if aHint>
+        <br>
+        <span class="small">${aHint}</span>      
+      </if>
+    </td>
+    
+    <td class="${aValueClass}">
+</function>\r
+\r
+<function EditFieldEnd()>\r
+    </td>
+  </tr>\r
+</function>  
+
+<function EditSubmitButtonNormal(aLabel, aFieldName)>\r
+  <tr>
+    <td class="${TABLE_FOOT_CLASS}" colspan="2" align="right"> 
+      <input type="submit" name="${aFieldName}" value="${aLabel}">
+    </td>
+  </tr>
+</function>  
+\r
+\r
+<function EditReadonlyTextNormal(label, fieldcontent)>\r
+  <call EditFieldStart(label, "", "table-left", "listrow2")>
+      ${utility.encodeHTML(fieldcontent)}
+  <call EditFieldEnd()>
+</function>
+
+
+<function EditText(label, size, maxlength, fieldname, fieldcontent, aLabelClass, aValueClass)>\r
+  <call EditFieldStart(label, "", aLabelClass, aValueClass)>
+      <input type="text" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
+  <call EditFieldEnd()>
+</function>
+<function EditTextNormal(label, size, maxlength, fieldname, fieldcontent)>\r
+  <call EditText(label, size, maxlength, fieldname, fieldcontent, "table-left", "listrow2")>\r
+</function>
+<function EditTextHighlighted(label, size, maxlength, fieldname, fieldcontent)>\r
+  <call EditText(label, size, maxlength, fieldname, fieldcontent, "table-left-light", "listrow1")>\r
+</function>
+\r
+\r
+<function EditPassword(label, size, maxlength, fieldname, fieldcontent, aLabelClass, aValueClass)>
+  <call EditFieldStart(label, "", aLabelClass, aValueClass)>
+      <input type="password" size="${size}" maxlength="${maxlength}" name="${fieldname}" value="${utility.encodeHTML(fieldcontent)}">
+  <call EditFieldEnd()>
+</function>\r
+\r
+<function EditPasswordNormal(label, size, maxlength, fieldname, fieldcontent)>\r
+  <call EditPassword(label, size, maxlength, fieldname, fieldcontent, "table-left", "listrow2")>\r
+</function>
+<function EditPasswordHighlighted(label, size, maxlength, fieldname, fieldcontent)>\r
+  <call EditPassword(label, size, maxlength, fieldname, fieldcontent, "table-left-light", "listrow1")>\r
+</function>
+\r
+
+<function EditCheckbox(label, fieldname, fieldcontent, aLabelClass, aValueClass)>
+  <call EditFieldStart(label, "", aLabelClass, aValueClass)>
+      <input type="checkbox" name="${fieldname}" value="1"<if fieldcontent=="1"> checked</if>>&nbsp;&nbsp;
+  <call EditFieldEnd()>
+</function> \r
+\r
+<function EditCheckboxNormal(label, fieldname, fieldcontent)>\r
+  <call EditCheckbox(label, fieldname, fieldcontent, "table-left", "listrow2")>\r
+</function>
+<function EditCheckboxHighlighted(label, fieldname, fieldcontent)>\r
+  <call EditCheckbox(label, fieldname, fieldcontent, "table-left-light", "listrow1")>\r
+</function>
+
+
+<function EditTextArea(label, aHint, cols, rows, fieldname, fieldcontent, aLabelClass, aValueClass)>
+  <call EditFieldStart(label, aHint, aLabelClass, aValueClass)>
+      <textarea cols="${cols}" rows="${rows}" name="${fieldname}" wrap="virtual">${utility.encodeHTML(fieldcontent)}</textarea>
+  <call EditFieldEnd()>
+</function>\r
+\r
+<function EditTextAreaNormal(label, aHint, cols, rows, fieldname, fieldcontent)>\r
+  <call EditTextArea(label, aHint, cols, rows, fieldname, fieldcontent, "table-left", "listrow2")>\r
+</function>
+<function EditTextAreaHighlighted(label, size, maxlength, fieldname, fieldcontent)>\r
+  <call EditTextArea(label, aHint, cols, rows, fieldname, fieldcontent, "table-left-light", "listrow1")>\r
+</function>
+\r
+
+\r
+\r
+<function EditPullDown (label, fieldname, entrieslist, keyfield, valuefield, value, langprefix, aLabelClass, aValueClass)>
+  <call EditFieldStart(label, "", aLabelClass, aValueClass)>
+       <select name="${fieldname}">
+         <list entrieslist as a>
+           <option value="${a[keyfield]}" <if (a[keyfield] == value)>selected</if>><if langprefix>${lang(langprefix+a[valuefield])}<else>${a[valuefield]}</if></option>
+         </list>
+       </select>
+  <call EditFieldEnd()>
+</function>   \r
+
+<function EditPullDownNormal(label, fieldname, entrieslist, keyfield, valuefield, value, langprefix)>\r
+  <call EditPullDown(label, fieldname, entrieslist, keyfield, valuefield, value, langprefix, "table-left", "listrow2")>\r
+</function>
+<function EditPullDownHighlighted(label, fieldname, entrieslist, keyfield, valuefield, value, langprefix)>\r
+  <call EditPullDown(label, fieldname, entrieslist, keyfield, valuefield, value, langprefix, "table-left-light", "listrow1")>\r
+</function>
+\r
+
index 4befc08..2b1eeed 100755 (executable)
@@ -1,72 +1,84 @@
-<comment>creates a full table incl. edit/delete entry.id</comment>
-<function ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>
+<include "EDITFUNCTIONS.template">
 
-<table cellspacing="2" border="0">
-  
-  <tr>
-    <list column_head_texts as indexVariable>
-      <td class="${column_head_CSS}">
-        <b>${indexVariable}</b> 
-      </td>
-    </list>
-      <td class="${column_head_CSS}">
-        &nbsp;
-      </td> 
-  </tr>
+<function showAbsoluteLinkButton(anUrl, aLabel)>
+    <span class="link-box-div">
+  <a class="link-box" href="${utility.encodeHTML(anUrl)}">${aLabel}</a>
+    </span>
+</function>
+<function showButton(anUrl, aLabel)>
+  <call showAbsoluteLinkButton(config.actionRoot+"?"+anUrl, aLabel)>
+</function>
 
-  
-<list contentlist as entry>
-  <if grey=="1">
-    <assign grey="0">
-    <tr class="${listrow1CSS}">
-  <else>
-    <assign grey="1"> 
-    <tr class="${listrow2CSS}">
+
+<assign TABLE_HEAD_CLASS          "table-head">
+<assign TABLE_FOOT_CLASS          "table-foot">
+<assign LIST_ROW_CLASS             "listrow1">
+<assign LIST_ROW_CLASS_ALTERNATIVE "listrow2">
+
+<function EntityTable(anEntityList, aDataKeys, aHeaders, aFrom, aTo, aCount, aShowDelete, aShowEdit, aModuleName)>
+  <assign nrColumns="0">
+  <list aHeaders as h>
+    <assign nrColumns=utility.increment(nrColumns)>
+  </list>
+  <if aShowDelete == "1" || aShowEdit == "1" >
+    <assign nrColumns=utility.increment(nrColumns)>
   </if>
+
+  <table cellspacing="2" border="0">
+    <tr>
+      <list aHeaders as i>
+        <td class="${TABLE_HEAD_CLASS}">
+          <b>${i}</b> 
+        </td>
+      </list>
+      <if aShowDelete == "1" || aShowEdit == "1">
+        <td class="${TABLE_HEAD_CLASS}">
+          &nbsp;
+        </td> 
+      </if>
+    </tr>
+    <assign alternative="0">
+    
+    <list anEntityList as entry>
+      <if alternative=="0">
+        <assign alternative="1">
+        <tr class="${LIST_ROW_CLASS}">
+      <else>
+        <assign alternative="0">
+        <tr class="${LIST_ROW_CLASS_ALTERNATIVE}">
+      </if>
+        
+        <list aDataKeys as i>   
+            <td>
+              ${entry[i]}
+            </td>
+        </list>
+        <if aShowDelete == "1" || aShowEdit == "1" >
+          <td>
+            <if aShowDelete>
+            <a class="listcommand" href="${config.actionRoot}?module=${aModuleName}&do=delete&id=${entry.id}">${lang("delete")}</a>
+            </if>
+            <if aShowDelete == "1" && aShowEdit == "1">
+            | 
+            </if>
+            <if aShowEdit == "1">
+              <a class="listcommand" href="${config.actionRoot}?module=${aModuleName}&do=edit&id=${entry.id}">${lang("edit")}</a>
+            </if>
+          </td>
+        </if>
+      </tr>
+    </list>
+    
     
-  <list data_keys as indexVariable>   
-      <td>
-        ${entry[indexVariable]}
+    <tr>    
+      <td colspan="${nrColumns}" class="${TABLE_FOOT_CLASS}">
+        ${aCount} ${lang("records")} / ${lang("show_from_to", aFrom, aTo)}
       </td>
-  </list>
-    <td>
-      <a class="listcommand" href="${config.actionRoot}?module=${module_name}&do=delete&id=${entry.id}">${lang("delete")}</a>
-      | <a class="listcommand" href="${config.actionRoot}?module=${module_name}&do=edit&id=${entry.id}">${lang("edit")}</a>
-    </td>
-  </tr>
-</list>
-  
+    </tr>
   
-  <tr>    
-    <td colspan="${column_nr}" class="table-foot">
-      ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)}
-    </td>
-  </tr>
-
-</table>
+  </table>
 </function>
 
-<comment>creates browse links, only called if necessary</comment>
-<function PrevNextPage(module_name)>
-  <p>
-      <if (data.prev || data.next)>
-        <form method="post" action="${config.actionRoot}">
-          <input type="hidden" name="module" value="${module_name}">
-          <input type="hidden" name="where" value="${data.where}">
-          <if data.prev>
-            <input type="hidden" name="do" value="list">
-            <input type="hidden" name="prevoffset" value="${data.prev}">
-            <input type="submit" name="prev" value="${lang("list.previous")}">
-          </if>
-          <if data.next>
-            <input type="hidden" name="do" value="list">
-            <input type="hidden" name="nextoffset" value="${data.next}">
-            <input type="submit" name="next" value="${lang("list.next")}">
-          </if>
-        </form>
-      </if>
-  </p>
-</function>
 
 <comment>extra navigation</comment>
 <function AddOrBack(module_name, module_jumpback, do_jumpback)>
   </p>
 </function>
 
+<function showAddOrBack(anAllowAdd, anAddModule, aBackModule, aBackMethod, )>
+    <p>
+      <if anAllowAdd == "1">
+        <a class="link-box" href="${config.actionRoot}?module=${anAddModule}&do=add">[+] ${lang("add")}</a> &nbsp;
+      </if>
+      <a class="link-box" href="${config.actionRoot}?module=${aBackModule}&do=${aBackMethod}">[&lt;] ${lang("back")} </a> &nbsp;
+<comment>      <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a></comment>
+  </p>
+</function>
 
-
+<function showBack(aBackUrl)>
+  <p><a class="link-box" href="${config.actionRoot}?${aBackUrl}">[&lt;] ${lang("back")} </a> &nbsp;</p>
+</function>
 
 <function PulldownTableRow (label, fieldname, entrieslist, keyfield, valuefield, value, langprefix)>
   <tr>
 </function>   
 
 
-<comment>4 functions to create Table rows with input-fields</comment>
+
+
+
+
+
+
+
 <function TextInputTableRow (label, size, maxlength, fieldname, fieldcontent)>
   <tr>
     <td align="right" class="table-left">
   </tr>
 </function>
 
+<function ReadonlyTextTableRow (label, fieldcontent)>
+  <tr>
+    <td align="right" class="table-left">
+      <b>${label}:</b>
+    </td>
+    
+    <td class="listrow2">
+      ${utility.encodeHTML(fieldcontent)}
+    </td>
+  </tr>
+</function>
+
 <function PasswordTextInputTableRow (label, size, maxlength, fieldname, fieldcontent)>
   <tr>
     <td align="right" class="table-left">
 </function>
 
 <function CheckboxTableRow (label, fieldname, fieldcontent )>
+  <call EditCheckboxNormal(label, fieldname, fieldcontent)>
+<comment>
   <tr>
     <td align="right" valign="top" class="table-left">
       <b>${label}:</b>
       <input type="checkbox" name="${fieldname}" value="1"<if fieldcontent=="1"> checked</if>>&nbsp;&nbsp;
     </td>
   </tr>
+</comment>  
 </function> 
 
 <function TextAreaTableRow (label, hint, cols, rows, fieldname, fieldcontent )>
                   <option value="title"<if searchfield=="title"> selected</if>>${lang("contentsearch.field.title")}</option>
                   <option value="creator"<if searchfield=="creator"> selected</if>>${lang("contentsearch.field.creator")}</option>
                   <option value="contents"<if searchfield=="content"> selected</if>>${lang("contentsearch.field.contents")}</option>
+                  <option value="creator_main_url"<if searchfield=="creator_main_url"> selected</if>>${lang("contentsearch.field.creator_main_url")}</option>
+                  <option value="creator_email"<if searchfield=="creator_email"> selected</if>>${lang("contentsearch.field.creator_email")}</option>
                 </select>
             </td>
             <td <if layout>class="listrow2"</if>>
index bf21f42..3a0932c 100755 (executable)
@@ -3,14 +3,16 @@
   not used for image-list because imagelist uses other display method
 </comment>
 
+<include "FUNCTIONS.template">
+
 <function MediaSearch (module)>
 
 <form method="post" action="${config.actionRoot}">
 
 <input type="hidden" name="module" value="${module}">
-<input type="hidden" name="do" value="list">
-<input type="hidden" name="articleid" value="${data.articleid}">
-<input type="hidden" name="commentid" value="${data.commentid}">
+<input type="hidden" name="do" value="search">
+<input type="hidden" name="articleid" value="${articleid}">
+<input type="hidden" name="commentid" value="${commentid}">
 
 <table border="0" cellspacing="2" cellpadding="2">
   <tr>
 
   <tr>
     <td class="listrow2">
-      <input type="text" size="20" maxlength="30" name="query_text" value="${data.query_text}">
+      <input type="text" size="20" maxlength="30" name="searchtext" value="${searchtext}">
     </td> 
     <td class="listrow2">
-      <select name="query_field">
-        <option value="title"<if data.query_field=="title"> selected</if>>${lang("media.title")}</option>
-        <option value="creator"<if data.query_field=="creator"> selected</if>>${lang("media.creator")}</option>
-        <option value="place"<if data.query_field=="place"> selected</if>>${lang("media.location")}</option>
+      <select name="searchfield">
+        <option value="title"<if searchfield=="title"> selected</if>>${lang("media.title")}</option>
+        <option value="creator"<if searchfield=="creator"> selected</if>>${lang("media.creator")}</option>
+        <option value="place"<if searchfield=="place"> selected</if>>${lang("media.location")}</option>
       </select>
     </td>
     
     <td class="listrow2">
-      <select name="query_is_published">
+      <select name="searchispublished">
         <option value="">${lang("dontcare")}</option>
-        <option value="0" <if data.query_is_published=="0"> selected</if>>${lang("no")}</option>
-        <option value="1" <if data.query_is_published=="1"> selected</if>>${lang("yes")}</option>
+        <option value="0" <if searchispublished=="0"> selected</if>>${lang("no")}</option>
+        <option value="1" <if searchispublished=="1"> selected</if>>${lang("yes")}</option>
       </select>
     </td>
     
     <td class="listrow2">
-    <select name="query_media_folder">
-    <list extra.mediafolderPopupData as m>
-    <option value="${m.key}" <if m.key == data.query_media_folder>selected</if>>${m.value}</option>
-    </list>
+    <select name="searchmediafolder">
+      <option value="">-</option>
+      <list mediafolders as m>
+        <option value="${m.id}" <if m.id == searchmediafolder>selected</if>>${m.name}</option>
+      </list>
     </select>
     </td>
     
 
 <function MediaList (module)>
 
-<table>
-
-  <tr class="darkgrey" >
-    <td class="table-head">
-  <b>${lang("media.icon")}</b></td>
-  <td class="table-head">
-  <b>${lang("media.title")}</b></td>
-    <td class="table-head">
-  <b>${lang("media.format")}</b></td>
-    <td class="table-head">
-  <b>${lang("media.size")}</b></td>
-    <td class="table-head">
-  <b>${lang("media.mediafolder")}</b></td>
-    <td class="table-head">
-  <b>${lang("media.creator")}</b></td>
-    <td class="table-head">
-  &nbsp;</td>
+  <call showAddOrBack("1", module, "Admin", "start")>
+    <if medialist>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
 
-  </tr>
-    <if data.contentlist>
-    <list data.contentlist as entry>
-    <tr <if grey=="1"><assign grey="0">class="listrow1"<else>class="listrow2"<assign grey="1"> </if>>
-    <td>
-          <a href="${config.actionRoot}?module=${module}&do=getMedia&id=${entry.id}">
-        <img src="${config.docRoot}/img/${entry.big_icon}" border=0></a>
-    </td>
-      <td>
-      ${entry.title}&nbsp;
-          <if entry.description><br>${entry.description}</if>
-    </td>
-      <td>
-      ${entry.media_descr}&nbsp;
-    </td>
-      <td>
-      ${entry.human_readable_size}&nbsp;
-    </td>
-      <td>
-      ${data.mediafolderHashdata[entry.to_media_folder]["name"]}&nbsp;
-    </td>
-      <td>
-      ${entry.creator}&nbsp;
-    </td>
-      <td>&nbsp;
-      <if data.articleid>
-        <a href="${config.actionRoot}?module=Content&do=attach&mid=${entry.id}&articleid=${data.articleid}">${lang("attach")}</a>
+      <table>
+      
+        <tr class="darkgrey" >
+          <td class="table-head">
+        <b>${lang("media.icon")}</b></td>
+        <td class="table-head">
+        <b>${lang("media.title")}</b></td>
+          <td class="table-head">
+        <b>${lang("media.format")}</b></td>
+          <td class="table-head">
+        <b>${lang("media.size")}</b></td>
+          <td class="table-head">
+        <b>${lang("media.mediafolder")}</b></td>
+          <td class="table-head">
+        <b>${lang("media.creator")}</b></td>
+          <td class="table-head">
+        &nbsp;</td>
+      
+        </tr>
+          <assign grey="0">
+          <list medialist as entry>
+          <tr <if grey=="1"><assign grey="0">class="listrow1"<else>class="listrow2"<assign grey="1"> </if>>
+          <td>
+              <a href="${config.actionRoot}?module=${module}&do=getMedia&id=${entry.id}">
+      <if module=="Images">
+              <img src="${config.actionRoot}?module=${module}&do=getIcon&id=${entry.id}" border=0></a>        
       <else>
-        <if data.commentid>
-          <a href="${config.actionRoot}?module=Comment&do=attach&mid=${entry.id}&commentid=${data.commentid}">${lang("attach")}</a>
-        <else>
-          <a href="${config.actionRoot}?module=${module}&do=delete&id=${entry.id}&query_text=${utility.encodeHTML(data.query_text_encoded)}&query_field=${utility.encodeHTML(data.query_field)}&query_is_published=${data.query_is_published}&query_media_folder=${data.query_media_folder}&offset=${data.offset}">${lang("delete")}</a>
-          | <a href="${config.actionRoot}?module=${module}&do=edit&id=${entry.id}">${lang("edit")}</a>
-        </if>
+              <img src="${config.docRoot}/img/${entry.big_icon}" border=0></a>
       </if>
-    </td>
-    </tr>
-  </list>
-  <tr>
-    <td colspan="7" class="table-foot">
-      ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)}
-    </td>
-  </tr>
-
-  <tr>
-    <td>
-      <if data.prev>
-        <a href="${config.actionRoot}?module=${module}&do=list&query_text=${data.query_text_encoded}&query_field=${data.query_field}&query_is_published=${data.query_is_published}&query_media_folder=${data.query_media_folder}&offset=${data.prev}&prev=zur&uuml;ck&articleid=${data.articleid}&commentid=${data.commentid}">${lang("list.previous")}</a>&nbsp;
-      </if>
-      <if data.next>
-        <a href="${config.actionRoot}?module=${module}&do=list&query_text=${data.query_text_encoded}&query_field=${data.query_field}&query_is_published=${data.query_is_published}&query_media_folder=${data.query_media_folder}&offset=${data.next}&next=weiter&articleid=${data.articleid}&commentid=${data.commentid}">${lang("list.next")}</a>
-      </if>
-    </td>
-  </tr>
-
-<else>
-  <tr><td align="center" class="box" colspan="7">${lang("no_matches_found")}</td></tr>
-</if>
-</table>
+          </td>
+            <td>
+            ${entry.title}&nbsp;
+                <if entry.description><br>${entry.description}</if>
+          </td>
+            <td>
+            ${entry.media_descr}&nbsp;
+          </td>
+            <td>
+            ${entry.human_readable_size}&nbsp;
+          </td>
+            <td>
+             <if entry.mediafolder>
+                ${entry.mediafolder.name}
+             </if>&nbsp;
+          </td>
+            <td>
+            ${entry.creator}&nbsp;
+          </td>
+            <td>&nbsp;
+            <if articleid>
+              <a href="${config.actionRoot}?module=Content&do=attach&mid=${entry.id}&articleid=${articleid}">${lang("attach")}</a>
+            <else>
+              <if commentid>
+                <a href="${config.actionRoot}?module=Comment&do=attach&mid=${entry.id}&commentid=${commentid}">${lang("attach")}</a>
+              <else>
+                <a href="${config.actionRoot}?module=${module}&do=delete&id=${entry.id}&okurl=${utility.encodeURI(thisurl)}&cancelurl=${utility.encodeURI(thisurl)}">${lang("delete")}</a>
+                | 
+                <a href="${config.actionRoot}?module=${module}&do=edit&id=${entry.id}">${lang("edit")}</a>
+              </if>
+            </if>
+          </td>
+          </tr>
+        </list>
+        <tr>
+          <td colspan="7" class="table-foot">
+            ${count} ${lang("records")} / ${lang("show_from_to", from, to)}
+          </td>
+        </tr>
+      </table>
+      
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "start")>
+  
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
+    </if>
 
 </function>
diff --git a/templates/admin/LISTFUNCTIONS.template b/templates/admin/LISTFUNCTIONS.template
new file mode 100755 (executable)
index 0000000..256e652
--- /dev/null
@@ -0,0 +1,66 @@
+<include "SETTINGS.template">\r
+<function ListStart()>\r
+  <table cellspacing="2" border="0">
+  <assign alt="0">
+</function>
+\r
+<function ListHead(aHeaders)>\r
+  <assign TABLE_NR_COLUMNS="1">
+  <list aHeaders as h>
+    <assign TABLE_NR_COLUMNS=utility.increment(TABLE_NR_COLUMNS)>
+  </list>
+\r
+  <tr class="${TABLE_HEAD_CLASS}">
+    <list aHeaders as i>
+      <td class="${TABLE_HEAD_CLASS}">
+        <b>${i}</b> 
+      </td>
+    </list>
+      <td class="${TABLE_HEAD_CLASS}">
+        &nbsp;
+      </td> 
+  </tr>
+</function>
+\r
+<function ListFoot(aNrRecords, aFrom, aTo)>\r
+  <tr>    
+    <td colspan="${TABLE_NR_COLUMNS}" class="table-foot">
+      ${aNrRecords} ${lang("records")} / ${lang("show_from_to", aFrom, aTo)}
+    </td>
+  </tr>
+</function>
+\r
+<function ListEnd()>\r
+</table>\r
+</function>\r
+
+<function ListEntry(aFields, aLinkPrefix, aLinks, aLinkTitles)>\r
+    <if alt=="1">
+      <assign alt="0">
+      <tr class="${LIST_ROW_CLASS_ALTERNATIVE}">
+    <else>
+      <assign alt="1"> 
+      <tr class="${LIST_ROW_CLASS}">
+    </if>
+      
+    <list aFields as i>   
+      <td>
+        ${i}
+      </td>
+    </list>
+      <td>\r
+        <assign index="0">\r
+        <assign first="1">\r
+        <list aLinks as i>\r
+          <if first=="1">\r
+            <assign first="0">\r
+          <else>  \r
+            |\r
+          </if>\r
+          <a class="listcommand" href="${config.actionRoot}?${utility.encodeHTML(aLinkPrefix)}${utility.encodeHTML(i)}">${aLinkTitles[index]}</a>        \r
+          <assign index=utility.increment(index)>
+        </list>\r
+      </td>
+    </tr>
+</function>\r
+\r
diff --git a/templates/admin/SETTINGS.template b/templates/admin/SETTINGS.template
new file mode 100755 (executable)
index 0000000..ccbdc43
--- /dev/null
@@ -0,0 +1,4 @@
+<assign TABLE_HEAD_CLASS          "table-head">
+<assign TABLE_FOOT_CLASS          "table-foot">
+<assign LIST_ROW_CLASS             "listrow1">
+<assign LIST_ROW_CLASS_ALTERNATIVE "listrow2">
diff --git a/templates/admin/abuse.filter.template b/templates/admin/abuse.filter.template
new file mode 100755 (executable)
index 0000000..0fc20dc
--- /dev/null
@@ -0,0 +1,46 @@
+<html>
+<head>
+  <title>${lang("abuse.filter.htmltitle")}</title>
+  <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css"
+</head>
+
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+<include "FUNCTIONS.template">
+<include "EDITFUNCTIONS.template">
+
+<include "head.template">
+
+<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+  <if errormessage>
+     <p class="text-alert"> ${lang("abuse.filtererror."+errormessage)}
+     </p>
+  </if>
+
+
+  <call EditStart( 
+        ["module", "id", "do"], 
+        ["Abuse", id, "updatefilter"])>
+
+        <call EditPullDownNormal(lang("abuse.filter.type"), "type", filtertypes, "identifier", "resource", type, "abuse.filtertype.")>\r
+        <call EditTextNormal (lang("abuse.filter.expression"), 40, 255, "expression", expression)>
+        <call EditPullDownNormal(lang("abuse.filter.articleaction"), "articleaction", articleactions, "identifier", "resource", articleaction, "content.operation.")>\r
+        <call EditPullDownNormal(lang("abuse.filter.commentaction"), "commentaction", commentactions, "identifier", "resource", commentaction, "comment.operation.")>\r
+        <call EditTextAreaNormal (lang("abuse.filter.comments"), "", 40, 3, "comments", comments)>
+        
+        <tr>
+          <td class="table-foot" colspan="2" align="right"> 
+          <if id>
+            <input type="submit" name="save" value="${lang("save")}">
+          <else>
+            <input type="submit" name="save" value="${lang("insert")}">
+          </if> 
+          </td>
+        </tr>
+        
+  <call EditEnd()>
+  <p><a class="link-box" href="${config.actionRoot}?module=Abuse&do=showfilters">[&lt;] ${lang("back")} </a> &nbsp;</p>
+    <include "foot.template">
+  </body>
+</html>
index 1c02048..9ec9763 100755 (executable)
@@ -1,75 +1,74 @@
-<function showFilterEntry(aType, anExpression, anId)>
-      <form method="post" action="${config.actionRoot}">
-        <input type="hidden" name="module" value="Abuse">
-        <input type="hidden" name="do" value="editfilter">
-        <if anId>
-          <input type="hidden" name="id" value="${anId}">
-        </if>
-        <if grey=="1"><assign grey="0"><tr class="listrow1"><else><tr class="listrow2"><assign grey="1"> </if>
-          <td>
-            <select name="type">
-              <list filtertypes as t>
-                <option value="${t.id}" <if t.id==aType>selected</if>>${lang("abuse.filtertype."+t.resource)}</option>
-              </list>
-            </select>
-          </td>
-          <td><input type="text" name="expression" size="30" value="${utility.encodeHTML(anExpression)}"></td>
-          <if anId>
-            <td>
-              <input type="submit" name="save" value="${lang("save")}">
-            </td>
-            <td>
-                <a class="listcommand" href="${config.actionRoot}?module=Abuse&do=deletefilter&id=${anId}">[${lang("delete")}]</a>
-                &nbsp;
-            </td>
-          <else>
-            <td>
-              <input class="majorbutton" type="submit" name="save" value="${lang("add")}">
-            </td>
-          </if>
-        </tr>
-      </form>
-</function>
-
-
 <html>
 <head>
-  <title>${config["Mir.Name"]} | ${lang("userlist.htmltitle")}</title>
+  <title>${config["Mir.Name"]} | ${lang("abuse.filters.htmltitle")}</title>
   <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
 </head>
-
 <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+<include "LISTFUNCTIONS.template">
+<include "FUNCTIONS.template">
 <include "head.template">
-<p>
-  <a class="link-box" href="${config.actionRoot}?module=Abuse">[ &lt; ] ${lang("back")}</a>&nbsp;&nbsp;
-  <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
-  <br><br>
-</p>
-<table border="0" cellpadding="2" cellspacing="1">
-  <tr>
-    <td class="table-head"><b>${lang("abuse.filter.type")}</b></td>
-    <td class="table-head"><b>${lang("abuse.filter.expression")}</b></td>
-    <td class="table-head"><b>&nbsp;</b></td>
-    <td class="table-head"><b>&nbsp;</b></td>
-  </tr>
 
-  <assign grey="0">      
-  <list filters as i>
-    <call showFilterEntry(i.type, i.expression, i.id)>
-  </list>
+    <p>
+      <a class="link-box" href="${config.actionRoot}?module=Abuse">[ &lt; ] ${lang("back")}</a>&nbsp;&nbsp;
+      <a class="link-box" href="${config.actionRoot}?module=Abuse&do=add">[+] ${lang("add")}</a> &nbsp;
+      <if config["Abuse.DisallowIPLogging"]!="1">
+        <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
+      </if>
+      <br><br>
+    </p>
+    <call ListStart()>\r
+    <call ListHead([
+          lang("abuse.filter.type"), 
+          lang("abuse.filter.expression"),
+          lang("abuse.filter.articleaction"),
+          lang("abuse.filter.commentaction"),
+          lang("abuse.filter.comments"),
+          lang("abuse.filter.lasthit"), 
+           ])>
+    <list filters as f>    
+    <if f.lastHit>\r
+        <call ListEntry([
+          lang("abuse.filtertype."+f.type),
+          utility.encodeHTML(f.expression),
+          lang("content.operation."+f.articleAction),
+          lang("comment.operation."+f.commentAction),
+          f.comments,                                                   
+          f.lastHit.format(config["Mir.DefaultDateTimeFormat"], config["Mir.DefaultTimezone"])
+          ], 
+          "module=Abuse&id="+f.id, 
+          ["&do=edit", "&do=delete"], 
+          [lang("edit"), lang("delete")])
+        >
+    <else>
+        <call ListEntry([
+          lang("abuse.filtertype."+f.type),
+          utility.encodeHTML(f.expression),
+          lang("content.operation."+f.articleAction),
+          lang("comment.operation."+f.commentAction),
+          f.comments,
+          "-"
+          ], 
+          "module=Abuse&id="+f.id, 
+          ["&do=edit", "&do=delete"], 
+          [lang("edit"), lang("delete")])
+        >
+    </if>
+    </list>\r
+    <call ListEnd()>\r
+    
+    <p>
+      <a class="link-box" href="${config.actionRoot}?module=Abuse">[ &lt; ] ${lang("back")}</a>&nbsp;&nbsp;
+      <a class="link-box" href="${config.actionRoot}?module=Abuse&do=add">[+] ${lang("add")}</a> &nbsp;
+      <if config["Abuse.DisallowIPLogging"]!="1">
+        <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
+      </if>
+      <br><br>
+    </p>
 
-  <call showFilterEntry("", "", "")>
-  </table>
-
-  
-<p>
-  <a class="link-box" href="${config.actionRoot}?module=Abuse">[ &lt; ] ${lang("back")}</a>&nbsp;&nbsp;
-  <a class="link-box" href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a>
-</p>
-    <include "foot.template">
-  </body>
+  <include "foot.template">
+</body>
 </html>
 
 
+
+
index b6b201c..73882a5 100755 (executable)
@@ -23,7 +23,7 @@
       <assign grey="0">      
       <list log as l>
         <if grey=="1"><assign grey="0"><tr class="listrow1"><else><tr class="listrow2"><assign grey="1"> </if>
-          <td>${l.timestamp["yyyy-MM-dd  HH:mm"]}</td>
+          <td>${l.timestamp.format(config["Mir.DefaultDateTimeFormat"])}</td>
           <td>${l.ip}</td>
           <td>
             <if l.type=="content">
index 05cd275..53e27cd 100755 (executable)
     
     <tr class="x-small"><td colspan="2">&nbsp;</td></tr>
 
-    <call CheckboxTableRow (lang("abuse.logpostings"), "logenabled", logenabled)>
-    <call TextInputTableRow (lang("abuse.logsize"), 10, 10, "logsize", logsize)>
+    <if config["Abuse.DisallowIPLogging"]!="1">
+      <call CheckboxTableRow (lang("abuse.logpostings"), "logenabled", logenabled)>
+      <call TextInputTableRow (lang("abuse.logsize"), 10, 10, "logsize", logsize)>
+    </if>
     
     <tr class="x-small"><td colspan="2">&nbsp;</td></tr>    
     
@@ -55,7 +57,9 @@
 <td valign="top">
 
 <p class="box">
-  &gt; <a href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a><br>
+  <if config["Abuse.DisallowIPLogging"]!="1">
+    &gt; <a href="${config.actionRoot}?module=Abuse&do=showlog">${lang("abuse.showlog")}</a><br>
+  </if>  
   &gt; <a href="${config.actionRoot}?module=Abuse&do=showfilters">${lang("abuse.showfilters")}</a>
 </p>
 
index 5d7c98f..2a21ed1 100755 (executable)
@@ -4,46 +4,36 @@
     <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
 <head>
 <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-<include "FUNCTIONS.template">  
-<include "head.template">
-<form action="${config.actionRoot}" method="post">
-
-  <input type="hidden" name="module" value="ArticleType">
-  <input type="hidden" name="id" value="${data.id}">
-  <if data.new>
-    <input type="hidden" name="do" value="insert">
-  <else>
-    <input type="hidden" name="do" value="update">
-  </if>
-    
-  <table border="0">
-    <tr>
-      <td align="right" class="table-left">
-        <B>${lang("articletype.id")}: </B>
-      </td>
-      <td class="listrow2">
-        ${data.id}
-      </td>
-    </tr>
-
-    <call TextInputTableRow (lang("articletype.name"), 40, 255, "name", data.name)>
-
-
-    <tr>
-      <td colspan="2" align="right" class="table-foot">
-        <if data.new>
-          <input type="submit" name="save" value="${lang("insert")}">
+    <include "FUNCTIONS.template">
+    <include "head.template">
+  
+      <if new=="1">
+        <assign method="insert">
+      <else>
+        <assign method="update">
+      </if>
+      
+      <call EditStart(
+         ["module", "id", "do"],
+         [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("articletype.id"), entity.id)>
+        <call EditTextNormal(lang("articletype.name"), 40, 255, "name", entity.name)>
+      
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
         <else>
-          <input type="submit" name="save" value="${lang("save")}">
+          <call EditSubmitButtonNormal(lang("save"), "save")>
         </if> 
-      </td>
-    </tr>
-  </table>
-
-</form>
 
-<p><a class="link-box" href="${config.actionRoot}?module=ArticleType&do=list">[&lt;] ${lang("back")} </a> &nbsp;</p>
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
+      <else>
+        <call showBack("module="+module+"&amp;do=list")>
+      </if>
 
-<include "foot.template">
+    <include "foot.template">
 </body>
 </html>
index 937896c..4361cfa 100755 (executable)
@@ -7,26 +7,14 @@
     
     <include "FUNCTIONS.template">
     <include "head.template">
+    
+    <call showAddOrBack("1", module, "Admin", "superusermenu")>
 
-    <assign contentlist = data.contentlist>
-    <assign column_nr = 3>
-    <assign data_keys = ["id","name"]>
-    <assign column_head_texts = [lang("articletype.id"), lang("articletype.name")]>
-    <assign column_head_CSS = "table_head">
-    <assign listrow1CSS = "listrow1">
-    <assign listrow2CSS = "listrow2">
-    <assign footer_css = "table_foot">
-    <assign module_name = "ArticleType">
-    <assign module_jumpback = "Admin">
-    <assign do_jumpback = "superusermenu">
-  
-    <include "templates/admin/head.template">
-  
-    <call AddOrBack(module_name, module_jumpback, do_jumpback)>
-
-    <if data.contentlist>
-      <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>
-      <call AddOrBack(module_name, module_jumpback, do_jumpback)>
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, ["id","name"], [lang("articletype.id"), lang("articletype.name")], from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "superusermenu")>
     <else>
       <P align="center">${lang("no_matches_found")}</p>
     </if>
index 17fb604..aab208a 100755 (executable)
-<html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("audio.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
-<SCRIPT LANGUAGE="JavaScript">
-function openWin(url) {
-   window.open(url,"vc","scrollbars=0,height=${data.img_height},width=${data.img_width}");
-}
-</SCRIPT>
+<if new!="1">
+  </SCRIPT>
 
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "FUNCTIONS.template">
-<include "head.template">
-
-<if data.new>
-<form action="${config.actionRoot}?module=Audio&do=add" method="post">
-  <if data.articleid>
-    <input type="hidden" name="articleid" value="${data.articleid}">
-  </if>
-  <if data.commentid>
-    <input type="hidden" name="commentid" value="${data.commentid}">
-  </if>
-  <table border="0">
-    <tr>
-      <td align="right" class="table-left">
-        <b>${lang("media.nr_of_media")} :</b><br>
-      </td>
-      <td class="listrow2">
-        <input type="text" size="3" name="medianum" value="${medianum}">&nbsp;&nbsp;<input type="submit" value="${lang("media.nr_of_media.submit")}">
-      </td>
-    </tr>
-  </table>
-</form>
+  <tr>
+    <td align="right" valign="top">
+      <a href="${config.actionRoot}?module=${module}&do=getMedia&id=${uploadedmedia.id}">
+      <img src="/img/${uploadedmedia.big_icon}" border=0></a>&nbsp;&nbsp;
+    </td>
+    <td valign="bottom" class="small">
+      ${lang("media.created")}: ${uploadedmedia.webdb_create}
+      <if uploadedmedia.webdb_lastchange>/ ${lang("media.changed")} ${uploadedmedia.webdb_lastchange}</if><br>
+      <if uploadedmedia.is_published=="1">${lang("media.published")}: ${uploadedmedia.publish_date} / ${uploadedmedia.publish_server}${uploadedmedia.publish_path}<br></if>
+      ${lang("media.format")}: ${uploadedmedia.mimetype} / ${uploadedmedia.media_descr}<br>
+      ${lang("media.size")}: ${uploadedmedia.human_readable_size}<br>
+      ${lang("media.rights")}: <b>${uploadedmedia.rightsHashdata[to_rights]["name"]}</b><br>
+    </td>
+  </tr>
 </if>
 
-
-    <form enctype="multipart/form-data" method="post" action="${config.actionRoot}?module=Audio&do=<if data.new>insert<else>update</if>&id=${data.id}">
-      <if data.articleid>
-        <input type="hidden" name="articleid" value="${data.articleid}">
-      </if>
-      <if data.commentid>
-        <input type="hidden" name="commentid" value="${data.commentid}">
-      </if>
-      <input type="hidden" name="where" value="${data.where}">
-      <input type="hidden" name="offset" value="${data.offset}">
-      <input type="hidden" name="order" value="${data.order}">
-      <input type="hidden" name="id" value="${data.id}">
-    
-      <table border="0">
-    
-        <if !data.new>
-        <tr>
-          <td align="right" valign="top">
-            <a href="${config.actionRoot}?module=Audio&do=getMedia&id=${data.id}">
-            <img src="${config.docRoot}/img/${data.big_icon}" border=0></a>&nbsp;&nbsp;
-          </td>
-          <td valign="bottom" class="small">
-            ${lang("media.created")}: ${data.webdb_create}
-            <if data.webdb_lastchange>/ ${lang("media.changed")} ${data.webdb_lastchange}</if><br>
-            <if data.is_published=="1">${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}<br></if>
-            ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}<br>
-            ${lang("media.size")}: ${data.human_readable_size}<br>
-            ${lang("media.rights")}: <b>${data.rightsHashdata[to_rights]["name"]}</b><br>
-          </td>
-          </tr>
-        </if>
-      
-        <tr>
-          <td align="right" class="table-left">
-            <b>${lang("media.mediafolder")}:</b>
-          </td>
-          <td class="listrow2">
-            <select name="to_media_folder">
-            <list extra.mediafolderPopupData as m>
-              <option value="${m.key}" <if m.key == data.to_media_folder>selected</if>>${m.value}</option>
-            </list>
-              </select>
-          </td>
-        </tr>
+<tr>
+  <td align="right" class="table-left">
+    <B>${lang("media.mediafolder")}:</B>
+  </td>
+  <td class="listrow2">
+    <select name="to_media_folder">
+    <list mediafolders as m>
+      <option value="${m.id}" <if m.id == uploadedmedia.to_media_folder>selected</if>>${m.name}</option>
+    </list>
+      </select>
+  </td>
+</tr>
         
-          <if !data.new>
-            <call TextInputTableRow (lang("media.title"), 40, 80, "title", data.title)>
-          </if>
-          <call TextInputTableRow (lang("media.date"), 8, 8, "date", data.date)>
-          <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-          <call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", data.description)>
-          <call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", data.comment)>
-          <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
-        
-          <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-        
-        
-          <if data.new>
-            <tr>
-              <td align="right" class="table-left">
-                ${lang("media.is_published")} : 
-              </td>
-              <td class="listrow2" style='border: 1px solid #FF0000;'>
-                <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>> 
-              </td>
-            </tr>
-            <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-          
-            <list data.mediafields as m>
-              <tr>
-                <td align="right" class="table-left">
-                  <B>${lang("media.title")}:<B>
-                 </td>
-                <td class="listrow2">
-                  <input type="text" name="media_title${m}" size="40" maxlength="80" value="">
-                </td>
-              </tr>
-              <tr>
-                <td align="right">
-                  &nbsp;
-                </td>
-                <td class="listrow2">
-                  <input type="file" name="media${m}"><br>
-                </td>
-              </tr>
-            </list>
-          </if>
+<if new!="1">
+  <call TextInputTableRow (lang("media.title"), 40, 80, "title", uploadedmedia.title)>
+</if>
+<call TextInputTableRow (lang("media.creator"), 40, 80, "creator", uploadedmedia.creator)>
+<call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", uploadedmedia.description)>
+<call TextInputTableRow (lang("media.source"), 40, 80, "source", uploadedmedia.source)>
+<call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", uploadedmedia.comment)>
       
-          <td colspan="2" align="right" class="table-foot">
-            <if data.new>
-              <input type="submit" name="save" value="${lang("insert")}">
-            <else>
-              ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>
-              &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
-            </if> 
-          </td>
-      </table>
-    </form>
-  
-    <p><a class="link-box" href="${config.actionRoot}?module=Audio&do=list">[&lt;] ${lang("list")} </a> &nbsp;</p>
-  
-    <include "foot.template">
-  </body>
-</html>
index 3ec1243..e84c0a8 100755 (executable)
@@ -1,52 +1,42 @@
 <html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("breaking.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
+  <head>
+    <title>${config["Mir.Name"]} | ${lang("breaking.htmltitle")}</title>
+    <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+  <head>
 
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "head.template">
-<include "FUNCTIONS.template">
-
-
-<form action="${config.actionRoot}" method="post">
-  <input type="hidden" name="module" value="Breaking">
-  <input type="hidden" name="id" value="${data.id}">
-  <if data.new><input type="hidden" name="do" value="insert">
-  <else><input type="hidden" name="do" value="update"></if>
-<table border="0">
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+    <include "FUNCTIONS.template">
+    <include "head.template">
   
-  <tr>
-    <td align="right" class="table-left">
-   <B>${lang("breaking.date")}:</B>
-  </td>
-    <td class="listrow2">
-      ${data.webdb_create_formatted}
-    </td>
-  </tr>
+      <if new=="1">
+        <assign method="insert">
+      <else>
+        <assign method="update">
+      </if>
+      
+      <call EditStart(["module", "id", "do"], [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("breaking.id"), entity.id)>
+        
+        <if new!="">
+          <call EditReadonlyTextNormal(lang("breaking.date"), entity.creationdate.format(config["Mir.DefaultDateTimeFormat"]))>
+        </if>
+        <call EditTextAreaNormal(lang("breaking.text"), lang("breaking.textinfo"), "50", "5", "text", entity.text)>\r
+      
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
+        <else>
+          <call EditSubmitButtonNormal(lang("save"), "save")>
+        </if> 
 
-  
-  
-  <tr>
-    <td align="right" class="table-left">
-  <B>${lang("breaking.text")}:</B><br> ${lang("breaking.textinfo")}</td>
-    <td class="listrow2">
-   <textarea cols="50" rows="5" name="text" wrap=virtual>${data.text}</textarea>
-    </td>
-  </tr>
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
+      <else>
+        <call showBack("module="+module+"&amp;do=list")>
+      </if>
 
-  <tr>
-    <td colspan="2" align="right" class="table-foot">
-    <if data.new>
-      <input type="submit" name="save" value="${lang("insert")}">
-    <else>
-      <input type="submit" name="save" value="${lang("save")}">
-    </if> 
-    </td>
-</table>
-</form>
-<p><a class="link-box" href="${config.actionRoot}?module=Breaking&do=list">[&lt;] ${lang("back")}</a></p>
-<include "foot.template">
-</body>
+    <include "foot.template">
+  </body>
 </html>
index 9b2cef8..7fe2f46 100755 (executable)
@@ -1,50 +1,26 @@
 <html>
-<head>
-  <title>${config["Mir.Name"]} | ${lang("breakinglist.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-</head>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+  <head>
+    <title>${config["Mir.Name"]} | ${lang("breakinglist.htmltitle")}</title>
+    <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+  </head>
 
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
     <include "FUNCTIONS.template">
-  
     <include "head.template">
-
-    <comment>configure this template here</comment>
-    <assign contentlist =
-     data.contentlist>
-    <assign column_nr = 3>
-    <assign column_head_texts = [lang("breaking.date"), lang("breaking.text")]>
-    <assign data_keys = ["webdb_create_formatted", "text",]>
-    <assign column_head_CSS = "table_head">
-    <assign listrow1CSS = "listrow1">
-    <assign listrow2CSS = "listrow2">
-    <assign footer_css = "table_foot">
-    <assign module_name = "Breaking">
-    <assign module_jumpback = "Admin">
-    <assign do_jumpback = "">
-
-    <if data.contentlist>
-  
-  <p>
-      <a class="link-box" href="${config.actionRoot}?module=Breaking&do=add">[+] ${lang("add")}</a> &nbsp;
-      <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a>
-  </p>
     
-    <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>   
-    <call PrevNextPage(module_name)>    
-   <else>
-    <P align="center" class="box">${lang("no_matches_found")}</p>
+    <call showAddOrBack("1", module, "Admin", "start")>
+
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, ["webdb_create_formatted", "text"], [lang("breaking.date"), lang("breaking.text")], from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "start")>
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
     </if>
-    
-   <p>
-      <a class="link-box" href="${config.actionRoot}?module=Breaking&do=add">[+] ${lang("add")}</a> &nbsp;
-      <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a>
-  </p>
-
 
     <include "foot.template">
-</body>
+  </body>
 </html>
 
 
index 9d2b339..deb5feb 100755 (executable)
         <input type="hidden" name="do" value="update">
       </if>
     
-      <table border="0">    
+<table width="100%" cellspacing="0" cellpadding="5">
+  <tr>
+    <td align="left" valign="top">
+      <if new=="0">
+        <if comment.to_content>
+          <call showButton(
+            "module=Content&do=edit&id="+comment.to_content.id+"&returnurl="+utility.encodeURI(thisurl),
+            lang("comment.article"))>
+          <call showButton(
+            "module=Comment&do=articlecomments&articleid="+comment.to_content.id+"&returnurl="+utility.encodeURI(thisurl),
+            lang("comment.allcomments"))>
+          <call showAbsoluteLinkButton(
+            comment.publicurl,
+            lang("preview"))>
+        </if>
+
+        <list comment.operations as op>
+          <call showButton(
+            "module=Localizer&do=commentoperation&operation="+op+"&id="+comment.id+"&returnurl="+utility.encodeURI(thisurl), 
+            lang("comment.operation."+op))>
+        </list>
+      </if>
+      
+    </td>
+    <td align="right" valign="top">
+      ${lang("comment.published")} <input type="checkbox" name="is_published" value="1" <if comment.is_published=="1"> checked</if>>
+      <if new=="1">
+        <input type="submit" name="save" value="${lang("insert")}">
+      <else>
+        <input type="submit" name="save" value="${lang("save")}">
+      </if> 
+    </td>
+  </tr>
+</table>
+
+<table width="100%" cellspacing="3" cellpadding="2">
         
-    <tr><td colspan="2" class="table-head">${lang("comment.htmltitle")}</td></tr>
+      <tr><td colspan="2" class="table-head">${lang("comment.htmltitle")}</td></tr>
     
     
-    <tr> 
-          <td align="right" class="table-left">
-            ${lang("comment.date")}
-          </td>
-          <td class="listrow2">
-            ${utility.encodeHTML(utility.encodeHTML(comment.webdb_create))}
-          </td>
-        </tr>
+      <tr>
+        <td align="right" class="table-left">
+          id # :
+        </td>
+        <td class="listrow2">
+          ${comment.id}
+        </td>
+      </tr>
+      
+      <tr> 
+        <td align="right" class="table-left">
+          ${lang("comment.date")}
+        </td>
+        <td class="listrow2">
+          ${utility.encodeHTML(utility.encodeHTML(comment.webdb_create))}
+        </td>
+      </tr>
 
 
     <call PulldownTableRow (lang("comment.status"), "to_comment_status", commentstatuses, "id", "name", comment.to_comment_status, "commentstatus.")>
@@ -49,7 +93,6 @@
         <tr>
           <td colspan="2" align="right" class="table-foot" > 
             <span class="text">
-              ${lang("comment.published")} <input type="checkbox" name="is_published" value="1" <if comment.is_published=="1"> checked</if>>
               <if new=="1">
                 <input type="submit" name="save" value="${lang("insert")}">
               <else>
 <table width="90%" cellspacing="0" cellpadding="0">
 
 <tr>
-<comment>
-<td align="left" valign="top">
-<table cellspacing="3" cellpadding="2">
-  <tr>
-    <td class="table-head" colspan="2">
-      ${lang("content.family")}
-    </td>
-  </tr>
-    
-  <tr>
-    <td align=right valign=top class="table-left">
-      ${lang("content.parent")}:
-    </td>
-    <td align="left" valign="top" class="listrow2">
-      <if article.parent>
-        <b>${utility.encodeHTML(article.parent.title)}</b><br>
-        <a href="${config.actionRoot}?module=Content&do=edit&id=${article.parent.id}&returnurl=${utility.encodeURI(thisurl)}">${lang("content.viewparent")}</a> |
-        <a href="${config.actionRoot}?module=Content&do=clearparent&id=${article.id}&returnurl=${utility.encodeURI(thisurl)}">${lang("content.clearparent")}</a> |
-      </if>    
-        &nbsp;<a href="${config.actionRoot}?module=Content&do=selectparent&id=${article.id}&returnurl=${utility.encodeURI(thisurl)}">${lang("content.selectparent")}</a>
-    </td>
-  </tr>
-    
-  <tr>
-    <td align=right valign=top class="table-left">
-      ${lang("content.children")}:
-    </td>
-    <td align="left" valign="top" class="listrow2">
-      <a href="${config.actionRoot}?module=Content&do=listchildren&article_id=${article.id}">${lang("content.viewchildren")}</a>
-    </td>
-  </tr>
-</table>
-
-</td>
-</comment>
 <td align="left" valign="top">
 <call showCommentAttachments(comment)>
 </td>
index 38fce1b..229f756 100755 (executable)
@@ -35,6 +35,8 @@
         <option value="title"<if searchfield=="title"> selected</if>>${lang("commentsearch.field.title")}</option>
         <option value="creator"<if searchfield=="creator"> selected</if>>${lang("commentsearch.field.creator")}</option>
         <option value="description"<if searchfield=="description"> selected</if>>${lang("commentsearch.field.description")}</option>
+        <option value="main_url"<if searchfield=="main_url"> selected</if>>${lang("commentsearch.field.main_url")}</option>
+        <option value="email"<if searchfield=="email"> selected</if>>${lang("commentsearch.field.email")}</option>
       </select>
     </td>
     <td class="listrow2">
@@ -96,7 +98,7 @@
   <list comments as entry>
     <tr <if grey=="1"><assign grey="0">class="listrow1"<else><assign grey="1">class="listrow2"</if>>
       <td valign="top" class="small">
-        ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}<br>
+        ${entry.creationdate.format(config["Mir.DefaultDateTimeFormat"])}<br>
         <if entry.is_published=="0"><b>${lang("commentlist.hidden")}</b><else>-</if><br>
         <br>
         ${lang("comment.status")}: <br>
             <div class="small">
             ${lang("comment.article")}:
             <a href="${config.actionRoot}?module=Content&do=edit&id=${entry.to_content.id}">
-              ${utility.encodeHTML(entry.to_content.title)}
+              ${utility.encodeHTML(entry.to_content.title)} (${entry.to_content.id})
             </a>
               (${lang("articletypes."+entry.to_content.article_type.name)}) 
   
             </if>
   
         
-        <b>${entry.title}</b> &nbsp;
+        <b>${entry.title}</b> (${entry.id})&nbsp;
         <if entry.creator>
           ${lang("by")}: ${entry.creator}
         </if>
       <td valign="top">
         &nbsp;
         <if config["Mir.Localizer.Admin.AllowDeleteComment"]=="1">
-          <a class="small" href="${config.actionRoot}?module=Comment&do=delete&id=${entry.id}&searchtext=${utility.encodeHTML(searchtext)}&searchfield=${utility.encodeHTML(searchfield)}&searchispublished=${searchispublished}&searchorder=${searchorder}&offset=${offset}">[${lang("delete")}]</a>
+          <a class="small" href="${config.actionRoot}?module=Comment&do=delete&id=${entry.id}&okurl=${utility.encodeURI(thisurl)}&cancelurl=${utility.encodeURI(thisurl)}">[${lang("delete")}]</a>
         </if>
       </td>    
     </tr>
index bb77827..7f0b593 100755 (executable)
@@ -4,43 +4,36 @@
     <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
   <head>
   <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-  <include "FUNCTIONS.template">
+    <include "FUNCTIONS.template">
     <include "head.template">
-    <form action="${config.actionRoot}" method="post">
+  
+      <if new=="1">
+        <assign method="insert">
+      <else>
+        <assign method="update">
+      </if>
+      
+      <call EditStart(
+         ["module", "id", "do"],
+         [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("commentstatus.id"), entity.id)>
+        <call EditTextNormal(lang("commentstatus.name"), 40, 255, "name", entity.name)>
+      
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
+        <else>
+          <call EditSubmitButtonNormal(lang("save"), "save")>
+        </if> 
 
-      <input type="hidden" name="module" value="CommentStatus">
-      <input type="hidden" name="id" value="${data.id}">
-      <if data.new>
-        <input type="hidden" name="do" value="insert">
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
       <else>
-        <input type="hidden" name="do" value="update">
+        <call showBack("module="+module+"&amp;do=list")>
       </if>
-    
-      <table border="0">
-        <tr>
-          <td align="right" class="table-left">
-          <B>${lang("commentstatus.id")}:</B></td>
-          <td class="listrow2">
-            ${data.id}
-          </td>
-        </tr>
-        
-    <call TextInputTableRow (lang("commentstatus.name"), 40, 255, "name", data.name)>
-        <tr>
-          <td colspan="2" align="right" class="table-foot">
-            <span class="witetext">
-              <if data.new>
-                <input type="submit" name="save" value="${lang("insert")}">
-              <else>
-                <input type="submit" name="save" value="${lang("save")}">
-              </if> 
-            </span>
-          </td>
-        </tr>
-      </table>
 
-    </form>
-  <p><a class="link-box" href="${config.actionRoot}?module=CommentStatus&do=list">[&lt;] ${lang("back")} </a> &nbsp;</p>
     <include "foot.template">
   </body>
 </html>
index 8944f9b..d137d28 100755 (executable)
@@ -5,35 +5,21 @@
   </head>
   <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
   
-  <include "FUNCTIONS.template">
-  
+    <include "FUNCTIONS.template">
     <include "head.template">
+    
+    <call showAddOrBack("1", module, "Admin", "superusermenu")>
 
-    <comment>configure this template here</comment>
-    <assign contentlist = data.contentlist>
-    <assign column_nr = 3>
-    <assign data_keys = ["id","name"]>
-    <assign column_head_texts = [lang("commentstatus.id"), lang("commentstatus.name")]>
-    <assign column_head_CSS = "table_head">
-    <assign listrow1CSS = "listrow1">
-    <assign listrow2CSS = "listrow2">
-    <assign footer_css = "table_foot">
-    <assign module_name = "CommentStatus">
-    <assign module_jumpback = "Admin">
-    <assign do_jumpback = "superusermenu">
-
-    <if data.contentlist>
-    <call AddOrBack(module_name, module_jumpback, do_jumpback)>
-    <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>   
-    <call PrevNextPage(module_name)>    
-   <else>
-    <P align="center">${lang("no_matches_found")}</p>
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, ["id","name"], [lang("commentstatus.id"), lang("commentstatus.name")], from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "superusermenu")>
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
     </if>
-    
-  <call AddOrBack(module_name, module_jumpback, do_jumpback)>
 
     <include "foot.template">
-  
   </body>
 </html>
 
index a317b1f..38d307f 100755 (executable)
@@ -4,32 +4,26 @@
         <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
   </head>
 
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-<center>
-  <include "head_nonavi.template">
-      <form method="post" action="${config.actionRoot}">
-      <table><tr><td>
-    <p class="box-head" align="center"><b>${lang("confirm.really_delete")}</b></p>
-        <p class="box" align="center">
-          <input type="hidden" name="module" value="${data.module}">
-          <input type="hidden" name="do" value="delete">
-          <input type="hidden" name="id" value="${data.id}">
-          <input type="hidden" name="where" value="${data.where}">
-          <input type="hidden" name="order" value="${data.order}">
-          <input type="hidden" name="query_text" value="${utility.encodeHTML(data.query_text)}">
-          <input type="hidden" name="query_field" value="${utility.encodeHTML(data.query_field)}">
-          <input type="hidden" name="query_is_pubished" value="${data.query_is_pubished}">
-          <input type="hidden" name="query_media_folder" value="${data.query_media_folder}">
-          <input type="hidden" name="offset" value="${data.offset}">
-          <input type="submit" name="cancel" value="${lang("cancel")}">
-          <input type="submit" name="confirm" value="${lang("delete")}"><br>
-      <br>
-      <b><span class="text-alert">${lang("confirm.text")}</span></b>
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+    <center>
+      <include "head.template">
+        <form method="post" action="${config.actionRoot}">
+          <table><tr><td>
+            <p class="box-head" align="center"><b>${lang("confirm.really_delete")}</b></p>
+            <p class="box" align="center">
+             <input type="hidden" name="module" value="${module}">
+             <input type="hidden" name="do" value="confirmdelete">
+             <input type="hidden" name="id" value="${id}">
+             <input type="hidden" name="okurl" value="${okurl}">
+             <input type="hidden" name="cancelurl" value="${cancelurl}">
+             <input type="submit" name="cancel" value="${lang("cancel")}">
+             <input type="submit" name="confirm" value="${lang("delete")}"><br>
+             <br>
+            <b><span class="text-alert">${lang("confirm.text")}</span></b>
         </p>
-    
       </td></tr></table>
-    </form>
-</center>
-<include "foot.template">
+       </form>
+      </center>
+    <include "foot.template">
   </body>
 </html>
index fb51eac..665ae7b 100755 (executable)
     <input type="hidden" name="do" value="update">
   </if>
 
-<table width="90%" cellspacing="3" cellpadding="2">
+<table width="100%" cellspacing="0" cellpadding="5">
   <tr>
     <td align="left" valign="top">
       <if new=="0">
-        [ <a href="${config.actionRoot}?module=Comment&do=articlecomments&articleid=${article.id}&returnurl=${thisurl}">${lang("content.comments")}</a> ] &nbsp;&nbsp;
-          [ <a href="${article.publicurl}">${lang("preview")}</a> ]
+        <call showButton(
+          "module=Comment&do=articlecomments&articleid="+article.id+"&returnurl="+utility.encodeURI(thisurl),
+          lang("content.comments"))>
+        <call showAbsoluteLinkButton(
+          article.publicurl,
+          lang("preview"))>
+        <list article.operations as op>
+          <call showButton(
+            "module=Localizer&do=articleoperation&operation="+op+"&articleid="+article.id+"&returnurl="+utility.encodeURI(thisurl), 
+            lang("content.operation."+op))>
+        </list>
       </if>
       
     </td>
@@ -38,7 +47,8 @@
       </if>
     </td>
   </tr>
-
+</table>
+<table width="100%" cellspacing="3" cellpadding="2">
   <tr>
     <td align="right" class="table-left">
       id # :
@@ -53,7 +63,7 @@
       ${lang("content.lastchange_date")}:
     </td>
     <td class="listrow2">
-      ${utility.encodeHTML(article.webdb_lastchange)}<br>
+      ${utility.encodeHTML(article.changedate.format(config["Mir.DefaultDateTimeFormat"]))}<br>
     </td>
   </tr>
 
       ${lang("content.create_date")}:
     </td>
     <td class="listrow2">
-      ${utility.encodeHTML(article.webdb_create)}<br>${lang("edit")}:
+      ${utility.encodeHTML(article.creationdate.format(config["Mir.DefaultDateTimeFormat"]))}<br>${lang("edit")}:
       <input type="text" size="10" maxlength="16" name="webdb_create" value=""> &nbsp; <span class="small">(yyyy-mm-dd [HH:mm])</span>
     </td>
   </tr>
 
-
   <call PulldownTableRow (lang("content.articletype"), "to_article_type", articletypes, "id", "name", article.to_article_type, "articletypes.")>
   <call PulldownTableRow (lang("content.language"), "to_language", languages, "id", "name", article.to_language, "")>
   
@@ -76,7 +85,7 @@
       ${lang("content.topic")}:
     </td>
     <td class="listrow2" >
-      <if config["Mir.Localizer.Admin.TopicListFlavor"]!="0">      
+      <if config["Mir.Localizer.Admin.TopicListFlavor"]!="0">
       <table border=0 cellpadding="2" cellspacing="0">
         <tr> 
           <assign col=config["Mir.Localizer.Admin.TopicListColumns"]>
         </tr>
       </table>
       <else>
-      <select name="to_topic" size="5" multiple>
-        <list topics as t>
-          <option value="${t.id}" <list article.to_topics as to><if (t.id == to["id"])>selected</if></list>>${t.title}</option>
+      <select name="to_topic" size="7" multiple>
+               <list topics as t>
+                 <option value="${t.id}" <list article.to_topics as to><if (t.id == to["id"])>selected</if></list>>${t.title}</option>
         </list>
       </select>
-      </if>        
+      </if>
     </td>
   </tr>
   
index f1b2503..e580010 100755 (executable)
@@ -50,8 +50,8 @@
       </span>
     </td>
     <td class="table-head" valign="top">
-      ${lang("content.type")} - ${lang("content.title")} <br>
-      ${lang("content.creator")}
+      ${lang("content.type")} - ${lang("content.title")} (id # )<br>
+      ${lang("content.creator")} 
     </td>
     <td class="table-head" valign="top">
       ${lang("content.comment")}
   </tr>
 
 <assign grey="0">
-
   <list articles as entry>
     <tr <if grey=="1"><assign grey="0">class="listrow1"<else>class="listrow2"<assign grey="1"></if>>
       <td class="x-small">
-          ${entry.creationdate.formatted["dd.MM.yyyy HH:mm"]}<br>
-          ${entry.changedate.formatted["dd.MM.yyyy HH:mm"]}<br>
+          ${entry.creationdate.format(config["Mir.DefaultDateTimeFormat"])}<br>
+          ${entry.changedate.format(config["Mir.DefaultDateTimeFormat"])}<br>
           <if entry.is_published!="0">Pub.<else>-</if> <if entry.is_html!="0">HTML<else>-</if>
       </td>
       <td>
-        <b>${entry.title}</b><br>
-        ${lang("by")}: ${entry.creator}<br>
-        (${lang("articletypes." + entry.article_type.name)}) 
+        ${lang("articletypes." + entry.article_type.name)} <b>${entry.title}</b> (${entry.id})<br>
+        ${lang("by")} <i>${utility.encodeHTML(entry.creator)}</i><br>
         <if showactions=="1">
           <if config["Mir.Localizer.Admin.ListOperationsFlavor"]=="0">
             <list entry.operations as op>
           </list>
         </if>
           <if config["Mir.Localizer.Admin.ListOperationsFlavor"]=="2">
-            <select name="operation">
-              <option value="" selected>&nbsp;</option>
-              <list entry.operations as op>
-                <option value="${entry.id};${op}">${lang("content.operation."+op)}</option>
-              </list>
-            </select>
+            <if entry.operations>
+              <br>
+              <select name="operation">
+                <option value="" selected>&nbsp;</option>
+                <list entry.operations as op>
+                  <option value="${entry.id};${op}">${lang("content.operation."+op)}</option>
+                </list>
+              </select>
+            </if>
           </if>
           <if entry.operations> | </if>
           <a href="${config.actionRoot}?module=Content&do=edit&id=${entry.id}&returnurl=${utility.encodeURI(thisurl)}">${lang("edit")}</a> |
+          <a href="${entry.publicurl}">${lang("preview")}</a> |
           <a href="${config.actionRoot}?module=Comment&do=articlecomments&articleid=${entry.id}&returnurl=${utility.encodeURI(thisurl)}">${lang("contentlist.comments")}</a> (${entry.commentcount})
         <else>
           <span class="text">
       <td valign="top" class="listcommand">
         <if showactions=="1">
           <if config["Mir.Localizer.Admin.AllowDeleteArticle"]=="1">
-            <a href="${config.actionRoot}?module=Content&do=delete&id=${entry.id}&where=${utility.encodeURI(where)}&order=${utility.encodeURI(order)}&offset=${utility.encodeURI(offset)}">[${lang("delete")}]</a>
+            <a href="${config.actionRoot}?module=Content&do=delete&id=${entry.id}&okurl=${utility.encodeURI(thisurl)}&cancelurl=${utility.encodeURI(thisurl)}">[${lang("delete")}]</a>
           </if>
         </if>
       </td>
   </if>  
 </if>
 
-
 <call showPrevNextLinks(prevurl, nexturl, "right")>
 
-
-
 <else>
 <p align="center" class="box">${lang("no_matches_found")}</p>
 </if>
index 288e156..65f7d00 100755 (executable)
@@ -1,20 +1,20 @@
 <html>
-<head>
+  <head>
     <title>${config["Mir.Name"]} | ${lang("error.htmltitle")}</title>
     <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-</head>
-<body>
-<include "head.template">
+  </head>
+  <body>
+    <include "head.template">
 
-<table width="70%" align="center"><tr><td>
+    <table width="70%" align="center"><tr><td>
 
-<p class="box-head" align="center"><font size="+2"><b>${lang("error.title")}</b></font></p>
-<p align="center">${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}</p>
-<p align="center" class="bg-neutral"><br><font color="red">${data.date} -- ${data.errorstring}</font><br><br></p>
-<p align="center">${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}</p>
+      <p class="box-head" align="center"><font size="+2"><b>${lang("error.title")}</b></font></p>
+      <p align="center">${lang("error.text", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}</p>
+      <p align="center" class="bg-neutral"><br><font color="red">${date.format(config["Mir.DefaultDateTimeFormat"])} -- ${errorstring}</font><br><br></p>
+      <p align="center">${lang("error.text2", config["Mir.Tech-email.address"], config["Mir.Tech-email.name"])}</p>
 
-</td></tr></table>
+    </td></tr></table>
 
-<include "foot.template">
-</body>
+    <include "foot.template">
+  </body>
 </html>
index e1432d3..d67fe76 100755 (executable)
@@ -1,5 +1,5 @@
 <hr>  
-<table width="99%" cellspacing="0">
+<table width="100%" cellspacing="0">
   <tbody>
   <tr>
     <td align="left" class="table-head">
index a2cf60d..0c942f7 100755 (executable)
@@ -2,16 +2,19 @@
 
 <table class="table-head" width="100%" cellspacing="0" cellpadding="0">
   <tr>
+    <td><img src="${config.docRoot}/img/logo_small.gif" border="0" align="left"></td>
     <td>
-      <img src="${config.docRoot}/img/logo_small.gif" border="0" align="middle">&nbsp;
-      ${config["Mir.Name"]}
+      ${config["Mir.Name"]} &nbsp; | &nbsp; ${config.now.format(config["Mir.DefaultDateTimeFormat"])} 
     </td>
-    <td align="right">
+    <td class="table-head" align="right">
+      <a href="${config.actionRoot}?module=Users&amp;do=changepassword&amp;id=${login_user.id}&amp;returnurl="><span class="table-head">${lang("head.changepassword")}</span></a> &nbsp; | &nbsp;
       <if returnurl>
-        <a href="${config.actionRoot}?${returnurl}"><span class="table-head">[ &lt; ] ${lang("back")}</span></a>&nbsp;&nbsp;|
-      </if>
-      <a href="${config.actionRoot}"><span class="table-head">${lang("head.start")}</span></a> |
-      <a href="${config.actionRoot}?module=logout"><span class="table-head">${lang("head.logout")}</span></a>
+        <a href="${config.actionRoot}?${returnurl}"><span class="table-head">[ &lt; ] ${lang("back")}</span></a> &nbsp; | &nbsp;
+      </if> 
+      <a href="${config.actionRoot}"><span class="table-head">${lang("head.start")}</span></a> &nbsp; | &nbsp;
+      <a href="${config.actionRoot}?module=logout"><span class="table-head">${lang("head.logout")}
+      <if login_user> <i>${login_user.login}</i> </if>
+      </span></a>
     </td>
   </tr>
 </table>
index 1cdb111..2238ae5 100755 (executable)
@@ -1,18 +1,11 @@
 <a name="top"></a>
-<table width="100%" cellspacing="0" cellpadding="0">
+
+<table class="table-head" width="100%" cellspacing="0" cellpadding="0">
   <tr>
-    <td class="table-head">
-      <img src="${config.docRoot}/img/logo_small.gif" border="0" align="middle">&nbsp;
-      <b>${config["Mir.Name"]}</b>
+    <td><img src="${config.docRoot}/img/logo_small.gif" border="0" align="left"></td>
+    <td>
+      ${config["Mir.Name"]} 
     </td>
   </tr>
-<if login_user>
-  <tr>
-    <td align="right">
-      <b>${login_user.login}</b> ${lang("head.logged_in")} |
-      <a href="${actionRoot}?module=logout">${lang("head.logout")}</a>
-    </td>
-  </tr>
-</if>
-  <tr><td><hr></td></tr>
 </table>
+<hr>
index 043c8ea..cd2191b 100755 (executable)
   <input type="hidden" name="module" value="Hidden">
   <input type="hidden" name="do" value="list">
 
-
-
   ${lang("month")}
   <select name="month">
-  <option value="01" selected >01</option>
-  <option value="02">02</option>
-  <option value="03">03</option>
-  <option value="04">04</option>
-  <option value="05">05</option>
-  <option value="06">06</option>
-  <option value="07">07</option>
-  <option value="08">08</option>
-  <option value="09">09</option>
-  <option value="10">10</option>
-  <option value="11">11</option>
-  <option value="12">12</option>
+    <option value="01" selected >01</option>
+    <option value="02">02</option>
+    <option value="03">03</option>
+    <option value="04">04</option>
+    <option value="05">05</option>
+    <option value="06">06</option>
+    <option value="07">07</option>
+    <option value="08">08</option>
+    <option value="09">09</option>
+    <option value="10">10</option>
+    <option value="11">11</option>
+    <option value="12">12</option>
   </select>
   ${lang("year")}
   <select name="year">
-  <option value="2001">2001</option>
-  <option value="2002">2002</option>
-  <option value="2003" selected >2003</option>
-  <option value="2004">2004</option>
-  <option value="2005">2005</option>
-  <option value="2006">2006</option>
-  <option value="2007">2007</option>
-  <option value="2008">2008</option>
+    <option value="2001">2001</option>
+    <option value="2002">2002</option>
+    <option value="2003" selected >2003</option>
+    <option value="2004">2004</option>
+    <option value="2005">2005</option>
+    <option value="2006">2006</option>
+    <option value="2007">2007</option>
+    <option value="2008">2008</option>
   </select>
 
   &nbsp;
 
 <hr size="4" width="98%" noshade>
 
-<if data.contentlist>
+<if articles>
 <table cellpadding="6" width="98%" class="litegrey">
 <tr>
   <td>
-  <p>${lang("start.content.hidden")} | ${lang("month")}: ${data.month} , ${lang("year")}:${data.year}</p>
+  <p>${lang("start.content.hidden")} | ${lang("month")}: ${month} , ${lang("year")}:${year}</p>
   </td>
 </tr>
 </table>
 
-<list data.contentlist as i>
-  <p
+<list articles as i>
+  <p style='background: #FFFFFF; padding: 8px;'>
     ${lang("content.title")}: <b>${i.title}</b><br>
     ${lang("content.creator")}: ${i.creator}<br>
-    ${lang("message.date")}: ${i.webdb_create_formatted}<br>
+    ${lang("message.date")}: ${i.creationdate.format(config["Mir.DefaultDateTimeFormat"])}<br>
     <br>
-    <if i.to_media_audio >additional media, type: audio<br></if>
-    <if i.to_media_video >additional media, type: video<br></if>
-    <if i.to_media_other >additional media, type: other<br></if>
-    <if i.to_media_images >additional media, type: image<br></if>
+    <if i.to_media_audio>additional media, type: audio<br></if>
+    <if i.to_media_video>additional media, type: video<br></if>
+    <if i.to_media_other>additional media, type: other<br></if>
+    <if i.to_media_images>additional media, type: image<br></if>
   </p>
 
   <p>
index 1e89c10..18ffebe 100755 (executable)
-<html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("image.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
-<SCRIPT LANGUAGE="JavaScript">
-function openWin(url) {
-   window.open(url,"vc","scrollbars=0,height=${data.img_height},width=${data.img_width}");
-}
-</SCRIPT>
+<if new!="1">
+  <SCRIPT LANGUAGE="JavaScript">
+    function openWin(url) {
+       window.open(url,"vc","scrollbars=0,height=${uploadedmedia.img_height},width=${uploadedmedia.img_width}");
+    }
+  </SCRIPT>
 
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "FUNCTIONS.template">
-<include "head.template">
-
-<if data.new>
-<form action="${config.actionRoot}?module=Images&do=add" method="post">
-
-  <if data.articleid>
-    <input type="hidden" name="articleid" value="${data.articleid}">
-  </if>
-  <if data.commentid>
-    <input type="hidden" name="commentid" value="${data.commentid}">
-  </if>
-  
-  
-  <table border="0">
-    <tr>
-      <td align="right" class="table-left">
-        <b>${lang("media.nr_of_media")} :</b><br>
-      </td>
-      <td class="listrow2">
-        <input type="text" size="3" name="medianum" value="${medianum}">&nbsp;&nbsp;<input type="submit" value="${lang("media.nr_of_media.submit")}">
-      </td>
-    </tr>
-  </table>
-</form>
-</if>
-
-
-<form enctype="multipart/form-data" method="post" action="${config.actionRoot}?module=Images&do=<if data.new>insert<else>update</if>&id=${data.id}">
-  
-  <if data.articleid>
-    <input type="hidden" name="articleid" value="${data.articleid}">
-  </if>
-
-  <if data.commentid>
-    <input type="hidden" name="commentid" value="${data.commentid}">
-  </if>
-
-  <input type="hidden" name="where" value="${data.where}">
-  <input type="hidden" name="offset" value="${data.offset}">
-  <input type="hidden" name="order" value="${data.order}">
-  <input type="hidden" name="id" value="${data.id}">
-
-  <table border="0">
-
-  <if !data.new>
   <tr>
-      <td align="right" valign="top">
-      <a href="JavaScript:openWin('${config.actionRoot}?module=Images&do=getMedia&id=${data.id}')">
-        <img src="${config.actionRoot}?module=Images&do=getIcon&id=${data.id}" border=0></a>&nbsp;&nbsp;
+    <td align="right" valign="top">
+      <a href="JavaScript:openWin('${config.actionRoot}?module=${module}&do=getMedia&id=${uploadedmedia.id}')">
+        <img src="${config.actionRoot}?module=${module}&do=getIcon&id=${uploadedmedia.id}" border=0>
+      </a>&nbsp;&nbsp;
     </td>
     <td valign="bottom" class="small">
-      ${lang("media.created")}: ${data.webdb_create}
-      <if data.webdb_lastchange>/ ${lang("media.changed")} ${data.webdb_lastchange}</if><br>
-      <if data.is_published=="1">${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}<br></if>
-      ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}<br>
-      ${lang("media.size")}: ${data.human_readable_size}<br>
-      ${lang("media.rights")}: <b>${data.rightsHashdata[to_rights]["name"]}</b><br>
-    </td>
-    </tr>
-  </if>
-
-  <tr>
-    <td align="right" class="table-left">
-      <B>${lang("media.mediafolder")}:</B>
-    </td>
-    <td class="listrow2">
-      <select name="to_media_folder">
-      <list extra.mediafolderPopupData as m>
-        <option value="${m.key}" <if m.key == data.to_media_folder>selected</if>>${m.value}</option>
-      </list>
-        </select>
-    </td>
-  </tr>
-  
-  <if !data.new>
-    <call TextInputTableRow (lang("media.title"), 40, 80, "title", data.title)>
-  </if>
-  <call TextInputTableRow (lang("media.date"), 8, 8, "date", data.date)>
-  <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-  <call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", data.description)>
-  <call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", data.comment)>
-  <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
-  
-  <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-  
-  <if data.new>
-  <tr>
-    <td align="right" class="table-left">
-      ${lang("media.is_published")} : 
-    </td>
-    <td class="listrow2" style='border: 1px solid #FF0000;'>
-      <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>  
-    </td>
-  </tr>
-  
-  <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-  
-  <list data.mediafields as m>
-  <tr>
-    <td align="right" class="table-left">
-      <B>${lang("media.title")}:<B>
-     </td>
-    <td class="listrow2">
-      <input type="text" name="media_title${m}" size="40" maxlength="80" value="">
+      ${lang("media.created")}: ${uploadedmedia.webdb_create}
+      <if uploadedmedia.webdb_lastchange>/ ${lang("media.changed")} ${uploadedmedia.webdb_lastchange}</if><br>
+      <if uploadedmedia.is_published=="1">${lang("media.published")}: ${uploadedmedia.publish_date} / ${uploadedmedia.publish_server}${uploadedmedia.publish_path}<br></if>
+      ${lang("media.format")}: ${uploadedmedia.mimetype} / ${uploadedmedia.media_descr}<br>
+      ${lang("media.size")}: ${uploadedmedia.human_readable_size}<br>
+      ${lang("media.rights")}: <b>${uploadedmedia.rightsHashdata[to_rights]["name"]}</b><br>
     </td>
   </tr>
-  <tr>
-    <td align="right">
-      &nbsp;
-    </td>
-    <td class="listrow2">
-      <input type="file" name="media${m}"><br>
-    </td>
-  </tr>
-  </list>
-  </if>
-
-    <td colspan="2" align="right" class="table-foot">
-  <if data.new>
-      <input type="submit" name="save" value="${lang("insert")}">
-    <else>
-     ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>
-    &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
-    </if> </form>
-    </td>
-</table>
-
-<p><a class="link-box" href="${config.actionRoot}?module=Images&do=list">[&lt;] ${lang("list")} </a> &nbsp;</p>
+</if>
 
-<include "foot.template">
-</body>
-</html>
+<tr>
+  <td align="right" class="table-left">
+    <B>${lang("media.mediafolder")}:</B>
+  </td>
+  <td class="listrow2">
+    <select name="to_media_folder">
+    <list mediafolders as m>
+      <option value="${m.id}" <if m.id == uploadedmedia.to_media_folder>selected</if>>${m.name}</option>
+    </list>
+      </select>
+  </td>
+</tr>
+        
+<if new!="1">
+  <call TextInputTableRow (lang("media.title"), 40, 80, "title", uploadedmedia.title)>
+</if>
+<call TextInputTableRow (lang("media.creator"), 40, 80, "creator", uploadedmedia.creator)>
+<call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", uploadedmedia.description)>
+<call TextInputTableRow (lang("media.source"), 40, 80, "source", uploadedmedia.source)>
+<call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", uploadedmedia.comment)>
+      
index b166e3f..f6b7456 100755 (executable)
@@ -3,96 +3,20 @@
        <title>${config["Mir.Name"]} | ${lang("imagelist.htmltitle")}</title>
         <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
 <SCRIPT LANGUAGE="JavaScript">
-function openWin(url) {
-   window.open(url,"vc","scrollbars=1,height=400,width=300");
-}
+  function openWin(url) {
+     window.open(url,"vc","scrollbars=1,height=400,width=300");
+  }
 </SCRIPT>
 </head>
 
 <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
 
-
 <include "head.template">
 <include "FUNCTIONS_media.template">
-<call MediaSearch ("Images")>
-
-<table>
 
-  <tr class="darkgrey" >
-       <td class="table-head">
-       <b>${lang("media.icon")}</b></td>
-       <td class="table-head">
-       <b>${lang("media.title")}</b></td>
-    <td class="table-head">
-       <b>${lang("media.format")}</b></td>
-    <td class="table-head">
-       <b>${lang("media.size")}</b></td>
-    <td class="table-head">
-       <b>${lang("media.mediafolder")}</b></td>
-    <td class="table-head">
-       <b>${lang("media.creator")}</b></td>
-    <td class="table-head">
-       &nbsp;</td>
-
-  </tr>
-       <if data.contentlist>
-       <list data.contentlist as entry>
-       <tr <if grey=="1"><assign grey="0">class="listrow1"<else>class="listrow2"<assign grey="1"> </if>>
-               <td>
-                               <a href="JavaScript:openWin('${config.actionRoot}?module=Images&do=getMedia&id=${entry.id}')">
-                               <img src="${config.actionRoot}?module=Images&do=getIcon&id=${entry.id}" border=0></a>
-               </td>
-               <td>
-                       ${entry.title}&nbsp;
-                       <if entry.description><br>${entry.description}</if>
-               </td>
-               <td>
-                       ${entry.media_descr}&nbsp;
-               </td>
-               <td>
-                       ${entry.human_readable_size}&nbsp;
-               </td>
-               <td>
-                       ${data.mediafolderHashdata[entry.to_media_folder]["name"]}&nbsp;
-               </td>
-               <td>
-                       ${entry.creator}&nbsp;
-               </td>
-               <td>&nbsp;
-                       <if data.articleid>
-                               <a href="${config.actionRoot}?module=Content&do=attach&mid=${entry.id}&articleid=${data.articleid}">${lang("attach")}</a>
-                       <else>
-                       <if data.commentid>
-                               <a href="${config.actionRoot}?module=Comment&do=attach&mid=${entry.id}&commentid=${data.commentid}">${lang("attach")}</a>
-                       <else>
-                               <a href="${config.actionRoot}?module=Images&do=delete&id=${entry.id}&query_text=${utility.encodeHTML(data.query_text_encoded)}&query_field=${utility.encodeHTML(data.query_field)}&query_is_published=${data.query_is_published}&query_media_folder=${data.query_media_folder}&offset=${data.offset}">${lang("delete")}</a>
-                       | <a href="${config.actionRoot}?module=Images&do=edit&id=${entry.id}">${lang("edit")}</a>
-        </if>
-                       </if>
-               </td>
-       </tr>
-       </list>
-       <tr>
-               <td colspan="7" class="table-foot">
-                       ${data.count} ${lang("records")} / ${lang("show_from_to", data.from, data.to)}
-               </td>
-       </tr>
-
-       <tr>
-               <td>
-                       <if data.prev>
-                               <a href="${config.actionRoot}?module=Images&do=list&query_text=${data.query_text_encoded}&query_field=${data.query_field}&query_is_published=${data.query_is_published}&query_media_folder=${data.query_media_folder}&offset=${data.prev}&prev=zur&uuml;ck&articleid=${data.articleid}&commentid=${data.commentid}">${lang("list.previous")}</a>&nbsp;
-                       </if>
-                       <if data.next>
-                               <a href="${config.actionRoot}?module=Images&do=list&query_text=${data.query_text_encoded}&query_field=${data.query_field}&query_is_published=${data.query_is_published}&query_media_folder=${data.query_media_folder}&offset=${data.next}&next=weiter&articleid=${data.articleid}&commentid=${data.commentid}">${lang("list.next")}</a>
-                       </if>
-               </td>
-       </tr>
+<call MediaSearch ("Images")>
 
-<else>
-  <tr><td align="center" class="box" colspan="7">${lang("no_matches_found")}</td></tr>
-</if>
-</table>
+<call MediaList   ("Images")>
 
 <include "foot.template">
 </body>
index de733de..1c20ece 100755 (executable)
@@ -1,33 +1,41 @@
 <html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("language.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
+  <head>
+    <title>${config["Mir.Name"]} | ${lang("language.htmltitle")}</title>
+    <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+  <head>
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
 
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-<include "FUNCTIONS.template">
-<include "head.template">
+    <include "FUNCTIONS.template">
+    <include "head.template">
+  
+      <if new=="1">
+        <assign method="insert">
+      <else>
+        <assign method="update">
+      </if>
+      
+      <call EditStart(
+         ["module", "id", "do"],
+         [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("language.id"), entity.id)>
+        <call EditTextNormal(lang("language.name"), 40, 255, "name", entity.name)>
+        <call EditTextNormal(lang("language.code"), 2, 2, "code", entity.code)>
+      
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
+        <else>
+          <call EditSubmitButtonNormal(lang("save"), "save")>
+        </if> 
 
-<form action="${config.actionRoot}" method="post">
-  <input type="hidden" name="module" value="Language">
-  <input type="hidden" name="id" value="${data.id}">
-  <if data.new><input type="hidden" name="do" value="insert">
-  <else><input type="hidden" name="do" value="update"></if>
-<table border="0">
-    <call TextInputTableRow (lang("language.name"), 30, 255, "name", data.name)>
-    <call TextInputTableRow (lang("language.code"), 2, 2,"code", data.code)>
-  <tr>
-    <td class="table-foot" colspan="2" align="right"> 
-  <if data.new>
-      <input type="submit" name="save" value="${lang("insert")}">
-    <else>
-      <input type="submit" name="save" value="${lang("save")}">
-    </if>
-  </td>
-  </tr>
-</table>
-</form>
-<p><a class="link-box" href="${config.actionRoot}?module=Language&do=list">[&lt;] ${lang("back")} </a> &nbsp;</p>
-<include "foot.template">
-</body>
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
+      <else>
+        <call showBack("module="+module+"&amp;do=list")>
+      </if>
+
+    <include "foot.template">
+  </body>
 </html>
index 5ee774f..58a2eae 100755 (executable)
@@ -4,33 +4,20 @@
     <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
   </head>
   <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
     <include "FUNCTIONS.template">
-  
     <include "head.template">
+    
+    <call showAddOrBack("1", module, "Admin", "superusermenu")>
 
-    <comment>configure this template here</comment>
-    <assign contentlist = data.contentlist>
-    <assign column_nr = 3>
-    <assign data_keys = ["name","code"]>
-    <assign column_head_texts = [lang("language.name"), lang("language.code")]>
-    <assign column_head_CSS = "table_head">
-    <assign listrow1CSS = "listrow1">
-    <assign listrow2CSS = "listrow2">
-    <assign footer_css = "table_foot">
-    <assign module_name = "Language">
-    <assign module_jumpback = "Admin">
-    <assign do_jumpback = "superusermenu">
-
-    <if data.contentlist>
-    <call AddOrBack(module_name, module_jumpback, do_jumpback)>
-    <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>   
-    <call PrevNextPage(module_name)>    
-   <else>
-    <P align="center">${lang("no_matches_found")}</p>
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, ["id", "name","code"], [lang("language.id"), lang("language.name"), lang("language.code")], from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "superusermenu")>
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
     </if>
-    
-  <call AddOrBack(module_name, module_jumpback, do_jumpback)>
+
     <include "foot.template">
   </body>
 </html>
diff --git a/templates/admin/linksimcs.template b/templates/admin/linksimcs.template
deleted file mode 100755 (executable)
index ab40ab1..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-<html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("linkimcs.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "head.template">
-<form action="${config.actionRoot}" method="post">
-  <input type=hidden name=module value=LinksImcs>
-  <input type="hidden" name="id" value="${data.entity.id}">
-  <if data.new><input type="hidden" name="do" value="insert">
-  <else><input type="hidden" name="do" value="update"></if>
-<table border="0">
-  <tr>
-    <td align="right" class="darkgrey"><span class="witesmall>
-    <B>${lang("linkimcs.name")}:</B></span></td>
-    <td>
-        <input type="text" size="40" name="title" value="${data.entity.title}">
-    </td>
-  </tr>
-  <tr>
-    <td align="right" class="darkgrey"><span class="witesmall>
-    <B>${lang("linkimcs.continent")}:</B></span></td>
-    <td>
-    <if data.parentlist>
-      <select name="to_parent_id" size="1">
-      <option value=NULL> ${lang("linkimcs.new_parent")}
-      <list data.parentlist as entry><option value="${entry.id}"<if entry.id == data.entity.to_parent_id> selected</if>> ${entry.title}</list>
-    </select>
-    </if>
-    </td>
-  </tr>
-  <tr>
-    <td align="right" class="darkgrey"><span class="witetext"><B>${lang("linkimcs.url")}:</B></span></td>
-    <td>
-      <input type="text" size="40" name="url" value="${data.entity.url}">
-    </td>
-  </tr>
-  <tr>
-    <td align="right" class="darkgrey"><span class="witetext"><B>${lang("linkimcs.sort-by")}:</B></span></td>
-    <td>
-      <select name="sortpriority" size="1">
-    <option value="1"<if data.entity.sortpriority == 1> selected</if>> 1
-    <option value="2"<if data.entity.sortpriority == 2> selected</if>> 2
-    <option value="3"<if data.entity.sortpriority == 3> selected</if>> 3
-    <option value="4"<if data.entity.sortpriority == 4> selected</if>> 4
-    </select>
-    </td>
-  </tr>
-  <tr>
-    <td align="right" class="darkgrey"><span class="witetext"><B>${lang("linkimcs.language")}:</B></span></td>
-    <td>
-      <select name="to_language" size="1">
-      <list data.languagelist as language>
-      <option value="${language.id}"<if data.entity.to_language == language.id> selected</if>> ${language.name}
-    </list>
-    </select>
-    </td>
-  </tr>
-  <tr>
-    <td colspan="2" align="right"><span class="witetext">
-    <if data.new>
-          <input type="submit" name="save" value="${lang("insert")}">
-      <else>
-        <input type="submit" name="save" value="${lang("save")}">
-      </if> </span></form></span>
-    </td>
-  </tr>
-</table>
-<include "foot.template">
-</body>
-</html>
index 279f8c6..0fd062c 100755 (executable)
@@ -50,8 +50,8 @@
       <td align="right">${lang("login.language")}:</td>
       <td align="left">  
         <select name="language">
-        <list data.languages as l>
-          <option value="${l.code}" <if l.code==data.defaultlanguage>selected</if> >${l.name}</option>
+        <list languages as l>
+          <option value="${l.code}" <if l.code==defaultlanguage>selected</if> >${l.name}</option>
         </list>
         </select>
       </td>
diff --git a/templates/admin/media.template b/templates/admin/media.template
deleted file mode 100755 (executable)
index a1907ad..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-<html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("other_media.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
-<SCRIPT LANGUAGE="JavaScript">
-function openWin(url) {
-   window.open(url,"vc","scrollbars=0,height=${data.img_height},width=${data.img_width}");
-}
-</SCRIPT>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "FUNCTIONS.template">
-<include "head.template">
-
-<if data.new>
-<form action="${config.actionRoot}?module=OtherMedia&do=add" method="post">
-  <if data.articleid>
-    <input type="hidden" name="articleid" value="${data.articleid}">
-  </if>
-  <if data.commentid>
-    <input type="hidden" name="commentid" value="${data.commentid}">
-  </if>
-  
-  <table border="0">
-    <tr>
-      <td align="right" class="table-left">
-        <b>${lang("media.nr_of_media")} :</b><br>
-      </td>
-      <td class="listrow2">
-        <input type="text" size="3" name="medianum" value="${medianum}">&nbsp;&nbsp;<input type="submit" value="${lang("media.nr_of_media.submit")}">
-      </td>
-    </tr>
-  </table>
-</form>
-</if>
-
-
-<form enctype="multipart/form-data" method="post" action="${config.actionRoot}?module=OtherMedia&do=<if data.new>insert<else>update</if>&id=${data.id}">
-  
-  <if data.articleid>
-    <input type="hidden" name="articleid" value="${data.articleid}">
-  </if>
-  <if data.commentid>
-    <input type="hidden" name="commentid" value="${data.commentid}">
-  </if>
-  <input type="hidden" name="where" value="${data.where}">
-  <input type="hidden" name="offset" value="${data.offset}">
-  <input type="hidden" name="order" value="${data.order}">
-  <input type="hidden" name="id" value="${data.id}">
-
-  <table border="0">
-
-  <if !data.new>
-  <tr>
-      <td align="right" valign="top">
-      <a href="${config.actionRoot}?module=OtherMedia&do=getMedia&id=${data.id}">
-          <img src="${config.docRoot}/img/${data.big_icon}" border=0></a>&nbsp;&nbsp;
-    </td>
-    <td valign="bottom" class="small">
-      ${lang("media.created")}: ${data.webdb_create}
-      <if data.webdb_lastchange>/ ${lang("media.changed")} ${data.webdb_lastchange}</if><br>
-      <if data.is_published=="1">${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}<br></if>
-      ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}<br>
-      ${lang("media.size")}: ${data.human_readable_size}<br>
-      ${lang("media.rights")}: <b>${data.rightsHashdata[to_rights]["name"]}</b><br>
-    </td>
-    </tr>
-  </if>
-
-  <tr>
-    <td align="right" class="table-left">
-      <B>${lang("media.mediafolder")}:</B>
-    </td>
-    <td class="listrow2">
-      <select name="to_media_folder">
-      <list extra.mediafolderPopupData as m>
-        <option value="${m.key}" <if m.key == data.to_media_folder>selected</if>>${m.value}</option>
-      </list>
-        </select>
-    </td>
-  </tr>
-
-        <if !data.new>
-          <call TextInputTableRow (lang("media.title"), 40, 80, "title", data.title)>
-        </if>
-        <call TextInputTableRow (lang("media.date"), 8, 8, "date", data.date)>
-        <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-        <call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", data.description)>
-        <call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", data.comment)>
-        <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
-  
-  <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-  
-  <if data.new>
-  <tr>
-    <td align="right" class="table-left">
-      ${lang("media.is_published")} : 
-    </td>
-    <td class="listrow2" style='border: 1px solid #FF0000;'>
-      <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>  
-    </td>
-  </tr>
-  
-  <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-  
-  <list data.mediafields as m>
-  <tr>
-    <td align="right" class="table-left">
-      <B>${lang("media.title")}:<B>
-     </td>
-    <td class="listrow2">
-      <input type="text" name="media_title${m}" size="40" maxlength="80" value="">
-    </td>
-  </tr>
-  <tr>
-    <td align="right">
-      &nbsp;
-    </td>
-    <td class="listrow2">
-      <input type="file" name="media${m}"><br>
-    </td>
-  </tr>
-  </list>
-  </if>
-
-    <td colspan="2" align="right" class="table-foot">
-  <if data.new>
-      <input type="submit" name="save" value="${lang("insert")}">
-    <else>
-     ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>
-    &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
-    </if> </form>
-    </td>
-</table>
-
-<p><a class="link-box" href="${config.actionRoot}?module=OtherMedia&do=list">[&lt;] ${lang("list")} </a> &nbsp;</p>
-
-<include "foot.template">
-
-</body>
-</html>
index 0389eb9..61ec50c 100755 (executable)
@@ -5,39 +5,40 @@
 <head>
 
 <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "FUNCTIONS.template">  
-<include "head.template">
-
-<form method="post" action="${config.actionRoot}">
-  <input type=hidden name=module value=Mediafolder>
-  <input type="hidden" name="id" value="${data.id}">
-  <if data.new> <input type="hidden" name="do" value="insert">
-  <else>   <input type="hidden" name="do" value="update"></if>
-
-<table border="0" cellspacing="2" cellpadding="2">
-<call TextInputTableRow (lang("mediafolder.date"), 8, 8, "date", data.date)>
-<call TextInputTableRow (lang("mediafolder.name"), 40, 80, "name", data.name)>  
-<call TextInputTableRow (lang("mediafolder.location"), 40, 80, "place", data.place)>  
-<call TextAreaTableRow (lang("mediafolder.comment"), "", 40, 5, "comment", data.comment)>  
-<call TextAreaTableRow (lang("mediafolder.keywords"), "", 40, 4, "keywords", data.keywords)>  
-
-
-  <tr>
-    <td colspan="4" align="right" class="table-foot"> 
-    <if data.new> <input type="submit" name="save" value="${lang("insert")}">
-      <else>   <input type="submit" name="save" value="${lang("save")}"></if>
-    
-    </td>
-  </tr>
-</table>
-
-</form>
-    <p>      
-      <a class="link-box" href="${config.actionRoot}?module=Mediafolder&do=list">[&lt;] ${lang("list")} </a> &nbsp;
-      <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a>
-  </p>
-
-<include "foot.template">
+    <include "FUNCTIONS.template">
+    <include "head.template">
+  
+      <if new=="1">
+        <assign method="insert">
+      <else>
+        <assign method="update">
+      </if>
+      
+      <call EditStart( ["module", "id", "do"], [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("mediafolder.id"), entity.id)>
+        
+        <call EditTextNormal(lang("mediafolder.date"), 8, 8, "date", entity.date)>
+        <call EditTextNormal(lang("mediafolder.name"), 40, 80, "name", entity.name)>
+        <call EditTextNormal(lang("mediafolder.location"), 40, 80, "place", entity.place)>
+
+        <call EditTextAreaNormal(lang("mediafolder.comment"), "", 40, 5, "comment", entity.comment)>\r
+        <call EditTextAreaNormal(lang("mediafolder.keywords"), "", 40,5, "keywords", entity.keywords)>\r
+        
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
+        <else>
+          <call EditSubmitButtonNormal(lang("save"), "save")>
+        </if> 
+
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
+      <else>
+        <call showBack("module="+module+"&amp;do=list")>
+      </if>
+
+    <include "foot.template">
 </body>
 </html>
index 06b3a31..62787b7 100755 (executable)
@@ -5,53 +5,24 @@
 </head>
 
 <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+    <include "FUNCTIONS.template">
+    <include "head.template">
+    
+    <call showAddOrBack("1", module, "Admin", "superusermenu")>
 
-<include "head.template">
-<if data.contentlist>
-  <table border="0">
-      <tr class="darkgrey">
-        <td class="table-head">${lang("mediafolder.date")}</td>
-        <td class="table-head">${lang("mediafolder.name")}</td>
-        <td class="table-head">${lang("mediafolder.location")}</td>
-      <td class="table-head">${lang("mediafolder.comment")}</td>
-      <td class="table-head">${lang("mediafolder.keywords")}</td>
-      <td class="table-head">&nbsp;</td>
-     </tr>
-    <list data.contentlist as entry>
-      <tr <if grey=="1"><assign grey="0">class="listrow1"<else>class="listrow2"<assign grey="1"> </if>>
-      <td>${entry.date}&nbsp;</td>
-        <td><b>${entry.name}</b>&nbsp;</td>
-        <td>${entry.place}&nbsp;</td>
-        <td>${entry.comment}&nbsp;</td>
-        <td>${entry.keywords}&nbsp;</td>
-        <td><a href="${config.actionRoot}?module=Mediafolder&do=delete&id=${entry.id}">${lang("delete")}</a>
-          | <a href="${config.actionRoot}?module=Mediafolder&do=edit&id=${entry.id}">${lang("edit")}</a>
-        | <a href="${config.actionRoot}?module=Images&do=list&query_media_folder=${entry.id}">${lang("list")}</a></td>
-      </tr>
-      </list>
-      <tr>
-      <td colspan="6" class="table-foot">${data.count} ${lang("records")} /
-        ${lang("show_from_to", data.from, data.to)}</td>
-      <td>&nbsp;</td>
-      </tr>
-  </table>
-      <P>
-  <if data.prev>
-  <a href="${config.actionRoot}?module=Mediafolder&do=list&where=${data.where}&prevoffset=${data.prev}&prev=zur&uuml;ck">${lang("list.previous")}</a>&nbsp;
-  </if>
-  <if data.next>
-  <a href="${config.actionRoot}?module=Mediafolder&do=list&where=${data.where}&nextoffset=${data.next}&next=weiter">${lang("list.next")}</a>
-  </if>
-<else>
-  <P align="center" class="box">${lang("no_matches_found")}</p>
-</if>
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, ["name", "place","comment"], 
+         [ lang("mediafolder.name"), 
+           lang("mediafolder.location"),
+           lang("mediafolder.comment")], from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "start")>
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
+    </if>
 
-    <p>
-      <a class="link-box" href="${config.actionRoot}?module=Mediafolder&do=add">[+] ${lang("add")}</a> &nbsp;
-      <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a>
-  </p>
-
-<include "foot.template">
+    <include "foot.template">
 </body>
 </html>
 
index 244b290..d203287 100755 (executable)
@@ -1,63 +1,43 @@
 <html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("message.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-<include "FUNCTIONS.template">
-<include "head.template">
-
-
-<form action="${config.actionRoot}" method="post">
-  <input type="hidden" name="module" value="Message">
-  <input type="hidden" name="id" value="${data.id}">
-  <if data.new>
-    <input type="hidden" name="do" value="insert">
-  <else>
-    <input type="hidden" name="do" value="update">
-  </if>
-  
-<table border="0">
+  <head>
+    <title>${config["Mir.Name"]} | ${lang("message.htmltitle")}</title>
+    <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+  <head>
+
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+    <include "FUNCTIONS.template">
+    <include "head.template">
   
-  <tr>
-    <td align="right" class="table-left">
-  ${lang("message.date")}:</td>
-    <td>
-      ${data.date}
-    </td>
-  </tr>
-
-  
-  <call TextInputTableRow (lang("message.title"), 30, 30, "title", data.title)> 
-  <call TextInputTableRow (lang("message.creator"), 12, 30, "creator", data.creator)> 
-  <call TextAreaTableRow  (lang("message.text"), "", 50, 5, "description", data.description)> 
-  
-
-
-  <tr>
-    <td class="table-foot">
-  ${lang("message.textinfo")}
-  </td>
-  
-  <td align="right" class="table-foot"> 
-  <if new>
-    <input type="submit" name="save" value="${lang("insert")}">
-    <else>
-    <input type="submit" name="save" value="${lang("save")}">
-    </if> 
-    </td>
-  </tr>
-</table>
-
-</form>
-    <p>
+      <if new=="1">
+        <assign method="insert">
+      <else>
+        <assign method="update">
+      </if>
       
-      <a class="link-box" href="${config.actionRoot}?module=Message&do=list">[&lt;] ${lang("back")} </a> &nbsp;
-      <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a>
-  </p>
-
+      
+      <call EditStart(["module", "id", "do"], [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("message.id"), entity.id)>
+        <call EditReadonlyTextNormal(lang("message.date"), entity.creationdate.format(config["Mir.DefaultDateTimeFormat"]))>
+        <call EditTextNormal(lang("message.title"), 30, 30, "title", entity.title)>
+        <call EditTextNormal(lang("message.creator"), 30, 30, "creator", entity.creator)>
+
+        <call EditTextAreaNormal(lang("message.text"), "", "50", "5", "description", entity.description)>\r
+      
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
+        <else>
+          <call EditSubmitButtonNormal(lang("save"), "save")>
+        </if> 
 
-<include "foot.template">
-</body>
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
+      <else>
+        <call showBack("module="+module+"&amp;do=list")>
+      </if>
+
+    <include "foot.template">
+  </body>
 </html>
index 42cb181..0782eac 100755 (executable)
@@ -6,63 +6,24 @@
 
 <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
 
-<include "head.template">
-
-<p>
-  <a class="link-box" href="${config.actionRoot}?module=Message&do=add">[+] ${lang("add")}</a> &nbsp;
-  <a class="link-box" href="${config.actionRoot}">[&lt;&lt;&lt;] ${lang("head.start")}</a>
-</p>
-
-<if data.contentlist>
-
-<table border="0" cellpadding="2" cellspacing="1" width="70%">
-  <tr>
-    <td class="table-head">
-    ${lang("message.date")}</td>
-    <td class="table-head">
-    ${lang("message.title")} /<br>${lang("message.creator")}</td>
-    <td colspan="2" class="table-head">
-    ${lang("message.text")}</td>
-  </tr>
-
-  <list data.contentlist as entry>
-  <tr
-    <if grey=="1">
-      <assign grey="0">class="listrow1"
-    <else>class="listrow2"
-      <assign grey="1"> 
-    </if> >
-  <td class="x-small" valign="top">${entry.webdb_create}&nbsp;</td>
-  <td valign="top"><span class="small"><b>${entry.title}</b></span><br>
-     <span class="x-small">${lang("by")}: ${entry.creator}</span></td>
-  <td>${entry.description}&nbsp;</td>
-  <td valign="top">
-      <a class="listcommand" href="${config.actionRoot}?module=Message&do=delete&id=${entry.id}">[&nbsp;${lang("delete")}&nbsp;]</a><br>
-    <a class="listcommand" href="${config.actionRoot}?module=Message&do=edit&id=${entry.id}">[&nbsp;${lang("edit")}&nbsp;]</a>
-  </td>
-  </tr>
-  </list>
-  
-  <tr>
-    <td colspan="4" class="table-foot">${data.count} ${lang("records")} /
-        ${lang("show_from_to", data.from, data.to)}</td>
+    <include "FUNCTIONS.template">
+    <include "head.template">
     
-  </tr>
-
-</table>
-
-<P>
-  <if data.prev>
-    <a class="majorcommand" href="${config.actionRoot}?module=Message&do=list&where=${data.where}&offset=${data.prev}">[&nbsp;${lang("list.previous")}&nbsp;]</a>&nbsp;
-  </if>
-  <if data.next>
-    <a class="majorcommand" href="${config.actionRoot}?module=Message&do=list&where=${data.where}&offset=${data.next}">[&nbsp;${lang("list.next")}&nbsp;]</a>
-  </if>
-
-<else>
-  <P align="center">${lang("no_matches_found")}</p>
-</if>
+    <call showAddOrBack("1", module, "Admin", "start")>
+
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, [
+           "id", "title", "creator", "description"], 
+           [ lang("message.id"), lang("message.title"), lang("message.creator"), lang("message.text")], 
+          from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "start")>
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
+    </if>
+
+    <include "foot.template">
 
-<include "foot.template">
 </body>
 </html>
diff --git a/templates/admin/other.template b/templates/admin/other.template
new file mode 100755 (executable)
index 0000000..037cb20
--- /dev/null
@@ -0,0 +1,39 @@
+<if new!="1">
+  </SCRIPT>
+
+  <tr>
+    <td align="right" valign="top">
+      <a href="${config.actionRoot}?module=${module}&do=getMedia&id=${uploadedmedia.id}">
+      <img src="/img/${uploadedmedia.big_icon}" border=0></a>&nbsp;&nbsp;
+    </td>
+    <td valign="bottom" class="small">
+      ${lang("media.created")}: ${uploadedmedia.webdb_create}
+      <if uploadedmedia.webdb_lastchange>/ ${lang("media.changed")} ${uploadedmedia.webdb_lastchange}</if><br>
+      <if uploadedmedia.is_published=="1">${lang("media.published")}: ${uploadedmedia.publish_date} / ${uploadedmedia.publish_server}${uploadedmedia.publish_path}<br></if>
+      ${lang("media.format")}: ${uploadedmedia.mimetype} / ${uploadedmedia.media_descr}<br>
+      ${lang("media.size")}: ${uploadedmedia.human_readable_size}<br>
+      ${lang("media.rights")}: <b>${uploadedmedia.rightsHashdata[to_rights]["name"]}</b><br>
+    </td>
+  </tr>
+</if>
+
+<tr>
+  <td align="right" class="table-left">
+    <B>${lang("media.mediafolder")}:</B>
+  </td>
+  <td class="listrow2">
+    <select name="to_media_folder">
+    <list mediafolders as m>
+      <option value="${m.id}" <if m.id == uploadedmedia.to_media_folder>selected</if>>${m.name}</option>
+    </list>
+      </select>
+  </td>
+</tr>
+        
+<if new!="1">
+  <call TextInputTableRow (lang("media.title"), 40, 80, "title", uploadedmedia.title)>
+</if>
+<call TextInputTableRow (lang("media.creator"), 40, 80, "creator", uploadedmedia.creator)>
+<call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", uploadedmedia.description)>
+<call TextInputTableRow (lang("media.source"), 40, 80, "source", uploadedmedia.source)>
+<call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", uploadedmedia.comment)>
index ce9631b..aa24a48 100755 (executable)
 
 <td valign="top" align="right">
 
-<p class="box" align="left"><b>${lang("producer.jobqueue.title")}</b></p>
+<p class="box" align="left"><b>${lang("producer.jobqueue.title")}</b> <a class="link-box"  href="${config.actionRoot}?${thisurl}">${lang("producer.jobqueue.refresh")}</a></p>
 
+<form method="post" action="${config.actionRoot}">
+      <input type="hidden" name="module" value="Producer">
+      <input type="hidden" name="do" value="cancel">
+      
 <table border="0" cellspacing="3" cellpadding="2">
   <tr >
-    <td class="bg-neutral" colspan="2"><b>${lang("producer.job.name")}</b></td>
-    <td class="bg-neutral" ><b>${lang("producer.job.status")}</b></td>
-    <td class="bg-neutral small" ><b>${lang("producer.job.date")}</b></td>
-    <comment>    
-    <td class="box-head" >&nbsp;</td>
-    </comment>    
+    <td class="bg-neutral"><b>${lang("producer.job.name")}</b></td>
+    <td class="bg-neutral"><b>${lang("producer.job.status")}</b></td>
+    <td class="bg-neutral small"><b>${lang("producer.job.date")}</b></td>
+    <td class="bg-neutral small"><b>${lang("producer.job.runningtime")}</b></td>
+    <td class="bg-neutral">&nbsp;</td>
   </tr>
 
   <if queue>
     <assign grey="1">
     <list queue as q>
       <tr <if grey=="1">class="listrow1"<else>class="listrow2"</if>>
-        <td class="small">${q.factory}</td>
-        <td class="small">(${q.verb})</td>
+        <td class="small">${q.description}</td>
         
         <if q.status=="pending">
           <td class="text-alert small">${q.status}</td>
           <td class="small">${q.status}</td>
         </if>
         
-        <td class="small">${q.lastchange["HH:mm:ss"]}</td>
-        <comment> ML: needs to be implemented       
-          <td><a href="${config.actionRoot}?module=Producer&do=abort">${lang("producer.job.cancel")}</a></td>
-        </comment>        
+        <td class="small">${q.lastchange.format("HH:mm:ss")}</td>
+        <td class="small">${q.runningtime.format("####.#")}s</td>
+        <td class="small">
+          <if q.finished!="1">
+            <input type="checkbox" name="jobid" value="${q.identifier}">
+          <else>
+            &nbsp;
+          </if>  
+        </td>
       </tr>
       <if grey=="1"><assign grey="0"><else><assign grey="1"></if>
     </list>
     </tr>
   </if>
   <tr>
-    <td colspan="5" class="table-foot">
+    <td colspan="5" class="table-foot" align="left">
       <br>
-      <a class="link-box"  href="${config.actionRoot}?${thisurl}">${lang("producer.jobqueue.refresh")}</a>
+      <input class="minorbutton" type="submit" value="${lang("producer.jobqueue.canceljobs")}">
     </td>
   </tr>
 </table>
+</form>
 
 </td></tr></table>
 
index 903f410..fd89391 100755 (executable)
       <list administeroperations as a>
           <a href="${config.actionRoot}?${a.url}">${lang("start.administer."+a.name)}</a><br>
       </list>
-<!--      
-      <a href="${config.actionRoot}?module=Content&do=list&where=is_published%3d'1'%20and%20to_article_type%3D0&order=webdb_create%20desc">&gt; ${lang("start.allarticlesoftype", lang("articletypes.openposting"))}</a>  
-      <br>
-      <a href="${config.actionRoot}?module=Comment&do=list">
-        &gt; ${lang("start.content.comments")}
-      </a>
--->     
     </p>
 
-    <p class="box-head"><b>${lang("start.list.title")}</b></p>  
+    <p class="box-head"><b>${lang("start.articles.title")}</b></p>  
     <p class="box">
       <list articletypes as a>
-          <a href="${config.actionRoot}?module=Content&do=list&where=is_published%3d'1'%20and%20to_article_type%3D${a.id}&order=webdb_create%20desc">&gt; ${lang("start.allarticlesoftype", lang("articletypes."+a.name))}</a><br>
+          <a href="${config.actionRoot}?module=Content&do=search&searcharticletype=${a.id}&searchorder=datedesc">&gt; ${lang("start.allarticlesoftype", lang("articletypes."+a.name))}</a><br>
       </list>
       <br>  
       <a href="${config.actionRoot}?module=Content&do=list&where=${utility.encodeURI("is_published='f'")}&order=${utility.encodeURI("webdb_create desc")}" >&gt; ${lang("start.content.not_published")}</a><br>
       <br>
       <a href="${config.actionRoot}?module=Content&do=list&where=&order=${utility.encodeURI("webdb_create desc")}">&gt; ${lang("start.content.all")}</a><br>
     </p>
+    <p class="box-head"><b>${lang("start.comments.title")}</b></p>  
+    <p class="box">
+      <list commentstatuses as a>
+          <a href="${config.actionRoot}?module=Comment&do=list&where=to_comment_status%3D${a.id}&order=webdb_create%20desc">&gt; ${lang("start.allcommentswithstatus", lang("commentstatus."+a.name))}</a><br>
+      </list>
+    </p>
+
 
     <p class="box-head"><b>${lang("start.extra.title")}</b></p>   
     <p class="box"> 
       <form>
         <input type="hidden" name="module" value="Content">
         <input type="hidden" name="do" value="edit">
-        ${lang("start.open_by_id")}: 
+        ${lang("start.content.open_by_id")}: 
+        <input type="text" name="id" value="" size="7">
+        <input type="submit" value=" &gt; ">
+      </form>
+      <form>
+        <input type="hidden" name="module" value="Comment">
+        <input type="hidden" name="do" value="edit">
+        ${lang("start.comment.open_by_id")}: 
         <input type="text" name="id" value="" size="7">
         <input type="submit" value=" &gt; ">
       </form>
             <if m.title><b>${m.title}</b><br></if>
             ${m.description}<br>
             <span class="x-small">
-              <if m.creator><i>by: ${m.creator}</i> / </if>${m.webdb_create}<br>
+              <if m.creator><i>by: ${m.creator}</i> / </if>${m.creationdate.format(config["Mir.DefaultDateTimeFormat"])}}<br>
             </span>
           </p>
         </list>
       <div class="box">
         <call ContentSearch ("")>
       </div>
-      
+
+<comment>      
       <!-- HELP -DEMO -->
       <p class="box">
         <b>HELP-Demo:</b><br>
         popup small-link: <call Help ("../help/content_datum.html", "1", "" )>&nbsp;&nbsp;  popup big-link: <call Help ("../help/content_datum.html", "1", "1" )><br><br>
         newwin small-link: <call Help ("../help/content_datum.html", "", "" )>&nbsp;&nbsp; newwin big-link: <call Help ("../help/content_datum.html", "", "1" )>
       </p>
-      
+</comment>      
       
     </td>
-    <td>&nbsp;</td>
   </tr>
   
 </table>
index 999547d..3fae6b8 100755 (executable)
@@ -6,36 +6,42 @@
 
   <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
     <include "FUNCTIONS.template">
+    <include "head.template">
   
-  <include "head.template">
-
-    <form action="${config.actionRoot}" method="post">
-      <input type=hidden name=module value=Topics>
-      <input type="hidden" name="id" value="${data.id}">
-      <if data.new>
-        <input type="hidden" name="do" value="insert">
+      <if new=="1">
+        <assign method="insert">
       <else>
-        <input type="hidden" name="do" value="update">
+        <assign method="update">
       </if>
+      
+      <call EditStart(
+         ["module", "id", "do"],
+         [module, entity.id, method])>
+         
+        <call EditReadonlyTextNormal(lang("topic.id"), entity.id)>
+         
+        <call EditTextNormal(lang("topic.title"), 40, 255, "title", entity.title)>
+        <call EditTextAreaNormal(lang("topic.description"), "", 40, 3, "description", entity.description)>
+        <call EditTextNormal(lang("topic.filename"), 20, 255, "filename", entity.filename)>
+        <call EditTextNormal(lang("topic.main_url"), 40, 255, "main_url", entity.main_url)>
+        <call EditTextNormal(lang("topic.archive_url"), 40, 255, "archiv_url", entity.archiv_url)>
+        
+        
+      
+        <if new=="1">
+          <call EditSubmitButtonNormal(lang("insert"), "save")>
+        <else>
+          <call EditSubmitButtonNormal(lang("save"), "save")>
+        </if> 
 
-      <table border="0">
-    <call TextInputTableRow (lang("topic.title"), 40, 255, "title", data.title)>
-    <call TextAreaTableRow (lang("topic.description"), "", 40, 3, "description", data.description)>
-    <call TextInputTableRow (lang("topic.filename"), 20, 255, "filename", data.filename)>
-    <call TextInputTableRow (lang("topic.main_url"), 40, 255, "main_url", data.main_url)>
-    <call TextInputTableRow (lang("topic.archive_url"), 40, 255, "archiv_url", data.archiv_url)>
+      <call EditEnd()>
+      
+      <if returnurl>
+        <call showBack(returnurl)>
+      <else>
+        <call showBack("module=Topics&do=list")>
+      </if>
 
-          <td class="table-foot" colspan="2" align="right"> 
-          <if data.new>
-            <input type="submit" name="save" value="${lang("insert")}">
-          <else>
-            <input type="submit" name="save" value="${lang("save")}">
-          </if> 
-          </td>
-        </tr>
-      </table>    
-    </form>
-  <p><a class="link-box" href="${config.actionRoot}?module=Topics&do=list">[&lt;] ${lang("back")} </a> &nbsp;</p>
     <include "foot.template">
   </body>
 </html>
index 21a3c58..6a08c89 100755 (executable)
@@ -6,36 +6,32 @@
 
   <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
 
-
     <include "FUNCTIONS.template">
-  
     <include "head.template">
-
-    <comment>configure this template here</comment>
-    <assign contentlist = data.contentlist>
-    <assign column_nr = 5>
-    <assign column_head_texts = [lang("topic.title"), lang("topic.description"), lang("topic.main_url"), lang("topic.archive_url")]>
-    <assign data_keys = ["title", "description", "main_url", "archiv_url"]>
-    <assign column_head_CSS = "table_head">
-    <assign listrow1CSS = "listrow1">
-    <assign listrow2CSS = "listrow2">
-    <assign footer_css = "table_foot">
-    <assign module_name = "Topics">
-    <assign module_jumpback = "Admin">
-    <assign do_jumpback = "superusermenu">
-
-    <if data.contentlist>
-    <call AddOrBack(module_name, module_jumpback, do_jumpback)>
-    <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>   
-    <call PrevNextPage(module_name)>    
-   <else>
-    <P align="center">${lang("no_matches_found")}</p>
-    </if>
     
-  <call AddOrBack(module_name, module_jumpback, do_jumpback)>
+    <call showAddOrBack("1", module, "Admin", "superusermenu")>
+
+    <if entities>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(entities, [
+           "title", 
+           "filename", 
+           "main_url", 
+           "archiv_url",
+           "description"], 
+           [ lang("topic.title"), 
+             lang("topic.filename"), 
+             lang("topic.main_url"), 
+             lang("topic.archive_url"), 
+             lang("topic.description")], 
+          from, to, count, "1", "1", module)>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack("1", module, "Admin", "superusermenu")>
+    <else>
+      <P align="center">${lang("no_matches_found")}</p>
+    </if>
 
     <include "foot.template">
-  
   </body>
 </html>
 
diff --git a/templates/admin/uploadedmedia.template b/templates/admin/uploadedmedia.template
new file mode 100755 (executable)
index 0000000..72d0f8a
--- /dev/null
@@ -0,0 +1,100 @@
+<html>
+  <head>
+    <title>${config["Mir.Name"]}<comment> | ${lang("image.htmltitle")}</comment></title>
+    <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+  <head>
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+
+    <include "FUNCTIONS.template">
+    <include "head.template">
+
+    <if new=="1">
+      <form action="${config.actionRoot}?module=${module}&do=add" method="post">
+
+        <input type="hidden" name="returnurl" value="${returnurl}">
+      <if articleid>
+          <input type="hidden" name="articleid" value="${articleid}">
+      </if>
+      <if commentid>
+          <input type="hidden" name="commentid" value="${commentid}">
+      </if>
+        <table border="0">
+          <tr>
+            <td align="right" class="table-left">
+              <b>${lang("media.nr_of_media")} :</b><br>
+            </td>
+            <td class="listrow2">
+              <input type="text" size="3" name="nrmedia" value="${nrmedia}">&nbsp;&nbsp;<input type="submit" value="${lang("media.nr_of_media.submit")}">
+            </td>
+          </tr>
+        </table>
+      </form>
+    </if>
+
+
+    <form enctype="multipart/form-data" method="post" action="${config.actionRoot}?module=${module}&do=<if new=="1">insert<else>update</if>&id=${uploadedmedia.id}">
+      <if articleid>
+        <input type="hidden" name="articleid" value="${articleid}">
+      </if>
+      <if commentid>
+        <input type="hidden" name="commentid" value="${commentid}">
+      </if>
+      <input type="hidden" name="returnurl" value="${returnurl}">
+      <input type="hidden" name="id" value="${uploadedmedia.id}">
+    
+      <table border="0">
+    
+        <include edittemplate>
+      
+        <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
+      
+        <if new=="1">
+          <tr>
+            <td align="right" class="table-left">
+              ${lang("media.is_published")} : 
+            </td>
+            <td class="listrow2" style='border: 1px solid #FF0000;'>
+              <input type="checkbox" name="is_published" value="1"<if uploadedmedia.is_published!="0" && uploadedmedia.is_published!=""> checked</if>>  
+            </td>
+          </tr>
+          
+          <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
+          
+          <list mediafields as m>
+              <tr>
+                <td align="right" class="table-left">
+                  <B>${lang("media.title")}:<B>
+                 </td>
+                <td class="listrow2">
+                  <input type="text" name="media_title${m}" size="40" maxlength="80" value="">
+                </td>
+              </tr>
+              <tr>
+                <td align="right">
+                  &nbsp;
+                </td>
+                <td class="listrow2">
+                  <input type="file" name="media${m}"><br>
+                </td>
+              </tr>
+          </list>
+        </if>
+        
+        <tr>
+          <td colspan="2" align="right" class="table-foot">
+            <if new=="1">
+              <input type="submit" name="save" value="${lang("insert")}">
+            <else>
+              ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if uploadedmedia.is_published!="0" && uploadedmedia.is_published!=""> checked</if>>
+              &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
+            </if> 
+          </td>
+        </tr>
+      </table>
+    </form>
+    
+    <p><a class="link-box" href="${config.actionRoot}?module=${module}&do=list">[&lt;] ${lang("list")} </a> &nbsp;</p>
+
+    <include "foot.template">
+  </body>
+</html>
index a4df489..ddef833 100755 (executable)
 
 <form action="${config.actionRoot}" method="post">
   <input type="hidden" name="module" value="Users">
-  <input type="hidden" name="id" value="${data.id}">
-  <if data.new>
-    <input type="hidden" name="do" value="insert">
+  <input type="hidden" name="id" value="${user.id}">
+  <if passwordonly=="1">
+      <input type="hidden" name="do" value="updatepassword">
   <else>
-    <input type="hidden" name="do" value="update">
+    <if new=="1">
+      <input type="hidden" name="do" value="insert">
+    <else>
+      <input type="hidden" name="do" value="update">
+    </if>
   </if>
 
   <table border="0">
-    <call TextInputTableRow (lang("user.login"), 40, 40, "login", data.login)>
+    <if passwordonly=="1">
+      <call ReadonlyTextTableRow(lang("user.login"), user.login)>
+      <call PasswordTextInputTableRow (lang("user.oldpassword"), 40, 40, "oldpassword", "")>
+    <else>
+      <call TextInputTableRow (lang("user.login"), 40, 40, "login", user.login)>
+      <call PasswordTextInputTableRow (lang("user.ownpassword"), 40, 40, "oldpassword", "")>
+    </if>
     <call PasswordTextInputTableRow (lang("user.password"), 40, 40, "newpassword", "")>
     <call PasswordTextInputTableRow (lang("user.password2"), 40, 40, "newpassword2", "")>
-    <tr>
-      <td align="right" class="table-left">
-        <b>${lang("user.admin")}:</b>
-      </td>
-      <td class="listrow2">
-        <input type="checkbox" name="is_admin" value="1"<if data.is_admin=="1"> checked</if>>
-      </td>
-    </tr>
+    <if passwordonly=="1">
+      <call ReadonlyTextTableRow(lang("user.admin"), user.is_admin)>
+    <else>
+      <call CheckboxTableRow(lang("user.admin"), "is_admin", user.is_admin)>
+    </if>
     <tr>
     <td colspan="2" align="right" class="table-foot"> 
       <span class="witetext">
-      <if data.new>
+      <if new=="1">
         <input type="submit" name="save" value="${lang("insert")}">
       <else>
         <input type="submit" name="save" value="${lang("save")}">
     </tr>
   </table>
 </form>
-  
-  <p><a class="link-box" href="${config.actionRoot}?module=Users&do=list">[&lt;] ${lang("back")} </a> &nbsp;</p>
-  
+  <if passwordonly>
+    <call showBack("")>
+  <else>
+    <call showBack("module=Users&amp;do=list")>
+  </if>
+
   <include "foot.template">
 
 </body>
index 567dddf..c97ebfb 100755 (executable)
@@ -9,30 +9,16 @@
     <include "FUNCTIONS.template">
     <include "head.template">
     
-    <assign contentlist = data.contentlist>
-    <assign column_nr = 3>
-    
-    <assign column_head_texts = [lang("user.login"), lang("user.admin")]>   
-    <assign data_keys = ["login","is_admin"]>
-    <assign column_head_CSS = "table_head">
-    <assign listrow1CSS = "listrow1">
-    <assign listrow2CSS = "listrow2">
-    <assign footer_css = "table_foot">
-    <assign module_name = "Users">
-    <assign module_jumpback = "Admin">
-    <assign do_jumpback = "superusermenu">
-  
-
-  
-  <call AddOrBack(module_name, module_jumpback, do_jumpback)>
+    <call showAddOrBack(mayAddUsers, "Users", "Admin", "superusermenu")>
 
-    <if data.contentlist>
-    <call ListTable(contentlist, data_keys, column_head_texts, column_head_CSS, listrow1CSS, listrow2CSS, footer_css, module_name)>
-    <call AddOrBack(module_name, module_jumpback, do_jumpback)>
-  <else>
+    <if users>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call EntityTable(users, ["login","is_admin"], [lang("user.login"), lang("user.admin")], from, to, count, mayDeleteUsers, mayEditUsers, "Users")>
+      <call showPrevNextLinks(prevurl, nexturl, "left")>
+      <call showAddOrBack(mayAddUsers, "Users", "Admin", "superusermenu")>
+    <else>
       <P align="center">${lang("no_matches_found")}</p>
     </if>
-    
 
     <include "foot.template">
   </body>
index 7cd4fcc..037cb20 100755 (executable)
-<html>
-<head>
-        <title>${config["Mir.Name"]} | ${lang("video.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-<head>
-<SCRIPT LANGUAGE="JavaScript">
-function openWin(url) {
-   window.open(url,"vc","scrollbars=0,height=${data.img_height},width=${data.img_width}");
-}
-</SCRIPT>
-
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-<include "FUNCTIONS.template">
-<include "head.template">
-
-<if data.new>
-<form action="${config.actionRoot}?module=Video&do=add" method="post">
-  <if data.articleid>
-    <input type="hidden" name="articleid" value="${data.articleid}">
-  </if>
-  <if data.commentid>
-    <input type="hidden" name="commentid" value="${data.commentid}">
-  </if>
-  <table border="0">
-    <tr>
-      <td align="right" class="table-left">
-        <b>${lang("media.nr_of_media")} :</b><br>
-      </td>
-      <td class="listrow2">
-        <input type="text" size="3" name="medianum" value="${medianum}">&nbsp;&nbsp;<input type="submit" value="${lang("media.nr_of_media.submit")}">
-      </td>
-    </tr>
-  </table>
-</form>
+<if new!="1">
+  </SCRIPT>
+
+  <tr>
+    <td align="right" valign="top">
+      <a href="${config.actionRoot}?module=${module}&do=getMedia&id=${uploadedmedia.id}">
+      <img src="/img/${uploadedmedia.big_icon}" border=0></a>&nbsp;&nbsp;
+    </td>
+    <td valign="bottom" class="small">
+      ${lang("media.created")}: ${uploadedmedia.webdb_create}
+      <if uploadedmedia.webdb_lastchange>/ ${lang("media.changed")} ${uploadedmedia.webdb_lastchange}</if><br>
+      <if uploadedmedia.is_published=="1">${lang("media.published")}: ${uploadedmedia.publish_date} / ${uploadedmedia.publish_server}${uploadedmedia.publish_path}<br></if>
+      ${lang("media.format")}: ${uploadedmedia.mimetype} / ${uploadedmedia.media_descr}<br>
+      ${lang("media.size")}: ${uploadedmedia.human_readable_size}<br>
+      ${lang("media.rights")}: <b>${uploadedmedia.rightsHashdata[to_rights]["name"]}</b><br>
+    </td>
+  </tr>
 </if>
 
-
-    <form enctype="multipart/form-data" method="post" action="${config.actionRoot}?module=Video&do=<if data.new>insert<else>update</if>&id=${data.id}">
-      <if data.articleid>
-        <input type="hidden" name="articleid" value="${data.articleid}">
-      </if>
-      <if data.commentid>
-        <input type="hidden" name="commentid" value="${data.commentid}">
-      </if>
-  
-      <input type="hidden" name="where" value="${data.where}">
-      <input type="hidden" name="offset" value="${data.offset}">
-      <input type="hidden" name="order" value="${data.order}">
-      <input type="hidden" name="id" value="${data.id}">
-
-      <table border="0">
-      
-        <if !data.new>
-        <tr>
-            <td align="right" valign="top">
-            <a href="${config.actionRoot}?module=Video&do=getMedia&id=${data.id}">
-                <img src="${config.docRoot}/img/${data.big_icon}" border=0></a>&nbsp;&nbsp;
-          </td>
-          <td valign="bottom" class="small">
-            ${lang("media.created")}: ${data.webdb_create}
-            <if data.webdb_lastchange>/ ${lang("media.changed")} ${data.webdb_lastchange}</if><br>
-            <if data.is_published=="1">${lang("media.published")}: ${data.publish_date} / ${data.publish_server}${data.publish_path}<br></if>
-            ${lang("media.format")}: ${data.mimetype} / ${data.media_descr}<br>
-            ${lang("media.size")}: ${data.human_readable_size}<br>
-            ${lang("media.rights")}: <b>${data.rightsHashdata[to_rights]["name"]}</b><br>
-          </td>
-          </tr>
-        </if>
-      
-        <tr>
-          <td align="right" class="table-left">
-            <B>${lang("media.mediafolder")}:</B>
-          </td>
-          <td class="listrow2">
-            <select name="to_media_folder">
-            <list extra.mediafolderPopupData as m>
-              <option value="${m.key}" <if m.key == data.to_media_folder>selected</if>>${m.value}</option>
-            </list>
-              </select>
-          </td>
-        </tr>
-      
-        <if !data.new>
-          <call TextInputTableRow (lang("media.title"), 40, 80, "title", data.title)>
-        </if>
-        <call TextInputTableRow (lang("media.date"), 8, 8, "date", data.date)>
-        <call TextInputTableRow (lang("media.creator"), 40, 80, "creator", data.creator)>
-        <call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", data.description)>
-        <call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", data.comment)>
-        <call TextInputTableRow (lang("media.source"), 40, 80, "source", data.source)>
-        
-        <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
+<tr>
+  <td align="right" class="table-left">
+    <B>${lang("media.mediafolder")}:</B>
+  </td>
+  <td class="listrow2">
+    <select name="to_media_folder">
+    <list mediafolders as m>
+      <option value="${m.id}" <if m.id == uploadedmedia.to_media_folder>selected</if>>${m.name}</option>
+    </list>
+      </select>
+  </td>
+</tr>
         
-        
-        <if data.new>
-          <tr>
-            <td align="right" class="table-left">
-              ${lang("media.is_published")} : 
-            </td>
-            <td class="listrow2" style='border: 1px solid #FF0000;'>
-              <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>> 
-            </td>
-          </tr>
-          <tr><td colspan="2" class="x-small">&nbsp;</td></tr>
-          
-          <list data.mediafields as m>
-          <tr>
-            <td align="right" class="table-left">
-              <B>${lang("media.title")}:<B>
-             </td>
-            <td class="listrow2">
-              <input type="text" name="media_title${m}" size="40" maxlength="80" value="">
-            </td>
-          </tr>
-          <tr>
-            <td align="right">
-              &nbsp;
-            </td>
-            <td class="listrow2">
-              <input type="file" name="media${m}"><br>
-            </td>
-          </tr>
-          </list>
-        </if>
-      
-        <td colspan="2" align="right" class="table-foot">
-        <if data.new>
-          <input type="submit" name="save" value="${lang("insert")}">
-        <else>
-          ${lang("media.is_published")} <input type="checkbox" name="is_published" value="1"<if data.is_published!="0" && data.is_published!=""> checked</if>>
-          &nbsp;&nbsp;<input type="submit" name="save" value="${lang("save")}">
-        </if> 
-        </td>
-      </table>
-    </form>
-
-    <p><a class="link-box" href="${config.actionRoot}?module=Video&do=list">[&lt;] ${lang("list")} </a> &nbsp;</p>
-
-    <include "foot.template">
-
-  </body>
-</html>
+<if new!="1">
+  <call TextInputTableRow (lang("media.title"), 40, 80, "title", uploadedmedia.title)>
+</if>
+<call TextInputTableRow (lang("media.creator"), 40, 80, "creator", uploadedmedia.creator)>
+<call TextAreaTableRow  (lang("media.description"), "", 40, 2, "description", uploadedmedia.description)>
+<call TextInputTableRow (lang("media.source"), 40, 80, "source", uploadedmedia.source)>
+<call TextAreaTableRow  (lang("media.comment"), "", 40, 2, "comment", uploadedmedia.comment)>
index 852fb6d..c516599 100755 (executable)
@@ -1,17 +1,16 @@
 <html>
-<head>
-  <title>${config["Mir.Name"]} | ${lang("video.htmltitle")}</title>
-        <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
-</head>
+  <head>
+    <title>${config["Mir.Name"]} | ${lang("video.htmltitle")}</title>
+    <link rel="stylesheet" type="text/css" href="${config.docRoot}/style/admin.css">
+  </head>
+  
+  <body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
+    <include "head.template">
+    <include "FUNCTIONS_media.template">
 
-<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0">
-
-<include "head.template">
-<include "FUNCTIONS_media.template">
-<call MediaSearch ("Video")>
-<p>&nbsp;</p>
-<call MediaList   ("Video")>
-
-<include "foot.template">
-</body>
+    <call MediaSearch ("Video")>
+    <p>&nbsp;</p>
+    <call MediaList   ("Video")>
+    <include "foot.template">
+  </body>
 </html>
diff --git a/web/img/pdfbanner.png b/web/img/pdfbanner.png
new file mode 100755 (executable)
index 0000000..f4eeedb
Binary files /dev/null and b/web/img/pdfbanner.png differ
index 21c49a7..4b528a4 100755 (executable)
@@ -144,6 +144,10 @@ a:hover            {
        padding-right:8px;
        border:1px solid #990000;  
 }
+.link-box-div {
+       padding-top:5px;
+       padding-bottom:5px;
+}
 
 .link-help {  
        background-color:#DDDDDD; 
@@ -178,7 +182,19 @@ a:hover            {
 }  
 
 .small {font-size: 0.8em;}
-.x-small       {font-size: 0.7em;}
+.x-small       {font-size: 0.8em;}
 
 .lynx            { display:none; }
 
+.majorbutton {
+}
+
+.minorbutton {
+       background-color:#DDDDDD; 
+       color: #990000;
+       font-size:1em;
+       padding:2px;
+       padding-left:8px;
+       padding-right:8px;
+//     border:1px solid #990000;  
+}