001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.bookmarks.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.json.JSONFactoryUtil;
020    import com.liferay.portal.kernel.json.JSONObject;
021    import com.liferay.portal.kernel.log.Log;
022    import com.liferay.portal.kernel.log.LogFactoryUtil;
023    import com.liferay.portal.kernel.search.Indexable;
024    import com.liferay.portal.kernel.search.IndexableType;
025    import com.liferay.portal.kernel.util.ArrayUtil;
026    import com.liferay.portal.kernel.util.ContentTypes;
027    import com.liferay.portal.kernel.util.OrderByComparator;
028    import com.liferay.portal.kernel.util.StringPool;
029    import com.liferay.portal.kernel.util.Validator;
030    import com.liferay.portal.kernel.workflow.WorkflowConstants;
031    import com.liferay.portal.model.ResourceConstants;
032    import com.liferay.portal.model.User;
033    import com.liferay.portal.service.ServiceContext;
034    import com.liferay.portal.service.ServiceContextUtil;
035    import com.liferay.portal.util.Portal;
036    import com.liferay.portal.util.PortletKeys;
037    import com.liferay.portal.util.SubscriptionSender;
038    import com.liferay.portlet.asset.model.AssetEntry;
039    import com.liferay.portlet.asset.model.AssetLinkConstants;
040    import com.liferay.portlet.bookmarks.EntryURLException;
041    import com.liferay.portlet.bookmarks.model.BookmarksEntry;
042    import com.liferay.portlet.bookmarks.model.BookmarksFolder;
043    import com.liferay.portlet.bookmarks.model.BookmarksFolderConstants;
044    import com.liferay.portlet.bookmarks.service.base.BookmarksEntryLocalServiceBaseImpl;
045    import com.liferay.portlet.bookmarks.social.BookmarksActivityKeys;
046    import com.liferay.portlet.bookmarks.util.BookmarksUtil;
047    import com.liferay.portlet.bookmarks.util.comparator.EntryModifiedDateComparator;
048    import com.liferay.portlet.social.model.SocialActivityConstants;
049    import com.liferay.portlet.trash.model.TrashEntry;
050    
051    import java.util.Date;
052    import java.util.List;
053    import java.util.Locale;
054    import java.util.Map;
055    
056    import javax.portlet.PortletPreferences;
057    
058    /**
059     * @author Brian Wing Shun Chan
060     * @author Raymond Augé
061     * @author Levente Hudák
062     */
063    public class BookmarksEntryLocalServiceImpl
064            extends BookmarksEntryLocalServiceBaseImpl {
065    
066            @Indexable(type = IndexableType.REINDEX)
067            public BookmarksEntry addEntry(
068                            long userId, long groupId, long folderId, String name, String url,
069                            String description, ServiceContext serviceContext)
070                    throws PortalException, SystemException {
071    
072                    // Entry
073    
074                    User user = userPersistence.findByPrimaryKey(userId);
075    
076                    if (Validator.isNull(name)) {
077                            name = url;
078                    }
079    
080                    Date now = new Date();
081    
082                    validate(url);
083    
084                    long entryId = counterLocalService.increment();
085    
086                    BookmarksEntry entry = bookmarksEntryPersistence.create(entryId);
087    
088                    entry.setUuid(serviceContext.getUuid());
089                    entry.setGroupId(groupId);
090                    entry.setCompanyId(user.getCompanyId());
091                    entry.setUserId(user.getUserId());
092                    entry.setUserName(user.getFullName());
093                    entry.setCreateDate(serviceContext.getCreateDate(now));
094                    entry.setModifiedDate(serviceContext.getModifiedDate(now));
095                    entry.setFolderId(folderId);
096                    entry.setName(name);
097                    entry.setUrl(url);
098                    entry.setDescription(description);
099                    entry.setExpandoBridgeAttributes(serviceContext);
100    
101                    bookmarksEntryPersistence.update(entry);
102    
103                    // Resources
104    
105                    resourceLocalService.addModelResources(entry, serviceContext);
106    
107                    // Asset
108    
109                    updateAsset(
110                            userId, entry, serviceContext.getAssetCategoryIds(),
111                            serviceContext.getAssetTagNames(),
112                            serviceContext.getAssetLinkEntryIds());
113    
114                    // Social
115    
116                    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();
117    
118                    extraDataJSONObject.put("title", entry.getName());
119    
120                    socialActivityLocalService.addActivity(
121                            userId, groupId, BookmarksEntry.class.getName(), entryId,
122                            BookmarksActivityKeys.ADD_ENTRY, extraDataJSONObject.toString(), 0);
123    
124                    // Subscriptions
125    
126                    notifySubscribers(entry, serviceContext);
127    
128                    return entry;
129            }
130    
131            public void deleteEntries(long groupId, long folderId)
132                    throws PortalException, SystemException {
133    
134                    deleteEntries(groupId, folderId, true);
135            }
136    
137            public void deleteEntries(
138                            long groupId, long folderId, boolean includeTrashedEntries)
139                    throws PortalException, SystemException {
140    
141                    List<BookmarksEntry> entries = bookmarksEntryPersistence.findByG_F(
142                            groupId, folderId);
143    
144                    for (BookmarksEntry entry : entries) {
145                            if (includeTrashedEntries || !entry.isInTrash()) {
146                                    bookmarksEntryLocalService.deleteEntry(entry);
147                            }
148                    }
149            }
150    
151            @Indexable(type = IndexableType.DELETE)
152            public BookmarksEntry deleteEntry(BookmarksEntry entry)
153                    throws PortalException, SystemException {
154    
155                    // Entry
156    
157                    bookmarksEntryPersistence.remove(entry);
158    
159                    // Resources
160    
161                    resourceLocalService.deleteResource(
162                            entry, ResourceConstants.SCOPE_INDIVIDUAL);
163    
164                    // Asset
165    
166                    assetEntryLocalService.deleteEntry(
167                            BookmarksEntry.class.getName(), entry.getEntryId());
168    
169                    // Expando
170    
171                    expandoValueLocalService.deleteValues(
172                            BookmarksEntry.class.getName(), entry.getEntryId());
173    
174                    // Subscriptions
175    
176                    subscriptionLocalService.deleteSubscriptions(
177                            entry.getCompanyId(), BookmarksEntry.class.getName(),
178                            entry.getEntryId());
179    
180                    // Trash
181    
182                    trashEntryLocalService.deleteEntry(
183                            BookmarksEntry.class.getName(), entry.getEntryId());
184    
185                    return entry;
186            }
187    
188            @Indexable(type = IndexableType.DELETE)
189            public BookmarksEntry deleteEntry(long entryId)
190                    throws PortalException, SystemException {
191    
192                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
193                            entryId);
194    
195                    return deleteEntry(entry);
196            }
197    
198            public List<BookmarksEntry> getEntries(
199                            long groupId, long folderId, int start, int end)
200                    throws SystemException {
201    
202                    return bookmarksEntryPersistence.findByG_F_S(
203                            groupId, folderId, WorkflowConstants.STATUS_APPROVED, start, end);
204            }
205    
206            public List<BookmarksEntry> getEntries(
207                            long groupId, long folderId, int start, int end,
208                            OrderByComparator orderByComparator)
209                    throws SystemException {
210    
211                    return bookmarksEntryPersistence.findByG_F_S(
212                            groupId, folderId, WorkflowConstants.STATUS_APPROVED, start, end,
213                            orderByComparator);
214            }
215    
216            public int getEntriesCount(long groupId, long folderId)
217                    throws SystemException {
218    
219                    return bookmarksEntryPersistence.countByG_F_S(
220                            groupId, folderId, WorkflowConstants.STATUS_APPROVED);
221            }
222    
223            public BookmarksEntry getEntry(long entryId)
224                    throws PortalException, SystemException {
225    
226                    return bookmarksEntryPersistence.findByPrimaryKey(entryId);
227            }
228    
229            public int getFoldersEntriesCount(long groupId, List<Long> folderIds)
230                    throws SystemException {
231    
232                    return bookmarksEntryPersistence.countByG_F_S(
233                            groupId,
234                            ArrayUtil.toArray(folderIds.toArray(new Long[folderIds.size()])),
235                            WorkflowConstants.STATUS_APPROVED);
236            }
237    
238            public List<BookmarksEntry> getGroupEntries(
239                            long groupId, int start, int end)
240                    throws SystemException {
241    
242                    return bookmarksEntryPersistence.findByG_S(
243                            groupId, WorkflowConstants.STATUS_APPROVED, start, end,
244                            new EntryModifiedDateComparator());
245            }
246    
247            public List<BookmarksEntry> getGroupEntries(
248                            long groupId, long userId, int start, int end)
249                    throws SystemException {
250    
251                    OrderByComparator orderByComparator = new EntryModifiedDateComparator();
252    
253                    if (userId <= 0) {
254                            return bookmarksEntryPersistence.findByG_S(
255                                    groupId, WorkflowConstants.STATUS_APPROVED, start, end,
256                                    orderByComparator);
257                    }
258                    else {
259                            return bookmarksEntryPersistence.findByG_U_S(
260                                    groupId, userId, WorkflowConstants.STATUS_APPROVED, start, end,
261                                    orderByComparator);
262                    }
263            }
264    
265            public int getGroupEntriesCount(long groupId) throws SystemException {
266                    return bookmarksEntryPersistence.countByG_S(
267                            groupId, WorkflowConstants.STATUS_APPROVED);
268            }
269    
270            public int getGroupEntriesCount(long groupId, long userId)
271                    throws SystemException {
272    
273                    if (userId <= 0) {
274                            return getGroupEntriesCount(groupId);
275                    }
276                    else {
277                            return bookmarksEntryPersistence.countByG_U_S(
278                                    groupId, userId, WorkflowConstants.STATUS_APPROVED);
279                    }
280            }
281    
282            public List<BookmarksEntry> getNoAssetEntries() throws SystemException {
283                    return bookmarksEntryFinder.findByNoAssets();
284            }
285    
286            @Indexable(type = IndexableType.REINDEX)
287            public BookmarksEntry moveEntry(long entryId, long parentFolderId)
288                    throws PortalException, SystemException {
289    
290                    BookmarksEntry entry = getBookmarksEntry(entryId);
291    
292                    entry.setFolderId(parentFolderId);
293    
294                    bookmarksEntryPersistence.update(entry);
295    
296                    return entry;
297            }
298    
299            public BookmarksEntry moveEntryFromTrash(
300                            long userId, long entryId, long parentFolderId)
301                    throws PortalException, SystemException {
302    
303                    restoreEntryFromTrash(userId, entryId);
304    
305                    return moveEntry(entryId, parentFolderId);
306            }
307    
308            @Indexable(type = IndexableType.REINDEX)
309            public BookmarksEntry moveEntryToTrash(long userId, BookmarksEntry entry)
310                    throws PortalException, SystemException {
311    
312                    return updateStatus(userId, entry, WorkflowConstants.STATUS_IN_TRASH);
313            }
314    
315            @Indexable(type = IndexableType.REINDEX)
316            public BookmarksEntry moveEntryToTrash(long userId, long entryId)
317                    throws PortalException, SystemException {
318    
319                    BookmarksEntry entry = getEntry(entryId);
320    
321                    return moveEntryToTrash(userId, entry);
322            }
323    
324            public BookmarksEntry openEntry(long userId, BookmarksEntry entry)
325                    throws SystemException {
326    
327                    entry.setVisits(entry.getVisits() + 1);
328    
329                    bookmarksEntryPersistence.update(entry);
330    
331                    assetEntryLocalService.incrementViewCounter(
332                            userId, BookmarksEntry.class.getName(), entry.getEntryId(), 1);
333    
334                    return entry;
335            }
336    
337            public BookmarksEntry openEntry(long userId, long entryId)
338                    throws PortalException, SystemException {
339    
340                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
341                            entryId);
342    
343                    return openEntry(userId, entry);
344            }
345    
346            @Indexable(type = IndexableType.REINDEX)
347            public BookmarksEntry restoreEntryFromTrash(long userId, long entryId)
348                    throws PortalException, SystemException {
349    
350                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
351                            entryId);
352    
353                    TrashEntry trashEntry = trashEntryLocalService.getEntry(
354                            BookmarksEntry.class.getName(), entryId);
355    
356                    return updateStatus(userId, entry, trashEntry.getStatus());
357            }
358    
359            public void subscribeEntry(long userId, long entryId)
360                    throws PortalException, SystemException {
361    
362                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
363                            entryId);
364    
365                    subscriptionLocalService.addSubscription(
366                            userId, entry.getGroupId(), BookmarksEntry.class.getName(),
367                            entryId);
368            }
369    
370            public void unsubscribeEntry(long userId, long entryId)
371                    throws PortalException, SystemException {
372    
373                    subscriptionLocalService.deleteSubscription(
374                            userId, BookmarksEntry.class.getName(), entryId);
375            }
376    
377            public void updateAsset(
378                            long userId, BookmarksEntry entry, long[] assetCategoryIds,
379                            String[] assetTagNames, long[] assetLinkEntryIds)
380                    throws PortalException, SystemException {
381    
382                    AssetEntry assetEntry = assetEntryLocalService.updateEntry(
383                            userId, entry.getGroupId(), entry.getCreateDate(),
384                            entry.getModifiedDate(), BookmarksEntry.class.getName(),
385                            entry.getEntryId(), entry.getUuid(), 0, assetCategoryIds,
386                            assetTagNames, true, null, null, null, ContentTypes.TEXT_PLAIN,
387                            entry.getName(), entry.getDescription(), null, entry.getUrl(), null,
388                            0, 0, null, false);
389    
390                    assetLinkLocalService.updateLinks(
391                            userId, assetEntry.getEntryId(), assetLinkEntryIds,
392                            AssetLinkConstants.TYPE_RELATED);
393            }
394    
395            @Indexable(type = IndexableType.REINDEX)
396            public BookmarksEntry updateEntry(
397                            long userId, long entryId, long groupId, long folderId, String name,
398                            String url, String description, ServiceContext serviceContext)
399                    throws PortalException, SystemException {
400    
401                    // Entry
402    
403                    BookmarksEntry entry = bookmarksEntryPersistence.findByPrimaryKey(
404                            entryId);
405    
406                    if (Validator.isNull(name)) {
407                            name = url;
408                    }
409    
410                    validate(url);
411    
412                    entry.setModifiedDate(serviceContext.getModifiedDate(null));
413                    entry.setFolderId(folderId);
414                    entry.setName(name);
415                    entry.setUrl(url);
416                    entry.setDescription(description);
417                    entry.setExpandoBridgeAttributes(serviceContext);
418    
419                    bookmarksEntryPersistence.update(entry);
420    
421                    // Asset
422    
423                    updateAsset(
424                            userId, entry, serviceContext.getAssetCategoryIds(),
425                            serviceContext.getAssetTagNames(),
426                            serviceContext.getAssetLinkEntryIds());
427    
428                    // Social
429    
430                    JSONObject extraDataJSONObject = JSONFactoryUtil.createJSONObject();
431    
432                    extraDataJSONObject.put("title", entry.getName());
433    
434                    socialActivityLocalService.addActivity(
435                            userId, entry.getGroupId(), BookmarksEntry.class.getName(), entryId,
436                            BookmarksActivityKeys.UPDATE_ENTRY, extraDataJSONObject.toString(),
437                            0);
438    
439                    // Subscriptions
440    
441                    notifySubscribers(entry, serviceContext);
442    
443                    return entry;
444            }
445    
446            public BookmarksEntry updateStatus(
447                            long userId, BookmarksEntry entry, int status)
448                    throws PortalException, SystemException {
449    
450                    // Entry
451    
452                    User user = userPersistence.findByPrimaryKey(userId);
453    
454                    int oldStatus = entry.getStatus();
455    
456                    entry.setStatus(status);
457                    entry.setStatusByUserId(userId);
458                    entry.setStatusByUserName(user.getScreenName());
459                    entry.setStatusDate(new Date());
460    
461                    bookmarksEntryPersistence.update(entry);
462    
463                    if (status == WorkflowConstants.STATUS_APPROVED) {
464    
465                            // Asset
466    
467                            assetEntryLocalService.updateVisible(
468                                    BookmarksEntry.class.getName(), entry.getEntryId(), true);
469    
470                            // Social
471    
472                            socialActivityCounterLocalService.enableActivityCounters(
473                                    BookmarksEntry.class.getName(), entry.getEntryId());
474    
475                            socialActivityLocalService.addActivity(
476                                    userId, entry.getGroupId(), BookmarksEntry.class.getName(),
477                                    entry.getEntryId(),
478                                    SocialActivityConstants.TYPE_RESTORE_FROM_TRASH,
479                                    StringPool.BLANK, 0);
480                    }
481                    else if (status == WorkflowConstants.STATUS_IN_TRASH) {
482    
483                            // Asset
484    
485                            assetEntryLocalService.updateVisible(
486                                    BookmarksEntry.class.getName(), entry.getEntryId(), false);
487    
488                            // Social
489    
490                            socialActivityCounterLocalService.disableActivityCounters(
491                                    BookmarksEntry.class.getName(), entry.getEntryId());
492    
493                            socialActivityLocalService.addActivity(
494                                    userId, entry.getGroupId(), BookmarksEntry.class.getName(),
495                                    entry.getEntryId(), SocialActivityConstants.TYPE_MOVE_TO_TRASH,
496                                    StringPool.BLANK, 0);
497                    }
498    
499                    // Trash
500    
501                    if (oldStatus == WorkflowConstants.STATUS_IN_TRASH) {
502                            trashEntryLocalService.deleteEntry(
503                                    BookmarksEntry.class.getName(), entry.getEntryId());
504                    }
505                    else if (status == WorkflowConstants.STATUS_IN_TRASH) {
506                            trashEntryLocalService.addTrashEntry(
507                                    userId, entry.getGroupId(), BookmarksEntry.class.getName(),
508                                    entry.getEntryId(), oldStatus, null, null);
509                    }
510    
511                    return entry;
512            }
513    
514            protected long getFolder(BookmarksEntry entry, long folderId)
515                    throws SystemException {
516    
517                    if ((entry.getFolderId() != folderId) &&
518                            (folderId != BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
519    
520                            BookmarksFolder newFolder =
521                                    bookmarksFolderPersistence.fetchByPrimaryKey(folderId);
522    
523                            if ((newFolder == null) ||
524                                    (entry.getGroupId() != newFolder.getGroupId())) {
525    
526                                    folderId = entry.getFolderId();
527                            }
528                    }
529    
530                    return folderId;
531            }
532    
533            protected void notifySubscribers(
534                            BookmarksEntry entry, ServiceContext serviceContext)
535                    throws PortalException, SystemException {
536    
537                    String layoutFullURL = serviceContext.getLayoutFullURL();
538    
539                    if (Validator.isNull(layoutFullURL)) {
540                            return;
541                    }
542    
543                    PortletPreferences preferences =
544                            ServiceContextUtil.getPortletPreferences(serviceContext);
545    
546                    if (preferences == null) {
547                            long ownerId = entry.getGroupId();
548                            int ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP;
549                            long plid = PortletKeys.PREFS_PLID_SHARED;
550                            String portletId = PortletKeys.BOOKMARKS;
551                            String defaultPreferences = null;
552    
553                            preferences = portletPreferencesLocalService.getPreferences(
554                                    entry.getCompanyId(), ownerId, ownerType, plid, portletId,
555                                    defaultPreferences);
556                    }
557    
558                    if ((serviceContext.isCommandAdd() &&
559                             !BookmarksUtil.getEmailEntryAddedEnabled(preferences)) ||
560                            (serviceContext.isCommandUpdate() &&
561                             !BookmarksUtil.getEmailEntryUpdatedEnabled(preferences))) {
562    
563                            return;
564                    }
565    
566                    String statusByUserName = StringPool.BLANK;
567    
568                    try {
569                            User user = userLocalService.getUserById(
570                                    serviceContext.getGuestOrUserId());
571    
572                            statusByUserName = user.getFullName();
573                    }
574                    catch (Exception e) {
575                            _log.error(e, e);
576                    }
577    
578                    String entryURL =
579                            layoutFullURL + Portal.FRIENDLY_URL_SEPARATOR + "bookmarks" +
580                                    StringPool.SLASH + entry.getEntryId();
581    
582                    String fromAddress = BookmarksUtil.getEmailFromAddress(
583                            preferences, entry.getCompanyId());
584                    String fromName = BookmarksUtil.getEmailFromName(
585                            preferences, entry.getCompanyId());
586    
587                    Map<Locale, String> localizedSubjectMap = null;
588                    Map<Locale, String> localizedBodyMap = null;
589    
590                    if (serviceContext.isCommandUpdate()) {
591                            localizedSubjectMap = BookmarksUtil.getEmailEntryUpdatedSubjectMap(
592                                    preferences);
593                            localizedBodyMap = BookmarksUtil.getEmailEntryUpdatedBodyMap(
594                                    preferences);
595                    }
596                    else {
597                            localizedSubjectMap = BookmarksUtil.getEmailEntryAddedSubjectMap(
598                                    preferences);
599                            localizedBodyMap = BookmarksUtil.getEmailEntryAddedBodyMap(
600                                    preferences);
601                    }
602    
603                    SubscriptionSender subscriptionSender = new SubscriptionSender();
604    
605                    subscriptionSender.setCompanyId(entry.getCompanyId());
606                    subscriptionSender.setContextAttributes(
607                            "[$BOOKMARKS_ENTRY_STATUS_BY_USER_NAME$]", statusByUserName,
608                            "[$BOOKMARKS_ENTRY_URL$]", entryURL);
609                    subscriptionSender.setContextUserPrefix("BOOKMARKS_ENTRY");
610                    subscriptionSender.setFrom(fromAddress, fromName);
611                    subscriptionSender.setHtmlFormat(true);
612                    subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
613                    subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
614                    subscriptionSender.setMailId("bookmarks_entry", entry.getEntryId());
615                    subscriptionSender.setPortletId(PortletKeys.BOOKMARKS);
616                    subscriptionSender.setReplyToAddress(fromAddress);
617                    subscriptionSender.setScopeGroupId(entry.getGroupId());
618                    subscriptionSender.setServiceContext(serviceContext);
619                    subscriptionSender.setUserId(entry.getUserId());
620    
621                    subscriptionSender.addPersistedSubscribers(
622                            BookmarksEntry.class.getName(), entry.getEntryId());
623    
624                    BookmarksFolder folder = entry.getFolder();
625    
626                    if (folder.getFolderId() !=
627                                    BookmarksFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
628    
629                            subscriptionSender.addPersistedSubscribers(
630                                    BookmarksFolder.class.getName(), folder.getFolderId());
631    
632                            for (BookmarksFolder ancestor : folder.getAncestors()) {
633                                    subscriptionSender.addPersistedSubscribers(
634                                            BookmarksFolder.class.getName(), ancestor.getFolderId());
635                            }
636                    }
637    
638                    subscriptionSender.addPersistedSubscribers(
639                            BookmarksFolder.class.getName(), folder.getGroupId());
640    
641                    subscriptionSender.flushNotificationsAsync();
642            }
643    
644            protected void validate(String url) throws PortalException {
645                    if (!Validator.isUrl(url)) {
646                            throw new EntryURLException();
647                    }
648            }
649    
650            private static Log _log = LogFactoryUtil.getLog(
651                    BookmarksEntryLocalServiceImpl.class);
652    
653    }