001/*
002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Florent Guillaume
016 */
017package org.nuxeo.ecm.platform.htmlsanitizer;
018
019import org.nuxeo.ecm.core.api.DocumentModel;
020import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
021import org.nuxeo.ecm.core.event.Event;
022import org.nuxeo.ecm.core.event.EventContext;
023import org.nuxeo.ecm.core.event.EventListener;
024import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
025import org.nuxeo.ecm.core.schema.FacetNames;
026import org.nuxeo.runtime.api.Framework;
027
028/**
029 * Listener that sanitizes some HTML fields to remove potential cross-site scripting attacks in them.
030 */
031public class HtmlSanitizerListener implements EventListener {
032
033    public static final String DISABLE_HTMLSANITIZER_LISTENER = "disableHtmlSanitizerListener";
034
035    public void handleEvent(Event event) {
036        String eventId = event.getName();
037        if (!eventId.equals(DocumentEventTypes.ABOUT_TO_CREATE)
038                && !eventId.equals(DocumentEventTypes.BEFORE_DOC_UPDATE)) {
039            return;
040        }
041        EventContext context = event.getContext();
042        if (!(context instanceof DocumentEventContext)) {
043            return;
044        }
045        Boolean disableListener = (Boolean) context.getProperty(DISABLE_HTMLSANITIZER_LISTENER);
046        if (Boolean.TRUE.equals(disableListener)) {
047            return;
048        }
049
050        DocumentModel doc = ((DocumentEventContext) context).getSourceDocument();
051        if (doc.hasFacet(FacetNames.IMMUTABLE)) {
052            return;
053        }
054        HtmlSanitizerService sanitizer = Framework.getService(HtmlSanitizerService.class);
055        sanitizer.sanitizeDocument(doc);
056    }
057
058}