001/* 002 * (C) Copyright 2006-2016 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 * Bogdan Stefanescu 018 * Florent Guillaume 019 * Benoit Delbosc 020 */ 021 022package org.nuxeo.ecm.core.api; 023 024import static org.nuxeo.ecm.core.api.event.CoreEventConstants.CHANGED_ACL_NAME; 025import static org.nuxeo.ecm.core.api.event.CoreEventConstants.NEW_ACE; 026import static org.nuxeo.ecm.core.api.event.CoreEventConstants.OLD_ACE; 027import static org.nuxeo.ecm.core.api.security.SecurityConstants.ADD_CHILDREN; 028import static org.nuxeo.ecm.core.api.security.SecurityConstants.BROWSE; 029import static org.nuxeo.ecm.core.api.security.SecurityConstants.READ; 030import static org.nuxeo.ecm.core.api.security.SecurityConstants.READ_CHILDREN; 031import static org.nuxeo.ecm.core.api.security.SecurityConstants.READ_LIFE_CYCLE; 032import static org.nuxeo.ecm.core.api.security.SecurityConstants.READ_PROPERTIES; 033import static org.nuxeo.ecm.core.api.security.SecurityConstants.READ_SECURITY; 034import static org.nuxeo.ecm.core.api.security.SecurityConstants.READ_VERSION; 035import static org.nuxeo.ecm.core.api.security.SecurityConstants.REMOVE; 036import static org.nuxeo.ecm.core.api.security.SecurityConstants.REMOVE_CHILDREN; 037import static org.nuxeo.ecm.core.api.security.SecurityConstants.SYSTEM_USERNAME; 038import static org.nuxeo.ecm.core.api.security.SecurityConstants.UNLOCK; 039import static org.nuxeo.ecm.core.api.security.SecurityConstants.WRITE; 040import static org.nuxeo.ecm.core.api.security.SecurityConstants.WRITE_LIFE_CYCLE; 041import static org.nuxeo.ecm.core.api.security.SecurityConstants.WRITE_PROPERTIES; 042import static org.nuxeo.ecm.core.api.security.SecurityConstants.WRITE_SECURITY; 043import static org.nuxeo.ecm.core.api.security.SecurityConstants.WRITE_VERSION; 044 045import java.io.Serializable; 046import java.security.Principal; 047import java.text.DateFormat; 048import java.util.ArrayList; 049import java.util.Arrays; 050import java.util.Collection; 051import java.util.Collections; 052import java.util.Comparator; 053import java.util.Date; 054import java.util.GregorianCalendar; 055import java.util.HashMap; 056import java.util.List; 057import java.util.Map; 058import java.util.Map.Entry; 059import java.util.stream.Collectors; 060 061import org.apache.commons.logging.Log; 062import org.apache.commons.logging.LogFactory; 063import org.nuxeo.common.collections.ScopeType; 064import org.nuxeo.common.collections.ScopedMap; 065import org.nuxeo.ecm.core.CoreService; 066import org.nuxeo.ecm.core.NXCore; 067import org.nuxeo.ecm.core.api.DocumentModel.DocumentModelRefresh; 068import org.nuxeo.ecm.core.api.event.CoreEventConstants; 069import org.nuxeo.ecm.core.api.event.DocumentEventCategories; 070import org.nuxeo.ecm.core.api.event.DocumentEventTypes; 071import org.nuxeo.ecm.core.api.facet.VersioningDocument; 072import org.nuxeo.ecm.core.api.impl.DocumentModelChildrenIterator; 073import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl; 074import org.nuxeo.ecm.core.api.impl.FacetFilter; 075import org.nuxeo.ecm.core.api.impl.UserPrincipal; 076import org.nuxeo.ecm.core.api.impl.VersionModelImpl; 077import org.nuxeo.ecm.core.api.security.ACE; 078import org.nuxeo.ecm.core.api.security.ACP; 079import org.nuxeo.ecm.core.api.security.SecurityConstants; 080import org.nuxeo.ecm.core.api.security.UserEntry; 081import org.nuxeo.ecm.core.api.security.impl.ACPImpl; 082import org.nuxeo.ecm.core.api.security.impl.UserEntryImpl; 083import org.nuxeo.ecm.core.api.validation.DocumentValidationException; 084import org.nuxeo.ecm.core.api.validation.DocumentValidationReport; 085import org.nuxeo.ecm.core.api.validation.DocumentValidationService; 086import org.nuxeo.ecm.core.event.Event; 087import org.nuxeo.ecm.core.event.EventService; 088import org.nuxeo.ecm.core.event.impl.DocumentEventContext; 089import org.nuxeo.ecm.core.lifecycle.LifeCycleService; 090import org.nuxeo.ecm.core.model.Document; 091import org.nuxeo.ecm.core.model.PathComparator; 092import org.nuxeo.ecm.core.model.Session; 093import org.nuxeo.ecm.core.query.QueryFilter; 094import org.nuxeo.ecm.core.query.QueryParseException; 095import org.nuxeo.ecm.core.query.sql.NXQL; 096import org.nuxeo.ecm.core.query.sql.model.SQLQuery.Transformer; 097import org.nuxeo.ecm.core.schema.DocumentType; 098import org.nuxeo.ecm.core.schema.FacetNames; 099import org.nuxeo.ecm.core.schema.SchemaManager; 100import org.nuxeo.ecm.core.schema.types.CompositeType; 101import org.nuxeo.ecm.core.schema.types.Schema; 102import org.nuxeo.ecm.core.security.SecurityService; 103import org.nuxeo.ecm.core.versioning.VersioningService; 104import org.nuxeo.runtime.api.Framework; 105import org.nuxeo.runtime.metrics.MetricsService; 106import org.nuxeo.runtime.services.config.ConfigurationService; 107 108import com.codahale.metrics.Counter; 109import com.codahale.metrics.MetricRegistry; 110import com.codahale.metrics.SharedMetricRegistries; 111 112/** 113 * Abstract implementation of the client interface. 114 * <p> 115 * This handles all the aspects that are independent on the final implementation (like running inside a J2EE platform or 116 * not). 117 * <p> 118 * The only aspect not implemented is the session management that should be handled by subclasses. 119 * 120 * @author Bogdan Stefanescu 121 * @author Florent Guillaume 122 */ 123public abstract class AbstractSession implements CoreSession, Serializable { 124 125 public static final NuxeoPrincipal ANONYMOUS = new UserPrincipal("anonymous", new ArrayList<>(), true, false); 126 127 private static final Log log = LogFactory.getLog(CoreSession.class); 128 129 private static final long serialVersionUID = 1L; 130 131 private static final Comparator<? super Document> pathComparator = new PathComparator(); 132 133 public static final String DEFAULT_MAX_RESULTS = "1000"; 134 135 public static final String MAX_RESULTS_PROPERTY = "org.nuxeo.ecm.core.max.results"; 136 137 public static final String LIMIT_RESULTS_PROPERTY = "org.nuxeo.ecm.core.limit.results"; 138 139 public static final String TRASH_KEEP_CHECKED_IN_PROPERTY = "org.nuxeo.trash.keepCheckedIn"; 140 141 public static final String BINARY_TEXT_SYS_PROP = "fulltextBinary"; 142 143 private Boolean limitedResults; 144 145 private Long maxResults; 146 147 // @since 5.7.2 148 protected final MetricRegistry registry = SharedMetricRegistries.getOrCreate(MetricsService.class.getName()); 149 150 protected Counter createDocumentCount; 151 152 protected Counter deleteDocumentCount; 153 154 protected Counter updateDocumentCount; 155 156 protected void createMetrics() { 157 createDocumentCount = registry.counter(MetricRegistry.name("nuxeo.repositories", getRepositoryName(), 158 "documents", "create")); 159 deleteDocumentCount = registry.counter(MetricRegistry.name("nuxeo.repositories", getRepositoryName(), 160 "documents", "delete")); 161 updateDocumentCount = registry.counter(MetricRegistry.name("nuxeo.repositories", getRepositoryName(), 162 "documents", "update")); 163 } 164 165 /** 166 * Used to check permissions. 167 */ 168 private transient SecurityService securityService; 169 170 protected SecurityService getSecurityService() { 171 if (securityService == null) { 172 securityService = NXCore.getSecurityService(); 173 } 174 return securityService; 175 } 176 177 private transient VersioningService versioningService; 178 179 protected VersioningService getVersioningService() { 180 if (versioningService == null) { 181 versioningService = Framework.getService(VersioningService.class); 182 } 183 return versioningService; 184 } 185 186 private transient DocumentValidationService validationService; 187 188 protected DocumentValidationService getValidationService() { 189 if (validationService == null) { 190 validationService = Framework.getService(DocumentValidationService.class); 191 } 192 return validationService; 193 } 194 195 /** 196 * Internal method: Gets the current session based on the client session id. 197 * 198 * @return the repository session 199 */ 200 public abstract Session getSession(); 201 202 @Override 203 public DocumentType getDocumentType(String type) { 204 return Framework.getLocalService(SchemaManager.class).getDocumentType(type); 205 } 206 207 protected final void checkPermission(Document doc, String permission) throws DocumentSecurityException { 208 if (isAdministrator()) { 209 return; 210 } 211 if (!hasPermission(doc, permission)) { 212 log.debug("Permission '" + permission + "' is not granted to '" + getPrincipal().getName() 213 + "' on document " + doc.getPath() + " (" + doc.getUUID() + " - " + doc.getType().getName() + ")"); 214 throw new DocumentSecurityException("Privilege '" + permission + "' is not granted to '" 215 + getPrincipal().getName() + "'"); 216 } 217 } 218 219 protected Map<String, Serializable> getContextMapEventInfo(DocumentModel doc) { 220 Map<String, Serializable> options = new HashMap<>(); 221 if (doc != null) { 222 ScopedMap ctxData = doc.getContextData(); 223 if (ctxData != null) { 224 options.putAll(ctxData.getDefaultScopeValues()); 225 options.putAll(ctxData.getScopeValues(ScopeType.REQUEST)); 226 } 227 } 228 return options; 229 } 230 231 public DocumentEventContext newEventContext(DocumentModel source) { 232 DocumentEventContext ctx = new DocumentEventContext(this, getPrincipal(), source); 233 ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, getRepositoryName()); 234 ctx.setProperty(CoreEventConstants.SESSION_ID, getSessionId()); 235 return ctx; 236 } 237 238 protected void notifyEvent(String eventId, DocumentModel source, Map<String, Serializable> options, 239 String category, String comment, boolean withLifeCycle, boolean inline) { 240 241 DocumentEventContext ctx = new DocumentEventContext(this, getPrincipal(), source); 242 243 // compatibility with old code (< 5.2.M4) - import info from old event 244 // model 245 if (options != null) { 246 ctx.setProperties(options); 247 } 248 ctx.setProperty(CoreEventConstants.REPOSITORY_NAME, getRepositoryName()); 249 ctx.setProperty(CoreEventConstants.SESSION_ID, getSessionId()); 250 // Document life cycle 251 if (source != null && withLifeCycle) { 252 String currentLifeCycleState = source.getCurrentLifeCycleState(); 253 ctx.setProperty(CoreEventConstants.DOC_LIFE_CYCLE, currentLifeCycleState); 254 } 255 if (comment != null) { 256 ctx.setProperty("comment", comment); 257 } 258 ctx.setProperty("category", category == null ? DocumentEventCategories.EVENT_DOCUMENT_CATEGORY : category); 259 // compat code: mark SAVE event as a commit event 260 Event event = ctx.newEvent(eventId); 261 if (DocumentEventTypes.SESSION_SAVED.equals(eventId)) { 262 event.setIsCommitEvent(true); 263 } 264 if (inline) { 265 event.setInline(true); 266 } 267 // compat code: set isLocal on event if JMS is blocked 268 if (source != null) { 269 Boolean blockJms = (Boolean) source.getContextData("BLOCK_JMS_PRODUCING"); 270 if (blockJms != null && blockJms) { 271 event.setLocal(true); 272 event.setInline(true); 273 } 274 } 275 Framework.getLocalService(EventService.class).fireEvent(event); 276 } 277 278 /** 279 * Copied from obsolete VersionChangeNotifier. 280 * <p> 281 * Sends change notifications to core event listeners. The event contains info with older document (before version 282 * change) and newer doc (current document). 283 * 284 * @param options additional info to pass to the event 285 */ 286 protected void notifyVersionChange(DocumentModel oldDocument, DocumentModel newDocument, 287 Map<String, Serializable> options) { 288 final Map<String, Serializable> info = new HashMap<>(); 289 if (options != null) { 290 info.putAll(options); 291 } 292 info.put(VersioningChangeNotifier.EVT_INFO_NEW_DOC_KEY, newDocument); 293 info.put(VersioningChangeNotifier.EVT_INFO_OLD_DOC_KEY, oldDocument); 294 notifyEvent(VersioningChangeNotifier.CORE_EVENT_ID_VERSIONING_CHANGE, newDocument, info, 295 DocumentEventCategories.EVENT_CLIENT_NOTIF_CATEGORY, null, false, false); 296 } 297 298 @Override 299 public boolean hasPermission(Principal principal, DocumentRef docRef, String permission) { 300 Document doc = resolveReference(docRef); 301 return hasPermission(principal, doc, permission); 302 } 303 304 protected final boolean hasPermission(Principal principal, Document doc, String permission) { 305 return getSecurityService().checkPermission(doc, principal, permission); 306 } 307 308 @Override 309 public boolean hasPermission(DocumentRef docRef, String permission) { 310 Document doc = resolveReference(docRef); 311 return hasPermission(doc, permission); 312 } 313 314 protected final boolean hasPermission(Document doc, String permission) { 315 // TODO: optimize this - usually ACP is already available when calling 316 // this method. 317 // -> cache ACP at securitymanager level or try to reuse the ACP when 318 // it is known 319 return getSecurityService().checkPermission(doc, getPrincipal(), permission); 320 // return doc.getSession().getSecurityManager().checkPermission(doc, 321 // getPrincipal().getName(), permission); 322 } 323 324 protected Document resolveReference(DocumentRef docRef) { 325 if (docRef == null) { 326 throw new IllegalArgumentException("null docRref"); 327 } 328 Object ref = docRef.reference(); 329 if (ref == null) { 330 throw new IllegalArgumentException("null reference"); 331 } 332 int type = docRef.type(); 333 switch (type) { 334 case DocumentRef.ID: 335 return getSession().getDocumentByUUID((String) ref); 336 case DocumentRef.PATH: 337 return getSession().resolvePath((String) ref); 338 case DocumentRef.INSTANCE: 339 return getSession().getDocumentByUUID(((DocumentModel) ref).getId()); 340 default: 341 throw new IllegalArgumentException("Invalid type: " + type); 342 } 343 } 344 345 /** 346 * Gets the document model for the given core document. 347 * 348 * @param doc the document 349 * @return the document model 350 */ 351 protected DocumentModel readModel(Document doc) { 352 return DocumentModelFactory.createDocumentModel(doc, getSessionId(), null); 353 } 354 355 /** 356 * Gets the document model for the given core document, preserving the contextData. 357 * 358 * @param doc the document 359 * @return the document model 360 */ 361 protected DocumentModel readModel(Document doc, DocumentModel docModel) { 362 DocumentModel newModel = readModel(doc); 363 newModel.copyContextData(docModel); 364 return newModel; 365 } 366 367 protected DocumentModel writeModel(Document doc, DocumentModel docModel) { 368 return DocumentModelFactory.writeDocumentModel(docModel, doc); 369 } 370 371 @Override 372 @Deprecated 373 public DocumentModel copy(DocumentRef src, DocumentRef dst, String name, boolean resetLifeCycle) { 374 if (resetLifeCycle) { 375 return copy(src, dst, name, CopyOption.RESET_LIFE_CYCLE); 376 } 377 return copy(src, dst, name); 378 } 379 380 @Override 381 public DocumentModel copy(DocumentRef src, DocumentRef dst, String name, CopyOption... copyOptions) { 382 Document dstDoc = resolveReference(dst); 383 checkPermission(dstDoc, ADD_CHILDREN); 384 385 Document srcDoc = resolveReference(src); 386 if (name == null) { 387 name = srcDoc.getName(); 388 } else { 389 PathRef.checkName(name); 390 } 391 392 Map<String, Serializable> options = new HashMap<>(); 393 394 // add the destination name, destination, resetLifeCycle flag and 395 // source references in 396 // the options of the event 397 options.put(CoreEventConstants.SOURCE_REF, src); 398 options.put(CoreEventConstants.DESTINATION_REF, dst); 399 options.put(CoreEventConstants.DESTINATION_PATH, dstDoc.getPath()); 400 options.put(CoreEventConstants.DESTINATION_NAME, name); 401 options.put(CoreEventConstants.DESTINATION_EXISTS, dstDoc.hasChild(name)); 402 options.put(CoreEventConstants.RESET_LIFECYCLE, CopyOption.isResetLifeCycle(copyOptions)); 403 options.put(CoreEventConstants.RESET_CREATOR, CopyOption.isResetCreator(copyOptions)); 404 DocumentModel srcDocModel = readModel(srcDoc); 405 notifyEvent(DocumentEventTypes.ABOUT_TO_COPY, srcDocModel, options, null, null, true, true); 406 407 name = (String) options.get(CoreEventConstants.DESTINATION_NAME); 408 Document doc = getSession().copy(srcDoc, dstDoc, name); 409 // no need to clear lock, locks table is not copied 410 411 // notify document created by copy 412 DocumentModel docModel = readModel(doc); 413 414 String comment = srcDoc.getRepositoryName() + ':' + src.toString(); 415 notifyEvent(DocumentEventTypes.DOCUMENT_CREATED_BY_COPY, docModel, options, null, comment, true, false); 416 docModel = writeModel(doc, docModel); 417 418 // notify document copied 419 comment = doc.getRepositoryName() + ':' + docModel.getRef().toString(); 420 421 notifyEvent(DocumentEventTypes.DOCUMENT_DUPLICATED, srcDocModel, options, null, comment, true, false); 422 423 return docModel; 424 } 425 426 @Override 427 @Deprecated 428 public List<DocumentModel> copy(List<DocumentRef> src, DocumentRef dst, boolean resetLifeCycle) { 429 if (resetLifeCycle) { 430 return copy(src, dst, CopyOption.RESET_LIFE_CYCLE); 431 } 432 return copy(src, dst); 433 } 434 435 @Override 436 public List<DocumentModel> copy(List<DocumentRef> src, DocumentRef dst, CopyOption... opts) { 437 return src.stream().map(ref -> copy(ref, dst, null, opts)).collect(Collectors.toList()); 438 } 439 440 @Override 441 @Deprecated 442 public DocumentModel copyProxyAsDocument(DocumentRef src, DocumentRef dst, String name, boolean resetLifeCycle) { 443 if (resetLifeCycle) { 444 return copyProxyAsDocument(src, dst, name, CopyOption.RESET_LIFE_CYCLE); 445 } 446 return copyProxyAsDocument(src, dst, name); 447 } 448 449 @Override 450 public DocumentModel copyProxyAsDocument(DocumentRef src, DocumentRef dst, String name, CopyOption... copyOptions) { 451 Document srcDoc = resolveReference(src); 452 if (!srcDoc.isProxy()) { 453 return copy(src, dst, name); 454 } 455 Document dstDoc = resolveReference(dst); 456 checkPermission(dstDoc, WRITE); 457 458 // create a new document using the expanded proxy 459 DocumentModel srcDocModel = readModel(srcDoc); 460 String docName = (name != null) ? name : srcDocModel.getName(); 461 DocumentModel docModel = createDocumentModel(dstDoc.getPath(), docName, srcDocModel.getType()); 462 docModel.copyContent(srcDocModel); 463 notifyEvent(DocumentEventTypes.ABOUT_TO_COPY, srcDocModel, null, null, null, true, true); 464 docModel = createDocument(docModel); 465 Document doc = resolveReference(docModel.getRef()); 466 467 Map<String, Serializable> options = new HashMap<>(); 468 options.put(CoreEventConstants.RESET_LIFECYCLE, CopyOption.isResetLifeCycle(copyOptions)); 469 options.put(CoreEventConstants.RESET_CREATOR, CopyOption.isResetCreator(copyOptions)); 470 // notify document created by copy 471 String comment = srcDoc.getRepositoryName() + ':' + src.toString(); 472 notifyEvent(DocumentEventTypes.DOCUMENT_CREATED_BY_COPY, docModel, options, null, comment, true, false); 473 474 // notify document copied 475 comment = doc.getRepositoryName() + ':' + docModel.getRef().toString(); 476 notifyEvent(DocumentEventTypes.DOCUMENT_DUPLICATED, srcDocModel, options, null, comment, true, false); 477 478 return docModel; 479 } 480 481 @Override 482 @Deprecated 483 public List<DocumentModel> copyProxyAsDocument(List<DocumentRef> src, DocumentRef dst, boolean resetLifeCycle) { 484 if (resetLifeCycle) { 485 return copyProxyAsDocument(src, dst, CopyOption.RESET_LIFE_CYCLE); 486 } 487 return copyProxyAsDocument(src, dst); 488 } 489 490 @Override 491 public List<DocumentModel> copyProxyAsDocument(List<DocumentRef> src, DocumentRef dst, CopyOption... opts) { 492 return src.stream().map(ref -> copyProxyAsDocument(ref, dst, null, opts)).collect(Collectors.toList()); 493 } 494 495 @Override 496 public DocumentModel move(DocumentRef src, DocumentRef dst, String name) { 497 Document srcDoc = resolveReference(src); 498 Document dstDoc; 499 if (dst == null) { 500 // rename 501 dstDoc = srcDoc.getParent(); 502 checkPermission(dstDoc, WRITE_PROPERTIES); 503 } else { 504 dstDoc = resolveReference(dst); 505 checkPermission(dstDoc, ADD_CHILDREN); 506 checkPermission(srcDoc.getParent(), REMOVE_CHILDREN); 507 checkPermission(srcDoc, REMOVE); 508 } 509 510 DocumentModel srcDocModel = readModel(srcDoc); 511 String originalName = srcDocModel.getName(); 512 if (name == null) { 513 name = srcDocModel.getName(); 514 } else { 515 PathRef.checkName(name); 516 } 517 Map<String, Serializable> options = getContextMapEventInfo(srcDocModel); 518 // add the destination name, destination and source references in 519 // the options of the event 520 options.put(CoreEventConstants.SOURCE_REF, src); 521 options.put(CoreEventConstants.DESTINATION_REF, dst); 522 options.put(CoreEventConstants.DESTINATION_PATH, dstDoc.getPath()); 523 options.put(CoreEventConstants.DESTINATION_NAME, name); 524 options.put(CoreEventConstants.DESTINATION_EXISTS, dstDoc.hasChild(name)); 525 526 notifyEvent(DocumentEventTypes.ABOUT_TO_MOVE, srcDocModel, options, null, null, true, true); 527 528 name = (String) options.get(CoreEventConstants.DESTINATION_NAME); 529 530 if (!originalName.equals(name)) { 531 options.put(CoreEventConstants.ORIGINAL_NAME, originalName); 532 } 533 534 String comment = srcDoc.getRepositoryName() + ':' + srcDoc.getParent().getUUID(); 535 536 Document doc = getSession().move(srcDoc, dstDoc, name); 537 538 // notify document moved 539 DocumentModel docModel = readModel(doc); 540 options.put(CoreEventConstants.PARENT_PATH, srcDocModel.getParentRef()); 541 notifyEvent(DocumentEventTypes.DOCUMENT_MOVED, docModel, options, null, comment, true, false); 542 543 return docModel; 544 } 545 546 @Override 547 public void move(List<DocumentRef> src, DocumentRef dst) { 548 for (DocumentRef ref : src) { 549 move(ref, dst, null); 550 } 551 } 552 553 @Override 554 public ACP getACP(DocumentRef docRef) { 555 Document doc = resolveReference(docRef); 556 checkPermission(doc, READ_SECURITY); 557 return getSession().getMergedACP(doc); 558 } 559 560 @Override 561 public void setACP(DocumentRef docRef, ACP newAcp, boolean overwrite) { 562 Document doc = resolveReference(docRef); 563 checkPermission(doc, WRITE_SECURITY); 564 565 setACP(doc, newAcp, overwrite, null); 566 } 567 568 protected void setACP(Document doc, ACP newAcp, boolean overwrite, Map<String, Serializable> options) { 569 DocumentModel docModel = readModel(doc); 570 if (options == null) { 571 options = new HashMap<>(); 572 } 573 options.put(CoreEventConstants.OLD_ACP, docModel.getACP().clone()); 574 options.put(CoreEventConstants.NEW_ACP, newAcp); 575 576 notifyEvent(DocumentEventTypes.BEFORE_DOC_SECU_UPDATE, docModel, options, null, null, true, true); 577 getSession().setACP(doc, newAcp, overwrite); 578 docModel = readModel(doc); 579 options.put(CoreEventConstants.NEW_ACP, newAcp.clone()); 580 notifyEvent(DocumentEventTypes.DOCUMENT_SECURITY_UPDATED, docModel, options, null, null, true, false); 581 } 582 583 @Override 584 public void replaceACE(DocumentRef docRef, String aclName, ACE oldACE, ACE newACE) { 585 Document doc = resolveReference(docRef); 586 checkPermission(doc, WRITE_SECURITY); 587 588 ACP acp = getACP(docRef); 589 if (acp.replaceACE(aclName, oldACE, newACE)) { 590 Map<String, Serializable> options = new HashMap<>(); 591 options.put(OLD_ACE, oldACE); 592 options.put(NEW_ACE, newACE); 593 options.put(CHANGED_ACL_NAME, aclName); 594 setACP(doc, acp, true, options); 595 } 596 } 597 598 @Override 599 public boolean isNegativeAclAllowed() { 600 return getSession().isNegativeAclAllowed(); 601 } 602 603 @Override 604 public void cancel() { 605 // nothing 606 } 607 608 private DocumentModel createDocumentModelFromTypeName(String typeName, Map<String, Serializable> options) { 609 SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class); 610 DocumentType docType = schemaManager.getDocumentType(typeName); 611 if (docType == null) { 612 throw new IllegalArgumentException(typeName + " is not a registered core type"); 613 } 614 DocumentModel docModel = DocumentModelFactory.createDocumentModel(getSessionId(), docType); 615 if (options == null) { 616 options = new HashMap<>(); 617 } 618 // do not forward this event on the JMS Bus 619 options.put("BLOCK_JMS_PRODUCING", true); 620 notifyEvent(DocumentEventTypes.EMPTY_DOCUMENTMODEL_CREATED, docModel, options, null, null, false, true); 621 return docModel; 622 } 623 624 @Override 625 public DocumentModel createDocumentModel(String typeName) { 626 Map<String, Serializable> options = new HashMap<>(); 627 return createDocumentModelFromTypeName(typeName, options); 628 } 629 630 @Override 631 public DocumentModel createDocumentModel(String parentPath, String name, String typeName) { 632 Map<String, Serializable> options = new HashMap<>(); 633 options.put(CoreEventConstants.PARENT_PATH, parentPath); 634 options.put(CoreEventConstants.DOCUMENT_MODEL_ID, name); 635 options.put(CoreEventConstants.DESTINATION_NAME, name); 636 DocumentModel model = createDocumentModelFromTypeName(typeName, options); 637 model.setPathInfo(parentPath, name); 638 return model; 639 } 640 641 @Override 642 public DocumentModel createDocumentModel(String typeName, Map<String, Object> options) { 643 644 Map<String, Serializable> serializableOptions = new HashMap<>(); 645 646 for (Entry<String, Object> entry : options.entrySet()) { 647 serializableOptions.put(entry.getKey(), (Serializable) entry.getValue()); 648 } 649 return createDocumentModelFromTypeName(typeName, serializableOptions); 650 } 651 652 @Override 653 public DocumentModel createDocument(DocumentModel docModel) { 654 if (docModel.getSessionId() == null) { 655 // docModel was created using constructor instead of CoreSession.createDocumentModel 656 docModel.attach(getSessionId()); 657 } 658 String typeName = docModel.getType(); 659 DocumentRef parentRef = docModel.getParentRef(); 660 if (typeName == null) { 661 throw new NullPointerException("null typeName"); 662 } 663 if (parentRef == null && !isAdministrator()) { 664 throw new NuxeoException("Only Administrators can create placeless documents"); 665 } 666 String childName = docModel.getName(); 667 Map<String, Serializable> options = getContextMapEventInfo(docModel); 668 669 // document validation 670 if (getValidationService().isActivated(DocumentValidationService.CTX_CREATEDOC, options)) { 671 DocumentValidationReport report = getValidationService().validate(docModel, true); 672 if (report.hasError()) { 673 throw new DocumentValidationException(report); 674 } 675 } 676 677 Document folder = fillCreateOptions(parentRef, childName, options); 678 679 // get initial life cycle state info 680 String initialLifecycleState = null; 681 Object lifecycleStateInfo = docModel.getContextData(LifeCycleConstants.INITIAL_LIFECYCLE_STATE_OPTION_NAME); 682 if (lifecycleStateInfo instanceof String) { 683 initialLifecycleState = (String) lifecycleStateInfo; 684 } 685 notifyEvent(DocumentEventTypes.ABOUT_TO_CREATE, docModel, options, null, null, false, true); // no lifecycle 686 // yet 687 childName = (String) options.get(CoreEventConstants.DESTINATION_NAME); 688 Document doc = folder.addChild(childName, typeName); 689 690 // update facets too since some of them may be dynamic 691 for (String facetName : docModel.getFacets()) { 692 if (!doc.getAllFacets().contains(facetName) && !FacetNames.IMMUTABLE.equals(facetName)) { 693 doc.addFacet(facetName); 694 } 695 } 696 697 // init document life cycle 698 NXCore.getLifeCycleService().initialize(doc, initialLifecycleState); 699 700 // init document with data from doc model 701 docModel = writeModel(doc, docModel); 702 703 if (!Boolean.TRUE.equals(docModel.getContextData(ScopeType.REQUEST, VersioningService.SKIP_VERSIONING))) { 704 // during remote publishing we want to skip versioning 705 // to avoid overwriting the version number 706 getVersioningService().doPostCreate(doc, options); 707 docModel = readModel(doc, docModel); 708 } 709 710 notifyEvent(DocumentEventTypes.DOCUMENT_CREATED, docModel, options, null, null, true, false); 711 docModel = writeModel(doc, docModel); 712 713 createDocumentCount.inc(); 714 return docModel; 715 } 716 717 protected Document fillCreateOptions(DocumentRef parentRef, String childName, Map<String, Serializable> options) 718 throws DocumentSecurityException { 719 Document folder; 720 if (parentRef == null || EMPTY_PATH.equals(parentRef)) { 721 folder = getSession().getNullDocument(); 722 options.put(CoreEventConstants.DESTINATION_REF, null); 723 options.put(CoreEventConstants.DESTINATION_PATH, null); 724 options.put(CoreEventConstants.DESTINATION_NAME, childName); 725 options.put(CoreEventConstants.DESTINATION_EXISTS, false); 726 } else { 727 folder = resolveReference(parentRef); 728 checkPermission(folder, ADD_CHILDREN); 729 options.put(CoreEventConstants.DESTINATION_REF, parentRef); 730 options.put(CoreEventConstants.DESTINATION_PATH, folder.getPath()); 731 options.put(CoreEventConstants.DESTINATION_NAME, childName); 732 options.put(CoreEventConstants.DESTINATION_EXISTS, folder.hasChild(childName)); 733 } 734 return folder; 735 } 736 737 @Override 738 public void importDocuments(List<DocumentModel> docModels) { 739 docModels.forEach(this::importDocument); 740 } 741 742 protected static final PathRef EMPTY_PATH = new PathRef(""); 743 744 protected void importDocument(DocumentModel docModel) { 745 if (!isAdministrator()) { 746 throw new DocumentSecurityException("Only Administrator can import"); 747 } 748 String name = docModel.getName(); 749 if (name == null || name.length() == 0) { 750 throw new IllegalArgumentException("Invalid empty name"); 751 } 752 String typeName = docModel.getType(); 753 if (typeName == null || typeName.length() == 0) { 754 throw new IllegalArgumentException("Invalid empty type"); 755 } 756 String id = docModel.getId(); 757 if (id == null || id.length() == 0) { 758 throw new IllegalArgumentException("Invalid empty id"); 759 } 760 761 DocumentRef parentRef = docModel.getParentRef(); 762 Map<String, Serializable> props = getContextMapEventInfo(docModel); 763 764 // document validation 765 if (getValidationService().isActivated(DocumentValidationService.CTX_IMPORTDOC, props)) { 766 DocumentValidationReport report = getValidationService().validate(docModel, true); 767 if (report.hasError()) { 768 throw new DocumentValidationException(report); 769 } 770 } 771 772 if (parentRef != null && EMPTY_PATH.equals(parentRef)) { 773 parentRef = null; 774 } 775 Document parent = fillCreateOptions(parentRef, name, props); 776 notifyEvent(DocumentEventTypes.ABOUT_TO_IMPORT, docModel, props, null, null, false, true); 777 name = (String) props.get(CoreEventConstants.DESTINATION_NAME); 778 779 // create the document 780 Document doc = getSession().importDocument(id, parentRef == null ? null : parent, name, typeName, props); 781 782 if (typeName.equals(CoreSession.IMPORT_PROXY_TYPE)) { 783 // just reread the final document 784 docModel = readModel(doc); 785 } else { 786 // init document with data from doc model 787 docModel = writeModel(doc, docModel); 788 } 789 790 // send an event about the import 791 notifyEvent(DocumentEventTypes.DOCUMENT_IMPORTED, docModel, null, null, null, true, false); 792 } 793 794 @Override 795 public DocumentModel[] createDocument(DocumentModel[] docModels) { 796 DocumentModel[] models = new DocumentModel[docModels.length]; 797 int i = 0; 798 // TODO: optimize this (do not call at each iteration createDocument()) 799 for (DocumentModel docModel : docModels) { 800 models[i++] = createDocument(docModel); 801 } 802 return models; 803 } 804 805 @Override 806 public boolean exists(DocumentRef docRef) { 807 try { 808 Document doc = resolveReference(docRef); 809 return hasPermission(doc, BROWSE); 810 } catch (DocumentNotFoundException e) { 811 return false; 812 } 813 } 814 815 @Override 816 public DocumentModel getChild(DocumentRef parent, String name) { 817 Document doc = resolveReference(parent); 818 checkPermission(doc, READ_CHILDREN); 819 Document child = doc.getChild(name); 820 checkPermission(child, READ); 821 return readModel(child); 822 } 823 824 @Override 825 public boolean hasChild(DocumentRef parent, String name) { 826 Document doc = resolveReference(parent); 827 checkPermission(doc, READ_CHILDREN); 828 return doc.hasChild(name); 829 } 830 831 @Override 832 public DocumentModelList getChildren(DocumentRef parent) { 833 return getChildren(parent, null, READ, null, null); 834 } 835 836 @Override 837 public DocumentModelList getChildren(DocumentRef parent, String type) { 838 return getChildren(parent, type, READ, null, null); 839 } 840 841 @Override 842 public DocumentModelList getChildren(DocumentRef parent, String type, String perm) { 843 return getChildren(parent, type, perm, null, null); 844 } 845 846 @Override 847 public DocumentModelList getChildren(DocumentRef parent, String type, Filter filter, Sorter sorter) { 848 return getChildren(parent, type, null, filter, sorter); 849 } 850 851 @Override 852 public DocumentModelList getChildren(DocumentRef parent, String type, String perm, Filter filter, Sorter sorter) { 853 if (perm == null) { 854 perm = READ; 855 } 856 Document doc = resolveReference(parent); 857 checkPermission(doc, READ_CHILDREN); 858 DocumentModelList docs = new DocumentModelListImpl(); 859 for (Document child : doc.getChildren()) { 860 if (hasPermission(child, perm)) { 861 if (child.getType() != null && (type == null || type.equals(child.getType().getName()))) { 862 DocumentModel childModel = readModel(child); 863 if (filter == null || filter.accept(childModel)) { 864 docs.add(childModel); 865 } 866 } 867 } 868 } 869 if (sorter != null) { 870 Collections.sort(docs, sorter); 871 } 872 return docs; 873 } 874 875 @Override 876 public List<DocumentRef> getChildrenRefs(DocumentRef parentRef, String perm) { 877 if (perm != null) { 878 // XXX TODO 879 throw new NullPointerException("perm != null not implemented"); 880 } 881 Document parent = resolveReference(parentRef); 882 checkPermission(parent, READ_CHILDREN); 883 List<String> ids = parent.getChildrenIds(); 884 List<DocumentRef> refs = new ArrayList<>(ids.size()); 885 for (String id : ids) { 886 refs.add(new IdRef(id)); 887 } 888 return refs; 889 } 890 891 @Override 892 public DocumentModelIterator getChildrenIterator(DocumentRef parent) { 893 return getChildrenIterator(parent, null, null, null); 894 } 895 896 @Override 897 public DocumentModelIterator getChildrenIterator(DocumentRef parent, String type) { 898 return getChildrenIterator(parent, type, null, null); 899 } 900 901 @Override 902 public DocumentModelIterator getChildrenIterator(DocumentRef parent, String type, String perm, Filter filter) { 903 // perm unused, kept for API compat 904 return new DocumentModelChildrenIterator(this, parent, type, filter); 905 } 906 907 @Override 908 public DocumentModel getDocument(DocumentRef docRef) { 909 Document doc = resolveReference(docRef); 910 checkPermission(doc, READ); 911 return readModel(doc); 912 } 913 914 @Override 915 public DocumentModelList getDocuments(DocumentRef[] docRefs) { 916 List<DocumentModel> docs = new ArrayList<>(docRefs.length); 917 for (DocumentRef docRef : docRefs) { 918 Document doc; 919 try { 920 doc = resolveReference(docRef); 921 checkPermission(doc, READ); 922 } catch (DocumentSecurityException e) { 923 // no permission 924 continue; 925 } 926 docs.add(readModel(doc)); 927 } 928 return new DocumentModelListImpl(docs); 929 } 930 931 @Override 932 public DocumentModelList getFiles(DocumentRef parent) { 933 Document doc = resolveReference(parent); 934 checkPermission(doc, READ_CHILDREN); 935 DocumentModelList docs = new DocumentModelListImpl(); 936 for (Document child : doc.getChildren()) { 937 if (!child.isFolder() && hasPermission(child, READ)) { 938 docs.add(readModel(child)); 939 } 940 } 941 return docs; 942 } 943 944 @Override 945 public DocumentModelList getFiles(DocumentRef parent, Filter filter, Sorter sorter) { 946 Document doc = resolveReference(parent); 947 checkPermission(doc, READ_CHILDREN); 948 DocumentModelList docs = new DocumentModelListImpl(); 949 for (Document child : doc.getChildren()) { 950 if (!child.isFolder() && hasPermission(child, READ)) { 951 DocumentModel docModel = readModel(doc); 952 if (filter == null || filter.accept(docModel)) { 953 docs.add(readModel(child)); 954 } 955 } 956 } 957 if (sorter != null) { 958 Collections.sort(docs, sorter); 959 } 960 return docs; 961 } 962 963 @Override 964 public DocumentModelList getFolders(DocumentRef parent) { 965 Document doc = resolveReference(parent); 966 checkPermission(doc, READ_CHILDREN); 967 DocumentModelList docs = new DocumentModelListImpl(); 968 for (Document child : doc.getChildren()) { 969 if (child.isFolder() && hasPermission(child, READ)) { 970 docs.add(readModel(child)); 971 } 972 } 973 return docs; 974 } 975 976 @Override 977 public DocumentModelList getFolders(DocumentRef parent, Filter filter, Sorter sorter) { 978 Document doc = resolveReference(parent); 979 checkPermission(doc, READ_CHILDREN); 980 DocumentModelList docs = new DocumentModelListImpl(); 981 for (Document child : doc.getChildren()) { 982 if (child.isFolder() && hasPermission(child, READ)) { 983 DocumentModel childModel = readModel(child); 984 if (filter == null || filter.accept(childModel)) { 985 docs.add(childModel); 986 } 987 } 988 } 989 if (sorter != null) { 990 Collections.sort(docs, sorter); 991 } 992 return docs; 993 } 994 995 @Override 996 public DocumentRef getParentDocumentRef(DocumentRef docRef) { 997 final Document doc = resolveReference(docRef); 998 Document parentDoc = doc.getParent(); 999 return parentDoc != null ? new IdRef(parentDoc.getUUID()) : null; 1000 } 1001 1002 @Override 1003 public DocumentModel getParentDocument(DocumentRef docRef) { 1004 Document doc = resolveReference(docRef); 1005 Document parentDoc = doc.getParent(); 1006 if (parentDoc == null) { 1007 return null; 1008 } 1009 if (!hasPermission(parentDoc, READ)) { 1010 throw new DocumentSecurityException("Privilege READ is not granted to " + getPrincipal().getName()); 1011 } 1012 return readModel(parentDoc); 1013 } 1014 1015 @Override 1016 public List<DocumentModel> getParentDocuments(final DocumentRef docRef) { 1017 1018 if (null == docRef) { 1019 throw new IllegalArgumentException("null docRef"); 1020 } 1021 1022 final List<DocumentModel> docsList = new ArrayList<>(); 1023 Document doc = resolveReference(docRef); 1024 while (doc != null && !"/".equals(doc.getPath())) { 1025 // XXX OG: shouldn't we check BROWSE and READ_PROPERTIES 1026 // instead? 1027 if (!hasPermission(doc, READ)) { 1028 break; 1029 } 1030 docsList.add(readModel(doc)); 1031 doc = doc.getParent(); 1032 } 1033 Collections.reverse(docsList); 1034 return docsList; 1035 } 1036 1037 @Override 1038 public DocumentModel getRootDocument() { 1039 return readModel(getSession().getRootDocument()); 1040 } 1041 1042 @Override 1043 public boolean hasChildren(DocumentRef docRef) { 1044 // TODO: validate permission check with td 1045 Document doc = resolveReference(docRef); 1046 checkPermission(doc, BROWSE); 1047 return doc.hasChildren(); 1048 } 1049 1050 @Override 1051 public DocumentModelList query(String query) { 1052 return query(query, null, 0, 0, false); 1053 } 1054 1055 @Override 1056 public DocumentModelList query(String query, int max) { 1057 return query(query, null, max, 0, false); 1058 } 1059 1060 @Override 1061 public DocumentModelList query(String query, Filter filter) { 1062 return query(query, filter, 0, 0, false); 1063 } 1064 1065 @Override 1066 public DocumentModelList query(String query, Filter filter, int max) { 1067 return query(query, filter, max, 0, false); 1068 } 1069 1070 @Override 1071 public DocumentModelList query(String query, Filter filter, long limit, long offset, boolean countTotal) { 1072 return query(query, NXQL.NXQL, filter, limit, offset, countTotal); 1073 } 1074 1075 @Override 1076 public DocumentModelList query(String query, String queryType, Filter filter, long limit, long offset, 1077 boolean countTotal) { 1078 long countUpTo; 1079 if (!countTotal) { 1080 countUpTo = 0; 1081 } else { 1082 if (isLimitedResults()) { 1083 countUpTo = getMaxResults(); 1084 } else { 1085 countUpTo = -1; 1086 } 1087 } 1088 return query(query, queryType, filter, limit, offset, countUpTo); 1089 } 1090 1091 protected long getMaxResults() { 1092 if (maxResults == null) { 1093 maxResults = Long.parseLong(Framework.getProperty(MAX_RESULTS_PROPERTY, DEFAULT_MAX_RESULTS)); 1094 } 1095 return maxResults; 1096 } 1097 1098 protected boolean isLimitedResults() { 1099 if (limitedResults == null) { 1100 limitedResults = Boolean.parseBoolean(Framework.getProperty(LIMIT_RESULTS_PROPERTY)); 1101 } 1102 return limitedResults; 1103 } 1104 1105 protected void setMaxResults(long maxResults) { 1106 this.maxResults = maxResults; 1107 } 1108 1109 protected void setLimitedResults(boolean limitedResults) { 1110 this.limitedResults = limitedResults; 1111 } 1112 1113 @Override 1114 public DocumentModelList query(String query, Filter filter, long limit, long offset, long countUpTo) { 1115 return query(query, NXQL.NXQL, filter, limit, offset, countUpTo); 1116 } 1117 1118 @Override 1119 public DocumentModelList query(String query, String queryType, Filter filter, long limit, long offset, 1120 long countUpTo) { 1121 SecurityService securityService = getSecurityService(); 1122 Principal principal = getPrincipal(); 1123 try { 1124 String permission = BROWSE; 1125 String repoName = getRepositoryName(); 1126 boolean postFilterPolicies = !securityService.arePoliciesExpressibleInQuery(repoName); 1127 boolean postFilterFilter = filter != null && !(filter instanceof FacetFilter); 1128 boolean postFilter = postFilterPolicies || postFilterFilter; 1129 String[] principals; 1130 if (isAdministrator()) { 1131 principals = null; // means: no security check needed 1132 } else { 1133 principals = SecurityService.getPrincipalsToCheck(principal); 1134 } 1135 String[] permissions = securityService.getPermissionsToCheck(permission); 1136 QueryFilter queryFilter = new QueryFilter(principal, principals, permissions, 1137 filter instanceof FacetFilter ? (FacetFilter) filter : null, 1138 securityService.getPoliciesQueryTransformers(repoName), postFilter ? 0 : limit, postFilter ? 0 1139 : offset); 1140 1141 // get document list with total size 1142 PartialList<Document> pl = getSession().query(query, queryType, queryFilter, postFilter ? -1 : countUpTo); 1143 // convert to DocumentModelList 1144 DocumentModelListImpl dms = new DocumentModelListImpl(pl.list.size()); 1145 dms.setTotalSize(pl.totalSize); 1146 for (Document doc : pl.list) { 1147 dms.add(readModel(doc)); 1148 } 1149 1150 if (!postFilter) { 1151 // the backend has done all the needed filtering 1152 return dms; 1153 } 1154 1155 // post-filter the results "by hand", the backend couldn't do it 1156 long start = limit == 0 || offset < 0 ? 0 : offset; 1157 long stop = start + (limit == 0 ? dms.size() : limit); 1158 int n = 0; 1159 DocumentModelListImpl docs = new DocumentModelListImpl(); 1160 for (DocumentModel model : dms) { 1161 if (postFilterPolicies) { 1162 if (!hasPermission(model.getRef(), permission)) { 1163 continue; 1164 } 1165 } 1166 if (postFilterFilter) { 1167 if (!filter.accept(model)) { 1168 continue; 1169 } 1170 } 1171 if (n < start) { 1172 n++; 1173 continue; 1174 } 1175 if (n >= stop) { 1176 if (countUpTo == 0) { 1177 // can break early 1178 break; 1179 } 1180 n++; 1181 continue; 1182 } 1183 n++; 1184 docs.add(model); 1185 } 1186 if (countUpTo != 0) { 1187 docs.setTotalSize(n); 1188 } 1189 return docs; 1190 } catch (QueryParseException e) { 1191 e.addInfo("Failed to execute query: " + query); 1192 throw e; 1193 } 1194 } 1195 1196 @Override 1197 public IterableQueryResult queryAndFetch(String query, String queryType, Object... params) { 1198 return queryAndFetch(query, queryType, false, params); 1199 } 1200 1201 @Override 1202 public IterableQueryResult queryAndFetch(String query, String queryType, boolean distinctDocuments, 1203 Object... params) { 1204 try { 1205 SecurityService securityService = getSecurityService(); 1206 Principal principal = getPrincipal(); 1207 String[] principals; 1208 if (isAdministrator()) { 1209 principals = null; // means: no security check needed 1210 } else { 1211 principals = SecurityService.getPrincipalsToCheck(principal); 1212 } 1213 String permission = BROWSE; 1214 String[] permissions = securityService.getPermissionsToCheck(permission); 1215 Collection<Transformer> transformers; 1216 if (NXQL.NXQL.equals(queryType)) { 1217 String repoName = getRepositoryName(); 1218 transformers = securityService.getPoliciesQueryTransformers(repoName); 1219 } else { 1220 transformers = Collections.emptyList(); 1221 } 1222 QueryFilter queryFilter = new QueryFilter(principal, principals, permissions, null, transformers, 0, 0); 1223 IterableQueryResult result = getSession().queryAndFetch(query, queryType, queryFilter, distinctDocuments, 1224 params); 1225 return result; 1226 } catch (QueryParseException e) { 1227 e.addInfo("Failed to execute query: " + queryType + ": " + query); 1228 throw e; 1229 } 1230 } 1231 1232 @Override 1233 public void removeChildren(DocumentRef docRef) { 1234 // TODO: check req permissions with td 1235 Document doc = resolveReference(docRef); 1236 checkPermission(doc, REMOVE_CHILDREN); 1237 List<Document> children = doc.getChildren(); 1238 // remove proxies first, otherwise they could become dangling 1239 for (Document child : children) { 1240 if (child.isProxy()) { 1241 if (hasPermission(child, REMOVE)) { 1242 removeNotifyOneDoc(child); 1243 } 1244 } 1245 } 1246 // then remove regular docs or versions, both of which could be proxies targets 1247 for (Document child : children) { 1248 if (!child.isProxy()) { 1249 if (hasPermission(child, REMOVE)) { 1250 removeNotifyOneDoc(child); 1251 } 1252 } 1253 } 1254 } 1255 1256 @Override 1257 public boolean canRemoveDocument(DocumentRef docRef) { 1258 Document doc = resolveReference(docRef); 1259 return canRemoveDocument(doc) == null; 1260 } 1261 1262 /** 1263 * Checks if a document can be removed, and returns a failure reason if not. 1264 */ 1265 protected String canRemoveDocument(Document doc) { 1266 // TODO must also check for proxies on live docs 1267 if (doc.isVersion()) { 1268 // TODO a hasProxies method would be more efficient 1269 Collection<Document> proxies = getSession().getProxies(doc, null); 1270 if (!proxies.isEmpty()) { 1271 return "Proxy " + proxies.iterator().next().getUUID() + " targets version " + doc.getUUID(); 1272 } 1273 // find a working document to check security 1274 Document working = doc.getSourceDocument(); 1275 if (working != null) { 1276 Document baseVersion = working.getBaseVersion(); 1277 if (baseVersion != null && !baseVersion.isCheckedOut() && baseVersion.getUUID().equals(doc.getUUID())) { 1278 return "Working copy " + working.getUUID() + " is checked in with base version " + doc.getUUID(); 1279 } 1280 return hasPermission(working, WRITE_VERSION) ? null : "Missing permission '" + WRITE_VERSION 1281 + "' on working copy " + working.getUUID(); 1282 } else { 1283 // no working document, only admins can remove 1284 return isAdministrator() ? null : "No working copy and not an Administrator"; 1285 } 1286 } else { 1287 if (isAdministrator()) { 1288 return null; // ok 1289 } 1290 if (!hasPermission(doc, REMOVE)) { 1291 return "Missing permission '" + REMOVE + "' on document " + doc.getUUID(); 1292 } 1293 Document parent = doc.getParent(); 1294 if (parent == null) { 1295 return null; // ok 1296 } 1297 return hasPermission(parent, REMOVE_CHILDREN) ? null : "Missing permission '" + REMOVE_CHILDREN 1298 + "' on parent document " + parent.getUUID(); 1299 } 1300 } 1301 1302 @Override 1303 public void removeDocument(DocumentRef docRef) { 1304 Document doc = resolveReference(docRef); 1305 removeDocument(doc); 1306 } 1307 1308 protected void removeDocument(Document doc) { 1309 try { 1310 String reason = canRemoveDocument(doc); 1311 if (reason != null) { 1312 throw new DocumentSecurityException("Permission denied: cannot remove document " + doc.getUUID() + ", " 1313 + reason); 1314 } 1315 removeNotifyOneDoc(doc); 1316 1317 } catch (ConcurrentUpdateException e) { 1318 e.addInfo("Failed to remove document " + doc.getUUID()); 1319 throw e; 1320 } 1321 deleteDocumentCount.inc(); 1322 } 1323 1324 protected void removeNotifyOneDoc(Document doc) { 1325 // XXX notify with options if needed 1326 DocumentModel docModel = readModel(doc); 1327 Map<String, Serializable> options = new HashMap<>(); 1328 if (docModel != null) { 1329 options.put("docTitle", docModel.getTitle()); 1330 } 1331 String versionLabel = ""; 1332 Document sourceDoc = null; 1333 // notify different events depending on wether the document is a 1334 // version or not 1335 if (!doc.isVersion()) { 1336 notifyEvent(DocumentEventTypes.ABOUT_TO_REMOVE, docModel, options, null, null, true, true); 1337 CoreService coreService = Framework.getLocalService(CoreService.class); 1338 coreService.getVersionRemovalPolicy().removeVersions(getSession(), doc, this); 1339 } else { 1340 versionLabel = docModel.getVersionLabel(); 1341 sourceDoc = doc.getSourceDocument(); 1342 notifyEvent(DocumentEventTypes.ABOUT_TO_REMOVE_VERSION, docModel, options, null, null, true, true); 1343 1344 } 1345 doc.remove(); 1346 if (doc.isVersion()) { 1347 if (sourceDoc != null) { 1348 DocumentModel sourceDocModel = readModel(sourceDoc); 1349 if (sourceDocModel != null) { 1350 options.put("comment", versionLabel); // to be used by 1351 // audit 1352 // service 1353 notifyEvent(DocumentEventTypes.VERSION_REMOVED, sourceDocModel, options, null, null, false, false); 1354 options.remove("comment"); 1355 } 1356 options.put("docSource", sourceDoc.getUUID()); 1357 } 1358 } 1359 notifyEvent(DocumentEventTypes.DOCUMENT_REMOVED, docModel, options, null, null, false, false); 1360 } 1361 1362 /** 1363 * Implementation uses the fact that the lexicographic ordering of paths is a refinement of the "contains" partial 1364 * ordering. 1365 */ 1366 @Override 1367 public void removeDocuments(DocumentRef[] docRefs) { 1368 Document[] docs = new Document[docRefs.length]; 1369 1370 for (int i = 0; i < docs.length; i++) { 1371 docs[i] = resolveReference(docRefs[i]); 1372 } 1373 // TODO OPTIM: it's not guaranteed that getPath is cheap and 1374 // we call it a lot. Should use an object for pairs (document, path) 1375 // to call it just once per doc. 1376 Arrays.sort(docs, pathComparator); // nulls first 1377 String[] paths = new String[docs.length]; 1378 for (int i = 0; i < docs.length; i++) { 1379 paths[i] = docs[i].getPath(); 1380 } 1381 String lastRemovedWithSlash = "\u0000"; 1382 for (int i = 0; i < docs.length; i++) { 1383 String path = paths[i]; 1384 if (i == 0 || path == null || !path.startsWith(lastRemovedWithSlash)) { 1385 removeDocument(docs[i]); 1386 if (path != null) { 1387 lastRemovedWithSlash = path + "/"; 1388 } 1389 } 1390 } 1391 } 1392 1393 @Override 1394 public void save() { 1395 try { 1396 final Map<String, Serializable> options = new HashMap<>(); 1397 getSession().save(); 1398 notifyEvent(DocumentEventTypes.SESSION_SAVED, null, options, null, null, true, false); 1399 } catch (ConcurrentUpdateException e) { 1400 e.addInfo("Failed to save session"); 1401 throw e; 1402 } 1403 } 1404 1405 @Override 1406 public DocumentModel saveDocument(DocumentModel docModel) { 1407 if (docModel.getRef() == null) { 1408 throw new IllegalArgumentException(String.format("cannot save document '%s' with null reference: " 1409 + "document has probably not yet been created " + "in the repository with " 1410 + "'CoreSession.createDocument(docModel)'", docModel.getTitle())); 1411 } 1412 Document doc = resolveReference(docModel.getRef()); 1413 checkPermission(doc, WRITE_PROPERTIES); 1414 1415 Map<String, Serializable> options = getContextMapEventInfo(docModel); 1416 1417 boolean dirty = docModel.isDirty(); 1418 1419 // document validation 1420 if (dirty && getValidationService().isActivated(DocumentValidationService.CTX_SAVEDOC, options)) { 1421 DocumentValidationReport report = getValidationService().validate(docModel, true); 1422 if (report.hasError()) { 1423 throw new DocumentValidationException(report); 1424 } 1425 } 1426 1427 options.put(CoreEventConstants.PREVIOUS_DOCUMENT_MODEL, readModel(doc)); 1428 // regular event, last chance to modify docModel 1429 options.put(CoreEventConstants.DESTINATION_NAME, docModel.getName()); 1430 options.put(CoreEventConstants.DOCUMENT_DIRTY, dirty); 1431 notifyEvent(DocumentEventTypes.BEFORE_DOC_UPDATE, docModel, options, null, null, true, true); 1432 String name = (String) options.get(CoreEventConstants.DESTINATION_NAME); 1433 // did the event change the name? not applicable to Root whose 1434 // name is null/empty 1435 if (name != null && !name.equals(docModel.getName())) { 1436 doc = getSession().move(doc, doc.getParent(), name); 1437 } 1438 1439 // recompute the dirty state 1440 dirty = docModel.isDirty(); 1441 options.put(CoreEventConstants.DOCUMENT_DIRTY, dirty); 1442 1443 VersioningOption versioningOption = (VersioningOption) docModel.getContextData(VersioningService.VERSIONING_OPTION); 1444 docModel.putContextData(VersioningService.VERSIONING_OPTION, null); 1445 String checkinComment = (String) docModel.getContextData(VersioningService.CHECKIN_COMMENT); 1446 docModel.putContextData(VersioningService.CHECKIN_COMMENT, null); 1447 Boolean disableAutoCheckOut = (Boolean) docModel.getContextData(VersioningService.DISABLE_AUTO_CHECKOUT); 1448 docModel.putContextData(VersioningService.DISABLE_AUTO_CHECKOUT, null); 1449 options.put(VersioningService.DISABLE_AUTO_CHECKOUT, disableAutoCheckOut); 1450 // compat 1451 boolean snapshot = Boolean.TRUE.equals(docModel.getContextData(ScopeType.REQUEST, 1452 VersioningDocument.CREATE_SNAPSHOT_ON_SAVE_KEY)); 1453 docModel.putContextData(ScopeType.REQUEST, VersioningDocument.CREATE_SNAPSHOT_ON_SAVE_KEY, null); 1454 if (versioningOption == null && snapshot && dirty) { 1455 String key = String.valueOf(docModel.getContextData(ScopeType.REQUEST, 1456 VersioningDocument.KEY_FOR_INC_OPTION)); 1457 docModel.putContextData(ScopeType.REQUEST, VersioningDocument.KEY_FOR_INC_OPTION, null); 1458 versioningOption = "inc_major".equals(key) ? VersioningOption.MAJOR : VersioningOption.MINOR; 1459 } 1460 1461 if (!docModel.isImmutable()) { 1462 // pre-save versioning 1463 boolean checkout = getVersioningService().isPreSaveDoingCheckOut(doc, dirty, versioningOption, options); 1464 if (checkout) { 1465 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKOUT, docModel, options, null, null, true, true); 1466 } 1467 versioningOption = getVersioningService().doPreSave(doc, dirty, versioningOption, checkinComment, options); 1468 if (checkout) { 1469 DocumentModel checkedOutDoc = readModel(doc); 1470 notifyEvent(DocumentEventTypes.DOCUMENT_CHECKEDOUT, checkedOutDoc, options, null, null, true, false); 1471 } 1472 } 1473 1474 boolean allowVersionWrite = Boolean.TRUE.equals(docModel.getContextData(ALLOW_VERSION_WRITE)); 1475 docModel.putContextData(ALLOW_VERSION_WRITE, null); 1476 boolean setReadWrite = allowVersionWrite && doc.isVersion() && doc.isReadOnly(); 1477 1478 // actual save 1479 if (setReadWrite) { 1480 doc.setReadOnly(false); 1481 } 1482 docModel = writeModel(doc, docModel); 1483 if (setReadWrite) { 1484 doc.setReadOnly(true); 1485 } 1486 1487 Document checkedInDoc = null; 1488 if (!docModel.isImmutable()) { 1489 // post-save versioning 1490 boolean checkin = getVersioningService().isPostSaveDoingCheckIn(doc, versioningOption, options); 1491 if (checkin) { 1492 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKIN, docModel, options, null, null, true, true); 1493 } 1494 checkedInDoc = getVersioningService().doPostSave(doc, versioningOption, checkinComment, options); 1495 } 1496 1497 // post-save events 1498 docModel = readModel(doc); 1499 if (checkedInDoc != null) { 1500 DocumentRef checkedInVersionRef = new IdRef(checkedInDoc.getUUID()); 1501 notifyCheckedInVersion(docModel, checkedInVersionRef, options, checkinComment); 1502 } 1503 notifyEvent(DocumentEventTypes.DOCUMENT_UPDATED, docModel, options, null, null, true, false); 1504 updateDocumentCount.inc(); 1505 return docModel; 1506 } 1507 1508 @Override 1509 @Deprecated 1510 public boolean isDirty(DocumentRef docRef) { 1511 return resolveReference(docRef).isCheckedOut(); 1512 } 1513 1514 @Override 1515 public void saveDocuments(DocumentModel[] docModels) { 1516 // TODO: optimize this - avoid calling at each iteration saveDoc... 1517 for (DocumentModel docModel : docModels) { 1518 saveDocument(docModel); 1519 } 1520 } 1521 1522 @Override 1523 public DocumentModel getSourceDocument(DocumentRef docRef) { 1524 assert null != docRef; 1525 1526 Document doc = resolveReference(docRef); 1527 checkPermission(doc, READ_VERSION); 1528 Document headDocument = doc.getSourceDocument(); 1529 if (headDocument == null) { 1530 throw new DocumentNotFoundException("Source document has been deleted"); 1531 } 1532 return readModel(headDocument); 1533 } 1534 1535 protected VersionModel getVersionModel(Document version) { 1536 VersionModel versionModel = new VersionModelImpl(); 1537 versionModel.setId(version.getUUID()); 1538 versionModel.setCreated(version.getVersionCreationDate()); 1539 versionModel.setDescription(version.getCheckinComment()); 1540 versionModel.setLabel(version.getVersionLabel()); 1541 return versionModel; 1542 } 1543 1544 @Override 1545 public VersionModel getLastVersion(DocumentRef docRef) { 1546 Document doc = resolveReference(docRef); 1547 checkPermission(doc, READ_VERSION); 1548 Document version = doc.getLastVersion(); 1549 return version == null ? null : getVersionModel(version); 1550 } 1551 1552 @Override 1553 public DocumentModel getLastDocumentVersion(DocumentRef docRef) { 1554 Document doc = resolveReference(docRef); 1555 checkPermission(doc, READ_VERSION); 1556 Document version = doc.getLastVersion(); 1557 return version == null ? null : readModel(version); 1558 } 1559 1560 @Override 1561 public DocumentRef getLastDocumentVersionRef(DocumentRef docRef) { 1562 Document doc = resolveReference(docRef); 1563 checkPermission(doc, READ_VERSION); 1564 Document version = doc.getLastVersion(); 1565 return version == null ? null : new IdRef(version.getUUID()); 1566 } 1567 1568 @Override 1569 public List<DocumentRef> getVersionsRefs(DocumentRef docRef) { 1570 Document doc = resolveReference(docRef); 1571 checkPermission(doc, READ_VERSION); 1572 List<String> ids = doc.getVersionsIds(); 1573 List<DocumentRef> refs = new ArrayList<>(ids.size()); 1574 for (String id : ids) { 1575 refs.add(new IdRef(id)); 1576 } 1577 return refs; 1578 } 1579 1580 @Override 1581 public List<DocumentModel> getVersions(DocumentRef docRef) { 1582 Document doc = resolveReference(docRef); 1583 checkPermission(doc, READ_VERSION); 1584 List<Document> docVersions = doc.getVersions(); 1585 List<DocumentModel> versions = new ArrayList<>(docVersions.size()); 1586 for (Document version : docVersions) { 1587 versions.add(readModel(version)); 1588 } 1589 return versions; 1590 } 1591 1592 @Override 1593 public List<VersionModel> getVersionsForDocument(DocumentRef docRef) { 1594 Document doc = resolveReference(docRef); 1595 checkPermission(doc, READ_VERSION); 1596 List<Document> docVersions = doc.getVersions(); 1597 List<VersionModel> versions = new ArrayList<>(docVersions.size()); 1598 for (Document version : docVersions) { 1599 versions.add(getVersionModel(version)); 1600 } 1601 return versions; 1602 1603 } 1604 1605 @Override 1606 public DocumentModel restoreToVersion(DocumentRef docRef, DocumentRef versionRef) { 1607 Document doc = resolveReference(docRef); 1608 Document ver = resolveReference(versionRef); 1609 return restoreToVersion(doc, ver, false, true); 1610 } 1611 1612 @Override 1613 @Deprecated 1614 public DocumentModel restoreToVersion(DocumentRef docRef, VersionModel version) { 1615 return restoreToVersion(docRef, version, false); 1616 } 1617 1618 @Override 1619 @Deprecated 1620 public DocumentModel restoreToVersion(DocumentRef docRef, VersionModel version, boolean skipSnapshotCreation) { 1621 Document doc = resolveReference(docRef); 1622 Document ver = doc.getVersion(version.getLabel()); 1623 return restoreToVersion(doc, ver, skipSnapshotCreation, false); 1624 } 1625 1626 @Override 1627 public DocumentModel restoreToVersion(DocumentRef docRef, DocumentRef versionRef, boolean skipSnapshotCreation, 1628 boolean skipCheckout) { 1629 Document doc = resolveReference(docRef); 1630 Document ver = resolveReference(versionRef); 1631 return restoreToVersion(doc, ver, skipSnapshotCreation, skipCheckout); 1632 } 1633 1634 protected DocumentModel restoreToVersion(Document doc, Document version, boolean skipSnapshotCreation, 1635 boolean skipCheckout) { 1636 checkPermission(doc, WRITE_VERSION); 1637 1638 DocumentModel docModel = readModel(doc); 1639 1640 Map<String, Serializable> options = new HashMap<>(); 1641 1642 // we're about to overwrite the document, make sure it's archived 1643 if (!skipSnapshotCreation && doc.isCheckedOut()) { 1644 String checkinComment = (String) docModel.getContextData(VersioningService.CHECKIN_COMMENT); 1645 docModel.putContextData(VersioningService.CHECKIN_COMMENT, null); 1646 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKIN, docModel, options, null, null, true, true); 1647 Document ver = getVersioningService().doCheckIn(doc, null, checkinComment); 1648 docModel.refresh(DocumentModel.REFRESH_STATE, null); 1649 notifyCheckedInVersion(docModel, new IdRef(ver.getUUID()), null, checkinComment); 1650 } 1651 1652 // FIXME: the fields are hardcoded. should be moved in versioning 1653 // component 1654 // HOW? 1655 final Long majorVer = (Long) doc.getPropertyValue("major_version"); 1656 final Long minorVer = (Long) doc.getPropertyValue("minor_version"); 1657 if (majorVer != null || minorVer != null) { 1658 options.put(VersioningDocument.CURRENT_DOCUMENT_MAJOR_VERSION_KEY, majorVer); 1659 options.put(VersioningDocument.CURRENT_DOCUMENT_MINOR_VERSION_KEY, minorVer); 1660 } 1661 // add the uuid of the version being restored 1662 String versionUUID = version.getUUID(); 1663 options.put(VersioningDocument.RESTORED_VERSION_UUID_KEY, versionUUID); 1664 1665 notifyEvent(DocumentEventTypes.BEFORE_DOC_RESTORE, docModel, options, null, null, true, true); 1666 writeModel(doc, docModel); 1667 1668 doc.restore(version); 1669 // re-read doc model after restoration 1670 docModel = readModel(doc); 1671 notifyEvent(DocumentEventTypes.DOCUMENT_RESTORED, docModel, options, null, docModel.getVersionLabel(), true, 1672 false); 1673 docModel = writeModel(doc, docModel); 1674 1675 if (!skipCheckout) { 1676 // restore gives us a checked in document, so do a checkout 1677 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKOUT, docModel, options, null, null, true, true); 1678 getVersioningService().doCheckOut(doc); 1679 docModel = readModel(doc); 1680 notifyEvent(DocumentEventTypes.DOCUMENT_CHECKEDOUT, docModel, options, null, null, true, false); 1681 } 1682 1683 log.debug("Document restored to version:" + version.getUUID()); 1684 return docModel; 1685 } 1686 1687 @Override 1688 public DocumentRef getBaseVersion(DocumentRef docRef) { 1689 Document doc = resolveReference(docRef); 1690 checkPermission(doc, READ); 1691 Document ver = doc.getBaseVersion(); 1692 if (ver == null) { 1693 return null; 1694 } 1695 checkPermission(ver, READ); 1696 return new IdRef(ver.getUUID()); 1697 } 1698 1699 @Override 1700 @Deprecated 1701 public DocumentModel checkIn(DocumentRef docRef, VersionModel ver) { 1702 DocumentRef verRef = checkIn(docRef, VersioningOption.MINOR, ver == null ? null : ver.getDescription()); 1703 return readModel(resolveReference(verRef)); 1704 } 1705 1706 @Override 1707 public DocumentRef checkIn(DocumentRef docRef, VersioningOption option, String checkinComment) { 1708 Document doc = resolveReference(docRef); 1709 checkPermission(doc, WRITE_PROPERTIES); 1710 DocumentModel docModel = readModel(doc); 1711 1712 Map<String, Serializable> options = new HashMap<>(); 1713 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKIN, docModel, options, null, null, true, true); 1714 writeModel(doc, docModel); 1715 1716 Document version = getVersioningService().doCheckIn(doc, option, checkinComment); 1717 1718 docModel = readModel(doc); 1719 DocumentRef checkedInVersionRef = new IdRef(version.getUUID()); 1720 notifyCheckedInVersion(docModel, checkedInVersionRef, options, checkinComment); 1721 writeModel(doc, docModel); 1722 1723 return checkedInVersionRef; 1724 } 1725 1726 /** 1727 * Send a core event for the creation of a new check in version. The source document is the live document model used 1728 * as the source for the checkin, not the archived version it-self. 1729 * 1730 * @param docModel work document that has been checked-in as a version 1731 * @param checkedInVersionRef document ref of the new checked-in version 1732 * @param options initial option map, or null 1733 */ 1734 protected void notifyCheckedInVersion(DocumentModel docModel, DocumentRef checkedInVersionRef, 1735 Map<String, Serializable> options, String checkinComment) { 1736 String label = getVersioningService().getVersionLabel(docModel); 1737 Map<String, Serializable> props = new HashMap<>(); 1738 if (options != null) { 1739 props.putAll(options); 1740 } 1741 props.put("versionLabel", label); 1742 props.put("checkInComment", checkinComment); 1743 props.put("checkedInVersionRef", checkedInVersionRef); 1744 if (checkinComment == null && options != null) { 1745 // check if there's a comment already in options 1746 Object optionsComment = options.get("comment"); 1747 if (optionsComment instanceof String) { 1748 checkinComment = (String) optionsComment; 1749 } 1750 } 1751 String comment = checkinComment == null ? label : label + ' ' + checkinComment; 1752 props.put("comment", comment); // compat, used in audit 1753 // notify checkin on live document 1754 notifyEvent(DocumentEventTypes.DOCUMENT_CHECKEDIN, docModel, props, null, null, true, false); 1755 // notify creation on version document 1756 notifyEvent(DocumentEventTypes.DOCUMENT_CREATED, getDocument(checkedInVersionRef), props, null, null, true, 1757 false); 1758 1759 } 1760 1761 @Override 1762 public void checkOut(DocumentRef docRef) { 1763 Document doc = resolveReference(docRef); 1764 // TODO: add a new permission names CHECKOUT and use it instead of 1765 // WRITE_PROPERTIES 1766 checkPermission(doc, WRITE_PROPERTIES); 1767 DocumentModel docModel = readModel(doc); 1768 Map<String, Serializable> options = new HashMap<>(); 1769 1770 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKOUT, docModel, options, null, null, true, true); 1771 1772 getVersioningService().doCheckOut(doc); 1773 docModel = readModel(doc); 1774 1775 notifyEvent(DocumentEventTypes.DOCUMENT_CHECKEDOUT, docModel, options, null, null, true, false); 1776 writeModel(doc, docModel); 1777 } 1778 1779 @Override 1780 public boolean isCheckedOut(DocumentRef docRef) { 1781 assert null != docRef; 1782 Document doc = resolveReference(docRef); 1783 checkPermission(doc, BROWSE); 1784 return doc.isCheckedOut(); 1785 } 1786 1787 @Override 1788 public String getVersionSeriesId(DocumentRef docRef) { 1789 Document doc = resolveReference(docRef); 1790 checkPermission(doc, READ); 1791 return doc.getVersionSeriesId(); 1792 } 1793 1794 @Override 1795 public DocumentModel getWorkingCopy(DocumentRef docRef) { 1796 Document doc = resolveReference(docRef); 1797 checkPermission(doc, READ_VERSION); 1798 Document pwc = doc.getWorkingCopy(); 1799 checkPermission(pwc, READ); 1800 return pwc == null ? null : readModel(pwc); 1801 } 1802 1803 @Override 1804 public DocumentModel getVersion(String versionableId, VersionModel versionModel) { 1805 String id = versionModel.getId(); 1806 if (id != null) { 1807 return getDocument(new IdRef(id)); 1808 } 1809 Document doc = getSession().getVersion(versionableId, versionModel); 1810 if (doc == null) { 1811 return null; 1812 } 1813 checkPermission(doc, READ_PROPERTIES); 1814 checkPermission(doc, READ_VERSION); 1815 return readModel(doc); 1816 } 1817 1818 @Override 1819 public String getVersionLabel(DocumentModel docModel) { 1820 return getVersioningService().getVersionLabel(docModel); 1821 } 1822 1823 @Override 1824 public DocumentModel getDocumentWithVersion(DocumentRef docRef, VersionModel version) { 1825 String id = version.getId(); 1826 if (id != null) { 1827 return getDocument(new IdRef(id)); 1828 } 1829 Document doc = resolveReference(docRef); 1830 checkPermission(doc, READ_PROPERTIES); 1831 checkPermission(doc, READ_VERSION); 1832 String docPath = doc.getPath(); 1833 doc = doc.getVersion(version.getLabel()); 1834 if (doc == null) { 1835 // SQL Storage uses to return null if version not found 1836 log.debug("Version " + version.getLabel() + " does not exist for " + docPath); 1837 return null; 1838 } 1839 log.debug("Retrieved the version " + version.getLabel() + " of the document " + docPath); 1840 return readModel(doc); 1841 } 1842 1843 @Override 1844 public DocumentModel createProxy(DocumentRef docRef, DocumentRef folderRef) { 1845 Document doc = resolveReference(docRef); 1846 Document fold = resolveReference(folderRef); 1847 checkPermission(doc, READ); 1848 checkPermission(fold, ADD_CHILDREN); 1849 return createProxyInternal(doc, fold, new HashMap<>()); 1850 } 1851 1852 protected DocumentModel createProxyInternal(Document doc, Document folder, Map<String, Serializable> options) { 1853 // create the new proxy 1854 Document proxy = getSession().createProxy(doc, folder); 1855 DocumentModel proxyModel = readModel(proxy); 1856 1857 notifyEvent(DocumentEventTypes.DOCUMENT_CREATED, proxyModel, options, null, null, true, false); 1858 notifyEvent(DocumentEventTypes.DOCUMENT_PROXY_PUBLISHED, proxyModel, options, null, null, true, false); 1859 DocumentModel folderModel = readModel(folder); 1860 notifyEvent(DocumentEventTypes.SECTION_CONTENT_PUBLISHED, folderModel, options, null, null, true, false); 1861 return proxyModel; 1862 } 1863 1864 /** 1865 * Remove proxies for the same base document in the folder. doc may be a normal document or a proxy. 1866 */ 1867 protected List<String> removeExistingProxies(Document doc, Document folder) { 1868 Collection<Document> otherProxies = getSession().getProxies(doc, folder); 1869 List<String> removedProxyIds = new ArrayList<>(otherProxies.size()); 1870 for (Document otherProxy : otherProxies) { 1871 removedProxyIds.add(otherProxy.getUUID()); 1872 removeNotifyOneDoc(otherProxy); 1873 } 1874 return removedProxyIds; 1875 } 1876 1877 /** 1878 * Update the proxy for doc in the given section to point to the new target. Do nothing if there are several 1879 * proxies. 1880 * 1881 * @return the proxy if it was updated, or {@code null} if none or several were found 1882 */ 1883 protected DocumentModel updateExistingProxies(Document doc, Document folder, Document target) { 1884 Collection<Document> proxies = getSession().getProxies(doc, folder); 1885 try { 1886 if (proxies.size() == 1) { 1887 for (Document proxy : proxies) { 1888 proxy.setTargetDocument(target); 1889 return readModel(proxy); 1890 } 1891 } 1892 } catch (UnsupportedOperationException e) { 1893 log.error("Cannot update proxy, try to remove"); 1894 } 1895 return null; 1896 } 1897 1898 @Override 1899 public DocumentModelList getProxies(DocumentRef docRef, DocumentRef folderRef) { 1900 Document folder = null; 1901 if (folderRef != null) { 1902 folder = resolveReference(folderRef); 1903 checkPermission(folder, READ_CHILDREN); 1904 } 1905 Document doc = resolveReference(docRef); 1906 Collection<Document> children = getSession().getProxies(doc, folder); 1907 DocumentModelList docs = new DocumentModelListImpl(); 1908 for (Document child : children) { 1909 if (hasPermission(child, READ)) { 1910 docs.add(readModel(child)); 1911 } 1912 } 1913 return docs; 1914 } 1915 1916 @Override 1917 public String[] getProxyVersions(DocumentRef docRef, DocumentRef folderRef) { 1918 Document folder = resolveReference(folderRef); 1919 Document doc = resolveReference(docRef); 1920 checkPermission(folder, READ_CHILDREN); 1921 Collection<Document> children = getSession().getProxies(doc, folder); 1922 if (children.isEmpty()) { 1923 return null; 1924 } 1925 List<String> versions = new ArrayList<>(); 1926 for (Document child : children) { 1927 if (hasPermission(child, READ)) { 1928 Document target = child.getTargetDocument(); 1929 if (target.isVersion()) { 1930 versions.add(target.getVersionLabel()); 1931 } else { 1932 // live proxy 1933 versions.add(""); 1934 } 1935 } 1936 } 1937 return versions.toArray(new String[versions.size()]); 1938 } 1939 1940 @Override 1941 public List<String> getAvailableSecurityPermissions() { 1942 // XXX: add security check? 1943 return Arrays.asList(getSecurityService().getPermissionProvider().getPermissions()); 1944 } 1945 1946 @Override 1947 public DataModel getDataModel(DocumentRef docRef, Schema schema) { 1948 Document doc = resolveReference(docRef); 1949 checkPermission(doc, READ); 1950 return DocumentModelFactory.createDataModel(doc, schema); 1951 } 1952 1953 protected Object getDataModelField(DocumentRef docRef, String schema, String field) { 1954 Document doc = resolveReference(docRef); 1955 if (doc != null) { 1956 checkPermission(doc, READ); 1957 Schema docSchema = doc.getType().getSchema(schema); 1958 if (docSchema != null) { 1959 String prefix = docSchema.getNamespace().prefix; 1960 if (prefix != null && prefix.length() > 0) { 1961 field = prefix + ':' + field; 1962 } 1963 return doc.getPropertyValue(field); 1964 } else { 1965 log.warn("Cannot find schema with name=" + schema); 1966 } 1967 } else { 1968 log.warn("Cannot resolve docRef=" + docRef); 1969 } 1970 return null; 1971 } 1972 1973 @Override 1974 public String getCurrentLifeCycleState(DocumentRef docRef) { 1975 Document doc = resolveReference(docRef); 1976 checkPermission(doc, READ_LIFE_CYCLE); 1977 return doc.getLifeCycleState(); 1978 } 1979 1980 @Override 1981 public String getLifeCyclePolicy(DocumentRef docRef) { 1982 Document doc = resolveReference(docRef); 1983 checkPermission(doc, READ_LIFE_CYCLE); 1984 return doc.getLifeCyclePolicy(); 1985 } 1986 1987 /** 1988 * Make a document follow a transition. 1989 * 1990 * @param docRef a {@link DocumentRef} 1991 * @param transition the transition to follow 1992 * @param options an option map than can be used by callers to pass additional params 1993 * @since 5.9.3 1994 */ 1995 private boolean followTransition(DocumentRef docRef, String transition, ScopedMap options) 1996 throws LifeCycleException { 1997 Document doc = resolveReference(docRef); 1998 checkPermission(doc, WRITE_LIFE_CYCLE); 1999 2000 if (!doc.isVersion() && !doc.isProxy() && !doc.isCheckedOut()) { 2001 boolean deleteOrUndelete = LifeCycleConstants.DELETE_TRANSITION.equals(transition) 2002 || LifeCycleConstants.UNDELETE_TRANSITION.equals(transition); 2003 if (!deleteOrUndelete || Framework.getService(ConfigurationService.class).isBooleanPropertyFalse( 2004 TRASH_KEEP_CHECKED_IN_PROPERTY)) { 2005 checkOut(docRef); 2006 doc = resolveReference(docRef); 2007 } 2008 } 2009 String formerStateName = doc.getLifeCycleState(); 2010 doc.followTransition(transition); 2011 2012 // Construct a map holding meta information about the event. 2013 Map<String, Serializable> eventOptions = new HashMap<>(); 2014 eventOptions.put(org.nuxeo.ecm.core.api.LifeCycleConstants.TRANSTION_EVENT_OPTION_FROM, formerStateName); 2015 eventOptions.put(org.nuxeo.ecm.core.api.LifeCycleConstants.TRANSTION_EVENT_OPTION_TO, doc.getLifeCycleState()); 2016 eventOptions.put(org.nuxeo.ecm.core.api.LifeCycleConstants.TRANSTION_EVENT_OPTION_TRANSITION, transition); 2017 String comment = (String) options.getScopedValue("comment"); 2018 DocumentModel docModel = readModel(doc); 2019 notifyEvent(org.nuxeo.ecm.core.api.LifeCycleConstants.TRANSITION_EVENT, docModel, eventOptions, 2020 DocumentEventCategories.EVENT_LIFE_CYCLE_CATEGORY, comment, true, false); 2021 if (!docModel.isImmutable()) { 2022 writeModel(doc, docModel); 2023 } 2024 return true; // throws if error 2025 } 2026 2027 @Override 2028 public boolean followTransition(DocumentModel docModel, String transition) throws LifeCycleException { 2029 return followTransition(docModel.getRef(), transition, docModel.getContextData()); 2030 } 2031 2032 @Override 2033 public boolean followTransition(DocumentRef docRef, String transition) throws LifeCycleException { 2034 return followTransition(docRef, transition, new ScopedMap()); 2035 } 2036 2037 @Override 2038 public Collection<String> getAllowedStateTransitions(DocumentRef docRef) { 2039 Document doc = resolveReference(docRef); 2040 checkPermission(doc, READ_LIFE_CYCLE); 2041 return doc.getAllowedStateTransitions(); 2042 } 2043 2044 @Override 2045 public void reinitLifeCycleState(DocumentRef docRef) { 2046 Document doc = resolveReference(docRef); 2047 checkPermission(doc, WRITE_LIFE_CYCLE); 2048 LifeCycleService service = NXCore.getLifeCycleService(); 2049 service.reinitLifeCycle(doc); 2050 } 2051 2052 @Override 2053 public Object[] getDataModelsField(DocumentRef[] docRefs, String schema, String field) { 2054 2055 assert docRefs != null; 2056 assert schema != null; 2057 assert field != null; 2058 2059 final Object[] values = new Object[docRefs.length]; 2060 int i = 0; 2061 for (DocumentRef docRef : docRefs) { 2062 final Object value = getDataModelField(docRef, schema, field); 2063 values[i++] = value; 2064 } 2065 2066 return values; 2067 } 2068 2069 @Override 2070 public DocumentRef[] getParentDocumentRefs(DocumentRef docRef) { 2071 final List<DocumentRef> docRefs = new ArrayList<>(); 2072 final Document doc = resolveReference(docRef); 2073 Document parentDoc = doc.getParent(); 2074 while (parentDoc != null) { 2075 final DocumentRef parentDocRef = new IdRef(parentDoc.getUUID()); 2076 docRefs.add(parentDocRef); 2077 parentDoc = parentDoc.getParent(); 2078 } 2079 DocumentRef[] refs = new DocumentRef[docRefs.size()]; 2080 return docRefs.toArray(refs); 2081 } 2082 2083 @Override 2084 public Object[] getDataModelsFieldUp(DocumentRef docRef, String schema, String field) { 2085 2086 final DocumentRef[] parentRefs = getParentDocumentRefs(docRef); 2087 final DocumentRef[] allRefs = new DocumentRef[parentRefs.length + 1]; 2088 allRefs[0] = docRef; 2089 System.arraycopy(parentRefs, 0, allRefs, 1, parentRefs.length); 2090 2091 return getDataModelsField(allRefs, schema, field); 2092 } 2093 2094 protected String oldLockKey(Lock lock) { 2095 if (lock == null) { 2096 return null; 2097 } 2098 // return deprecated format, like "someuser:Nov 29, 2010" 2099 String lockCreationDate = (lock.getCreated() == null) ? null : DateFormat.getDateInstance(DateFormat.MEDIUM) 2100 .format(new Date( 2101 lock.getCreated() 2102 .getTimeInMillis())); 2103 return lock.getOwner() + ':' + lockCreationDate; 2104 } 2105 2106 @Override 2107 @Deprecated 2108 public String getLock(DocumentRef docRef) { 2109 Lock lock = getLockInfo(docRef); 2110 return oldLockKey(lock); 2111 } 2112 2113 @Override 2114 @Deprecated 2115 public void setLock(DocumentRef docRef, String key) { 2116 setLock(docRef); 2117 } 2118 2119 @Override 2120 @Deprecated 2121 public String unlock(DocumentRef docRef) { 2122 Lock lock = removeLock(docRef); 2123 return oldLockKey(lock); 2124 } 2125 2126 @Override 2127 public Lock setLock(DocumentRef docRef) throws LockException { 2128 Document doc = resolveReference(docRef); 2129 // TODO: add a new permission named LOCK and use it instead of 2130 // WRITE_PROPERTIES 2131 checkPermission(doc, WRITE_PROPERTIES); 2132 Lock lock = new Lock(getPrincipal().getName(), new GregorianCalendar()); 2133 Lock oldLock = doc.setLock(lock); 2134 if (oldLock != null) { 2135 throw new LockException("Document already locked by " + oldLock.getOwner() + ": " + docRef); 2136 } 2137 DocumentModel docModel = readModel(doc); 2138 Map<String, Serializable> options = new HashMap<>(); 2139 options.put("lock", lock); 2140 notifyEvent(DocumentEventTypes.DOCUMENT_LOCKED, docModel, options, null, null, true, false); 2141 return lock; 2142 } 2143 2144 @Override 2145 public Lock getLockInfo(DocumentRef docRef) { 2146 Document doc = resolveReference(docRef); 2147 checkPermission(doc, READ); 2148 return doc.getLock(); 2149 } 2150 2151 @Override 2152 public Lock removeLock(DocumentRef docRef) throws LockException { 2153 Document doc = resolveReference(docRef); 2154 String owner; 2155 if (hasPermission(docRef, UNLOCK)) { 2156 // always unlock 2157 owner = null; 2158 } else { 2159 owner = getPrincipal().getName(); 2160 } 2161 Lock lock = doc.removeLock(owner); 2162 if (lock == null) { 2163 // there was no lock, we're done 2164 return null; 2165 } 2166 if (lock.getFailed()) { 2167 // lock removal failed due to owner check 2168 throw new LockException("Document already locked by " + lock.getOwner() + ": " + docRef); 2169 } 2170 DocumentModel docModel = readModel(doc); 2171 Map<String, Serializable> options = new HashMap<>(); 2172 options.put("lock", lock); 2173 notifyEvent(DocumentEventTypes.DOCUMENT_UNLOCKED, docModel, options, null, null, true, false); 2174 return lock; 2175 } 2176 2177 protected boolean isAdministrator() { 2178 Principal principal = getPrincipal(); 2179 // FIXME: this is inconsistent with NuxeoPrincipal#isAdministrator 2180 // method because it allows hardcoded Administrator user 2181 if (Framework.isTestModeSet()) { 2182 if (SecurityConstants.ADMINISTRATOR.equals(principal.getName())) { 2183 return true; 2184 } 2185 } 2186 if (SYSTEM_USERNAME.equals(principal.getName())) { 2187 return true; 2188 } 2189 if (principal instanceof NuxeoPrincipal) { 2190 return ((NuxeoPrincipal) principal).isAdministrator(); 2191 } 2192 return false; 2193 } 2194 2195 @Override 2196 public void applyDefaultPermissions(String userOrGroupName) { 2197 if (userOrGroupName == null) { 2198 throw new NullPointerException("null userOrGroupName"); 2199 } 2200 if (!isAdministrator()) { 2201 throw new DocumentSecurityException("You need to be an Administrator to do this."); 2202 } 2203 DocumentModel rootDocument = getRootDocument(); 2204 ACP acp = new ACPImpl(); 2205 2206 UserEntry userEntry = new UserEntryImpl(userOrGroupName); 2207 userEntry.addPrivilege(READ); 2208 2209 acp.setRules(new UserEntry[] { userEntry }); 2210 2211 setACP(rootDocument.getRef(), acp, false); 2212 } 2213 2214 @Override 2215 public DocumentModel publishDocument(DocumentModel docToPublish, DocumentModel section) { 2216 return publishDocument(docToPublish, section, true); 2217 } 2218 2219 @Override 2220 public DocumentModel publishDocument(DocumentModel docModel, DocumentModel section, boolean overwriteExistingProxy) { 2221 Document doc = resolveReference(docModel.getRef()); 2222 Document sec = resolveReference(section.getRef()); 2223 checkPermission(doc, READ); 2224 checkPermission(sec, ADD_CHILDREN); 2225 2226 Map<String, Serializable> options = new HashMap<>(); 2227 DocumentModel proxy = null; 2228 Document target; 2229 if (docModel.isProxy() || docModel.isVersion()) { 2230 target = doc; 2231 if (overwriteExistingProxy) { 2232 if (docModel.isVersion()) { 2233 Document base = resolveReference(new IdRef(doc.getVersionSeriesId())); 2234 proxy = updateExistingProxies(base, sec, target); 2235 } 2236 if (proxy == null) { 2237 // remove previous 2238 List<String> removedProxyIds = removeExistingProxies(doc, sec); 2239 options.put(CoreEventConstants.REPLACED_PROXY_IDS, (Serializable) removedProxyIds); 2240 } 2241 } 2242 2243 } else { 2244 String checkinComment = (String) docModel.getContextData(VersioningService.CHECKIN_COMMENT); 2245 docModel.putContextData(VersioningService.CHECKIN_COMMENT, null); 2246 if (doc.isCheckedOut() || doc.getLastVersion() == null) { 2247 if (!doc.isCheckedOut()) { 2248 // last version was deleted while leaving a checked in 2249 // doc. recreate a version 2250 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKOUT, docModel, options, null, null, true, true); 2251 getVersioningService().doCheckOut(doc); 2252 docModel = readModel(doc); 2253 notifyEvent(DocumentEventTypes.DOCUMENT_CHECKEDOUT, docModel, options, null, null, true, false); 2254 } 2255 notifyEvent(DocumentEventTypes.ABOUT_TO_CHECKIN, docModel, options, null, null, true, true); 2256 Document version = getVersioningService().doCheckIn(doc, null, checkinComment); 2257 docModel.refresh(DocumentModel.REFRESH_STATE | DocumentModel.REFRESH_CONTENT_LAZY, null); 2258 notifyCheckedInVersion(docModel, new IdRef(version.getUUID()), null, checkinComment); 2259 } 2260 // NXP-12921: use base version because we could need to publish 2261 // a previous version (after restoring for example) 2262 target = doc.getBaseVersion(); 2263 if (overwriteExistingProxy) { 2264 proxy = updateExistingProxies(doc, sec, target); 2265 if (proxy == null) { 2266 // no or several proxies, remove them 2267 List<String> removedProxyIds = removeExistingProxies(doc, sec); 2268 options.put(CoreEventConstants.REPLACED_PROXY_IDS, (Serializable) removedProxyIds); 2269 } else { 2270 // notify proxy updates 2271 notifyEvent(DocumentEventTypes.DOCUMENT_PROXY_UPDATED, proxy, options, null, null, true, false); 2272 notifyEvent(DocumentEventTypes.DOCUMENT_PROXY_PUBLISHED, proxy, options, null, null, true, false); 2273 notifyEvent(DocumentEventTypes.SECTION_CONTENT_PUBLISHED, section, options, null, null, true, false); 2274 } 2275 } 2276 } 2277 if (proxy == null) { 2278 proxy = createProxyInternal(target, sec, options); 2279 } 2280 return proxy; 2281 } 2282 2283 @Override 2284 public String getSuperParentType(DocumentModel doc) { 2285 DocumentModel superSpace = getSuperSpace(doc); 2286 if (superSpace == null) { 2287 return null; 2288 } else { 2289 return superSpace.getType(); 2290 } 2291 } 2292 2293 @Override 2294 public DocumentModel getSuperSpace(DocumentModel doc) { 2295 if (doc == null) { 2296 throw new IllegalArgumentException("null document"); 2297 } 2298 if (doc.hasFacet(FacetNames.SUPER_SPACE)) { 2299 return doc; 2300 } else { 2301 2302 DocumentModel parent = getDirectAccessibleParent(doc.getRef()); 2303 if (parent == null || "/".equals(parent.getPathAsString())) { 2304 // return Root instead of null 2305 return getRootDocument(); 2306 } else { 2307 return getSuperSpace(parent); 2308 } 2309 } 2310 } 2311 2312 // walk the tree up until a accessible doc is found 2313 private DocumentModel getDirectAccessibleParent(DocumentRef docRef) { 2314 Document doc = resolveReference(docRef); 2315 Document parentDoc = doc.getParent(); 2316 if (parentDoc == null) { 2317 // return null for placeless document 2318 return null; 2319 } 2320 if (!hasPermission(parentDoc, READ)) { 2321 String parentPath = parentDoc.getPath(); 2322 if ("/".equals(parentPath)) { 2323 return getRootDocument(); 2324 } else { 2325 // try on parent 2326 return getDirectAccessibleParent(new PathRef(parentDoc.getPath())); 2327 } 2328 } 2329 return readModel(parentDoc); 2330 } 2331 2332 @Override 2333 public <T extends Serializable> T getDocumentSystemProp(DocumentRef ref, String systemProperty, Class<T> type) { 2334 Document doc = resolveReference(ref); 2335 return doc.getSystemProp(systemProperty, type); 2336 } 2337 2338 @Override 2339 public <T extends Serializable> void setDocumentSystemProp(DocumentRef ref, String systemProperty, T value) { 2340 Document doc = resolveReference(ref); 2341 if (systemProperty != null && systemProperty.startsWith(BINARY_TEXT_SYS_PROP)) { 2342 DocumentModel docModel = readModel(doc); 2343 Map<String, Serializable> options = new HashMap<>(); 2344 options.put(systemProperty, value != null); 2345 notifyEvent(DocumentEventTypes.BINARYTEXT_UPDATED, docModel, options, null, null, false, true); 2346 } 2347 doc.setSystemProp(systemProperty, value); 2348 } 2349 2350 @Override 2351 public void orderBefore(DocumentRef parent, String src, String dest) { 2352 if ((src == null) || (src.equals(dest))) { 2353 return; 2354 } 2355 Document doc = resolveReference(parent); 2356 doc.orderBefore(src, dest); 2357 Map<String, Serializable> options = new HashMap<>(); 2358 2359 // send event on container passing the reordered child as parameter 2360 DocumentModel docModel = readModel(doc); 2361 String comment = src; 2362 options.put(CoreEventConstants.REORDERED_CHILD, src); 2363 notifyEvent(DocumentEventTypes.DOCUMENT_CHILDREN_ORDER_CHANGED, docModel, options, null, comment, true, false); 2364 } 2365 2366 @Override 2367 public DocumentModelRefresh refreshDocument(DocumentRef ref, int refreshFlags, String[] schemas) { 2368 Document doc = resolveReference(ref); 2369 2370 // permission checks 2371 if ((refreshFlags & (DocumentModel.REFRESH_PREFETCH | DocumentModel.REFRESH_STATE | DocumentModel.REFRESH_CONTENT)) != 0) { 2372 checkPermission(doc, READ); 2373 } 2374 if ((refreshFlags & DocumentModel.REFRESH_ACP) != 0) { 2375 checkPermission(doc, READ_SECURITY); 2376 } 2377 2378 DocumentModelRefresh refresh = DocumentModelFactory.refreshDocumentModel(doc, refreshFlags, schemas); 2379 2380 // ACPs need the session, so aren't done in the factory method 2381 if ((refreshFlags & DocumentModel.REFRESH_ACP) != 0) { 2382 refresh.acp = getSession().getMergedACP(doc); 2383 } 2384 2385 return refresh; 2386 } 2387 2388 @Override 2389 public String[] getPermissionsToCheck(String permission) { 2390 return getSecurityService().getPermissionsToCheck(permission); 2391 } 2392 2393 @Override 2394 public <T extends DetachedAdapter> T adaptFirstMatchingDocumentWithFacet(DocumentRef docRef, String facet, 2395 Class<T> adapterClass) { 2396 Document doc = getFirstParentDocumentWithFacet(docRef, facet); 2397 if (doc != null) { 2398 DocumentModel docModel = readModel(doc); 2399 loadDataModelsForFacet(docModel, doc, facet); 2400 docModel.detach(false); 2401 return docModel.getAdapter(adapterClass); 2402 } 2403 return null; 2404 } 2405 2406 protected void loadDataModelsForFacet(DocumentModel docModel, Document doc, String facetName) { 2407 // Load all the data related to facet's schemas 2408 SchemaManager schemaManager = Framework.getLocalService(SchemaManager.class); 2409 CompositeType facet = schemaManager.getFacet(facetName); 2410 if (facet == null) { 2411 return; 2412 } 2413 2414 String[] facetSchemas = facet.getSchemaNames(); 2415 for (String schema : facetSchemas) { 2416 DataModel dm = DocumentModelFactory.createDataModel(doc, schemaManager.getSchema(schema)); 2417 docModel.getDataModels().put(schema, dm); 2418 } 2419 } 2420 2421 /** 2422 * Returns the first {@code Document} with the given {@code facet}, recursively going up the parent hierarchy. 2423 * Returns {@code null} if there is no more parent. 2424 * <p> 2425 * This method does not check security rights. 2426 */ 2427 protected Document getFirstParentDocumentWithFacet(DocumentRef docRef, String facet) { 2428 Document doc = resolveReference(docRef); 2429 while (doc != null && !doc.hasFacet(facet)) { 2430 doc = doc.getParent(); 2431 } 2432 return doc; 2433 } 2434 2435 @Override 2436 public Map<String, String> getBinaryFulltext(DocumentRef ref) { 2437 Document doc = resolveReference(ref); 2438 checkPermission(doc, READ); 2439 return getSession().getBinaryFulltext(doc.getUUID()); 2440 } 2441 2442}