View Javadoc
1   /**
2    * This file Copyright (c) 2013-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.dam.app.ui.field.factory;
35  
36  import info.magnolia.dam.api.Asset;
37  import info.magnolia.dam.api.AssetProviderRegistry;
38  import info.magnolia.dam.api.DamException;
39  import info.magnolia.dam.api.ItemKey;
40  import info.magnolia.dam.jcr.DamConstants;
41  import info.magnolia.i18nsystem.SimpleTranslator;
42  import info.magnolia.link.LinkException;
43  import info.magnolia.link.LinkUtil;
44  import info.magnolia.ui.api.app.AppController;
45  import info.magnolia.ui.api.app.ChooseDialogCallback;
46  import info.magnolia.ui.api.context.UiContext;
47  import info.magnolia.ui.form.field.definition.RichTextFieldDefinition;
48  import info.magnolia.ui.form.field.factory.RichTextFieldFactory;
49  import info.magnolia.ui.vaadin.integration.contentconnector.ContentConnector;
50  import info.magnolia.ui.vaadin.integration.jcr.JcrNodeItemId;
51  import info.magnolia.ui.vaadin.richtext.MagnoliaRichTextField;
52  import info.magnolia.ui.vaadin.richtext.MagnoliaRichTextFieldConfig;
53  
54  import java.util.Locale;
55  import java.util.regex.Matcher;
56  import java.util.regex.Pattern;
57  
58  import javax.inject.Inject;
59  
60  import org.apache.commons.lang3.StringUtils;
61  
62  import com.google.gson.Gson;
63  import com.vaadin.data.Item;
64  import com.vaadin.data.util.converter.Converter;
65  import com.vaadin.server.VaadinService;
66  import com.vaadin.ui.Field;
67  import com.vaadin.ui.UI;
68  
69  /**
70   * Extension of {@link RichTextFieldFactory} that overrides the fileBrowser plugin used in CKEditor's image link dialog, in order to enable to pick an image from assets.
71   *
72   * @see info.magnolia.ui.form.field.factory.RichTextFieldFactory
73   */
74  public class AssetsEnabledRichTextFieldFactory extends RichTextFieldFactory {
75  
76      private static final String FILE_BROWSER_PLUGIN = "magnoliaFileBrowser";
77  
78      private static final String FILE_BROWSER_PLUGIN_CHOOSE_ASSET_EVENT = "chooseAsset";
79  
80      public static final String ASSET_CHOSEN_EVENT_ID = "assetChosen";
81  
82      private AssetProviderRegistry assetProviderRegistry;
83  
84      private static final Pattern IMAGE_PATTERN = Pattern.compile(
85              "(<img " + // start <img
86                      "[^>]*" +  // some attributes
87                      "src[ ]*=[ ]*\")" + // start src
88                      "([^\"]*)" + // the link
89                      "(\"" + // ending "
90                      "[^>]*" + // any attributes
91                      ">)"); // end the tag
92  
93      @Inject
94      public AssetsEnabledRichTextFieldFactory(RichTextFieldDefinition definition, Item relatedFieldItem, AppController appController, UiContext uiContext, SimpleTranslator i18n, AssetProviderRegistry assetProviderRegistry) {
95          super(definition, relatedFieldItem, appController, uiContext, i18n);
96          this.assetProviderRegistry = assetProviderRegistry;
97      }
98  
99      /**
100      * @deprecated since 2.0.4 use {@link #AssetsEnabledRichTextFieldFactory(RichTextFieldDefinition, Item, AppController, UiContext, SimpleTranslator, AssetProviderRegistry)}; won't inject dam's content connector magically.
101      */
102     @Deprecated
103     public AssetsEnabledRichTextFieldFactory(RichTextFieldDefinition definition, Item relatedFieldItem, AppController appController, UiContext uiContext, SimpleTranslator i18n, AssetProviderRegistry assetProviderRegistry, ContentConnector contentConnector) {
104         this(definition, relatedFieldItem, appController, uiContext, i18n, assetProviderRegistry);
105     }
106 
107     @Override
108     protected Field<String> createFieldComponent() {
109         MagnoliaRichTextField field = (MagnoliaRichTextField) super.createFieldComponent();
110         if (definition.isImages() || StringUtils.isNotBlank(definition.getConfigJsFile())) {
111             // Hook in plugin listener to trigger assets choose dialog
112             field.addListener(new MagnoliaRichTextField.PluginListener() {
113                 @Override
114                 public void onPluginEvent(String eventName, String value) {
115                     if (eventName.equals(FILE_BROWSER_PLUGIN_CHOOSE_ASSET_EVENT)) {
116                         UI.getCurrent().addStyleName("ui-overlapping-ck-editor");
117                         chooseAsset();
118                     }
119                 }
120             });
121 
122             field.setConverter(new Converter<String, String>() {
123                 @Override
124                 public String convertToModel(String value, Class<? extends String> targetType, Locale locale) throws ConversionException {
125                     return LinkUtil.convertAbsoluteLinksToUUIDs(value);
126                 }
127 
128                 @Override
129                 public String convertToPresentation(String value, Class<? extends String> targetType, Locale locale) throws ConversionException {
130                     if (value != null) {
131                         // transform plain image links (img src attributes) to display images in the editor
132                         // but do *not* transform link hrefs — magnolialink plugin currently only supports the uuid pattern to keep them editable
133                         try {
134                             Matcher matcher = IMAGE_PATTERN.matcher(value);
135                             while (matcher.find()) {
136                                 value = value.replace(matcher.group(), LinkUtil.convertLinksFromUUIDPattern(matcher.group()));
137                             }
138                             return value;
139                         } catch (LinkException e) {
140                             return StringUtils.EMPTY;
141                         }
142                     }
143                     return StringUtils.EMPTY;
144                 }
145 
146                 @Override
147                 public Class<String> getModelType() {
148                     return String.class;
149                 }
150 
151                 @Override
152                 public Class<String> getPresentationType() {
153                     return String.class;
154                 }
155             });
156         }
157         return field;
158     }
159 
160     private void chooseAsset() {
161         appController.openChooseDialog("assets", uiContext, null, new ChooseDialogCallback() {
162             @Override
163             public void onItemChosen(String actionName, Object chosenValue) {
164                 UI.getCurrent().removeStyleName("ui-overlapping-ck-editor");
165 
166                 Gson gson = new Gson();
167                 String eventJson = "{}";
168                 Asset asset;
169 
170                 try {
171                     if (!(chosenValue instanceof JcrNodeItemId)) {
172                         return;
173                     }
174                     asset = assetProviderRegistry.getProviderById(DamConstants.DEFAULT_JCR_PROVIDER_ID).getAsset(new ItemKey(DamConstants.DEFAULT_JCR_PROVIDER_ID, ((JcrNodeItemId) chosenValue).getUuid()));
175                     if (asset != null && asset.getMimeType().matches("image.*")) {
176                         eventJson = gson.toJson(new FileBrowserUrlDTO(asset.getLink()));
177                     } else {
178                         eventJson = gson.toJson(new FileBrowserUrlDTO("", "Selected asset is not an image"));
179                     }
180                 } catch (DamException e) {
181                     eventJson = gson.toJson(new FileBrowserUrlDTO("", e.getMessage()));
182                 } finally {
183                     richTextEditor.firePluginEvent(ASSET_CHOSEN_EVENT_ID, eventJson);
184                 }
185             }
186 
187 
188             @Override
189             public void onCancel() {
190                 UI.getCurrent().removeStyleName("ui-overlapping-ck-editor");
191             }
192         });
193     }
194 
195     @Override
196     protected MagnoliaRichTextFieldConfig initializeCKEditorConfig() {
197         MagnoliaRichTextFieldConfig config = super.initializeCKEditorConfig();
198 
199         // MAGNOLIA FILEBROWSER PLUGIN — may be used with/without customConfig
200         boolean isCustomConfig = StringUtils.isNotBlank(definition.getConfigJsFile());
201         if (definition.isImages() || isCustomConfig) {
202 
203             // Hook in our patched filebrowser plugin for triggering assets choose dialog
204             String path = VaadinService.getCurrentRequest().getContextPath();
205             config.addExternalPlugin(FILE_BROWSER_PLUGIN, path + "/VAADIN/js/filebrowser/");
206             config.addListenedEvent(FILE_BROWSER_PLUGIN_CHOOSE_ASSET_EVENT);
207             if (!isCustomConfig) {
208                 config.addToExtraPlugins(FILE_BROWSER_PLUGIN);
209             }
210 
211             // Make filebrowser button visible inside image dialog - just needs non-null filebrowser Url properties
212             config.setFilebrowserImageBrowseLinkUrl("dummy");
213             config.setFilebrowserImageBrowseUrl("dummy");
214         }
215         return config;
216     }
217 
218     /**
219      * Data transfer object for communication with forked CK Editor file browser plugin.
220      */
221     public static class FileBrowserUrlDTO {
222         public String url;
223         public String errorMessage;
224 
225         public FileBrowserUrlDTO(String url, String errorMessage) {
226             this.url = url;
227             this.errorMessage = errorMessage;
228         }
229 
230         public FileBrowserUrlDTO(String url) {
231             this(url, null);
232         }
233     }
234 }