1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portlet.documentlibrary.service.impl;
24  
25  import com.liferay.documentlibrary.DuplicateFileException;
26  import com.liferay.documentlibrary.FileSizeException;
27  import com.liferay.documentlibrary.NoSuchFileException;
28  import com.liferay.documentlibrary.util.Indexer;
29  import com.liferay.portal.PortalException;
30  import com.liferay.portal.SystemException;
31  import com.liferay.portal.kernel.log.Log;
32  import com.liferay.portal.kernel.log.LogFactoryUtil;
33  import com.liferay.portal.kernel.search.SearchEngineUtil;
34  import com.liferay.portal.kernel.search.SearchException;
35  import com.liferay.portal.kernel.util.FileUtil;
36  import com.liferay.portal.kernel.util.GetterUtil;
37  import com.liferay.portal.kernel.util.MimeTypesUtil;
38  import com.liferay.portal.kernel.util.OrderByComparator;
39  import com.liferay.portal.kernel.util.StringPool;
40  import com.liferay.portal.kernel.util.Validator;
41  import com.liferay.portal.model.Resource;
42  import com.liferay.portal.model.ResourceConstants;
43  import com.liferay.portal.model.User;
44  import com.liferay.portal.util.PortalUtil;
45  import com.liferay.portal.util.PortletKeys;
46  import com.liferay.portal.util.PropsValues;
47  import com.liferay.portlet.documentlibrary.DuplicateFolderNameException;
48  import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
49  import com.liferay.portlet.documentlibrary.NoSuchFolderException;
50  import com.liferay.portlet.documentlibrary.model.DLFileEntry;
51  import com.liferay.portlet.documentlibrary.model.DLFileVersion;
52  import com.liferay.portlet.documentlibrary.model.DLFolder;
53  import com.liferay.portlet.documentlibrary.model.impl.DLFileEntryImpl;
54  import com.liferay.portlet.documentlibrary.model.impl.DLFolderImpl;
55  import com.liferay.portlet.documentlibrary.service.base.DLFileEntryLocalServiceBaseImpl;
56  import com.liferay.portlet.messageboards.model.MBDiscussion;
57  import com.liferay.portlet.ratings.model.RatingsEntry;
58  import com.liferay.portlet.ratings.model.RatingsStats;
59  import com.liferay.util.MathUtil;
60  
61  import java.io.BufferedInputStream;
62  import java.io.ByteArrayInputStream;
63  import java.io.File;
64  import java.io.FileInputStream;
65  import java.io.FileNotFoundException;
66  import java.io.IOException;
67  import java.io.InputStream;
68  
69  import java.util.Date;
70  import java.util.List;
71  
72  /**
73   * <a href="DLFileEntryLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
74   *
75   * <p>
76   * For DLFileEntries, the naming convention for some of the variables is not
77   * very informative, due to legacy code. Each DLFileEntry has a corresponding
78   * name and title. The "name" is a unique identifier for a given file and
79   * usually follows the format "DLFE-1234.xls" whereas the "title" is the actual
80   * name specified by the user (e.g., "Budget.xls").
81   * </p>
82   *
83   * @author Brian Wing Shun Chan
84   * @author Harry Mark
85   *
86   */
87  public class DLFileEntryLocalServiceImpl
88      extends DLFileEntryLocalServiceBaseImpl {
89  
90      public DLFileEntry addFileEntry(
91              long userId, long folderId, String name, String title,
92              String description, String[] tagsEntries, String extraSettings,
93              File file, boolean addCommunityPermissions,
94              boolean addGuestPermissions)
95          throws PortalException, SystemException {
96  
97          return addFileEntry(
98              userId, folderId, name, title, description, tagsEntries,
99              extraSettings, file, Boolean.valueOf(addCommunityPermissions),
100             Boolean.valueOf(addGuestPermissions), null, null);
101     }
102 
103     public DLFileEntry addFileEntry(
104             long userId, long folderId, String name, String title,
105             String description, String[] tagsEntries, String extraSettings,
106             byte[] bytes, boolean addCommunityPermissions,
107             boolean addGuestPermissions)
108         throws PortalException, SystemException {
109 
110         return addFileEntry(
111             null, userId, folderId, name, title, description, tagsEntries,
112             extraSettings, bytes, Boolean.valueOf(addCommunityPermissions),
113             Boolean.valueOf(addGuestPermissions), null, null);
114     }
115 
116     public DLFileEntry addFileEntry(
117             String uuid, long userId, long folderId, String name, String title,
118             String description, String[] tagsEntries, String extraSettings,
119             byte[] bytes, boolean addCommunityPermissions,
120             boolean addGuestPermissions)
121         throws PortalException, SystemException {
122 
123         return addFileEntry(
124             uuid, userId, folderId, name, title, description, tagsEntries,
125             extraSettings, bytes, Boolean.valueOf(addCommunityPermissions),
126             Boolean.valueOf(addGuestPermissions), null, null);
127     }
128 
129     public DLFileEntry addFileEntry(
130             long userId, long folderId, String name, String title,
131             String description, String[] tagsEntries, String extraSettings,
132             File file, String[] communityPermissions, String[] guestPermissions)
133         throws PortalException, SystemException {
134 
135         return addFileEntry(
136             userId, folderId, name, title, description, tagsEntries,
137             extraSettings, file, null, null, communityPermissions,
138             guestPermissions);
139     }
140 
141     public DLFileEntry addFileEntry(
142             long userId, long folderId, String name, String title,
143             String description, String[] tagsEntries, String extraSettings,
144             byte[] bytes, String[] communityPermissions,
145             String[] guestPermissions)
146         throws PortalException, SystemException {
147 
148         return addFileEntry(
149             null, userId, folderId, name, title, description, tagsEntries,
150             extraSettings, bytes, null, null, communityPermissions,
151             guestPermissions);
152     }
153 
154     public DLFileEntry addFileEntry(
155             long userId, long folderId, String name, String title,
156             String description, String[] tagsEntries, String extraSettings,
157             File file, Boolean addCommunityPermissions,
158             Boolean addGuestPermissions, String[] communityPermissions,
159             String[] guestPermissions)
160         throws PortalException, SystemException {
161 
162         if (!PropsValues.WEBDAV_LITMUS) {
163             if (file == null) {
164                 throw new FileSizeException();
165             }
166         }
167 
168         InputStream is = null;
169 
170         try {
171             is = new BufferedInputStream(new FileInputStream(file));
172 
173             return addFileEntry(
174                 null, userId, folderId, name, title, description, tagsEntries,
175                 extraSettings, is, file.length(), addCommunityPermissions,
176                 addGuestPermissions, communityPermissions, guestPermissions);
177         }
178         catch (FileNotFoundException fnfe) {
179             throw new FileSizeException();
180         }
181         finally {
182             try {
183                 if (is != null) {
184                     is.close();
185                 }
186             }
187             catch (IOException ioe) {
188                 _log.error(ioe);
189             }
190         }
191     }
192 
193     public DLFileEntry addFileEntry(
194             String uuid, long userId, long folderId, String name, String title,
195             String description, String[] tagsEntries, String extraSettings,
196             byte[] bytes, Boolean addCommunityPermissions,
197             Boolean addGuestPermissions, String[] communityPermissions,
198             String[] guestPermissions)
199         throws PortalException, SystemException {
200 
201         if (!PropsValues.WEBDAV_LITMUS) {
202             if ((bytes == null) || (bytes.length == 0)) {
203                 throw new FileSizeException();
204             }
205         }
206 
207         InputStream is = new ByteArrayInputStream(bytes);
208 
209         return addFileEntry(
210             uuid, userId, folderId, name, title, description, tagsEntries,
211             extraSettings, is, bytes.length, addCommunityPermissions,
212             addGuestPermissions, communityPermissions, guestPermissions);
213     }
214 
215     public DLFileEntry addFileEntry(
216             String uuid, long userId, long folderId, String name, String title,
217             String description, String[] tagsEntries, String extraSettings,
218             InputStream is, long size, Boolean addCommunityPermissions,
219             Boolean addGuestPermissions, String[] communityPermissions,
220             String[] guestPermissions)
221         throws PortalException, SystemException {
222 
223         // File entry
224 
225         User user = userPersistence.findByPrimaryKey(userId);
226         folderId = getFolderId(user.getCompanyId(), folderId);
227         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
228         Date now = new Date();
229 
230         if (Validator.isNull(title)) {
231             title = name;
232         }
233 
234         name = getName(name);
235         title = DLFileEntryImpl.stripExtension(name, title);
236 
237         validate(folder.getGroupId(), folderId, name, title, is);
238 
239         long fileEntryId = counterLocalService.increment();
240 
241         DLFileEntry fileEntry = dlFileEntryPersistence.create(fileEntryId);
242 
243         fileEntry.setUuid(uuid);
244         fileEntry.setCompanyId(user.getCompanyId());
245         fileEntry.setUserId(user.getUserId());
246         fileEntry.setUserName(user.getFullName());
247         fileEntry.setVersionUserId(user.getUserId());
248         fileEntry.setVersionUserName(user.getFullName());
249         fileEntry.setCreateDate(now);
250         fileEntry.setModifiedDate(now);
251         fileEntry.setFolderId(folderId);
252         fileEntry.setName(name);
253         fileEntry.setTitle(title);
254         fileEntry.setDescription(description);
255         fileEntry.setVersion(DLFileEntryImpl.DEFAULT_VERSION);
256         fileEntry.setSize((int)size);
257         fileEntry.setReadCount(DLFileEntryImpl.DEFAULT_READ_COUNT);
258         fileEntry.setExtraSettings(extraSettings);
259 
260         dlFileEntryPersistence.update(fileEntry, false);
261 
262         // Resources
263 
264         if ((addCommunityPermissions != null) &&
265             (addGuestPermissions != null)) {
266 
267             addFileEntryResources(
268                 folder, fileEntry, addCommunityPermissions.booleanValue(),
269                 addGuestPermissions.booleanValue());
270         }
271         else {
272             addFileEntryResources(
273                 folder, fileEntry, communityPermissions, guestPermissions);
274         }
275 
276         // File
277 
278         dlLocalService.addFile(
279             user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
280             folder.getGroupId(), folderId, name, fileEntryId,
281             fileEntry.getLuceneProperties(), fileEntry.getModifiedDate(),
282             tagsEntries, is);
283 
284         // Tags
285 
286         updateTagsAsset(userId, fileEntry, tagsEntries);
287 
288         // Folder
289 
290         folder.setLastPostDate(fileEntry.getModifiedDate());
291 
292         dlFolderPersistence.update(folder, false);
293 
294         return fileEntry;
295     }
296 
297     public void addFileEntryResources(
298             long folderId, String name, boolean addCommunityPermissions,
299             boolean addGuestPermissions)
300         throws PortalException, SystemException {
301 
302         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
303         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
304             folderId, name);
305 
306         addFileEntryResources(
307             folder, fileEntry, addCommunityPermissions, addGuestPermissions);
308     }
309 
310     public void addFileEntryResources(
311             DLFolder folder, DLFileEntry fileEntry,
312             boolean addCommunityPermissions, boolean addGuestPermissions)
313         throws PortalException, SystemException {
314 
315         resourceLocalService.addResources(
316             fileEntry.getCompanyId(), folder.getGroupId(),
317             fileEntry.getUserId(), DLFileEntry.class.getName(),
318             fileEntry.getFileEntryId(), false, addCommunityPermissions,
319             addGuestPermissions);
320     }
321 
322     public void addFileEntryResources(
323             long folderId, String name, String[] communityPermissions,
324             String[] guestPermissions)
325         throws PortalException, SystemException {
326 
327         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
328         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
329             folderId, name);
330 
331         addFileEntryResources(
332             folder, fileEntry, communityPermissions, guestPermissions);
333     }
334 
335     public void addFileEntryResources(
336             DLFolder folder, DLFileEntry fileEntry,
337             String[] communityPermissions, String[] guestPermissions)
338         throws PortalException, SystemException {
339 
340         resourceLocalService.addModelResources(
341             fileEntry.getCompanyId(), folder.getGroupId(),
342             fileEntry.getUserId(), DLFileEntry.class.getName(),
343             fileEntry.getFileEntryId(), communityPermissions, guestPermissions);
344     }
345 
346     public DLFileEntry addOrOverwriteFileEntry(
347             long userId, long folderId, String name, String sourceName,
348             String title, String description, String[] tagsEntries,
349             String extraSettings, File file, boolean addCommunityPermissions,
350             boolean addGuestPermissions)
351         throws PortalException, SystemException {
352 
353         boolean update = false;
354 
355         String extension = FileUtil.getExtension(name);
356 
357         List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
358             folderId, title);
359 
360         for (DLFileEntry fileEntry : fileEntries) {
361             String curExtension = FileUtil.getExtension(fileEntry.getName());
362 
363             if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
364                 if (Validator.isNull(curExtension)) {
365                     update = true;
366 
367                     name = fileEntry.getName();
368 
369                     break;
370                 }
371             }
372             else if (extension.equals(curExtension)) {
373                 update = true;
374 
375                 break;
376             }
377         }
378 
379         if (update) {
380             return updateFileEntry(
381                 userId, folderId, folderId, name, sourceName, title,
382                 description, tagsEntries, extraSettings, file);
383         }
384         else {
385             return addFileEntry(
386                 userId, folderId, name, title, description, tagsEntries,
387                 extraSettings, file, addCommunityPermissions,
388                 addGuestPermissions);
389         }
390     }
391 
392     public void deleteFileEntries(long folderId)
393         throws PortalException, SystemException {
394 
395         List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByFolderId(
396             folderId);
397 
398         for (DLFileEntry fileEntry : fileEntries) {
399             deleteFileEntry(fileEntry);
400         }
401     }
402 
403     public void deleteFileEntry(long folderId, String name)
404         throws PortalException, SystemException {
405 
406         deleteFileEntry(folderId, name, -1);
407     }
408 
409     public void deleteFileEntry(long folderId, String name, double version)
410         throws PortalException, SystemException {
411 
412         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
413             folderId, name);
414 
415         if (version > 0) {
416             try {
417                 dlService.deleteFile(
418                     fileEntry.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
419                     fileEntry.getFolderId(), fileEntry.getName(), version);
420             }
421             catch (Exception e) {
422                 if (_log.isWarnEnabled()) {
423                     _log.warn(e, e);
424                 }
425             }
426 
427             dlFileVersionPersistence.removeByF_N_V(folderId, name, version);
428         }
429         else {
430             deleteFileEntry(fileEntry);
431         }
432     }
433 
434     public void deleteFileEntry(DLFileEntry fileEntry)
435         throws PortalException, SystemException {
436 
437         // File
438 
439         try {
440             dlService.deleteFile(
441                 fileEntry.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
442                 fileEntry.getFolderId(), fileEntry.getName());
443         }
444         catch (Exception e) {
445             if (_log.isWarnEnabled()) {
446                 _log.warn(e, e);
447             }
448         }
449 
450         // File ranks
451 
452         dlFileRankLocalService.deleteFileRanks(
453             fileEntry.getFolderId(), fileEntry.getName());
454 
455         // File shortcuts
456 
457         dlFileShortcutLocalService.deleteFileShortcuts(
458             fileEntry.getFolderId(), fileEntry.getName());
459 
460         // File versions
461 
462         List<DLFileVersion> fileVersions = dlFileVersionPersistence.findByF_N(
463             fileEntry.getFolderId(), fileEntry.getName());
464 
465         for (DLFileVersion fileVersion : fileVersions) {
466             dlFileVersionPersistence.remove(fileVersion);
467         }
468 
469         // Tags
470 
471         tagsAssetLocalService.deleteAsset(
472             DLFileEntry.class.getName(), fileEntry.getFileEntryId());
473 
474         // Ratings
475 
476         ratingsStatsLocalService.deleteStats(
477             DLFileEntry.class.getName(), fileEntry.getFileEntryId());
478 
479         // Message boards
480 
481         mbMessageLocalService.deleteDiscussionMessages(
482             DLFileEntry.class.getName(), fileEntry.getFileEntryId());
483 
484         // WebDAVProps
485 
486         webDAVPropsLocalService.deleteWebDAVProps(
487             DLFileEntry.class.getName(), fileEntry.getPrimaryKey());
488 
489         // Resources
490 
491         resourceLocalService.deleteResource(
492             fileEntry.getCompanyId(), DLFileEntry.class.getName(),
493             ResourceConstants.SCOPE_INDIVIDUAL, fileEntry.getFileEntryId());
494 
495         // File entry
496 
497         dlFileEntryPersistence.remove(fileEntry);
498     }
499 
500     public List<DLFileEntry> getCompanyFileEntries(
501             long companyId, int start, int end)
502         throws SystemException {
503 
504         return dlFileEntryPersistence.findByCompanyId(companyId, start, end);
505     }
506 
507     public List<DLFileEntry> getCompanyFileEntries(
508             long companyId, int start, int end, OrderByComparator obc)
509         throws SystemException {
510 
511         return dlFileEntryPersistence.findByCompanyId(
512             companyId, start, end, obc);
513     }
514 
515     public int getCompanyFileEntriesCount(long companyId)
516         throws SystemException {
517 
518         return dlFileEntryPersistence.countByCompanyId(companyId);
519     }
520 
521     public InputStream getFileAsStream(
522             long companyId, long userId, long folderId, String name)
523         throws PortalException, SystemException {
524 
525         return getFileAsStream(companyId, userId, folderId, name, 0);
526     }
527 
528     public InputStream getFileAsStream(
529             long companyId, long userId, long folderId, String name,
530             double version)
531         throws PortalException, SystemException {
532 
533         if (userId > 0) {
534             DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
535 
536             dlFileRankLocalService.updateFileRank(
537                 folder.getGroupId(), companyId, userId, folderId, name);
538         }
539 
540         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
541             folderId, name);
542 
543         fileEntry.setReadCount(fileEntry.getReadCount() + 1);
544 
545         dlFileEntryPersistence.update(fileEntry, false);
546 
547         if ((version > 0) && (fileEntry.getVersion() != version)) {
548             return dlLocalService.getFileAsStream(
549                 companyId, folderId, name, version);
550         }
551         else {
552             return dlLocalService.getFileAsStream(companyId, folderId, name);
553         }
554     }
555 
556     public List<DLFileEntry> getFileEntries(long folderId)
557         throws SystemException {
558 
559         return dlFileEntryPersistence.findByFolderId(folderId);
560     }
561 
562     public List<DLFileEntry> getFileEntries(long folderId, int start, int end)
563         throws SystemException {
564 
565         return dlFileEntryPersistence.findByFolderId(folderId, start, end);
566     }
567 
568     public List<DLFileEntry> getFileEntries(
569             long folderId, int start, int end, OrderByComparator obc)
570         throws SystemException {
571 
572         return dlFileEntryPersistence.findByFolderId(folderId, start, end, obc);
573     }
574 
575     public int getFileEntriesCount(long folderId) throws SystemException {
576         return dlFileEntryPersistence.countByFolderId(folderId);
577     }
578 
579     public DLFileEntry getFileEntry(long fileEntryId)
580         throws PortalException, SystemException {
581 
582         return dlFileEntryPersistence.findByPrimaryKey(fileEntryId);
583     }
584 
585     public DLFileEntry getFileEntry(long folderId, String name)
586         throws PortalException, SystemException {
587 
588         return dlFileEntryPersistence.findByF_N(folderId, name);
589     }
590 
591     public DLFileEntry getFileEntryByUuidAndGroupId(String uuid, long groupId)
592         throws PortalException, SystemException {
593 
594         return dlFileEntryFinder.findByUuid_G(uuid, groupId);
595     }
596 
597     public DLFileEntry getFileEntryByTitle(
598             long folderId, String titleWithExtension)
599         throws PortalException, SystemException {
600 
601         String title = DLFileEntryImpl.stripExtension(
602             titleWithExtension, titleWithExtension);
603         String extension = FileUtil.getExtension(titleWithExtension);
604 
605         List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
606             folderId, title);
607 
608         for (DLFileEntry fileEntry : fileEntries) {
609             String curExtension = FileUtil.getExtension(fileEntry.getName());
610 
611             if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
612                 if (Validator.isNull(curExtension)) {
613                     return fileEntry;
614                 }
615             }
616             else if (extension.equals(curExtension)) {
617                 return fileEntry;
618             }
619         }
620 
621         throw new NoSuchFileEntryException();
622     }
623 
624     public int getFoldersFileEntriesCount(List<Long> folderIds)
625         throws SystemException {
626 
627         return dlFileEntryFinder.countByFolderIds(folderIds);
628     }
629 
630     public List<DLFileEntry> getGroupFileEntries(
631             long groupId, int start, int end)
632         throws SystemException {
633 
634         return dlFileEntryFinder.findByGroupId(groupId, start, end);
635     }
636 
637     public List<DLFileEntry> getGroupFileEntries(
638             long groupId, int start, int end, OrderByComparator obc)
639         throws SystemException {
640 
641         return dlFileEntryFinder.findByGroupId(groupId, start, end, obc);
642     }
643 
644     public List<DLFileEntry> getGroupFileEntries(
645             long groupId, long userId, int start, int end)
646         throws SystemException {
647 
648         if (userId <= 0) {
649             return dlFileEntryFinder.findByGroupId(groupId, start, end);
650         }
651         else {
652             return dlFileEntryFinder.findByG_U(groupId, userId, start, end);
653         }
654     }
655 
656     public List<DLFileEntry> getGroupFileEntries(
657             long groupId, long userId, int start, int end,
658             OrderByComparator obc)
659         throws SystemException {
660 
661         if (userId <= 0) {
662             return dlFileEntryFinder.findByGroupId(groupId, start, end, obc);
663         }
664         else {
665             return dlFileEntryFinder.findByG_U(
666                 groupId, userId, start, end, obc);
667         }
668     }
669 
670     public int getGroupFileEntriesCount(long groupId) throws SystemException {
671         return dlFileEntryFinder.countByGroupId(groupId);
672     }
673 
674     public int getGroupFileEntriesCount(long groupId, long userId)
675         throws SystemException {
676 
677         if (userId <= 0) {
678             return dlFileEntryFinder.countByGroupId(groupId);
679         }
680         else {
681             return dlFileEntryFinder.countByG_U(groupId, userId);
682         }
683     }
684 
685     public List<DLFileEntry> getNoAssetFileEntries() throws SystemException {
686         return dlFileEntryFinder.findByNoAssets();
687     }
688 
689     public void reIndex(long fileEntryId) throws SystemException {
690         if (SearchEngineUtil.isIndexReadOnly()) {
691             return;
692         }
693 
694         DLFileEntry fileEntry = dlFileEntryPersistence.fetchByPrimaryKey(
695             fileEntryId);
696 
697         if (fileEntry == null) {
698             return;
699         }
700 
701         DLFolder folder = fileEntry.getFolder();
702 
703         long companyId = fileEntry.getCompanyId();
704         String portletId = PortletKeys.DOCUMENT_LIBRARY;
705         long groupId = folder.getGroupId();
706         long folderId = folder.getFolderId();
707         String fileName = fileEntry.getName();
708         String properties = fileEntry.getLuceneProperties();
709         Date modifiedDate = fileEntry.getModifiedDate();
710 
711         String[] tagsEntries = tagsEntryLocalService.getEntryNames(
712             DLFileEntry.class.getName(), fileEntryId);
713 
714         try {
715             Indexer.updateFile(
716                 companyId, portletId, groupId, folderId, fileName, fileEntryId,
717                 properties, modifiedDate, tagsEntries);
718         }
719         catch (SearchException se) {
720             _log.error("Reindexing " + fileEntryId, se);
721         }
722     }
723 
724     public DLFileEntry updateFileEntry(
725             long userId, long folderId, long newFolderId, String name,
726             String sourceFileName, String title, String description,
727             String[] tagsEntries, String extraSettings, File file)
728         throws PortalException, SystemException {
729 
730         InputStream is = null;
731 
732         try {
733             long size = 0;
734 
735             if ((file != null) && (file.length() > 0)) {
736                 is = new BufferedInputStream(new FileInputStream(file));
737                 size = file.length();
738             }
739 
740             return updateFileEntry(
741                 userId, folderId, newFolderId, name, sourceFileName, title,
742                 description, tagsEntries, extraSettings, is, size);
743         }
744         catch (FileNotFoundException fnfe) {
745             throw new NoSuchFileException();
746         }
747         finally {
748             try {
749                 if (is != null) {
750                     is.close();
751                 }
752             }
753             catch (IOException ioe) {
754                 _log.error(ioe);
755             }
756         }
757     }
758 
759     public DLFileEntry updateFileEntry(
760             long userId, long folderId, long newFolderId, String name,
761             String sourceFileName, String title, String description,
762             String[] tagsEntries, String extraSettings, byte[] bytes)
763         throws PortalException, SystemException {
764 
765         InputStream is = null;
766         long size = 0;
767 
768         if ((bytes != null) && (bytes.length > 0)) {
769             is = new ByteArrayInputStream(bytes);
770             size = bytes.length;
771         }
772 
773         return updateFileEntry(
774             userId, folderId, newFolderId, name, sourceFileName, title,
775             description, tagsEntries, extraSettings, is, size);
776     }
777 
778     public DLFileEntry updateFileEntry(
779             long userId, long folderId, long newFolderId, String name,
780             String sourceFileName, String title, String description,
781             String[] tagsEntries, String extraSettings, InputStream is,
782             long size)
783         throws PortalException, SystemException {
784 
785         // File entry
786 
787         User user = userPersistence.findByPrimaryKey(userId);
788         DLFolder folder = dlFolderPersistence.findByPrimaryKey(folderId);
789 
790         if (Validator.isNull(title)) {
791             title = sourceFileName;
792 
793             if (Validator.isNull(title)) {
794                 title = name;
795             }
796         }
797 
798         title = DLFileEntryImpl.stripExtension(name, title);
799 
800         validate(
801             folder.getGroupId(), folderId, newFolderId, name, title,
802             sourceFileName, is);
803 
804         DLFileEntry fileEntry = dlFileEntryPersistence.findByF_N(
805             folderId, name);
806 
807         fileEntry.setTitle(title);
808         fileEntry.setDescription(description);
809         fileEntry.setExtraSettings(extraSettings);
810 
811         dlFileEntryPersistence.update(fileEntry, false);
812 
813         // Move file entry
814 
815         if ((newFolderId > 0) && (folderId != newFolderId)) {
816             long oldFileEntryId = fileEntry.getFileEntryId();
817 
818             DLFolder newFolder = dlFolderPersistence.findByPrimaryKey(
819                 newFolderId);
820 
821             if (folder.getGroupId() != newFolder.getGroupId()) {
822                 throw new NoSuchFolderException();
823             }
824 
825             if (dlLocalService.hasFile(
826                     user.getCompanyId(), newFolderId, name, 0)) {
827 
828                 throw new DuplicateFileException(name);
829             }
830 
831             long newFileEntryId = counterLocalService.increment();
832 
833             DLFileEntry newFileEntry = dlFileEntryPersistence.create(
834                 newFileEntryId);
835 
836             newFileEntry.setCompanyId(fileEntry.getCompanyId());
837             newFileEntry.setUserId(fileEntry.getUserId());
838             newFileEntry.setUserName(fileEntry.getUserName());
839             newFileEntry.setVersionUserId(fileEntry.getVersionUserId());
840             newFileEntry.setVersionUserName(fileEntry.getVersionUserName());
841             newFileEntry.setCreateDate(fileEntry.getCreateDate());
842             newFileEntry.setModifiedDate(fileEntry.getModifiedDate());
843             newFileEntry.setFolderId(newFolderId);
844             newFileEntry.setName(name);
845             newFileEntry.setTitle(fileEntry.getTitle());
846             newFileEntry.setDescription(fileEntry.getDescription());
847             newFileEntry.setVersion(fileEntry.getVersion());
848             newFileEntry.setSize(fileEntry.getSize());
849             newFileEntry.setReadCount(fileEntry.getReadCount());
850             newFileEntry.setExtraSettings(extraSettings);
851 
852             dlFileEntryPersistence.update(newFileEntry, false);
853 
854             dlFileEntryPersistence.remove(fileEntry);
855 
856             List<DLFileVersion> fileVersions =
857                 dlFileVersionPersistence.findByF_N(folderId, name);
858 
859             for (DLFileVersion fileVersion : fileVersions) {
860                 long newFileVersionId = counterLocalService.increment();
861 
862                 DLFileVersion newFileVersion = dlFileVersionPersistence.create(
863                     newFileVersionId);
864 
865                 newFileVersion.setCompanyId(fileVersion.getCompanyId());
866                 newFileVersion.setUserId(fileVersion.getUserId());
867                 newFileVersion.setUserName(fileVersion.getUserName());
868                 newFileVersion.setCreateDate(fileVersion.getCreateDate());
869                 newFileVersion.setFolderId(newFolderId);
870                 newFileVersion.setName(name);
871                 newFileVersion.setVersion(fileVersion.getVersion());
872                 newFileVersion.setSize(fileVersion.getSize());
873 
874                 dlFileVersionPersistence.update(newFileVersion, false);
875 
876                 dlFileVersionPersistence.remove(fileVersion);
877             }
878 
879             dlFileShortcutLocalService.updateFileShortcuts(
880                 folderId, name, newFolderId, name);
881 
882             // Resources
883 
884             Resource resource = resourceLocalService.getResource(
885                 fileEntry.getCompanyId(), DLFileEntry.class.getName(),
886                 ResourceConstants.SCOPE_INDIVIDUAL,
887                 String.valueOf(fileEntry.getPrimaryKey()));
888 
889             resource.setPrimKey(String.valueOf(newFileEntryId));
890 
891             resourcePersistence.update(resource, false);
892 
893             // File
894 
895             dlService.updateFile(
896                 user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
897                 folder.getGroupId(), folderId, newFolderId, name,
898                 newFileEntryId);
899 
900             // Ratings
901 
902             long classNameId = PortalUtil.getClassNameId(
903                 DLFileEntry.class.getName());
904 
905             RatingsStats stats = ratingsStatsPersistence.fetchByC_C(
906                 classNameId, oldFileEntryId);
907 
908             stats.setClassPK(newFileEntryId);
909 
910             ratingsStatsPersistence.update(stats, false);
911 
912             List<RatingsEntry> entries = ratingsEntryPersistence.findByC_C(
913                 classNameId, oldFileEntryId);
914 
915             for (RatingsEntry entry : entries) {
916                 entry.setClassPK(newFileEntryId);
917 
918                 ratingsEntryPersistence.update(entry, false);
919             }
920 
921             // Message boards
922 
923             MBDiscussion discussion = mbDiscussionPersistence.fetchByC_C(
924                 classNameId, oldFileEntryId);
925 
926             if (discussion != null) {
927                 discussion.setClassPK(newFileEntryId);
928 
929                 mbDiscussionPersistence.update(discussion, false);
930             }
931 
932             // Tags
933 
934             tagsAssetLocalService.deleteAsset(
935                 DLFileEntry.class.getName(), fileEntry.getFileEntryId());
936 
937             folderId = newFolderId;
938             folder = newFolder;
939             fileEntry = newFileEntry;
940         }
941 
942         // Tags
943 
944         updateTagsAsset(userId, fileEntry, tagsEntries);
945 
946         // File version
947 
948         double oldVersion = fileEntry.getVersion();
949         double newVersion = MathUtil.format(oldVersion + 0.1, 1, 1);
950 
951         if (is == null) {
952             fileEntry.setVersion(newVersion);
953 
954             dlFileEntryPersistence.update(fileEntry, false);
955 
956             is = dlLocalService.getFileAsStream(
957                 user.getCompanyId(), folderId, name);
958 
959             dlLocalService.updateFile(
960                 user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
961                 folder.getGroupId(), folderId, name, newVersion, name,
962                 fileEntry.getFileEntryId(), fileEntry.getLuceneProperties(),
963                 fileEntry.getModifiedDate(), tagsEntries, is);
964 
965             return fileEntry;
966         }
967 
968         long fileVersionId = counterLocalService.increment();
969 
970         DLFileVersion fileVersion = dlFileVersionPersistence.create(
971             fileVersionId);
972 
973         long versionUserId = fileEntry.getVersionUserId();
974 
975         if (versionUserId <= 0) {
976             versionUserId = fileEntry.getUserId();
977         }
978 
979         String versionUserName = GetterUtil.getString(
980             fileEntry.getVersionUserName(), fileEntry.getUserName());
981 
982         fileVersion.setCompanyId(fileEntry.getCompanyId());
983         fileVersion.setUserId(versionUserId);
984         fileVersion.setUserName(versionUserName);
985         fileVersion.setCreateDate(fileEntry.getModifiedDate());
986         fileVersion.setFolderId(folderId);
987         fileVersion.setName(name);
988         fileVersion.setVersion(oldVersion);
989         fileVersion.setSize(fileEntry.getSize());
990 
991         dlFileVersionPersistence.update(fileVersion, false);
992 
993         // File entry
994 
995         fileEntry.setVersionUserId(user.getUserId());
996         fileEntry.setVersionUserName(user.getFullName());
997         fileEntry.setModifiedDate(new Date());
998         fileEntry.setVersion(newVersion);
999         fileEntry.setSize((int)size);
1000
1001        dlFileEntryPersistence.update(fileEntry, false);
1002
1003        // File
1004
1005        dlLocalService.updateFile(
1006            user.getCompanyId(), PortletKeys.DOCUMENT_LIBRARY,
1007            folder.getGroupId(), folderId, name, newVersion, sourceFileName,
1008            fileEntry.getFileEntryId(), fileEntry.getLuceneProperties(),
1009            fileEntry.getModifiedDate(), tagsEntries, is);
1010
1011        // Folder
1012
1013        folder.setLastPostDate(fileEntry.getModifiedDate());
1014
1015        dlFolderPersistence.update(folder, false);
1016
1017        return fileEntry;
1018    }
1019
1020    public void updateTagsAsset(
1021            long userId, DLFileEntry fileEntry, String[] tagsEntries)
1022        throws PortalException, SystemException {
1023
1024        String mimeType = MimeTypesUtil.getContentType(fileEntry.getName());
1025
1026        tagsAssetLocalService.updateAsset(
1027            userId, fileEntry.getFolder().getGroupId(),
1028            DLFileEntry.class.getName(), fileEntry.getFileEntryId(), null,
1029            tagsEntries, true, null, null, null, null, mimeType,
1030            fileEntry.getTitle(), fileEntry.getDescription(), null, null, 0, 0,
1031            null, false);
1032    }
1033
1034    protected long getFolderId(long companyId, long folderId)
1035        throws SystemException {
1036
1037        if (folderId != DLFolderImpl.DEFAULT_PARENT_FOLDER_ID) {
1038
1039            // Ensure folder exists and belongs to the proper company
1040
1041            DLFolder folder = dlFolderPersistence.fetchByPrimaryKey(folderId);
1042
1043            if ((folder == null) || (companyId != folder.getCompanyId())) {
1044                folderId = DLFolderImpl.DEFAULT_PARENT_FOLDER_ID;
1045            }
1046        }
1047
1048        return folderId;
1049    }
1050
1051    protected String getName(String name) throws SystemException {
1052        String extension = StringPool.BLANK;
1053
1054        int pos = name.lastIndexOf(StringPool.PERIOD);
1055
1056        if (pos != -1) {
1057            extension = name.substring(pos + 1, name.length()).toLowerCase();
1058        }
1059
1060        name = String.valueOf(counterLocalService.increment(
1061            DLFileEntry.class.getName()));
1062
1063        if (Validator.isNotNull(extension)) {
1064            name = "DLFE-" + name + StringPool.PERIOD + extension;
1065        }
1066
1067        return name;
1068    }
1069
1070    protected void validate(
1071            long groupId, long folderId, long newFolderId, String name,
1072            String title, String sourceFileName, InputStream is)
1073        throws PortalException, SystemException {
1074
1075        if (Validator.isNotNull(sourceFileName)) {
1076            dlLocalService.validate(name, sourceFileName, is);
1077        }
1078
1079        if (newFolderId > 0 && (folderId != newFolderId)) {
1080            folderId = newFolderId;
1081        }
1082
1083        String extension = FileUtil.getExtension(name);
1084
1085        try {
1086            String titleWithExtension = title;
1087
1088            if (Validator.isNotNull(extension)) {
1089                titleWithExtension += StringPool.PERIOD + extension;
1090            }
1091
1092            dlFolderLocalService.getFolder(
1093                groupId, folderId, titleWithExtension);
1094
1095            throw new DuplicateFolderNameException();
1096        }
1097        catch (NoSuchFolderException nsfe) {
1098        }
1099
1100        List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
1101            folderId, title);
1102
1103        for (DLFileEntry fileEntry : fileEntries) {
1104            if (!name.equals(fileEntry.getName())) {
1105                String curExtension = FileUtil.getExtension(
1106                    fileEntry.getName());
1107
1108                if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
1109                    if (Validator.isNull(curExtension)) {
1110                        throw new DuplicateFileException(
1111                            fileEntry.getTitleWithExtension());
1112                    }
1113                }
1114                else if (extension.equals(curExtension)) {
1115                    throw new DuplicateFileException(
1116                        fileEntry.getTitleWithExtension());
1117                }
1118            }
1119        }
1120    }
1121
1122    protected void validate(
1123            long groupId, long folderId, String name, String title,
1124            InputStream is)
1125        throws PortalException, SystemException {
1126
1127        dlLocalService.validate(name, is);
1128
1129        String extension = FileUtil.getExtension(name);
1130
1131        try {
1132            String titleWithExtension = title;
1133
1134            if (Validator.isNotNull(extension)) {
1135                titleWithExtension += StringPool.PERIOD + extension;
1136            }
1137
1138            dlFolderLocalService.getFolder(
1139                groupId, folderId, titleWithExtension);
1140
1141            throw new DuplicateFolderNameException();
1142        }
1143        catch (NoSuchFolderException nsfe) {
1144        }
1145
1146        List<DLFileEntry> fileEntries = dlFileEntryPersistence.findByF_T(
1147            folderId, title);
1148
1149        for (DLFileEntry fileEntry : fileEntries) {
1150            String curExtension = FileUtil.getExtension(fileEntry.getName());
1151
1152            if (PropsValues.WEBDAV_LITMUS && Validator.isNull(extension)) {
1153                if (Validator.isNull(curExtension)) {
1154                    throw new DuplicateFileException(
1155                        fileEntry.getTitleWithExtension());
1156                }
1157            }
1158            else if (extension.equals(curExtension)) {
1159                throw new DuplicateFileException(
1160                    fileEntry.getTitleWithExtension());
1161            }
1162        }
1163    }
1164
1165    private static Log _log =
1166        LogFactoryUtil.getLog(DLFileEntryLocalServiceImpl.class);
1167
1168}