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