pjfanning commented on code in PR #1600:
URL: https://github.com/apache/poi/pull/1600#discussion_r4726479930
##########
poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java:
##########
@@ -1172,22 +1172,118 @@ public XWPFEndnote addEndnote(CTFtnEdn note) {
public boolean removeBodyElement(int pos) {
if (pos >= 0 && pos < bodyElements.size()) {
BodyElementType type = bodyElements.get(pos).getElementType();
+ Set<String> relIds = Collections.emptySet();
if (type == BodyElementType.TABLE) {
int tablePos = getTablePos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getTblArray(tablePos));
tables.remove(tablePos);
ctDocument.getBody().removeTbl(tablePos);
}
if (type == BodyElementType.PARAGRAPH) {
int paraPos = getParagraphPos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getPArray(paraPos));
paragraphs.remove(paraPos);
ctDocument.getBody().removeP(paraPos);
}
bodyElements.remove(pos);
+ if (!relIds.isEmpty()) {
+ removeUnusedRelations(relIds);
+ }
return true;
}
return false;
}
+ private static Set<String> collectRelationshipIds(XmlObject xml) {
+ Set<String> relIds = new LinkedHashSet<>();
+ try (XmlCursor cursor = xml.newCursor();
+ XmlCursor end = xml.newCursor()) {
+ end.toEndToken();
+ while (cursor.toNextToken() != XmlCursor.TokenType.NONE &&
!cursor.isAtSamePositionAs(end)) {
+ if (cursor.isAttr()) {
+ QName name = cursor.getName();
+ if (name != null &&
PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS.equals(name.getNamespaceURI()))
{
+ String id = cursor.getTextValue();
+ if (id != null && !id.isEmpty()) {
+ relIds.add(id);
+ }
+ }
+ }
+ }
+ }
+ return relIds;
+ }
+
+ private static void removeReferencedIds(XmlObject xml, Set<String>
candidateIds) {
+ try (XmlCursor cursor = xml.newCursor();
+ XmlCursor end = xml.newCursor()) {
+ end.toEndToken();
+ while (!candidateIds.isEmpty() && cursor.toNextToken() !=
XmlCursor.TokenType.NONE
+ && !cursor.isAtSamePositionAs(end)) {
+ if (cursor.isAttr()) {
+ QName name = cursor.getName();
+ if (name != null &&
PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS.equals(name.getNamespaceURI()))
{
+ candidateIds.remove(cursor.getTextValue());
+ }
+ }
+ }
+ }
+ }
+
+ private void removeUnusedRelations(Set<String> candidateIds) {
+ removeReferencedIds(ctDocument, candidateIds);
+ if (candidateIds.isEmpty()) {
+ return;
+ }
+
+ // Remove non-child-part relationships (hyperlinks, external links,
etc.) first
+ // so that isRelationshipTarget() sees their removal before deleting
child parts.
+ List<String> partRelIds = new ArrayList<>();
+ PackagePart docPart = getPackagePart();
+ for (String id : candidateIds) {
+ if (getRelationPartById(id) != null) {
+ partRelIds.add(id);
+ } else {
+ if (!removeReferenceRelationship(id) &&
docPart.hasRelationships() && docPart.getRelationship(id) != null) {
+ docPart.removeRelationship(id);
+ }
+ for (Iterator<XWPFHyperlink> it = hyperlinks.iterator();
it.hasNext(); ) {
+ XWPFHyperlink link = it.next();
+ if (readHyperlinks.contains(link) &&
id.equals(link.getId())) {
+ readHyperlinks.remove(link);
+ it.remove();
+ }
+ }
+ }
+ }
+
+ boolean removedPart = false;
+ for (String id : partRelIds) {
+ POIXMLDocumentPart part = getRelationById(id);
+ if (part == null || part instanceof XWPFHeaderFooter) {
Review Comment:
Every attribute value in the relationships namespace is treated as a
removable relationship id, and only headers and footers are excluded here. A
malformed or crafted document where an element in the body uses the id of a
structural relationship (styles, numbering, settings, footnotes, comments...),
e.g. a `w:hyperlink` whose `r:id` is the styles relationship, would have that
part removed from the package while the document still holds on to it.
I think an allow-list of the kinds of part that body content can own
(pictures, charts, embedded/OLE packages, diagram parts) would be safer than
excluding the known exceptions.
##########
poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java:
##########
@@ -1172,22 +1172,118 @@ public XWPFEndnote addEndnote(CTFtnEdn note) {
public boolean removeBodyElement(int pos) {
if (pos >= 0 && pos < bodyElements.size()) {
BodyElementType type = bodyElements.get(pos).getElementType();
+ Set<String> relIds = Collections.emptySet();
if (type == BodyElementType.TABLE) {
int tablePos = getTablePos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getTblArray(tablePos));
tables.remove(tablePos);
ctDocument.getBody().removeTbl(tablePos);
}
if (type == BodyElementType.PARAGRAPH) {
int paraPos = getParagraphPos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getPArray(paraPos));
paragraphs.remove(paraPos);
ctDocument.getBody().removeP(paraPos);
}
bodyElements.remove(pos);
+ if (!relIds.isEmpty()) {
+ removeUnusedRelations(relIds);
Review Comment:
My main concern is existing code that moves a paragraph or table: copy the
`CTP`/`CTTbl`, call `removeBodyElement`, then insert a new paragraph elsewhere
and `set` the saved copy. At the time of the remove, the copy is not in
`ctDocument`, so its picture/chart/hyperlink relationships (and parts) would
now be deleted, and the re-inserted element would have dangling
`r:embed`/`r:id` values. That code works today.
Would it be better to make the cleanup opt-in, e.g. a new overload or a
separate method, and leave `removeBodyElement(int)` as it is? At the least the
javadoc needs to describe the new behaviour.
##########
poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java:
##########
@@ -1172,22 +1172,118 @@ public XWPFEndnote addEndnote(CTFtnEdn note) {
public boolean removeBodyElement(int pos) {
if (pos >= 0 && pos < bodyElements.size()) {
BodyElementType type = bodyElements.get(pos).getElementType();
+ Set<String> relIds = Collections.emptySet();
if (type == BodyElementType.TABLE) {
int tablePos = getTablePos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getTblArray(tablePos));
tables.remove(tablePos);
ctDocument.getBody().removeTbl(tablePos);
}
if (type == BodyElementType.PARAGRAPH) {
int paraPos = getParagraphPos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getPArray(paraPos));
paragraphs.remove(paraPos);
ctDocument.getBody().removeP(paraPos);
}
bodyElements.remove(pos);
+ if (!relIds.isEmpty()) {
+ removeUnusedRelations(relIds);
+ }
return true;
}
return false;
}
+ private static Set<String> collectRelationshipIds(XmlObject xml) {
+ Set<String> relIds = new LinkedHashSet<>();
+ try (XmlCursor cursor = xml.newCursor();
+ XmlCursor end = xml.newCursor()) {
+ end.toEndToken();
+ while (cursor.toNextToken() != XmlCursor.TokenType.NONE &&
!cursor.isAtSamePositionAs(end)) {
+ if (cursor.isAttr()) {
+ QName name = cursor.getName();
+ if (name != null &&
PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS.equals(name.getNamespaceURI()))
{
+ String id = cursor.getTextValue();
+ if (id != null && !id.isEmpty()) {
+ relIds.add(id);
+ }
+ }
+ }
+ }
+ }
+ return relIds;
+ }
+
+ private static void removeReferencedIds(XmlObject xml, Set<String>
candidateIds) {
+ try (XmlCursor cursor = xml.newCursor();
+ XmlCursor end = xml.newCursor()) {
+ end.toEndToken();
+ while (!candidateIds.isEmpty() && cursor.toNextToken() !=
XmlCursor.TokenType.NONE
+ && !cursor.isAtSamePositionAs(end)) {
+ if (cursor.isAttr()) {
+ QName name = cursor.getName();
+ if (name != null &&
PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS.equals(name.getNamespaceURI()))
{
+ candidateIds.remove(cursor.getTextValue());
+ }
+ }
+ }
+ }
+ }
+
+ private void removeUnusedRelations(Set<String> candidateIds) {
+ removeReferencedIds(ctDocument, candidateIds);
+ if (candidateIds.isEmpty()) {
+ return;
+ }
+
+ // Remove non-child-part relationships (hyperlinks, external links,
etc.) first
+ // so that isRelationshipTarget() sees their removal before deleting
child parts.
+ List<String> partRelIds = new ArrayList<>();
+ PackagePart docPart = getPackagePart();
+ for (String id : candidateIds) {
+ if (getRelationPartById(id) != null) {
+ partRelIds.add(id);
+ } else {
+ if (!removeReferenceRelationship(id) &&
docPart.hasRelationships() && docPart.getRelationship(id) != null) {
+ docPart.removeRelationship(id);
Review Comment:
`PackagePart.removeRelationship` (and the part removal further down) call
`throwExceptionIfReadOnly()`. For a document opened with `PackageAccess.READ`,
`removeBodyElement` on an element with a hyperlink or picture would now throw
`InvalidOperationException`, after the XML and the
`paragraphs`/`tables`/`bodyElements` lists have already been changed. Today
that call succeeds (e.g. stripping content before text extraction). The cleanup
should be skipped when the package is read-only, with a test.
##########
poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFDocument.java:
##########
@@ -1172,22 +1172,118 @@ public XWPFEndnote addEndnote(CTFtnEdn note) {
public boolean removeBodyElement(int pos) {
if (pos >= 0 && pos < bodyElements.size()) {
BodyElementType type = bodyElements.get(pos).getElementType();
+ Set<String> relIds = Collections.emptySet();
if (type == BodyElementType.TABLE) {
int tablePos = getTablePos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getTblArray(tablePos));
tables.remove(tablePos);
ctDocument.getBody().removeTbl(tablePos);
}
if (type == BodyElementType.PARAGRAPH) {
int paraPos = getParagraphPos(pos);
+ relIds =
collectRelationshipIds(ctDocument.getBody().getPArray(paraPos));
paragraphs.remove(paraPos);
ctDocument.getBody().removeP(paraPos);
}
bodyElements.remove(pos);
+ if (!relIds.isEmpty()) {
+ removeUnusedRelations(relIds);
+ }
return true;
}
return false;
}
+ private static Set<String> collectRelationshipIds(XmlObject xml) {
+ Set<String> relIds = new LinkedHashSet<>();
+ try (XmlCursor cursor = xml.newCursor();
+ XmlCursor end = xml.newCursor()) {
+ end.toEndToken();
+ while (cursor.toNextToken() != XmlCursor.TokenType.NONE &&
!cursor.isAtSamePositionAs(end)) {
+ if (cursor.isAttr()) {
+ QName name = cursor.getName();
+ if (name != null &&
PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS.equals(name.getNamespaceURI()))
{
+ String id = cursor.getTextValue();
+ if (id != null && !id.isEmpty()) {
+ relIds.add(id);
+ }
+ }
+ }
+ }
+ }
+ return relIds;
+ }
+
+ private static void removeReferencedIds(XmlObject xml, Set<String>
candidateIds) {
+ try (XmlCursor cursor = xml.newCursor();
+ XmlCursor end = xml.newCursor()) {
+ end.toEndToken();
+ while (!candidateIds.isEmpty() && cursor.toNextToken() !=
XmlCursor.TokenType.NONE
+ && !cursor.isAtSamePositionAs(end)) {
+ if (cursor.isAttr()) {
+ QName name = cursor.getName();
+ if (name != null &&
PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS.equals(name.getNamespaceURI()))
{
+ candidateIds.remove(cursor.getTextValue());
+ }
+ }
+ }
+ }
+ }
+
+ private void removeUnusedRelations(Set<String> candidateIds) {
+ removeReferencedIds(ctDocument, candidateIds);
Review Comment:
This walks every token of the remaining document each time an element with
any relationship id is removed, so removing many such elements in a loop
becomes quadratic in the document size. For large documents that could be a big
slowdown for a call that is cheap today.
Related: the `POIXMLDocumentPart` change adds the `isRelationshipTarget()`
scan over all the parts of the package to `removeRelation` for every format,
not just XWPF. Have you looked at what that costs on a package with many parts?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]