Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support relative relationships starting without ./ #14

Merged
merged 2 commits into from
Oct 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions package.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,16 +290,25 @@ func (c *CoreProperties) encode(w io.Writer) error {
})
}

func decodeCoreProperties(r io.Reader) (*CoreProperties, error) {
func decodeCoreProperties(r io.Reader, props *CoreProperties) error {
propDecode := new(corePropertiesXMLUnmarshal)
if err := xml.NewDecoder(r).Decode(propDecode); err != nil {
return nil, fmt.Errorf("opc: %s: cannot be decoded: %v", contentTypesName, err)
return fmt.Errorf("opc: %s: cannot be decoded: %v", contentTypesName, err)
}
prop := &CoreProperties{Category: propDecode.Category, ContentStatus: propDecode.ContentStatus,
Created: propDecode.Created, Creator: propDecode.Creator, Description: propDecode.Description,
Identifier: propDecode.Identifier, Keywords: propDecode.Keywords, Language: propDecode.Language,
LastModifiedBy: propDecode.LastModifiedBy, LastPrinted: propDecode.LastPrinted, Modified: propDecode.Modified,
Revision: propDecode.Revision, Subject: propDecode.Subject, Title: propDecode.Title, Version: propDecode.Version}

return prop, nil
props.Category = propDecode.Category
props.ContentStatus = propDecode.ContentStatus
props.Created = propDecode.Created
props.Creator = propDecode.Creator
props.Description = propDecode.Description
props.Identifier = propDecode.Identifier
props.Keywords = propDecode.Keywords
props.Language = propDecode.Language
props.LastModifiedBy = propDecode.LastModifiedBy
props.LastPrinted = propDecode.LastPrinted
props.Modified = propDecode.Modified
props.Revision = propDecode.Revision
props.Subject = propDecode.Subject
props.Title = propDecode.Title
props.Version = propDecode.Version
return nil
}
9 changes: 7 additions & 2 deletions part.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,16 @@ var defaultRef, _ = url.Parse("http:https://defaultcontainer/")
// The source can be a valid part URI, for part relationships, or "/", for package relationships.
func ResolveRelationship(source string, rel string) string {
if source == "/" || source == "\\" {
return "/" + rel
if strings.HasPrefix(rel, "\\") {
rel = rel[1:]
}
if !strings.HasPrefix(rel, "/") {
rel = "/" + rel
}
}
if !strings.HasPrefix(rel, "/") && !strings.HasPrefix(rel, "\\") {
sourceDir := strings.Replace(filepath.Dir(source), "\\", "/", -1)
return fmt.Sprintf("%s/%s", sourceDir, rel)
rel = fmt.Sprintf("%s/%s", sourceDir, rel)
}
return rel
}
Expand Down
2 changes: 2 additions & 0 deletions part_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ func TestResolveRelationship(t *testing.T) {
want string
}{
{"package", args{"/", "c.xml"}, "/c.xml"},
{"packageWithSlash", args{"/", "/c.xml"}, "/c.xml"},
{"packageWin", args{"\\", "c.xml"}, "/c.xml"},
{"packageWinWithSlash", args{"\\", "\\c.xml"}, "/c.xml"},
{"rel", args{"/3D/3dmodel.model", "c.xml"}, "/3D/c.xml"},
{"rel", args{"/3D/3dmodel.model", "/3D/box1.model"}, "/3D/box1.model"},
{"rel", args{"/3D/box3.model", "/2D/2dmodel.model"}, "/2D/2dmodel.model"},
Expand Down
12 changes: 6 additions & 6 deletions reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,12 +106,11 @@ func (r *Reader) loadPackage() error {
if strings.EqualFold(fileName, contentTypesName) || isRelationshipURI(fileName) || strings.HasSuffix(fileName, "/") {
continue
}
if strings.EqualFold(fileName, r.Properties.PartName) {
cp, err := r.loadCoreProperties(file)
if strings.EqualFold(fileName, ResolveRelationship("/", r.Properties.PartName)) {
err := r.loadCoreProperties(file)
if err != nil {
return err
}
r.Properties = *cp
} else {
cType, err := ct.findType(fileName)
if err != nil {
Expand Down Expand Up @@ -162,12 +161,12 @@ func (r *Reader) loadContentType(file archiveFile) (*contentTypes, error) {
return decodeContentTypes(reader)
}

func (r *Reader) loadCoreProperties(file archiveFile) (*CoreProperties, error) {
func (r *Reader) loadCoreProperties(file archiveFile) error {
reader, err := file.Open()
if err != nil {
return nil, fmt.Errorf("opc: %s: cannot be opened: %v", r.Properties.PartName, err)
return fmt.Errorf("opc: %s: cannot be opened: %v", r.Properties.PartName, err)
}
return decodeCoreProperties(reader)
return decodeCoreProperties(reader, &r.Properties)
}

func loadRelationships(file archiveFile, rels *relationshipsPart) error {
Expand Down Expand Up @@ -201,6 +200,7 @@ func (r *Reader) loadPackageRelationships(file archiveFile) error {
for _, rel := range rls {
if strings.EqualFold(rel.Type, corePropsRel) {
r.Properties.PartName = rel.TargetURI
r.Properties.RelationshipID = rel.ID
break
}
}
Expand Down
46 changes: 34 additions & 12 deletions reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ func Test_newReader_CoreProperties(t *testing.T) {
<dcterms:modified xsi:type="dcterms:W3CDTF">2019-01-24T19:58:26Z</dcterms:modified>
</cp:coreProperties>`

cp := &CoreProperties{Created: "2015-06-05T18:19:34Z", Modified: "2019-01-24T19:58:26Z"}
cp := &CoreProperties{PartName: "docProps/core.xml", RelationshipID: "rId2", Created: "2015-06-05T18:19:34Z", Modified: "2019-01-24T19:58:26Z"}

tests := []struct {
name string
Expand All @@ -425,12 +425,17 @@ func Test_newReader_CoreProperties(t *testing.T) {
{"base", []archiveFile{
newMockFile(
"[Content_Types].xml",
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).
withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").
withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
nil,
),
newMockFile(
"_rels/.rels",
ioutil.NopCloser(bytes.NewBufferString(new(relsBuilder).withRel("rId3", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml").withRel("rId2", "http:https://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml").withRel("rId1", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xl/workbook.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(relsBuilder).
withRel("rId3", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml").
withRel("rId2", "http:https://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml").
withRel("rId1", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xl/workbook.xml").String())),
nil,
),
newMockFile("docProps/core.xml", ioutil.NopCloser(bytes.NewBufferString(coreFile)), nil),
Expand All @@ -439,12 +444,17 @@ func Test_newReader_CoreProperties(t *testing.T) {
{"decodeError", []archiveFile{
newMockFile(
"[Content_Types].xml",
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).
withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").
withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
nil,
),
newMockFile(
"_rels/.rels",
ioutil.NopCloser(bytes.NewBufferString(new(relsBuilder).withRel("rId3", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml").withRel("rId2", "http:https://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml").withRel("rId1", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xl/workbook.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(relsBuilder).
withRel("rId3", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml").
withRel("rId2", "http:https://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml").
withRel("rId1", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xl/workbook.xml").String())),
nil,
),
newMockFile("docProps/core.xml", ioutil.NopCloser(bytes.NewBufferString("{a : 2}")), nil),
Expand All @@ -453,12 +463,17 @@ func Test_newReader_CoreProperties(t *testing.T) {
{"openError", []archiveFile{
newMockFile(
"[Content_Types].xml",
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).
withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").
withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
nil,
),
newMockFile(
"_rels/.rels",
ioutil.NopCloser(bytes.NewBufferString(new(relsBuilder).withRel("rId3", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml").withRel("rId2", "http:https://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml").withRel("rId1", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xl/workbook.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(relsBuilder).
withRel("rId3", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", "docProps/app.xml").
withRel("rId2", "http:https://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties", "docProps/core.xml").
withRel("rId1", "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "xl/workbook.xml").String())),
nil,
),
newMockFile("docProps/core.xml", ioutil.NopCloser(nil), errors.New("")),
Expand Down Expand Up @@ -492,8 +507,8 @@ func Test_newReader_PackageRelationships(t *testing.T) {

r := []*Relationship{
{ID: "rId3", Type: "http:https://www.custom.com/external-resource", TargetURI: "http:https://www.custom.com/images/pic1.jpg", TargetMode: ModeExternal},
{ID: "rId2", Type: "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", TargetURI: "/DOCPROPS/app.xml", TargetMode: ModeInternal},
{ID: "rId1", Type: "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", TargetURI: "/xl/workbook.xml", TargetMode: ModeInternal},
{ID: "rId2", Type: "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties", TargetURI: "DOCPROPS/app.xml", TargetMode: ModeInternal},
{ID: "rId1", Type: "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", TargetURI: "xl/workbook.xml", TargetMode: ModeInternal},
{ID: "rId4", Type: "http:https://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", TargetURI: "./xl/other.xml", TargetMode: ModeInternal},
}
tests := []struct {
Expand All @@ -505,7 +520,9 @@ func Test_newReader_PackageRelationships(t *testing.T) {
{"base", []archiveFile{
newMockFile(
"[Content_Types].xml",
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).
withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/app.xml").
withOverride("application/vnd.openxmlformats-package.core-properties+xml", "/docProps/core.xml").String())),
nil,
),
newMockFile("_rels/.rels", ioutil.NopCloser(bytes.NewBufferString(validPackageRelationships)), nil),
Expand All @@ -516,7 +533,9 @@ func Test_newReader_PackageRelationships(t *testing.T) {
newMockFile("docProps/app.xml", ioutil.NopCloser(bytes.NewBufferString("")), nil),
newMockFile(
"[Content_Types].xml",
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/APP.xml").withDefault("image/png", "png").withDefault("application/xml", "xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).
withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/APP.xml").
withDefault("image/png", "png").withDefault("application/xml", "xml").String())),
nil,
),
newMockFile("_rels/.rels", ioutil.NopCloser(nil), errors.New("")),
Expand All @@ -525,7 +544,9 @@ func Test_newReader_PackageRelationships(t *testing.T) {
{"decodeMalformedXMLPackage", []archiveFile{
newMockFile(
"[Content_Types].xml",
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/APP.xml").withDefault("image/png", "png").withDefault("application/xml", "xml").String())),
ioutil.NopCloser(bytes.NewBufferString(new(cTypeBuilder).
withOverride("application/vnd.openxmlformats-officedocument.extended-properties+xml", "/docProps/APP.xml").
withDefault("image/png", "png").withDefault("application/xml", "xml").String())),
nil,
),
newMockFile("docProps/app.xml", ioutil.NopCloser(bytes.NewBufferString("")), nil),
Expand Down Expand Up @@ -634,6 +655,7 @@ func TestOpenReader(t *testing.T) {
args args
wantErr bool
}{
{"office", args{"testdata/office.docx"}, false},
{"extensioncustom", args{"testdata/extensioncustom.3mf"}, false},
{"overridecustom", args{"testdata/overridecustom.3mf"}, false},
{"overridepositive", args{"testdata/overridepositive.3mf"}, false},
Expand Down
26 changes: 8 additions & 18 deletions relationship.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,20 +70,11 @@ func (r *Relationship) validate(sourceURI string) error {
return r.validateRelationshipTarget(sourceURI)
}

func (r *Relationship) normalizeTargetURI() {
if r.TargetMode == ModeInternal {
if !strings.HasPrefix(r.TargetURI, "/") && !strings.HasPrefix(r.TargetURI, "\\") && !strings.HasPrefix(r.TargetURI, ".") {
r.TargetURI = "/" + r.TargetURI
}
}
}

func (r *Relationship) toXML() *relationshipXML {
var targetMode string
if r.TargetMode == ModeExternal {
targetMode = externalMode
}
r.normalizeTargetURI()
x := &relationshipXML{ID: r.ID, RelType: r.Type, TargetURI: r.TargetURI, Mode: targetMode}
return x
}
Expand Down Expand Up @@ -118,14 +109,14 @@ func (r *Relationship) validateRelationshipTarget(sourceURI string) error {
}

// ISO/IEC 29500-2 M1.29
if r.TargetMode == ModeInternal && uri.IsAbs() {
return newErrorRelationship(129, sourceURI, r.ID)
}

if r.TargetMode != ModeExternal && !uri.IsAbs() {
source, err := url.Parse(strings.TrimSpace(sourceURI))
if err != nil || source.String() == "" || isRelationshipURI(source.ResolveReference(uri).String()) {
return newErrorRelationship(125, sourceURI, r.ID)
if r.TargetMode == ModeInternal {
if uri.IsAbs() {
return newErrorRelationship(129, sourceURI, r.ID)
} else {
source, err := url.Parse(strings.TrimSpace(sourceURI))
if err != nil || source.String() == "" || isRelationshipURI(source.ResolveReference(uri).String()) {
return newErrorRelationship(125, sourceURI, r.ID)
}
}
}

Expand Down Expand Up @@ -172,7 +163,6 @@ func decodeRelationships(r io.Reader, partName string) ([]*Relationship, error)
} else {
newRel.TargetMode = ModeExternal
}
newRel.normalizeTargetURI()
rel[i] = newRel
}
return rel, nil
Expand Down
4 changes: 3 additions & 1 deletion relationship_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func TestRelationship_validate(t *testing.T) {
args args
wantErr bool
}{
{"relative", &Relationship{ID: "fakeId", Type: "fakeType", TargetURI: "./two/two.txt", TargetMode: ModeExternal}, args{"/one.txt"}, false},
{"new", &Relationship{ID: "fakeId", Type: "fakeType", TargetURI: "fakeTarget", TargetMode: ModeExternal}, args{""}, false},
{"abs", &Relationship{ID: "fakeId", Type: "fakeType", TargetURI: "http:https://a.com/b", TargetMode: ModeExternal}, args{""}, false},
{"internalRelRel", &Relationship{ID: "fakeId", Type: "fakeType", TargetURI: "/_rels/.rels", TargetMode: ModeInternal}, args{"/"}, true},
Expand All @@ -53,6 +54,7 @@ func TestRelationship_validate(t *testing.T) {
{"invalidTarget", &Relationship{ID: "fakeId", Type: "fakeType", TargetURI: "", TargetMode: ModeInternal}, args{""}, true},
{"invalidRel1", &Relationship{ID: "fakeId", Type: "", TargetURI: "fakeTarget", TargetMode: ModeInternal}, args{""}, true},
{"invalidRel2", &Relationship{ID: "fakeId", Type: " ", TargetURI: "fakeTarget", TargetMode: ModeInternal}, args{""}, true},
{"invalidRel2", &Relationship{ID: "fakeId", Type: "fakeType", TargetURI: "./fakeTarget", TargetMode: ModeInternal}, args{""}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down Expand Up @@ -93,7 +95,7 @@ func Test_encodeRelationships(t *testing.T) {
func expectedsolution() string {
return `<?xml version="1.0" encoding="UTF-8"?>
<Relationships xmlns="http:https://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="fakeId" Type="asd" Target="/fakeTarget"></Relationship>
<Relationship Id="fakeId" Type="asd" Target="fakeTarget"></Relationship>
</Relationships>`
}

Expand Down
Binary file added testdata/office.docx
Binary file not shown.
17 changes: 15 additions & 2 deletions writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,12 +112,25 @@ func (w *Writer) createCoreProperties() error {
partName = corePropsDefaultName
}
part := &Part{Name: partName, ContentType: corePropsContentType}
if !strings.HasPrefix(partName, "/") {
part.Name = "/" + partName
}
cw, err := w.addToPackage(part, CompressionNormal)
if err != nil {
return err
}
w.Relationships = append(w.Relationships,
&Relationship{w.Properties.RelationshipID, corePropsRel, part.Name, ModeInternal})
var hasCoreRel bool
for _, rel := range w.Relationships {
if strings.EqualFold(rel.Type, corePropsRel) {
hasCoreRel = true
break
}
}
if !hasCoreRel {
w.Relationships = append(w.Relationships, &Relationship{
w.Properties.RelationshipID, corePropsRel, partName, ModeInternal,
})
}
return w.Properties.encode(cw)
}

Expand Down
5 changes: 3 additions & 2 deletions writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ func TestWriter_Close(t *testing.T) {
{"invalidOwnRel", &Writer{p: newPackage(), w: zip.NewWriter(&bytes.Buffer{}), Relationships: []*Relationship{{}}, rnd: fakeRand()}, true},
{"withDuplicatedCoreProps", &Writer{p: pCore, w: zip.NewWriter(&bytes.Buffer{}), Properties: CoreProperties{Title: "Song"}, rnd: fakeRand()}, true},
{"withDuplicatedRels", &Writer{p: pRel, w: zip.NewWriter(&bytes.Buffer{}), Properties: CoreProperties{Title: "Song"}, rnd: fakeRand()}, true},
{"withDuplicatedRels", &Writer{p: pRel, w: zip.NewWriter(&bytes.Buffer{}), Properties: CoreProperties{Title: "Song"}, rnd: fakeRand()}, true},
{"withCoreProps", &Writer{p: newPackage(), w: zip.NewWriter(&bytes.Buffer{}), Properties: CoreProperties{Title: "Song"}, rnd: fakeRand()}, false},
{"withCorePropsWithName", &Writer{p: newPackage(), w: zip.NewWriter(&bytes.Buffer{}), Properties: CoreProperties{Title: "Song", PartName: "/props.xml"}, rnd: fakeRand()}, false},
{"withCorePropsWithName", &Writer{p: newPackage(), w: zip.NewWriter(&bytes.Buffer{}), Relationships: []*Relationship{
{TargetURI: "props.xml", Type: corePropsRel},
}, Properties: CoreProperties{Title: "Song", PartName: "props.xml"}, rnd: fakeRand()}, false},
{"withCorePropsWithNameAndId", &Writer{p: newPackage(), w: zip.NewWriter(&bytes.Buffer{}), Properties: CoreProperties{Title: "Song", PartName: "/docProps/props.xml", RelationshipID: "rId1"}, rnd: fakeRand()}, false},
}
for _, tt := range tests {
Expand Down