@Override
  public EntityReference getDefaultReference(EntityType type) {
    EntityReference result = null;

    XWikiContext xcontext = this.xcontextProvider.get();
    if (xcontext != null) {
      if (type == EntityType.WIKI) {
        result = xcontext.getWikiReference();
      } else if (type == EntityType.SPACE) {
        XWikiDocument currentDoc = xcontext.getDoc();
        if (currentDoc != null) {
          SpaceReference spaceReference = currentDoc.getDocumentReference().getLastSpaceReference();
          // Keep only the spaces part
          result = spaceReference.removeParent(spaceReference.getWikiReference());
        }
      } else if (type == EntityType.DOCUMENT) {
        XWikiDocument currentDoc = xcontext.getDoc();
        if (currentDoc != null) {
          DocumentReference documentReference = currentDoc.getDocumentReference();
          // Keep only the document part
          result = documentReference.removeParent(documentReference.getLastSpaceReference());
        }
      }
    }

    if (result == null) {
      result = super.getDefaultReference(type);
    }

    return result;
  }
  /**
   * Verify that {@link XWiki#rollback(XWikiDocument, String, XWikiContext)} fires the right events.
   */
  @Test
  public void rollbackFiresEvents() throws Exception {
    ObservationManager observationManager = mocker.getInstance(ObservationManager.class);

    DocumentReference documentReference = new DocumentReference("wiki", "Space", "Page");
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.getDocumentReference()).thenReturn(documentReference);

    XWikiDocument originalDocument = mock(XWikiDocument.class);
    // Mark the document as existing so that the roll-back method will fire an update event.
    when(originalDocument.isNew()).thenReturn(false);

    XWikiDocument result = mock(XWikiDocument.class);
    when(result.clone()).thenReturn(result);
    when(result.getDocumentReference()).thenReturn(documentReference);
    when(result.getOriginalDocument()).thenReturn(originalDocument);

    String revision = "3.5";
    when(xwiki.getVersioningStore().loadXWikiDoc(document, revision, context)).thenReturn(result);

    this.mocker.registerMockComponent(ContextualLocalizationManager.class);

    xwiki.rollback(document, revision, context);

    verify(observationManager)
        .notify(new DocumentRollingBackEvent(documentReference, revision), result, context);
    verify(observationManager)
        .notify(new DocumentUpdatingEvent(documentReference), result, context);
    verify(observationManager).notify(new DocumentUpdatedEvent(documentReference), result, context);
    verify(observationManager)
        .notify(new DocumentRolledBackEvent(documentReference, revision), result, context);
  }
  @Before
  public void setUp_AbstractDocumentUpdateListenerTest() throws Exception {
    context = getContext();
    classRef = new DocumentReference("wiki", "Classes", "SomeClass");
    fields = Arrays.asList("field1", "field2");
    docRef = new DocumentReference("wiki", "Space", "SomeDoc");
    docMock = createMockAndAddToDefault(XWikiDocument.class);
    expect(docMock.getDocumentReference()).andReturn(docRef).anyTimes();
    origDocMock = createMockAndAddToDefault(XWikiDocument.class);
    expect(origDocMock.getDocumentReference()).andReturn(docRef).anyTimes();
    expect(docMock.getOriginalDocument()).andReturn(origDocMock).anyTimes();

    listener = new TestDocumentUpdateListener();
    listener.injectWebUtilsService(Utils.getComponent(IWebUtilsService.class));
    listener.injecExecution(Utils.getComponent(Execution.class));
    listener.injectCopyDocService(Utils.getComponent(ICopyDocumentRole.class));
    listener.injectRemoteObservationManagerContext(
        remoteObsManContextMock = createMockAndAddToDefault(RemoteObservationManagerContext.class));
    listener.injectObservationManager(
        obsManagerMock = createMockAndAddToDefault(ObservationManager.class));
    listener.configSrc = Utils.getComponent(ConfigurationSource.class);

    creatingEventMock = createMockAndAddToDefault(Event.class);
    createdEventMock = createMockAndAddToDefault(Event.class);
    updatingEventMock = createMockAndAddToDefault(Event.class);
    updatedEventMock = createMockAndAddToDefault(Event.class);
    deletingEventMock = createMockAndAddToDefault(Event.class);
    deletedEventMock = createMockAndAddToDefault(Event.class);
  }
  @Test
  public void getMembersWhenGroupIsLooping() throws Exception {
    setUpBaseMocks();

    DocumentReference groupReference = new DocumentReference("groupwiki", "XWiki", "grouppage");
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(groupReference);
    when(xwiki.getDocument(groupReference, this.xwikiContext)).thenReturn(document);

    List<BaseObject> memberObjects = new ArrayList<>();
    BaseObject bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.othergroup");
    memberObjects.add(bo);
    bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.userpage");
    memberObjects.add(bo);
    when(document.getXObjects(new DocumentReference("groupwiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);

    DocumentReference userpageReference = new DocumentReference("groupwiki", "XWiki", "userpage");
    setUpUserPageMocks(userpageReference);
    when(this.resolver.resolve("XWiki.userpage", groupReference)).thenReturn(userpageReference);

    DocumentReference otherGroupReference =
        new DocumentReference("groupwiki", "XWiki", "othergroup");
    document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(otherGroupReference);
    when(xwiki.getDocument(otherGroupReference, this.xwikiContext)).thenReturn(document);

    memberObjects = new ArrayList<>();
    bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.grouppage");
    memberObjects.add(bo);
    bo = mock(BaseObject.class);
    when(bo.getStringValue("member")).thenReturn("XWiki.anotheruser");
    memberObjects.add(bo);
    when(document.getXObjects(new DocumentReference("groupwiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);

    DocumentReference anotheruserReference =
        new DocumentReference("groupwiki", "XWiki", "anotheruser");
    setUpUserPageMocks(anotheruserReference);
    when(this.resolver.resolve("XWiki.anotheruser", otherGroupReference))
        .thenReturn(anotheruserReference);

    when(this.resolver.resolve("XWiki.grouppage", otherGroupReference)).thenReturn(groupReference);
    when(this.resolver.resolve("XWiki.othergroup", groupReference)).thenReturn(otherGroupReference);

    Iterator<DocumentReference> iterator =
        new ReferenceUserIterator(groupReference, this.resolver, this.execution);

    assertThat(
        (List<DocumentReference>) IteratorUtils.toList(iterator),
        containsInAnyOrder(userpageReference, anotheruserReference));
  }
Example #5
0
  /**
   * Load document files from provided directory and sub-directories into packager.
   *
   * @param dir the directory from where to load documents.
   * @param context the XWiki context.
   * @param description the package descriptor.
   * @return the number of loaded documents.
   * @throws IOException error when loading documents.
   * @throws XWikiException error when loading documents.
   */
  public int readFromDir(File dir, XWikiContext context, Document description)
      throws IOException, XWikiException {
    File[] files = dir.listFiles();

    SAXReader reader = new SAXReader();

    int count = 0;
    for (int i = 0; i < files.length; ++i) {
      File file = files[i];

      if (file.isDirectory()) {
        count += readFromDir(file, context, description);
      } else {
        boolean validWikiDoc = false;
        Document domdoc = null;

        try {
          domdoc = reader.read(new FileInputStream(file));
          validWikiDoc = XWikiDocument.containsXMLWikiDocument(domdoc);
        } catch (DocumentException e1) {
        }

        if (validWikiDoc) {
          XWikiDocument doc = readFromXML(domdoc);

          try {
            filter(doc, context);

            if (documentExistInPackageFile(doc.getFullName(), doc.getLanguage(), description)) {
              add(doc, context);

              ++count;
            } else {
              throw new PackageException(
                  XWikiException.ERROR_XWIKI_UNKNOWN,
                  "document "
                      + doc.getDocumentReference()
                      + " does not exist in package definition");
            }
          } catch (ExcludeDocumentException e) {
            LOGGER.info("Skip the document '" + doc.getDocumentReference() + "'");
          }
        } else if (!file.getName().equals(DefaultPackageFileName)) {
          LOGGER.info(file.getAbsolutePath() + " is not a valid wiki document");
        }
      }
    }

    return count;
  }
  private Map<AccessLevel, List<DocumentReference>> getCollaborators(XWikiDocument doc) {
    Map<AccessLevel, List<DocumentReference>> collaborators =
        new LinkedHashMap<AccessLevel, List<DocumentReference>>();
    List<BaseObject> collaboratorObjects = doc.getXObjects(Collaborator.CLASS_REFERENCE);
    if (collaboratorObjects == null || collaboratorObjects.isEmpty()) {
      return Collections.emptyMap();
    }
    for (BaseObject collaborator : collaboratorObjects) {
      if (collaborator == null) {
        continue;
      }
      String collaboratorName = collaborator.getStringValue("collaborator");
      String accessName = collaborator.getStringValue("access");

      if (StringUtils.isBlank(collaboratorName) || StringUtils.isBlank(accessName)) {
        continue;
      }
      DocumentReference userOrGroup =
          this.stringEntityResolver.resolve(collaboratorName, doc.getDocumentReference());
      AccessLevel access = this.manager.resolveAccessLevel(accessName);
      List<DocumentReference> list = collaborators.get(access);
      if (list == null) {
        list = new LinkedList<DocumentReference>();
        collaborators.put(access, list);
      }
      list.add(userOrGroup);
    }
    return collaborators;
  }
Example #7
0
 /**
  * Generate a relative path based on provided document for the directory where the document should
  * be stored.
  *
  * @param doc the document to export
  * @return the corresponding path
  */
 public String getDirectoryForDocument(XWikiDocument doc) {
   StringBuilder path = new StringBuilder();
   for (SpaceReference space : doc.getDocumentReference().getSpaceReferences()) {
     path.append(space.getName()).append('/');
   }
   return path.toString();
 }
  private void addWikiTranslation(String key, String message, Locale locale) throws XWikiException {
    XWikiDocument document =
        this.oldcore
            .getMockXWiki()
            .getDocument(this.defaultWikiTranslationReference, this.oldcore.getXWikiContext());

    if (!locale.equals(Locale.ROOT)) {
      XWikiDocument translatedDocument =
          document.getTranslatedDocument(locale, this.oldcore.getXWikiContext());
      if (translatedDocument == document) {
        translatedDocument = new XWikiDocument(document.getDocumentReference(), locale);
        translatedDocument.setDefaultLocale(document.getDefaultLocale());
      }
      document = translatedDocument;
    }

    document.setSyntax(Syntax.PLAIN_1_0);

    StringBuilder builder = new StringBuilder(document.getContent());

    builder.append('\n');
    builder.append(key);
    builder.append('=');
    builder.append(message);

    document.setContent(builder.toString());

    this.oldcore.getMockXWiki().saveDocument(document, "", this.oldcore.getXWikiContext());

    setBundles(document.getFullName());
  }
  @Test
  public void getMembersWhenSingleUserButBothUserAndGroupReference() throws Exception {
    setUpBaseMocks();
    DocumentReference reference = new DocumentReference("wiki", "XWiki", "page");

    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(reference);
    when(this.xwiki.getDocument(reference, this.xwikiContext)).thenReturn(document);

    // It's a user reference
    BaseObject bo1 = mock(BaseObject.class);
    when(document.getXObject(new DocumentReference("wiki", "XWiki", "XWikiUsers"))).thenReturn(bo1);

    // It's also a group reference (with one user in it)
    List<BaseObject> memberObjects = new ArrayList<>();
    BaseObject bo2 = mock(BaseObject.class);
    when(bo2.getStringValue("member")).thenReturn("XWiki.user");
    memberObjects.add(bo2);
    when(document.getXObjects(new DocumentReference("wiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);
    DocumentReference userReference = new DocumentReference("wiki", "XWiki", "user");
    when(this.resolver.resolve("XWiki.user", reference)).thenReturn(userReference);
    setUpUserPageMocks(userReference);

    Iterator<DocumentReference> iterator =
        new ReferenceUserIterator(reference, this.resolver, this.execution);

    assertTrue(iterator.hasNext());
    assertEquals(new DocumentReference("wiki", "XWiki", "page"), iterator.next());
    assertTrue(iterator.hasNext());
    assertEquals(new DocumentReference("wiki", "XWiki", "user"), iterator.next());
    assertFalse(iterator.hasNext());
  }
  @Test
  public void deleteAllDocumentsAndWithoutSendingToTrash() throws Exception {
    XWiki xwiki = new XWiki();

    XWikiDocument document = mock(XWikiDocument.class);
    DocumentReference reference = new DocumentReference("wiki", "space", "page");
    when(document.getDocumentReference()).thenReturn(reference);

    // Make sure we have a trash for the test.
    XWikiRecycleBinStoreInterface recycleBinStoreInterface =
        mock(XWikiRecycleBinStoreInterface.class);
    xwiki.setRecycleBinStore(recycleBinStoreInterface);
    when(xwikiCfgConfigurationSource.getProperty("xwiki.recyclebin", "1")).thenReturn("1");

    // Configure the mocked Store to later verify if it's called
    XWikiStoreInterface storeInterface = mock(XWikiStoreInterface.class);
    xwiki.setStore(storeInterface);
    XWikiContext xwikiContext = mock(XWikiContext.class);

    xwiki.deleteAllDocuments(document, false, xwikiContext);

    // Verify that saveToRecycleBin is never called since otherwise it would mean the doc has been
    // saved in the
    // trash
    verify(recycleBinStoreInterface, never())
        .saveToRecycleBin(
            any(XWikiDocument.class),
            any(String.class),
            any(Date.class),
            any(XWikiContext.class),
            any(Boolean.class));

    // Verify that deleteXWikiDoc() is called
    verify(storeInterface).deleteXWikiDoc(document, xwikiContext);
  }
  @Test
  public void onEventWithExceptions() throws ComponentLookupException, XWikiException {
    Utils.setComponentManager(this.mocker);

    DocumentReference docReference = new DocumentReference("xwiki", "Groups", "Group1");
    XWikiContext context = mock(XWikiContext.class);
    XWiki xwiki = mock(XWiki.class);
    when(context.getWiki()).thenReturn(xwiki);

    XWikiDocument doc = mock(XWikiDocument.class);
    when(doc.getDocumentReference()).thenReturn(docReference);
    when(doc.getXObject(Group.CLASS_REFERENCE)).thenReturn(mock(BaseObject.class));

    DocumentReference adminsDocReference =
        new DocumentReference("xwiki", "Groups", "Group1 Administrators");
    when(xwiki.getDocument(eq(adminsDocReference), eq(context)))
        .thenThrow(new XWikiException(0, 0, "DB Error"));

    DocumentAccessBridge dab = this.mocker.getInstance(DocumentAccessBridge.class);

    DocumentReference userReference = new DocumentReference("xwiki", "XWiki", "User");
    when(dab.getCurrentUserReference()).thenReturn(userReference);

    this.mocker
        .getComponentUnderTest()
        .onEvent(new DocumentCreatingEvent(docReference), doc, context);

    Mockito.verify(xwiki, Mockito.never())
        .saveDocument(eq(doc), any(String.class), any(Boolean.class), eq(context));

    Mockito.verify(doc).getXObject(Group.CLASS_REFERENCE);
    Mockito.verify(doc).getDocumentReference();
    Mockito.verifyNoMoreInteractions(doc);
  }
  /**
   * @see "XWIKI-9399: Attachment version is incremented when a document is rolled back even if the
   *     attachment did not change"
   */
  @Test
  public void rollbackDoesNotSaveUnchangedAttachment() throws Exception {
    String version = "1.1";
    String fileName = "logo.png";
    Date date = new Date();
    XWikiAttachment currentAttachment = mock(XWikiAttachment.class);
    when(currentAttachment.getAttachmentRevision(version, context)).thenReturn(currentAttachment);
    when(currentAttachment.getDate()).thenReturn(new Timestamp(date.getTime()));
    when(currentAttachment.getVersion()).thenReturn(version);
    when(currentAttachment.getFilename()).thenReturn(fileName);

    XWikiAttachment oldAttachment = mock(XWikiAttachment.class);
    when(oldAttachment.getFilename()).thenReturn(fileName);
    when(oldAttachment.getVersion()).thenReturn(version);
    when(oldAttachment.getDate()).thenReturn(date);

    DocumentReference documentReference = new DocumentReference("wiki", "Space", "Page");
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.getDocumentReference()).thenReturn(documentReference);
    when(document.getAttachmentList()).thenReturn(Arrays.asList(currentAttachment));
    when(document.getAttachment(fileName)).thenReturn(currentAttachment);

    XWikiDocument result = mock(XWikiDocument.class);
    when(result.clone()).thenReturn(result);
    when(result.getDocumentReference()).thenReturn(documentReference);
    when(result.getAttachmentList()).thenReturn(Arrays.asList(oldAttachment));
    when(result.getAttachment(fileName)).thenReturn(oldAttachment);

    String revision = "3.5";
    when(xwiki.getVersioningStore().loadXWikiDoc(document, revision, context)).thenReturn(result);

    AttachmentRecycleBinStore attachmentRecycleBinStore = mock(AttachmentRecycleBinStore.class);
    xwiki.setAttachmentRecycleBinStore(attachmentRecycleBinStore);

    DocumentReference reference = document.getDocumentReference();
    this.mocker.registerMockComponent(ContextualLocalizationManager.class);
    when(xwiki.getStore().loadXWikiDoc(any(XWikiDocument.class), same(context)))
        .thenReturn(new XWikiDocument(reference));

    xwiki.rollback(document, revision, context);

    verify(attachmentRecycleBinStore, never())
        .saveToRecycleBin(
            same(currentAttachment), any(String.class), any(Date.class), same(context), eq(true));
    verify(oldAttachment, never()).setMetaDataDirty(true);
  }
  @Override
  public boolean checkAccess(String action, XWikiDocument doc, XWikiContext context)
      throws XWikiException {
    DocumentReference userReference = getCurrentUser(context);
    User user =
        this.userManager.getUser(userReference != null ? userReference.toString() : null, true);
    boolean result =
        this.service.hasAccess(user, actionToRight(action), doc.getDocumentReference());
    if (!result && context.getUserReference() == null && !"login".equals(context.getAction())) {
      this.logger.debug(
          "Redirecting unauthenticated user to login, since it have been denied [{}] on [{}].",
          actionToRight(action),
          doc.getDocumentReference());
      context.getWiki().getAuthService().showLogin(context);
    }

    return result;
  }
  @Test
  public void onEvent() throws ComponentLookupException, XWikiException {
    Utils.setComponentManager(this.mocker);

    DocumentReference docReference = new DocumentReference("xwiki", "Groups", "Group1");
    XWikiContext context = mock(XWikiContext.class);
    XWiki xwiki = mock(XWiki.class);
    when(context.getWiki()).thenReturn(xwiki);

    XWikiDocument doc = mock(XWikiDocument.class);
    when(doc.getDocumentReference()).thenReturn(docReference);
    BaseObject groupObject = new BaseObject();
    BaseObject rightsObject = new BaseObject();
    when(doc.newXObject(eq(this.groupsClassReference), eq(context))).thenReturn(groupObject);
    when(doc.newXObject(eq(this.rightsClassReference), eq(context))).thenReturn(rightsObject);
    when(doc.getXObject(Group.CLASS_REFERENCE)).thenReturn(mock(BaseObject.class));

    DocumentReference adminsDocReference =
        new DocumentReference("xwiki", "Groups", "Group1 Administrators");
    XWikiDocument adminsDoc = mock(XWikiDocument.class);
    BaseObject adminsGroupObject = new BaseObject();
    BaseObject adminsRightsObject = new BaseObject();
    when(adminsDoc.newXObject(eq(this.groupsClassReference), eq(context)))
        .thenReturn(adminsGroupObject);
    when(adminsDoc.newXObject(eq(this.rightsClassReference), eq(context)))
        .thenReturn(adminsRightsObject);
    when(xwiki.getDocument(eq(adminsDocReference), eq(context))).thenReturn(adminsDoc);

    DocumentAccessBridge dab = this.mocker.getInstance(DocumentAccessBridge.class);

    DocumentReference userReference = new DocumentReference("xwiki", "XWiki", "User");
    when(dab.getCurrentUserReference()).thenReturn(userReference);

    this.mocker
        .getComponentUnderTest()
        .onEvent(new DocumentCreatingEvent(docReference), doc, context);

    Mockito.verify(xwiki).saveDocument(eq(adminsDoc), any(String.class), eq(true), eq(context));
    Mockito.verify(xwiki, Mockito.never())
        .saveDocument(eq(doc), any(String.class), any(Boolean.class), eq(context));

    Assert.assertEquals(1, rightsObject.getIntValue("allow"));
    Assert.assertEquals("edit", rightsObject.getStringValue("levels"));
    Assert.assertEquals(
        "xwiki:Groups.Group1 Administrators", rightsObject.getLargeStringValue("groups"));
    Assert.assertEquals("", rightsObject.getLargeStringValue("users"));

    Assert.assertEquals(1, adminsRightsObject.getIntValue("allow"));
    Assert.assertEquals("edit", adminsRightsObject.getStringValue("levels"));
    Assert.assertEquals(
        "xwiki:Groups.Group1 Administrators", adminsRightsObject.getLargeStringValue("groups"));
    Assert.assertEquals("", adminsRightsObject.getLargeStringValue("users"));

    Assert.assertEquals("xwiki:Groups.Group1 Administrators", groupObject.getStringValue("member"));
    Assert.assertEquals("xwiki:XWiki.User", adminsGroupObject.getStringValue("member"));
  }
Example #15
0
  /**
   * Add rendered document to ZIP stream.
   *
   * @param pageName the name (used with {@link com.xpn.xwiki.XWiki#getDocument(String,
   *     XWikiContext)}) of the page to render.
   * @param zos the ZIP output stream.
   * @param context the XWiki context.
   * @param vcontext the Velocity context.
   * @throws XWikiException error when rendering document.
   * @throws IOException error when rendering document.
   */
  private void renderDocument(
      String pageName, ZipOutputStream zos, XWikiContext context, VelocityContext vcontext)
      throws XWikiException, IOException {
    @SuppressWarnings("unchecked")
    EntityReferenceResolver<String> resolver = Utils.getComponent(EntityReferenceResolver.class);
    DocumentReference docReference =
        new DocumentReference(resolver.resolve(pageName, EntityType.DOCUMENT));
    XWikiDocument doc = context.getWiki().getDocument(docReference, context);

    String zipname = doc.getDocumentReference().getWikiReference().getName();
    for (EntityReference space : doc.getDocumentReference().getSpaceReferences()) {
      zipname += POINT + space.getName();
    }
    zipname += POINT + doc.getDocumentReference().getName();
    String language = doc.getLanguage();
    if (language != null && language.length() != 0) {
      zipname += POINT + language;
    }

    zipname += ".html";

    ZipEntry zipentry = new ZipEntry(zipname);
    zos.putNextEntry(zipentry);

    String originalDatabase = context.getDatabase();
    try {
      context.setDatabase(doc.getDocumentReference().getWikiReference().getName());
      context.setDoc(doc);
      vcontext.put(VCONTEXT_DOC, doc.newDocument(context));
      vcontext.put(VCONTEXT_CDOC, vcontext.get(VCONTEXT_DOC));

      XWikiDocument tdoc = doc.getTranslatedDocument(context);
      context.put(CONTEXT_TDOC, tdoc);
      vcontext.put(VCONTEXT_TDOC, tdoc.newDocument(context));

      String content = context.getWiki().evaluateTemplate("view.vm", context);

      zos.write(content.getBytes(context.getWiki().getEncoding()));
      zos.closeEntry();
    } finally {
      context.setDatabase(originalDatabase);
    }
  }
Example #16
0
  private String export(String format, XWikiContext context) throws XWikiException, IOException {
    // We currently use the PDF export infrastructure but we have to redesign the export code.
    XWikiURLFactory urlFactory = new OfficeExporterURLFactory();
    PdfExport exporter = new OfficeExporter();
    // Check if the office exporter supports the specified format.
    ExportType exportType = ((OfficeExporter) exporter).getExportType(format);
    // Note 1: exportType will be null if no office server is started or it doesn't support the
    // passed format
    // Note 2: we don't use the office server for PDF exports since it doesn't work OOB. Instead we
    // use FOP.
    if ("pdf".equalsIgnoreCase(format)) {
      // The export format is PDF or the office converter can't be used (either it doesn't support
      // the specified
      // format or the office server is not started).
      urlFactory = new PdfURLFactory();
      exporter = new PdfExportImpl();
      exportType = ExportType.PDF;
    } else if (exportType == null) {
      context.put("message", "core.export.formatUnknown");
      return "exception";
    }

    urlFactory.init(context);
    context.setURLFactory(urlFactory);
    handleRevision(context);

    XWikiDocument doc = context.getDoc();
    context.getResponse().setContentType(exportType.getMimeType());
    context
        .getResponse()
        .addHeader(
            "Content-disposition",
            String.format(
                "inline; filename=%s_%s.%s",
                Util.encodeURI(
                    doc.getDocumentReference().getLastSpaceReference().getName(), context),
                Util.encodeURI(doc.getDocumentReference().getName(), context),
                exportType.getExtension()));
    exporter.export(doc, context.getResponse().getOutputStream(), exportType, context);

    return null;
  }
 private void setUpUserPageMocks(DocumentReference userReference) throws Exception {
   XWikiDocument document = mock(XWikiDocument.class);
   when(document.isNew()).thenReturn(false);
   when(document.getDocumentReference()).thenReturn(userReference);
   BaseObject baseObject = mock(BaseObject.class);
   when(document.getXObject(
           new DocumentReference(
               userReference.getWikiReference().getName(), "XWiki", "XWikiUsers")))
       .thenReturn(baseObject);
   when(this.xwiki.getDocument(userReference, this.xwikiContext)).thenReturn(document);
 }
 private void removeExistingDescriptor(XWikiDocument document) {
   List<BaseObject> existingServerClassObjects = document.getXObjects(SERVER_CLASS);
   if (existingServerClassObjects != null && !existingServerClassObjects.isEmpty()) {
     String wikiId =
         wikiDescriptorDocumentHelper.getWikiIdFromDocumentReference(
             document.getDocumentReference());
     DefaultWikiDescriptor existingDescriptor = cache.getFromId(wikiId);
     if (existingDescriptor != null) {
       cache.remove(existingDescriptor);
     }
   }
 }
Example #19
0
  public void addToDir(XWikiDocument doc, File dir, boolean withVersions, XWikiContext context)
      throws XWikiException {
    try {
      filter(doc, context);
      File spacedir = new File(dir, getDirectoryForDocument(doc));
      if (!spacedir.exists()) {
        if (!spacedir.mkdirs()) {
          Object[] args = new Object[1];
          args[0] = dir.toString();
          throw new XWikiException(
              XWikiException.MODULE_XWIKI,
              XWikiException.ERROR_XWIKI_MKDIR,
              "Error creating directory {0}",
              null,
              args);
        }
      }
      String filename = getFileNameFromDocument(doc, context);
      File file = new File(spacedir, filename);
      FileOutputStream fos = new FileOutputStream(file);
      doc.toXML(fos, true, false, true, withVersions, context);
      fos.flush();
      fos.close();
    } catch (ExcludeDocumentException e) {
      LOGGER.info("Skip the document " + doc.getDocumentReference());
    } catch (Exception e) {
      Object[] args = new Object[1];
      args[0] = doc.getDocumentReference();

      throw new XWikiException(
          XWikiException.MODULE_XWIKI_DOC,
          XWikiException.ERROR_XWIKI_DOC_EXPORT,
          "Error creating file {0}",
          e,
          args);
    }
  }
Example #20
0
  /**
   * Generate a file name based on provided document.
   *
   * @param doc the document to export.
   * @return the corresponding file name.
   */
  public String getFileNameFromDocument(XWikiDocument doc, XWikiContext context) {
    StringBuffer fileName = new StringBuffer(doc.getDocumentReference().getName());

    // Add language
    String language = doc.getLanguage();
    if ((language != null) && (!language.equals(""))) {
      fileName.append(".");
      fileName.append(language);
    }

    // Add extension
    fileName.append('.').append(DEFAULT_FILEEXT);

    return fileName.toString();
  }
  @Override
  public boolean hasProgrammingRights(XWikiDocument doc, XWikiContext context) {
    DocumentReference user;
    WikiReference wiki;

    if (doc != null) {
      user = doc.getContentAuthorReference();
      wiki = doc.getDocumentReference().getWikiReference();
    } else {
      user = context.getUserReference();
      wiki = new WikiReference(context.getDatabase());
    }

    return authorizationManager.hasAccess(Right.PROGRAM, user, wiki);
  }
  @Test
  public void getMembersWhenSingleReferenceNotAUser() throws Exception {
    setUpBaseMocks();
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    DocumentReference reference = new DocumentReference("somewiki", "XWiki", "somepage");
    when(document.getDocumentReference()).thenReturn(reference);
    when(document.getXObject(new DocumentReference("somewiki", "XWiki", "XWikiUsers")))
        .thenReturn(null);
    when(this.xwiki.getDocument(reference, this.xwikiContext)).thenReturn(document);

    Iterator<DocumentReference> iterator =
        new ReferenceUserIterator(reference, null, this.execution);

    assertFalse(iterator.hasNext());
  }
  @Test
  public void getMembersWhenGroupWithNullMember() throws Exception {
    setUpBaseMocks();
    DocumentReference groupReference = new DocumentReference("groupwiki", "XWiki", "grouppage");
    XWikiDocument document = mock(XWikiDocument.class);
    when(document.isNew()).thenReturn(false);
    when(document.getDocumentReference()).thenReturn(groupReference);
    when(xwiki.getDocument(groupReference, this.xwikiContext)).thenReturn(document);
    List<BaseObject> memberObjects = new ArrayList<>();
    memberObjects.add(null);
    when(document.getXObjects(new DocumentReference("groupwiki", "XWiki", "XWikiGroups")))
        .thenReturn(memberObjects);

    Iterator<DocumentReference> iterator =
        new ReferenceUserIterator(groupReference, this.resolver, this.execution);

    assertFalse(iterator.hasNext());
  }
Example #24
0
 /**
  * Gets the translated version of a document, in the specified language. If the translation does
  * not exist, a new document translation is created. If the requested language does not correspond
  * to a translation (is not defined or is the same as the main document), then the main document
  * is returned.
  *
  * @param doc the main (default, untranslated) document to translate
  * @param language the requested document language
  * @param context the current request context
  * @return the translated document, or the original untranslated document if the requested
  *     language is not a translation
  * @throws XWikiException if the translation cannot be retrieved from the database
  */
 protected XWikiDocument getTranslatedDocument(
     XWikiDocument doc, String language, XWikiContext context) throws XWikiException {
   XWikiDocument tdoc;
   if (StringUtils.isBlank(language)
       || language.equals("default")
       || language.equals(doc.getDefaultLanguage())) {
     tdoc = doc;
   } else {
     tdoc = doc.getTranslatedDocument(language, context);
     if (tdoc == doc) {
       tdoc = new XWikiDocument(doc.getDocumentReference());
       tdoc.setLanguage(language);
       tdoc.setStore(doc.getStore());
     }
     tdoc.setTranslation(1);
   }
   return tdoc;
 }
Example #25
0
  public boolean add(XWikiDocument doc, int defaultAction, XWikiContext context)
      throws XWikiException {
    if (!context.getWiki().checkAccess("edit", doc, context)) {
      return false;
    }

    for (int i = 0; i < this.files.size(); i++) {
      DocumentInfo di = this.files.get(i);
      if (di.getFullName().equals(doc.getFullName())
          && (di.getLanguage().equals(doc.getLanguage()))) {
        if (defaultAction != DocumentInfo.ACTION_NOT_DEFINED) {
          di.setAction(defaultAction);
        }
        if (!doc.isNew()) {
          di.setDoc(doc);
        }

        return true;
      }
    }

    doc = doc.clone();

    try {
      filter(doc, context);

      DocumentInfo docinfo = new DocumentInfo(doc);
      docinfo.setAction(defaultAction);
      this.files.add(docinfo);
      BaseClass bclass = doc.getXClass();
      if (bclass.getFieldList().size() > 0) {
        this.classFiles.add(docinfo);
      }
      if (bclass.getCustomMapping() != null) {
        this.customMappingFiles.add(docinfo);
      }
      return true;
    } catch (ExcludeDocumentException e) {
      LOGGER.info("Skip the document " + doc.getDocumentReference());

      return false;
    }
  }
  @Test
  public void onEventWithTemplate() throws ComponentLookupException, XWikiException {
    Utils.setComponentManager(this.mocker);

    DocumentReference docReference =
        new DocumentReference("xwiki", "PhenoTips", "PhenoTipsGroupTemplate");
    XWikiContext context = mock(XWikiContext.class);
    XWikiDocument doc = mock(XWikiDocument.class);
    when(doc.getXObject(Group.CLASS_REFERENCE)).thenReturn(mock(BaseObject.class));
    when(doc.getDocumentReference()).thenReturn(docReference);

    this.mocker
        .getComponentUnderTest()
        .onEvent(new DocumentCreatingEvent(docReference), doc, context);

    Mockito.verifyZeroInteractions(context);
    Mockito.verify(doc).getXObject(Group.CLASS_REFERENCE);
    Mockito.verify(doc).getDocumentReference();
    Mockito.verifyNoMoreInteractions(doc);
  }
  private void renameLinks(
      XWikiDocument document, DocumentReference oldTarget, DocumentReference newTarget)
      throws XWikiException {
    DocumentReference currentDocumentReference = document.getDocumentReference();

    // We support only the syntaxes for which there is an available renderer.
    if (!this.contextComponentManagerProvider
        .get()
        .hasComponent(BlockRenderer.class, document.getSyntax().toIdString())) {
      this.logger.warn(
          "We can't rename the links from [{}] "
              + "because there is no renderer available for its syntax [{}].",
          currentDocumentReference,
          document.getSyntax());
      return;
    }

    XDOM xdom = document.getXDOM();
    List<Block> blocks = linkedResourceHelper.getBlocks(xdom);

    boolean modified = false;
    for (Block block : blocks) {
      try {
        modified |= renameLink(block, currentDocumentReference, oldTarget, newTarget);
      } catch (InvalidArgumentException e) {
        continue;
      }
    }

    if (modified) {
      document.setContent(xdom);
      saveDocumentPreservingContentAuthor(document, "Renamed back-links.", false);
      this.logger.info(
          "The links from [{}] that were targeting [{}] have been updated to target [{}].",
          document.getDocumentReferenceWithLocale(),
          oldTarget,
          newTarget);
    } else {
      this.logger.info("No back-links to update in [{}].", currentDocumentReference);
    }
  }
  private void deleteOldWorkspaceObject(BaseObject oldObject, XWikiDocument oldWikiDescriptor)
      throws DataMigrationException {
    // Context, XWiki
    XWikiContext context = getXWikiContext();
    XWiki xwiki = context.getWiki();

    // Delete the old object
    oldWikiDescriptor.removeXObject(oldObject);

    // Save the document
    try {
      xwiki.saveDocument(
          oldWikiDescriptor, "Remove the old WorkspaceManager.WorkspaceClass object.", context);
    } catch (XWikiException e) {
      throw new DataMigrationException(
          String.format(
              "Failed to save the document [%s] to remove the WorkspaceManager.WorkspaceClass object.",
              oldWikiDescriptor.getDocumentReference().toString()),
          e);
    }
  }
  @Override
  public boolean checkAccess(String action, XWikiDocument doc, XWikiContext context)
      throws XWikiException {
    Right right = actionToRight(action);
    EntityReference entityReference = doc.getDocumentReference();

    LOGGER.debug("checkAccess for action {} on entity {}.", right, entityReference);

    DocumentReference userReference = authenticateUser(right, entityReference, context);
    if (userReference == null) {
      showLogin(context);
      return false;
    }

    if (authorizationManager.hasAccess(right, userReference, entityReference)) {
      return true;
    }

    // If the right has been denied, and we have guest user, redirect the user to login page
    // unless the denied is on the login action, which could cause infinite redirection.
    // FIXME: The hasAccessLevel is broken (do not allow document creator) on the delete action in
    // the old
    // implementation, so code that simply want to verify if a user can delete (but is not actually
    // deleting)
    // has to call checkAccess. This happen really often, and this why we should not redirect to
    // login on failed
    // delete, since it would prevent most user to do anything.
    if (context.getUserReference() == null
        && !DELETE_ACTION.equals(action)
        && !LOGIN_ACTION.equals(action)) {
      LOGGER.debug(
          "Redirecting guest user to login, since it have been denied {} on {}.",
          right,
          entityReference);
      showLogin(context);
    }

    return false;
  }
  @Test
  public void getPlainUserName() throws XWikiException {
    XWikiDocument document = mock(XWikiDocument.class);
    DocumentReference userReference = new DocumentReference("wiki", "XWiki", "user");
    when(document.getDocumentReference()).thenReturn(userReference);
    when(this.storeMock.loadXWikiDoc(any(XWikiDocument.class), any(XWikiContext.class)))
        .thenReturn(document);
    BaseObject userObject = mock(BaseObject.class);
    when(document.getObject("XWiki.XWikiUsers")).thenReturn(userObject);

    when(userObject.getStringValue("first_name")).thenReturn("first<name");
    when(userObject.getStringValue("last_name")).thenReturn("last'name");
    assertEquals("first<name last'name", xwiki.getPlainUserName(userReference, context));

    when(userObject.getStringValue("first_name")).thenReturn("first<name");
    when(userObject.getStringValue("last_name")).thenReturn("");
    assertEquals("first<name", xwiki.getPlainUserName(userReference, context));

    when(userObject.getStringValue("first_name")).thenReturn("");
    when(userObject.getStringValue("last_name")).thenReturn("last'name");
    assertEquals("last'name", xwiki.getPlainUserName(userReference, context));
  }