001/* 002 * Copyright 2011 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.plugins.forms; 017 018import org.apache.cocoon.xml.AttributesImpl; 019import org.xml.sax.Attributes; 020import org.xml.sax.SAXException; 021 022import org.ametys.cms.contenttype.DockbookUpdateHandler; 023import org.ametys.web.repository.content.SharedContent; 024 025/** 026 * This handler look for CMS forms in a RichText. 027 * It must be used after a copy of a Content to changes theses references if necessary. 028 */ 029public class FormDocbookUpdateHandler extends DockbookUpdateHandler 030{ 031 @Override 032 public void startElement(String uri, String loc, String raw, Attributes attrs) throws SAXException 033 { 034 if (!(_createdContent instanceof SharedContent) && "form".equals(loc)) 035 { 036 Attributes newAttrs = _getAttributesForForm(attrs); 037 super.startElement(uri, loc, raw, newAttrs); 038 return; 039 } 040 041 super.startElement(uri, loc, raw, attrs); 042 } 043 044 /** 045 * Get attributes for media objects such as image, flash 046 * @param attrs the attributes 047 * @return the new attributes 048 */ 049 protected Attributes _getAttributesForForm (Attributes attrs) 050 { 051 String type = attrs.getValue("type"); 052 if (!(_createdContent instanceof SharedContent) && "cms".equals(type)) 053 { 054 String updateId = _generateFormId(); 055 056 AttributesImpl newAttrs = new AttributesImpl(); 057 _copyAttributes(attrs, newAttrs); 058 newAttrs.addAttribute("", "id", "id", "CDATA", updateId); 059 060 return newAttrs; 061 } 062 else 063 { 064 return attrs; 065 } 066 067 } 068 069 /** 070 * Copy attributes 071 * @param attrs the attributes to copy 072 * @param newAttrs the new attributes 073 */ 074 protected void _copyAttributes(Attributes attrs, AttributesImpl newAttrs) 075 { 076 for (int i = 0; i < attrs.getLength(); i++) 077 { 078 String name = attrs.getQName(i); 079 080 if (!"id".equals(name)) 081 { 082 newAttrs.addAttribute(attrs.getURI(i), attrs.getLocalName(i), name, attrs.getType(i), attrs.getValue(i)); 083 } 084 } 085 } 086 087 /** 088 * Generate a new form id 089 * @return a form id 090 */ 091 protected String _generateFormId () 092 { 093 // random 15-digit number 094 long random = Math.round((Math.random() * 0.9 + 0.1) * Math.pow(10, 15)); 095 return "form_" + String.valueOf(random); 096 } 097}