001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.dynamicdatalists.util;
016    
017    import com.liferay.portal.kernel.json.JSONArray;
018    import com.liferay.portal.kernel.json.JSONFactoryUtil;
019    import com.liferay.portal.kernel.json.JSONObject;
020    import com.liferay.portal.kernel.language.LanguageUtil;
021    import com.liferay.portal.kernel.log.Log;
022    import com.liferay.portal.kernel.log.LogFactoryUtil;
023    import com.liferay.portal.kernel.repository.model.FileEntry;
024    import com.liferay.portal.kernel.search.Hits;
025    import com.liferay.portal.kernel.search.Indexer;
026    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
027    import com.liferay.portal.kernel.security.pacl.DoPrivileged;
028    import com.liferay.portal.kernel.template.TemplateConstants;
029    import com.liferay.portal.kernel.util.Constants;
030    import com.liferay.portal.kernel.util.GetterUtil;
031    import com.liferay.portal.kernel.util.LocaleThreadLocal;
032    import com.liferay.portal.kernel.util.LocaleUtil;
033    import com.liferay.portal.kernel.util.ParamUtil;
034    import com.liferay.portal.kernel.util.PropsKeys;
035    import com.liferay.portal.kernel.util.StringPool;
036    import com.liferay.portal.kernel.util.Validator;
037    import com.liferay.portal.service.LayoutServiceUtil;
038    import com.liferay.portal.service.ServiceContext;
039    import com.liferay.portal.templateparser.Transformer;
040    import com.liferay.portal.theme.ThemeDisplay;
041    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
042    import com.liferay.portlet.dynamicdatalists.NoSuchRecordException;
043    import com.liferay.portlet.dynamicdatalists.model.DDLRecord;
044    import com.liferay.portlet.dynamicdatalists.model.DDLRecordConstants;
045    import com.liferay.portlet.dynamicdatalists.model.DDLRecordSet;
046    import com.liferay.portlet.dynamicdatalists.model.DDLRecordVersion;
047    import com.liferay.portlet.dynamicdatalists.service.DDLRecordLocalServiceUtil;
048    import com.liferay.portlet.dynamicdatalists.service.DDLRecordServiceUtil;
049    import com.liferay.portlet.dynamicdatalists.service.DDLRecordSetLocalServiceUtil;
050    import com.liferay.portlet.dynamicdatamapping.model.DDMFormField;
051    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
052    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
053    import com.liferay.portlet.dynamicdatamapping.model.LocalizedValue;
054    import com.liferay.portlet.dynamicdatamapping.service.DDMTemplateLocalServiceUtil;
055    import com.liferay.portlet.dynamicdatamapping.storage.Field;
056    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
057    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
058    import com.liferay.portlet.dynamicdatamapping.util.DDMImpl;
059    import com.liferay.portlet.dynamicdatamapping.util.DDMUtil;
060    
061    import java.util.ArrayList;
062    import java.util.Date;
063    import java.util.HashMap;
064    import java.util.List;
065    import java.util.Locale;
066    import java.util.Map;
067    
068    import javax.portlet.PortletPreferences;
069    import javax.portlet.RenderRequest;
070    import javax.portlet.RenderResponse;
071    
072    import javax.servlet.http.HttpServletRequest;
073    
074    /**
075     * @author Marcellus Tavares
076     * @author Eduardo Lundgren
077     */
078    @DoPrivileged
079    public class DDLImpl implements DDL {
080    
081            @Override
082            public JSONObject getRecordJSONObject(DDLRecord record) throws Exception {
083                    return getRecordJSONObject(record, false);
084            }
085    
086            @Override
087            public JSONObject getRecordJSONObject(
088                            DDLRecord record, boolean latestRecordVersion)
089                    throws Exception {
090    
091                    DDLRecordSet recordSet = record.getRecordSet();
092    
093                    DDMStructure ddmStructure = recordSet.getDDMStructure();
094    
095                    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
096    
097                    for (String fieldName : ddmStructure.getFieldNames()) {
098                            jsonObject.put(fieldName, StringPool.BLANK);
099                    }
100    
101                    jsonObject.put("displayIndex", record.getDisplayIndex());
102                    jsonObject.put("recordId", record.getRecordId());
103    
104                    DDLRecordVersion recordVersion = record.getRecordVersion();
105    
106                    if (latestRecordVersion) {
107                            recordVersion = record.getLatestRecordVersion();
108                    }
109    
110                    Fields fields = StorageEngineUtil.getFields(
111                            recordVersion.getDDMStorageId());
112    
113                    for (Field field : fields) {
114                            String fieldName = field.getName();
115                            String fieldType = field.getType();
116                            Object fieldValue = field.getValue();
117    
118                            if (fieldValue instanceof Date) {
119                                    jsonObject.put(fieldName, ((Date)fieldValue).getTime());
120                            }
121                            else if (fieldType.equals(DDMImpl.TYPE_DDM_DOCUMENTLIBRARY) &&
122                                             Validator.isNotNull(fieldValue)) {
123    
124                                    JSONObject fieldValueJSONObject =
125                                            JSONFactoryUtil.createJSONObject(
126                                                    String.valueOf(fieldValue));
127    
128                                    String uuid = fieldValueJSONObject.getString("uuid");
129                                    long groupId = fieldValueJSONObject.getLong("groupId");
130    
131                                    fieldValueJSONObject.put(
132                                            "title", getFileEntryTitle(uuid, groupId));
133    
134                                    jsonObject.put(fieldName, fieldValueJSONObject.toString());
135                            }
136                            else if (fieldType.equals(DDMImpl.TYPE_DDM_LINK_TO_PAGE) &&
137                                             Validator.isNotNull(fieldValue)) {
138    
139                                    JSONObject fieldValueJSONObject =
140                                            JSONFactoryUtil.createJSONObject(
141                                                    String.valueOf(fieldValue));
142    
143                                    long groupId = fieldValueJSONObject.getLong("groupId");
144                                    boolean privateLayout = fieldValueJSONObject.getBoolean(
145                                            "privateLayout");
146                                    long layoutId = fieldValueJSONObject.getLong("layoutId");
147                                    Locale locale = LocaleThreadLocal.getThemeDisplayLocale();
148    
149                                    String layoutName = getLayoutName(
150                                            groupId, privateLayout, layoutId,
151                                            LanguageUtil.getLanguageId(locale));
152    
153                                    fieldValueJSONObject.put("name", layoutName);
154    
155                                    jsonObject.put(fieldName, fieldValueJSONObject.toString());
156                            }
157                            else if ((fieldType.equals(DDMImpl.TYPE_RADIO) ||
158                                              fieldType.equals(DDMImpl.TYPE_SELECT)) &&
159                                             Validator.isNotNull(fieldValue)) {
160    
161                                    fieldValue = JSONFactoryUtil.createJSONArray(
162                                            String.valueOf(fieldValue));
163    
164                                    jsonObject.put(fieldName, (JSONArray)fieldValue);
165                            }
166                            else {
167                                    jsonObject.put(fieldName, String.valueOf(fieldValue));
168                            }
169                    }
170    
171                    return jsonObject;
172            }
173    
174            @Override
175            public List<DDLRecord> getRecords(Hits hits) throws Exception {
176                    List<DDLRecord> records = new ArrayList<DDLRecord>();
177    
178                    List<com.liferay.portal.kernel.search.Document> documents =
179                            hits.toList();
180    
181                    for (com.liferay.portal.kernel.search.Document document : documents) {
182                            long recordId = GetterUtil.getLong(
183                                    document.get(
184                                            com.liferay.portal.kernel.search.Field.ENTRY_CLASS_PK));
185    
186                            try {
187                                    DDLRecord record = DDLRecordLocalServiceUtil.getRecord(
188                                            recordId);
189    
190                                    records.add(record);
191                            }
192                            catch (NoSuchRecordException nsre) {
193                                    if (_log.isWarnEnabled()) {
194                                            _log.warn(
195                                                    "DDL record index is stale and contains record " +
196                                                            recordId);
197                                    }
198    
199                                    Indexer indexer = IndexerRegistryUtil.getIndexer(
200                                            DDLRecord.class);
201    
202                                    long companyId = GetterUtil.getLong(
203                                            document.get(
204                                                    com.liferay.portal.kernel.search.Field.COMPANY_ID));
205    
206                                    indexer.delete(companyId, document.getUID());
207                            }
208                    }
209    
210                    return records;
211            }
212    
213            @Override
214            public JSONArray getRecordSetJSONArray(DDLRecordSet recordSet)
215                    throws Exception {
216    
217                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
218    
219                    DDMStructure ddmStructure = recordSet.getDDMStructure();
220    
221                    Locale locale = LocaleUtil.fromLanguageId(
222                            ddmStructure.getDefaultLanguageId());
223    
224                    List<DDMFormField> ddmFormFields = ddmStructure.getDDMFormFields(false);
225    
226                    for (DDMFormField ddmFormField : ddmFormFields) {
227                            String name = ddmFormField.getName();
228    
229                            if (ddmStructure.isFieldPrivate(name)) {
230                                    continue;
231                            }
232    
233                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
234    
235                            String dataType = ddmFormField.getDataType();
236    
237                            jsonObject.put("dataType", dataType);
238    
239                            boolean readOnly = ddmFormField.isReadOnly();
240    
241                            jsonObject.put("editable", !readOnly);
242    
243                            LocalizedValue label = ddmFormField.getLabel();
244    
245                            jsonObject.put("label", label.getString(locale));
246    
247                            jsonObject.put("name", name);
248    
249                            boolean required = ddmFormField.isRequired();
250    
251                            jsonObject.put("required", required);
252    
253                            jsonObject.put("sortable", true);
254    
255                            String type = ddmFormField.getType();
256    
257                            jsonObject.put("type", type);
258    
259                            jsonArray.put(jsonObject);
260                    }
261    
262                    return jsonArray;
263            }
264    
265            @Override
266            public JSONArray getRecordsJSONArray(DDLRecordSet recordSet)
267                    throws Exception {
268    
269                    return getRecordsJSONArray(recordSet.getRecords(), false);
270            }
271    
272            @Override
273            public JSONArray getRecordsJSONArray(List<DDLRecord> records)
274                    throws Exception {
275    
276                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
277    
278                    for (DDLRecord record : records) {
279                            JSONObject jsonObject = getRecordJSONObject(record);
280    
281                            jsonArray.put(jsonObject);
282                    }
283    
284                    return jsonArray;
285            }
286    
287            @Override
288            public JSONArray getRecordsJSONArray(
289                            List<DDLRecord> records, boolean latestRecordVersion)
290                    throws Exception {
291    
292                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
293    
294                    for (DDLRecord record : records) {
295                            JSONObject jsonObject = getRecordJSONObject(
296                                    record, latestRecordVersion);
297    
298                            jsonArray.put(jsonObject);
299                    }
300    
301                    return jsonArray;
302            }
303    
304            @Override
305            public String getTemplateContent(
306                            long ddmTemplateId, DDLRecordSet recordSet,
307                            ThemeDisplay themeDisplay, RenderRequest renderRequest,
308                            RenderResponse renderResponse)
309                    throws Exception {
310    
311                    Map<String, Object> contextObjects = new HashMap<String, Object>();
312    
313                    contextObjects.put(
314                            DDLConstants.RESERVED_DDM_STRUCTURE_ID,
315                            recordSet.getDDMStructureId());
316                    contextObjects.put(
317                            DDLConstants.RESERVED_DDM_TEMPLATE_ID, ddmTemplateId);
318                    contextObjects.put(
319                            DDLConstants.RESERVED_RECORD_SET_DESCRIPTION,
320                            recordSet.getDescription(themeDisplay.getLocale()));
321                    contextObjects.put(
322                            DDLConstants.RESERVED_RECORD_SET_ID, recordSet.getRecordSetId());
323                    contextObjects.put(
324                            DDLConstants.RESERVED_RECORD_SET_NAME,
325                            recordSet.getName(themeDisplay.getLocale()));
326                    contextObjects.put(TemplateConstants.TEMPLATE_ID, ddmTemplateId);
327    
328                    String viewMode = ParamUtil.getString(renderRequest, "viewMode");
329    
330                    if (Validator.isNull(viewMode)) {
331                            viewMode = Constants.VIEW;
332                    }
333    
334                    contextObjects.put("viewMode", viewMode);
335    
336                    DDMTemplate ddmTemplate = DDMTemplateLocalServiceUtil.getTemplate(
337                            ddmTemplateId);
338    
339                    contextObjects.put(
340                            TemplateConstants.CLASS_NAME_ID, ddmTemplate.getClassNameId());
341    
342                    return _transformer.transform(
343                            themeDisplay, contextObjects, ddmTemplate.getScript(),
344                            ddmTemplate.getLanguage());
345            }
346    
347            /**
348             * @deprecated As of 7.0.0, with no direct replacement
349             */
350            @Deprecated
351            @Override
352            public boolean isEditable(
353                            HttpServletRequest request, String portletId, long groupId)
354                    throws Exception {
355    
356                    return true;
357            }
358    
359            /**
360             * @deprecated As of 7.0.0, with no direct replacement
361             */
362            @Deprecated
363            @Override
364            public boolean isEditable(
365                            PortletPreferences preferences, String portletId, long groupId)
366                    throws Exception {
367    
368                    return true;
369            }
370    
371            @Override
372            public DDLRecord updateRecord(
373                            long recordId, long recordSetId, boolean mergeFields,
374                            boolean checkPermission, ServiceContext serviceContext)
375                    throws Exception {
376    
377                    DDLRecord record = DDLRecordLocalServiceUtil.fetchRecord(recordId);
378    
379                    boolean majorVersion = ParamUtil.getBoolean(
380                            serviceContext, "majorVersion");
381    
382                    DDLRecordSet recordSet = DDLRecordSetLocalServiceUtil.getDDLRecordSet(
383                            recordSetId);
384    
385                    DDMStructure ddmStructure = recordSet.getDDMStructure();
386    
387                    Fields fields = DDMUtil.getFields(
388                            ddmStructure.getStructureId(), serviceContext);
389    
390                    if (record != null) {
391                            if (checkPermission) {
392                                    record = DDLRecordServiceUtil.updateRecord(
393                                            recordId, majorVersion,
394                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
395                                            mergeFields, serviceContext);
396                            }
397                            else {
398                                    record = DDLRecordLocalServiceUtil.updateRecord(
399                                            serviceContext.getUserId(), recordId, majorVersion,
400                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
401                                            mergeFields, serviceContext);
402                            }
403                    }
404                    else {
405                            if (checkPermission) {
406                                    record = DDLRecordServiceUtil.addRecord(
407                                            serviceContext.getScopeGroupId(), recordSetId,
408                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
409                                            serviceContext);
410                            }
411                            else {
412                                    record = DDLRecordLocalServiceUtil.addRecord(
413                                            serviceContext.getUserId(),
414                                            serviceContext.getScopeGroupId(), recordSetId,
415                                            DDLRecordConstants.DISPLAY_INDEX_DEFAULT, fields,
416                                            serviceContext);
417                            }
418                    }
419    
420                    return record;
421            }
422    
423            @Override
424            public DDLRecord updateRecord(
425                            long recordId, long recordSetId, boolean mergeFields,
426                            ServiceContext serviceContext)
427                    throws Exception {
428    
429                    return updateRecord(
430                            recordId, recordSetId, mergeFields, true, serviceContext);
431            }
432    
433            protected String getFileEntryTitle(String uuid, long groupId) {
434                    try {
435                            FileEntry fileEntry =
436                                    DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(
437                                            uuid, groupId);
438    
439                            return fileEntry.getTitle();
440                    }
441                    catch (Exception e) {
442                            return LanguageUtil.format(
443                                    LocaleUtil.getSiteDefault(), "is-temporarily-unavailable",
444                                    "content");
445                    }
446            }
447    
448            protected String getLayoutName(
449                    long groupId, boolean privateLayout, long layoutId, String languageId) {
450    
451                    try {
452                            return LayoutServiceUtil.getLayoutName(
453                                    groupId, privateLayout, layoutId, languageId);
454                    }
455                    catch (Exception e) {
456                            return LanguageUtil.format(
457                                    LocaleUtil.getSiteDefault(), "is-temporarily-unavailable",
458                                    "content");
459                    }
460            }
461    
462            private static final Log _log = LogFactoryUtil.getLog(DDLImpl.class);
463    
464            private final Transformer _transformer = new Transformer(
465                    PropsKeys.DYNAMIC_DATA_LISTS_ERROR_TEMPLATE, true);
466    
467    }