001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portlet.journal.service.impl;
016    
017    import com.liferay.portal.kernel.exception.PortalException;
018    import com.liferay.portal.kernel.exception.SystemException;
019    import com.liferay.portal.kernel.log.Log;
020    import com.liferay.portal.kernel.log.LogFactoryUtil;
021    import com.liferay.portal.kernel.util.CharPool;
022    import com.liferay.portal.kernel.util.FileUtil;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.OrderByComparator;
025    import com.liferay.portal.kernel.util.PropsKeys;
026    import com.liferay.portal.kernel.util.StringPool;
027    import com.liferay.portal.kernel.util.StringUtil;
028    import com.liferay.portal.kernel.util.Validator;
029    import com.liferay.portal.model.Image;
030    import com.liferay.portal.model.ResourceConstants;
031    import com.liferay.portal.model.User;
032    import com.liferay.portal.service.ServiceContext;
033    import com.liferay.portal.util.PortalUtil;
034    import com.liferay.portal.util.PrefsPropsUtil;
035    import com.liferay.portlet.dynamicdatamapping.util.DDMXMLUtil;
036    import com.liferay.portlet.expando.model.ExpandoBridge;
037    import com.liferay.portlet.journal.DuplicateTemplateIdException;
038    import com.liferay.portlet.journal.NoSuchTemplateException;
039    import com.liferay.portlet.journal.RequiredTemplateException;
040    import com.liferay.portlet.journal.TemplateIdException;
041    import com.liferay.portlet.journal.TemplateNameException;
042    import com.liferay.portlet.journal.TemplateSmallImageNameException;
043    import com.liferay.portlet.journal.TemplateSmallImageSizeException;
044    import com.liferay.portlet.journal.TemplateXslException;
045    import com.liferay.portlet.journal.model.JournalStructure;
046    import com.liferay.portlet.journal.model.JournalTemplate;
047    import com.liferay.portlet.journal.model.JournalTemplateConstants;
048    import com.liferay.portlet.journal.service.base.JournalTemplateLocalServiceBaseImpl;
049    import com.liferay.portlet.journal.util.JournalUtil;
050    
051    import java.io.File;
052    import java.io.IOException;
053    
054    import java.util.Date;
055    import java.util.List;
056    import java.util.Locale;
057    import java.util.Map;
058    
059    /**
060     * @author Brian Wing Shun Chan
061     * @author Raymond Augé
062     */
063    public class JournalTemplateLocalServiceImpl
064            extends JournalTemplateLocalServiceBaseImpl {
065    
066            public JournalTemplate addTemplate(
067                            long userId, long groupId, String templateId,
068                            boolean autoTemplateId, String structureId,
069                            Map<Locale, String> nameMap, Map<Locale, String> descriptionMap,
070                            String xsl, boolean formatXsl, String langType, boolean cacheable,
071                            boolean smallImage, String smallImageURL, File smallImageFile,
072                            ServiceContext serviceContext)
073                    throws PortalException, SystemException {
074    
075                    // Template
076    
077                    User user = userPersistence.findByPrimaryKey(userId);
078                    templateId = templateId.trim().toUpperCase();
079                    Date now = new Date();
080    
081                    try {
082                            if (formatXsl) {
083                                    if (langType.equals(JournalTemplateConstants.LANG_TYPE_VM)) {
084                                            xsl = JournalUtil.formatVM(xsl);
085                                    }
086                                    else {
087                                            xsl = DDMXMLUtil.formatXML(xsl);
088                                    }
089                            }
090                    }
091                    catch (Exception e) {
092                            throw new TemplateXslException();
093                    }
094    
095                    byte[] smallImageBytes = null;
096    
097                    try {
098                            smallImageBytes = FileUtil.getBytes(smallImageFile);
099                    }
100                    catch (IOException ioe) {
101                    }
102    
103                    validate(
104                            groupId, templateId, autoTemplateId, nameMap, xsl, smallImage,
105                            smallImageURL, smallImageFile, smallImageBytes);
106    
107                    if (autoTemplateId) {
108                            templateId = String.valueOf(counterLocalService.increment());
109                    }
110    
111                    long id = counterLocalService.increment();
112    
113                    JournalTemplate template = journalTemplatePersistence.create(id);
114    
115                    template.setUuid(serviceContext.getUuid());
116                    template.setGroupId(groupId);
117                    template.setCompanyId(user.getCompanyId());
118                    template.setUserId(user.getUserId());
119                    template.setUserName(user.getFullName());
120                    template.setCreateDate(serviceContext.getCreateDate(now));
121                    template.setModifiedDate(serviceContext.getModifiedDate(now));
122                    template.setTemplateId(templateId);
123                    template.setStructureId(structureId);
124                    template.setNameMap(nameMap);
125                    template.setDescriptionMap(descriptionMap);
126                    template.setXsl(xsl);
127                    template.setLangType(langType);
128                    template.setCacheable(cacheable);
129                    template.setSmallImage(smallImage);
130                    template.setSmallImageId(counterLocalService.increment());
131                    template.setSmallImageURL(smallImageURL);
132    
133                    journalTemplatePersistence.update(template, false);
134    
135                    // Resources
136    
137                    if (serviceContext.getAddGroupPermissions() ||
138                            serviceContext.getAddGuestPermissions()) {
139    
140                            addTemplateResources(
141                                    template, serviceContext.getAddGroupPermissions(),
142                                    serviceContext.getAddGuestPermissions());
143                    }
144                    else {
145                            addTemplateResources(
146                                    template, serviceContext.getGroupPermissions(),
147                                    serviceContext.getGuestPermissions());
148                    }
149    
150                    // Expando
151    
152                    ExpandoBridge expandoBridge = template.getExpandoBridge();
153    
154                    expandoBridge.setAttributes(serviceContext);
155    
156                    // Small image
157    
158                    saveImages(
159                            smallImage, template.getSmallImageId(), smallImageFile,
160                            smallImageBytes);
161    
162                    return template;
163            }
164    
165            public void addTemplateResources(
166                            long groupId, String templateId, boolean addGroupPermissions,
167                            boolean addGuestPermissions)
168                    throws PortalException, SystemException {
169    
170                    JournalTemplate template = journalTemplatePersistence.findByG_T(
171                            groupId, templateId);
172    
173                    addTemplateResources(
174                            template, addGroupPermissions, addGuestPermissions);
175            }
176    
177            public void addTemplateResources(
178                            JournalTemplate template, boolean addGroupPermissions,
179                            boolean addGuestPermissions)
180                    throws PortalException, SystemException {
181    
182                    resourceLocalService.addResources(
183                            template.getCompanyId(), template.getGroupId(),
184                            template.getUserId(), JournalTemplate.class.getName(),
185                            template.getId(), false, addGroupPermissions,
186                            addGuestPermissions);
187            }
188    
189            public void addTemplateResources(
190                            long groupId, String templateId, String[] groupPermissions,
191                            String[] guestPermissions)
192                    throws PortalException, SystemException {
193    
194                    JournalTemplate template = journalTemplatePersistence.findByG_T(
195                            groupId, templateId);
196    
197                    addTemplateResources(template, groupPermissions, guestPermissions);
198            }
199    
200            public void addTemplateResources(
201                            JournalTemplate template, String[] groupPermissions,
202                            String[] guestPermissions)
203                    throws PortalException, SystemException {
204    
205                    resourceLocalService.addModelResources(
206                            template.getCompanyId(), template.getGroupId(),
207                            template.getUserId(), JournalTemplate.class.getName(),
208                            template.getId(), groupPermissions, guestPermissions);
209            }
210    
211            public void checkNewLine(long groupId, String templateId)
212                    throws PortalException, SystemException {
213    
214                    JournalTemplate template = journalTemplatePersistence.findByG_T(
215                            groupId, templateId);
216    
217                    String xsl = template.getXsl();
218    
219                    if ((xsl != null) && (xsl.indexOf("\\n") != -1)) {
220                            xsl = StringUtil.replace(
221                                    xsl,
222                                    new String[] {"\\n", "\\r"},
223                                    new String[] {"\n", "\r"});
224    
225                            template.setXsl(xsl);
226    
227                            journalTemplatePersistence.update(template, false);
228                    }
229            }
230    
231            public JournalTemplate copyTemplate(
232                            long userId, long groupId, String oldTemplateId,
233                            String newTemplateId, boolean autoTemplateId)
234                    throws PortalException, SystemException {
235    
236                    // Template
237    
238                    User user = userPersistence.findByPrimaryKey(userId);
239                    oldTemplateId = oldTemplateId.trim().toUpperCase();
240                    newTemplateId = newTemplateId.trim().toUpperCase();
241                    Date now = new Date();
242    
243                    JournalTemplate oldTemplate = journalTemplatePersistence.findByG_T(
244                            groupId, oldTemplateId);
245    
246                    if (autoTemplateId) {
247                            newTemplateId = String.valueOf(counterLocalService.increment());
248                    }
249                    else {
250                            validate(newTemplateId);
251    
252                            JournalTemplate newTemplate = journalTemplatePersistence.fetchByG_T(
253                                    groupId, newTemplateId);
254    
255                            if (newTemplate != null) {
256                                    throw new DuplicateTemplateIdException();
257                            }
258                    }
259    
260                    long id = counterLocalService.increment();
261    
262                    JournalTemplate newTemplate = journalTemplatePersistence.create(id);
263    
264                    newTemplate.setGroupId(groupId);
265                    newTemplate.setCompanyId(user.getCompanyId());
266                    newTemplate.setUserId(user.getUserId());
267                    newTemplate.setUserName(user.getFullName());
268                    newTemplate.setCreateDate(now);
269                    newTemplate.setModifiedDate(now);
270                    newTemplate.setTemplateId(newTemplateId);
271                    newTemplate.setStructureId(oldTemplate.getStructureId());
272                    newTemplate.setNameMap(oldTemplate.getNameMap());
273                    newTemplate.setDescriptionMap(oldTemplate.getDescriptionMap());
274                    newTemplate.setXsl(oldTemplate.getXsl());
275                    newTemplate.setLangType(oldTemplate.getLangType());
276                    newTemplate.setCacheable(oldTemplate.isCacheable());
277                    newTemplate.setSmallImage(oldTemplate.isSmallImage());
278                    newTemplate.setSmallImageId(counterLocalService.increment());
279                    newTemplate.setSmallImageURL(oldTemplate.getSmallImageURL());
280    
281                    journalTemplatePersistence.update(newTemplate, false);
282    
283                    // Small image
284    
285                    if (oldTemplate.getSmallImage()) {
286                            Image image = imageLocalService.getImage(
287                                    oldTemplate.getSmallImageId());
288    
289                            byte[] smallImageBytes = image.getTextObj();
290    
291                            imageLocalService.updateImage(
292                                    newTemplate.getSmallImageId(), smallImageBytes);
293                    }
294    
295                    // Resources
296    
297                    addTemplateResources(newTemplate, true, true);
298    
299                    return newTemplate;
300            }
301    
302            public void deleteTemplate(long groupId, String templateId)
303                    throws PortalException, SystemException {
304    
305                    templateId = templateId.trim().toUpperCase();
306    
307                    JournalTemplate template = journalTemplatePersistence.findByG_T(
308                            groupId, templateId);
309    
310                    deleteTemplate(template);
311            }
312    
313            public void deleteTemplate(JournalTemplate template)
314                    throws PortalException, SystemException {
315    
316                    if (journalArticlePersistence.countByG_C_T(
317                                    template.getGroupId(), 0, template.getTemplateId()) > 0) {
318    
319                            throw new RequiredTemplateException();
320                    }
321    
322                    // WebDAVProps
323    
324                    webDAVPropsLocalService.deleteWebDAVProps(
325                            JournalTemplate.class.getName(), template.getId());
326    
327                    // Small image
328    
329                    imageLocalService.deleteImage(template.getSmallImageId());
330    
331                    // Expando
332    
333                    expandoValueLocalService.deleteValues(
334                            JournalTemplate.class.getName(), template.getId());
335    
336                    // Resources
337    
338                    resourceLocalService.deleteResource(
339                            template.getCompanyId(), JournalTemplate.class.getName(),
340                            ResourceConstants.SCOPE_INDIVIDUAL, template.getId());
341    
342                    // Article
343    
344                    journalArticleLocalService.updateTemplateId(
345                            template.getGroupId(),
346                            PortalUtil.getClassNameId(JournalStructure.class.getName()),
347                            template.getTemplateId(), StringPool.BLANK);
348    
349                    // Template
350    
351                    journalTemplatePersistence.remove(template);
352            }
353    
354            public void deleteTemplates(long groupId)
355                    throws PortalException, SystemException {
356    
357                    for (JournalTemplate template :
358                                    journalTemplatePersistence.findByGroupId(groupId)) {
359    
360                            deleteTemplate(template);
361                    }
362            }
363    
364            public List<JournalTemplate> getStructureTemplates(
365                            long groupId, String structureId)
366                    throws SystemException {
367    
368                    return journalTemplatePersistence.findByG_S(groupId, structureId);
369            }
370    
371            public List<JournalTemplate> getStructureTemplates(
372                            long groupId, String structureId, int start, int end)
373                    throws SystemException {
374    
375                    return journalTemplatePersistence.findByG_S(
376                            groupId, structureId, start, end);
377            }
378    
379            public int getStructureTemplatesCount(long groupId, String structureId)
380                    throws SystemException {
381    
382                    return journalTemplatePersistence.countByG_S(groupId, structureId);
383            }
384    
385            public JournalTemplate getTemplate(long id)
386                    throws PortalException, SystemException {
387    
388                    return journalTemplatePersistence.findByPrimaryKey(id);
389            }
390    
391            public JournalTemplate getTemplate(long groupId, String templateId)
392                    throws PortalException, SystemException {
393    
394                    templateId = GetterUtil.getString(templateId).toUpperCase();
395    
396                    if (groupId == 0) {
397                            _log.error(
398                                    "No group id was passed for " + templateId + ". Group id is " +
399                                            "required since 4.2.0. Please update all custom code and " +
400                                                    "data that references templates without a group id.");
401    
402                            List<JournalTemplate> templates =
403                                    journalTemplatePersistence.findByTemplateId(
404                                            templateId);
405    
406                            if (templates.size() == 0) {
407                                    throw new NoSuchTemplateException(
408                                            "No JournalTemplate exists with the template id " +
409                                                    templateId);
410                            }
411                            else {
412                                    return templates.get(0);
413                            }
414                    }
415                    else {
416                            return journalTemplatePersistence.findByG_T(groupId, templateId);
417                    }
418            }
419    
420            public JournalTemplate getTemplateBySmallImageId(long smallImageId)
421                    throws PortalException, SystemException {
422    
423                    return journalTemplatePersistence.findBySmallImageId(smallImageId);
424            }
425    
426            public List<JournalTemplate> getTemplates() throws SystemException {
427                    return journalTemplatePersistence.findAll();
428            }
429    
430            public List<JournalTemplate> getTemplates(long groupId)
431                    throws SystemException {
432    
433                    return journalTemplatePersistence.findByGroupId(groupId);
434            }
435    
436            public List<JournalTemplate> getTemplates(long groupId, int start, int end)
437                    throws SystemException {
438    
439                    return journalTemplatePersistence.findByGroupId(groupId, start, end);
440            }
441    
442            public int getTemplatesCount(long groupId) throws SystemException {
443                    return journalTemplatePersistence.countByGroupId(groupId);
444            }
445    
446            public boolean hasTemplate(long groupId, String templateId)
447                    throws SystemException {
448    
449                    try {
450                            getTemplate(groupId, templateId);
451    
452                            return true;
453                    }
454                    catch (PortalException pe) {
455                            return false;
456                    }
457            }
458    
459            public List<JournalTemplate> search(
460                            long companyId, long[] groupIds, String keywords,
461                            String structureId, String structureIdComparator, int start,
462                            int end, OrderByComparator obc)
463                    throws SystemException {
464    
465                    return journalTemplateFinder.findByKeywords(
466                            companyId, groupIds, keywords, structureId, structureIdComparator,
467                            start, end, obc);
468            }
469    
470            public List<JournalTemplate> search(
471                            long companyId, long[] groupIds, String templateId,
472                            String structureId, String structureIdComparator, String name,
473                            String description, boolean andOperator, int start, int end,
474                            OrderByComparator obc)
475                    throws SystemException {
476    
477                    return journalTemplateFinder.findByC_G_T_S_N_D(
478                            companyId, groupIds, templateId, structureId, structureIdComparator,
479                            name, description, andOperator, start, end, obc);
480            }
481    
482            public int searchCount(
483                            long companyId, long[] groupIds, String keywords,
484                            String structureId, String structureIdComparator)
485                    throws SystemException {
486    
487                    return journalTemplateFinder.countByKeywords(
488                            companyId, groupIds, keywords, structureId, structureIdComparator);
489            }
490    
491            public int searchCount(
492                            long companyId, long[] groupIds, String templateId,
493                            String structureId, String structureIdComparator, String name,
494                            String description,
495                            boolean andOperator)
496                    throws SystemException {
497    
498                    return journalTemplateFinder.countByC_G_T_S_N_D(
499                            companyId, groupIds, templateId, structureId, structureIdComparator,
500                            name, description, andOperator);
501            }
502    
503            public JournalTemplate updateTemplate(
504                            long groupId, String templateId, String structureId,
505                            Map<Locale, String> nameMap, Map<Locale, String> descriptionMap,
506                            String xsl, boolean formatXsl, String langType, boolean cacheable,
507                            boolean smallImage, String smallImageURL, File smallImageFile,
508                            ServiceContext serviceContext)
509                    throws PortalException, SystemException {
510    
511                    // Template
512    
513                    templateId = templateId.trim().toUpperCase();
514    
515                    try {
516                            if (formatXsl) {
517                                    if (langType.equals(JournalTemplateConstants.LANG_TYPE_VM)) {
518                                            xsl = JournalUtil.formatVM(xsl);
519                                    }
520                                    else {
521                                            xsl = DDMXMLUtil.formatXML(xsl);
522                                    }
523                            }
524                    }
525                    catch (Exception e) {
526                            throw new TemplateXslException();
527                    }
528    
529                    byte[] smallImageBytes = null;
530    
531                    try {
532                            smallImageBytes = FileUtil.getBytes(smallImageFile);
533                    }
534                    catch (IOException ioe) {
535                    }
536    
537                    validate(
538                            nameMap, xsl, smallImage, smallImageURL, smallImageFile,
539                            smallImageBytes);
540    
541                    JournalTemplate template = journalTemplatePersistence.findByG_T(
542                            groupId, templateId);
543    
544                    template.setModifiedDate(new Date());
545    
546                    if (Validator.isNull(template.getStructureId()) &&
547                            Validator.isNotNull(structureId)) {
548    
549                            // Allow users to set the structure if and only if it currently
550                            // does not have one. Otherwise, you can have bad data because there
551                            // may be an existing article that has chosen to use a structure and
552                            // template combination that no longer exists.
553    
554                            template.setStructureId(structureId);
555                    }
556    
557                    template.setNameMap(nameMap);
558                    template.setDescriptionMap(descriptionMap);
559                    template.setXsl(xsl);
560                    template.setLangType(langType);
561                    template.setCacheable(cacheable);
562                    template.setSmallImage(smallImage);
563                    template.setSmallImageURL(smallImageURL);
564                    template.setModifiedDate(serviceContext.getModifiedDate(null));
565    
566                    journalTemplatePersistence.update(template, false);
567    
568                    // Expando
569    
570                    ExpandoBridge expandoBridge = template.getExpandoBridge();
571    
572                    expandoBridge.setAttributes(serviceContext);
573    
574                    // Small image
575    
576                    saveImages(
577                            smallImage, template.getSmallImageId(), smallImageFile,
578                            smallImageBytes);
579    
580                    return template;
581            }
582    
583            protected void saveImages(
584                            boolean smallImage, long smallImageId, File smallImageFile,
585                            byte[] smallImageBytes)
586                    throws PortalException, SystemException {
587    
588                    if (smallImage) {
589                            if ((smallImageFile != null) && (smallImageBytes != null)) {
590                                    imageLocalService.updateImage(smallImageId, smallImageBytes);
591                            }
592                    }
593                    else {
594                            imageLocalService.deleteImage(smallImageId);
595                    }
596            }
597    
598            protected void validate(String templateId) throws PortalException {
599                    if ((Validator.isNull(templateId)) ||
600                            (Validator.isNumber(templateId)) ||
601                            (templateId.indexOf(CharPool.SPACE) != -1)) {
602    
603                            throw new TemplateIdException();
604                    }
605            }
606    
607            protected void validate(
608                            long groupId, String templateId, boolean autoTemplateId,
609                            Map<Locale, String> nameMap, String xsl, boolean smallImage,
610                            String smallImageURL, File smallImageFile, byte[] smallImageBytes)
611                    throws PortalException, SystemException {
612    
613                    if (!autoTemplateId) {
614                            validate(templateId);
615    
616                            JournalTemplate template = journalTemplatePersistence.fetchByG_T(
617                                    groupId, templateId);
618    
619                            if (template != null) {
620                                    throw new DuplicateTemplateIdException();
621                            }
622                    }
623    
624                    validate(
625                            nameMap, xsl, smallImage, smallImageURL, smallImageFile,
626                            smallImageBytes);
627            }
628    
629            protected void validate(
630                            Map<Locale, String> nameMap, String xsl, boolean smallImage,
631                            String smallImageURL, File smallImageFile, byte[] smallImageBytes)
632                    throws PortalException, SystemException {
633    
634                    if (nameMap.isEmpty()) {
635                            throw new TemplateNameException();
636                    }
637                    else if (Validator.isNull(xsl)) {
638                            throw new TemplateXslException();
639                    }
640    
641                    String[] imageExtensions = PrefsPropsUtil.getStringArray(
642                            PropsKeys.JOURNAL_IMAGE_EXTENSIONS, StringPool.COMMA);
643    
644                    if (smallImage && Validator.isNull(smallImageURL) &&
645                            (smallImageFile != null) && (smallImageBytes != null)) {
646    
647                            String smallImageName = smallImageFile.getName();
648    
649                            if (smallImageName != null) {
650                                    boolean validSmallImageExtension = false;
651    
652                                    for (int i = 0; i < imageExtensions.length; i++) {
653                                            if (StringPool.STAR.equals(imageExtensions[i]) ||
654                                                    StringUtil.endsWith(
655                                                            smallImageName, imageExtensions[i])) {
656    
657                                                    validSmallImageExtension = true;
658    
659                                                    break;
660                                            }
661                                    }
662    
663                                    if (!validSmallImageExtension) {
664                                            throw new TemplateSmallImageNameException(smallImageName);
665                                    }
666                            }
667    
668                            long smallImageMaxSize = PrefsPropsUtil.getLong(
669                                    PropsKeys.JOURNAL_IMAGE_SMALL_MAX_SIZE);
670    
671                            if ((smallImageMaxSize > 0) &&
672                                    ((smallImageBytes == null) ||
673                                     (smallImageBytes.length > smallImageMaxSize))) {
674    
675                                    throw new TemplateSmallImageSizeException();
676                            }
677                    }
678            }
679    
680            private static Log _log = LogFactoryUtil.getLog(
681                    JournalTemplateLocalServiceImpl.class);
682    
683    }