001/*
002 * (C) Copyright 2014 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
018 */
019package org.nuxeo.ecm.collections.core;
020
021import java.io.Serializable;
022import java.util.ArrayList;
023import java.util.HashMap;
024import java.util.List;
025import java.util.Locale;
026import java.util.Map;
027import java.util.MissingResourceException;
028import java.util.Set;
029import java.util.TreeSet;
030
031import org.apache.commons.lang.StringUtils;
032import org.nuxeo.common.utils.i18n.I18NUtils;
033import org.nuxeo.ecm.collections.api.CollectionConstants;
034import org.nuxeo.ecm.collections.api.CollectionManager;
035import org.nuxeo.ecm.collections.core.adapter.Collection;
036import org.nuxeo.ecm.collections.core.adapter.CollectionMember;
037import org.nuxeo.ecm.collections.core.listener.CollectionAsynchrnonousQuery;
038import org.nuxeo.ecm.collections.core.worker.DuplicateCollectionMemberWork;
039import org.nuxeo.ecm.collections.core.worker.RemoveFromCollectionWork;
040import org.nuxeo.ecm.collections.core.worker.RemovedAbstractWork;
041import org.nuxeo.ecm.collections.core.worker.RemovedCollectionMemberWork;
042import org.nuxeo.ecm.collections.core.worker.RemovedCollectionWork;
043import org.nuxeo.ecm.core.api.CoreSession;
044import org.nuxeo.ecm.core.api.DocumentModel;
045import org.nuxeo.ecm.core.api.DocumentRef;
046import org.nuxeo.ecm.core.api.DocumentSecurityException;
047import org.nuxeo.ecm.core.api.IdRef;
048import org.nuxeo.ecm.core.api.LifeCycleConstants;
049import org.nuxeo.ecm.core.api.NuxeoException;
050import org.nuxeo.ecm.core.api.PathRef;
051import org.nuxeo.ecm.core.api.UnrestrictedSessionRunner;
052import org.nuxeo.ecm.core.api.event.CoreEventConstants;
053import org.nuxeo.ecm.core.api.event.DocumentEventCategories;
054import org.nuxeo.ecm.core.api.security.ACE;
055import org.nuxeo.ecm.core.api.security.ACL;
056import org.nuxeo.ecm.core.api.security.ACP;
057import org.nuxeo.ecm.core.api.security.SecurityConstants;
058import org.nuxeo.ecm.core.api.security.impl.ACLImpl;
059import org.nuxeo.ecm.core.api.security.impl.ACPImpl;
060import org.nuxeo.ecm.core.event.Event;
061import org.nuxeo.ecm.core.event.EventService;
062import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
063import org.nuxeo.ecm.core.versioning.VersioningService;
064import org.nuxeo.ecm.core.work.api.WorkManager;
065import org.nuxeo.ecm.platform.audit.service.NXAuditEventsService;
066import org.nuxeo.ecm.platform.dublincore.listener.DublinCoreListener;
067import org.nuxeo.ecm.platform.ec.notification.NotificationConstants;
068import org.nuxeo.ecm.platform.userworkspace.api.UserWorkspaceService;
069import org.nuxeo.ecm.platform.web.common.locale.LocaleProvider;
070import org.nuxeo.runtime.api.Framework;
071import org.nuxeo.runtime.model.DefaultComponent;
072import org.nuxeo.runtime.transaction.TransactionHelper;
073
074/**
075 * @since 5.9.3
076 */
077public class CollectionManagerImpl extends DefaultComponent implements CollectionManager {
078
079    private static final String PERMISSION_ERROR_MESSAGE = "Privilege '%s' is not granted to '%s'";
080
081    public static void disableEvents(final DocumentModel doc) {
082        doc.putContextData(DublinCoreListener.DISABLE_DUBLINCORE_LISTENER, true);
083        doc.putContextData(NotificationConstants.DISABLE_NOTIFICATION_SERVICE, true);
084        doc.putContextData(NXAuditEventsService.DISABLE_AUDIT_LOGGER, true);
085        doc.putContextData(VersioningService.DISABLE_AUTO_CHECKOUT, true);
086    }
087
088    @Override
089    public void addToCollection(final DocumentModel collection, final DocumentModel documentToBeAdded,
090            final CoreSession session) throws DocumentSecurityException {
091        checkCanAddToCollection(collection, documentToBeAdded, session);
092        final Map<String, Serializable> props = new HashMap<>();
093        props.put(CollectionConstants.COLLECTION_REF_EVENT_CTX_PROP, collection.getRef());
094        fireEvent(documentToBeAdded, session, CollectionConstants.BEFORE_ADDED_TO_COLLECTION, props);
095        Collection colAdapter = collection.getAdapter(Collection.class);
096        colAdapter.addDocument(documentToBeAdded.getId());
097        collection.getCoreSession().saveDocument(colAdapter.getDocument());
098
099        new UnrestrictedSessionRunner(session) {
100
101            @Override
102            public void run() {
103
104                documentToBeAdded.addFacet(CollectionConstants.COLLECTABLE_FACET);
105
106                // We want to disable the following listener on a
107                // collection member when it is added to a collection
108                disableEvents(documentToBeAdded);
109
110                CollectionMember docAdapter = documentToBeAdded.getAdapter(CollectionMember.class);
111                docAdapter.addToCollection(collection.getId());
112                DocumentModel addedDoc = session.saveDocument(docAdapter.getDocument());
113                fireEvent(addedDoc, session, CollectionConstants.ADDED_TO_COLLECTION, props);
114            }
115
116        }.runUnrestricted();
117    }
118
119    @Override
120    public void addToCollection(final DocumentModel collection, final List<DocumentModel> documentListToBeAdded,
121            final CoreSession session) {
122        for (DocumentModel documentToBeAdded : documentListToBeAdded) {
123            addToCollection(collection, documentToBeAdded, session);
124        }
125    }
126
127    @Override
128    public void addToNewCollection(final String newTitle, final String newDescription,
129            final DocumentModel documentToBeAdded, final CoreSession session) {
130        addToCollection(createCollection(newTitle, newDescription, documentToBeAdded, session), documentToBeAdded,
131                session);
132    }
133
134    @Override
135    public void addToNewCollection(final String newTitle, final String newDescription,
136            final List<DocumentModel> documentListToBeAdded, CoreSession session) {
137        DocumentModel newCollection = createCollection(newTitle, newDescription, documentListToBeAdded.get(0), session);
138        for (DocumentModel documentToBeAdded : documentListToBeAdded) {
139            addToCollection(newCollection, documentToBeAdded, session);
140        }
141    }
142
143    @Override
144    public boolean canAddToCollection(final DocumentModel collection, final CoreSession session) {
145        return isCollection(collection)
146                && session.hasPermission(collection.getRef(), SecurityConstants.WRITE_PROPERTIES);
147    }
148
149    @Override
150    public boolean canManage(final DocumentModel collection, final CoreSession session) {
151        return isCollection(collection) && session.hasPermission(collection.getRef(), SecurityConstants.EVERYTHING);
152    }
153
154    public void checkCanAddToCollection(final DocumentModel collection, final DocumentModel documentToBeAdded,
155            final CoreSession session) {
156        if (!isCollectable(documentToBeAdded)) {
157            throw new IllegalArgumentException(
158                    String.format("Document %s is not collectable", documentToBeAdded.getTitle()));
159        }
160        checkCanCollectInCollection(collection, session);
161    }
162
163    /**
164     * @since 8.4
165     */
166    protected void checkCanCollectInCollection(final DocumentModel collection, final CoreSession session) {
167        if (!isCollection(collection)) {
168            throw new IllegalArgumentException(String.format("Document %s is not a collection", collection.getTitle()));
169        }
170        if (!session.hasPermission(collection.getRef(), SecurityConstants.WRITE_PROPERTIES)) {
171            throw new DocumentSecurityException(String.format(PERMISSION_ERROR_MESSAGE,
172                    CollectionConstants.CAN_COLLECT_PERMISSION, session.getPrincipal().getName()));
173        }
174    }
175
176    protected DocumentModel createCollection(final String newTitle, final String newDescription,
177            final DocumentModel context, final CoreSession session) {
178        DocumentModel defaultCollections = getUserDefaultCollections(context, session);
179        DocumentModel newCollection = session.createDocumentModel(defaultCollections.getPath().toString(), newTitle,
180                CollectionConstants.COLLECTION_TYPE);
181        newCollection.setPropertyValue("dc:title", newTitle);
182        newCollection.setPropertyValue("dc:description", newDescription);
183        return session.createDocument(newCollection);
184    }
185
186    protected DocumentModel createDefaultCollections(final CoreSession session, DocumentModel userWorkspace) {
187        DocumentModel doc = session.createDocumentModel(userWorkspace.getPath().toString(),
188                CollectionConstants.DEFAULT_COLLECTIONS_NAME, CollectionConstants.COLLECTIONS_TYPE);
189        String title = null;
190        try {
191            title = I18NUtils.getMessageString("messages", CollectionConstants.DEFAULT_COLLECTIONS_TITLE, new Object[0],
192                    getLocale(session));
193        } catch (MissingResourceException e) {
194            title = CollectionConstants.DEFAULT_COLLECTIONS_TITLE;
195        }
196        doc.setPropertyValue("dc:title", title);
197        doc.setPropertyValue("dc:description", "");
198        doc = session.createDocument(doc);
199
200        ACP acp = new ACPImpl();
201        ACE denyEverything = new ACE(SecurityConstants.EVERYONE, SecurityConstants.EVERYTHING, false);
202        ACE allowEverything = new ACE(session.getPrincipal().getName(), SecurityConstants.EVERYTHING, true);
203        ACL acl = new ACLImpl();
204        acl.setACEs(new ACE[] { allowEverything, denyEverything });
205        acp.addACL(acl);
206        doc.setACP(acp, true);
207
208        return doc;
209    }
210
211    @Override
212    public DocumentModel getUserDefaultCollections(final DocumentModel context, final CoreSession session) {
213        final UserWorkspaceService userWorkspaceService = Framework.getLocalService(UserWorkspaceService.class);
214        final DocumentModel userWorkspace = userWorkspaceService.getCurrentUserPersonalWorkspace(session, context);
215        final DocumentRef lookupRef = new PathRef(userWorkspace.getPath().toString(),
216                CollectionConstants.DEFAULT_COLLECTIONS_NAME);
217        if (session.exists(lookupRef)) {
218            return session.getChild(userWorkspace.getRef(), CollectionConstants.DEFAULT_COLLECTIONS_NAME);
219        } else {
220            // does not exist yet, let's create it
221            synchronized (this) {
222                TransactionHelper.commitOrRollbackTransaction();
223                TransactionHelper.startTransaction();
224                if (!session.exists(lookupRef)) {
225                    boolean succeed = false;
226                    try {
227                        createDefaultCollections(session, userWorkspace);
228                        succeed = true;
229                    } finally {
230                        if (succeed) {
231                            TransactionHelper.commitOrRollbackTransaction();
232                            TransactionHelper.startTransaction();
233                        }
234                    }
235                }
236                return session.getDocument(lookupRef);
237            }
238        }
239    }
240
241    @Override
242    public List<DocumentModel> getVisibleCollection(final DocumentModel collectionMember, final CoreSession session) {
243        return getVisibleCollection(collectionMember, CollectionConstants.MAX_COLLECTION_RETURNED, session);
244    }
245
246    @Override
247    public List<DocumentModel> getVisibleCollection(final DocumentModel collectionMember, int maxResult,
248            CoreSession session) {
249        List<DocumentModel> result = new ArrayList<DocumentModel>();
250        if (isCollected(collectionMember)) {
251            CollectionMember collectionMemberAdapter = collectionMember.getAdapter(CollectionMember.class);
252            List<String> collectionIds = collectionMemberAdapter.getCollectionIds();
253            for (int i = 0; i < collectionIds.size() && result.size() < maxResult; i++) {
254                final String collectionId = collectionIds.get(i);
255                DocumentRef documentRef = new IdRef(collectionId);
256                if (session.exists(documentRef) && session.hasPermission(documentRef, SecurityConstants.READ)
257                        && !LifeCycleConstants.DELETED_STATE.equals(session.getCurrentLifeCycleState(documentRef))) {
258                    DocumentModel collection = session.getDocument(documentRef);
259                    if (!collection.isVersion()) {
260                        result.add(collection);
261                    }
262                }
263            }
264        }
265        return result;
266    }
267
268    @Override
269    public boolean hasVisibleCollection(final DocumentModel collectionMember, CoreSession session) {
270        CollectionMember collectionMemberAdapter = collectionMember.getAdapter(CollectionMember.class);
271        List<String> collectionIds = collectionMemberAdapter.getCollectionIds();
272        for (final String collectionId : collectionIds) {
273            DocumentRef documentRef = new IdRef(collectionId);
274            if (session.exists(documentRef) && session.hasPermission(documentRef, SecurityConstants.READ)) {
275                return true;
276            }
277        }
278        return false;
279    }
280
281    @Override
282    public boolean isCollectable(final DocumentModel doc) {
283        return !doc.hasFacet(CollectionConstants.NOT_COLLECTABLE_FACET);
284    }
285
286    @Override
287    public boolean isCollected(final DocumentModel doc) {
288        return doc.hasFacet(CollectionConstants.COLLECTABLE_FACET);
289    }
290
291    @Override
292    public boolean isCollection(final DocumentModel doc) {
293        return doc.hasFacet(CollectionConstants.COLLECTION_FACET);
294    }
295
296    @Override
297    public boolean isInCollection(DocumentModel collection, DocumentModel document, CoreSession session) {
298        if (isCollected(document)) {
299            final CollectionMember collectionMemberAdapter = document.getAdapter(CollectionMember.class);
300            return collectionMemberAdapter.getCollectionIds().contains(collection.getId());
301        }
302        return false;
303    }
304
305    @Override
306    public void processCopiedCollection(final DocumentModel collection) {
307        Collection collectionAdapter = collection.getAdapter(Collection.class);
308        List<String> documentIds = collectionAdapter.getCollectedDocumentIds();
309
310        int i = 0;
311        while (i < documentIds.size()) {
312            int limit = (int) (((i + CollectionAsynchrnonousQuery.MAX_RESULT) > documentIds.size()) ? documentIds.size()
313                    : (i + CollectionAsynchrnonousQuery.MAX_RESULT));
314            DuplicateCollectionMemberWork work = new DuplicateCollectionMemberWork(collection.getRepositoryName(),
315                    collection.getId(), documentIds.subList(i, limit), i);
316            WorkManager workManager = Framework.getLocalService(WorkManager.class);
317            workManager.schedule(work, WorkManager.Scheduling.IF_NOT_SCHEDULED, true);
318
319            i = limit;
320        }
321    }
322
323    @Override
324    public void processRemovedCollection(final DocumentModel collection) {
325        final WorkManager workManager = Framework.getLocalService(WorkManager.class);
326        final RemovedAbstractWork work = new RemovedCollectionWork();
327        work.setDocument(collection.getRepositoryName(), collection.getId());
328        workManager.schedule(work, WorkManager.Scheduling.IF_NOT_SCHEDULED, true);
329    }
330
331    @Override
332    public void processRemovedCollectionMember(final DocumentModel collectionMember) {
333        final WorkManager workManager = Framework.getLocalService(WorkManager.class);
334        final RemovedAbstractWork work = new RemovedCollectionMemberWork();
335        work.setDocument(collectionMember.getRepositoryName(), collectionMember.getId());
336        workManager.schedule(work, WorkManager.Scheduling.IF_NOT_SCHEDULED, true);
337    }
338
339    @Override
340    public void processRestoredCollection(DocumentModel collection, DocumentModel version) {
341        final Set<String> collectionMemberIdsToBeRemoved = new TreeSet<String>(
342                collection.getAdapter(Collection.class).getCollectedDocumentIds());
343        collectionMemberIdsToBeRemoved.removeAll(version.getAdapter(Collection.class).getCollectedDocumentIds());
344
345        final Set<String> collectionMemberIdsToBeAdded = new TreeSet<String>(
346                version.getAdapter(Collection.class).getCollectedDocumentIds());
347        collectionMemberIdsToBeAdded.removeAll(collection.getAdapter(Collection.class).getCollectedDocumentIds());
348
349        int i = 0;
350        while (i < collectionMemberIdsToBeRemoved.size()) {
351            int limit = (int) (((i + CollectionAsynchrnonousQuery.MAX_RESULT) > collectionMemberIdsToBeRemoved.size())
352                    ? collectionMemberIdsToBeRemoved.size() : (i + CollectionAsynchrnonousQuery.MAX_RESULT));
353            RemoveFromCollectionWork work = new RemoveFromCollectionWork(collection.getRepositoryName(),
354                    collection.getId(), new ArrayList<String>(collectionMemberIdsToBeRemoved).subList(i, limit), i);
355            WorkManager workManager = Framework.getLocalService(WorkManager.class);
356            workManager.schedule(work, WorkManager.Scheduling.IF_NOT_SCHEDULED, true);
357
358            i = limit;
359        }
360        i = 0;
361        while (i < collectionMemberIdsToBeAdded.size()) {
362            int limit = (int) (((i + CollectionAsynchrnonousQuery.MAX_RESULT) > collectionMemberIdsToBeAdded.size())
363                    ? collectionMemberIdsToBeAdded.size() : (i + CollectionAsynchrnonousQuery.MAX_RESULT));
364            DuplicateCollectionMemberWork work = new DuplicateCollectionMemberWork(collection.getRepositoryName(),
365                    collection.getId(), new ArrayList<String>(collectionMemberIdsToBeAdded).subList(i, limit), i);
366            WorkManager workManager = Framework.getLocalService(WorkManager.class);
367            workManager.schedule(work, WorkManager.Scheduling.IF_NOT_SCHEDULED, true);
368
369            i = limit;
370        }
371    }
372
373    @Override
374    public void removeAllFromCollection(final DocumentModel collection,
375            final List<DocumentModel> documentListToBeRemoved, final CoreSession session) {
376        for (DocumentModel documentToBeRemoved : documentListToBeRemoved) {
377            removeFromCollection(collection, documentToBeRemoved, session);
378        }
379    }
380
381    @Override
382    public void removeFromCollection(final DocumentModel collection, final DocumentModel documentToBeRemoved,
383            final CoreSession session) {
384        checkCanAddToCollection(collection, documentToBeRemoved, session);
385        Map<String, Serializable> props = new HashMap<>();
386        props.put(CollectionConstants.COLLECTION_REF_EVENT_CTX_PROP, new IdRef(collection.getId()));
387        fireEvent(documentToBeRemoved, session, CollectionConstants.BEFORE_REMOVED_FROM_COLLECTION, props);
388        Collection colAdapter = collection.getAdapter(Collection.class);
389        colAdapter.removeDocument(documentToBeRemoved.getId());
390        collection.getCoreSession().saveDocument(colAdapter.getDocument());
391
392        new UnrestrictedSessionRunner(session) {
393
394            @Override
395            public void run() {
396                doRemoveFromCollection(documentToBeRemoved, collection.getId(), session);
397            }
398
399        }.runUnrestricted();
400    }
401
402    @Override
403    public void doRemoveFromCollection(DocumentModel documentToBeRemoved, String collectionId, CoreSession session) {
404        // We want to disable the following listener on a
405        // collection member when it is removed from a collection
406        disableEvents(documentToBeRemoved);
407
408        CollectionMember docAdapter = documentToBeRemoved.getAdapter(CollectionMember.class);
409        docAdapter.removeFromCollection(collectionId);
410        DocumentModel removedDoc = session.saveDocument(docAdapter.getDocument());
411        Map<String, Serializable> props = new HashMap<>();
412        props.put(CollectionConstants.COLLECTION_REF_EVENT_CTX_PROP, new IdRef(collectionId));
413        fireEvent(removedDoc, session, CollectionConstants.REMOVED_FROM_COLLECTION, props);
414    }
415
416    @Override
417    public DocumentModel createCollection(final CoreSession session, String title, String description, String path) {
418        DocumentModel newCollection = null;
419        // Test if the path is null or empty
420        if (StringUtils.isEmpty(path)) {
421            // A default collection is created with the given name
422            newCollection = createCollection(title, description, null, session);
423        } else {
424            // If the path does not exist, an exception is thrown
425            if (!session.exists(new PathRef(path))) {
426                throw new NuxeoException(String.format("Path \"%s\" specified in parameter not found", path));
427            }
428            // Create a new collection in the given path
429            DocumentModel collectionModel = session.createDocumentModel(path, title,
430                    CollectionConstants.COLLECTION_TYPE);
431            collectionModel.setPropertyValue("dc:title", title);
432            collectionModel.setPropertyValue("dc:description", description);
433            newCollection = session.createDocument(collectionModel);
434        }
435        return newCollection;
436    }
437
438    protected Locale getLocale(final CoreSession session) {
439        Locale locale = null;
440        locale = Framework.getLocalService(LocaleProvider.class).getLocale(session);
441        if (locale == null) {
442            locale = Locale.getDefault();
443        }
444        return new Locale(Locale.getDefault().getLanguage());
445    }
446
447    protected void fireEvent(DocumentModel doc, CoreSession session, String eventName,
448            Map<String, Serializable> props) {
449        EventService eventService = Framework.getService(EventService.class);
450        DocumentEventContext ctx = new DocumentEventContext(session, session.getPrincipal(), doc);
451        ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, session.getRepositoryName());
452        ctx.setProperty(CoreEventConstants.SESSION_ID, session.getSessionId());
453        ctx.setProperty("category", DocumentEventCategories.EVENT_DOCUMENT_CATEGORY);
454        ctx.setProperties(props);
455        Event event = ctx.newEvent(eventName);
456        eventService.fireEvent(event);
457    }
458
459    @Override
460    public boolean moveMembers(final CoreSession session, final DocumentModel collection, final DocumentModel member1,
461            final DocumentModel member2) {
462        checkCanCollectInCollection(collection, session);
463        ;
464        Collection collectionAdapter = collection.getAdapter(Collection.class);
465        boolean result = collectionAdapter.moveMembers(member1.getId(), member2 != null ? member2.getId() : null);
466        if (result) {
467            session.saveDocument(collectionAdapter.getDocument());
468        }
469        return result;
470    }
471
472}