diff --git a/src/app/collection-page/collection-item-mapper/collection-item-mapper.component.ts b/src/app/collection-page/collection-item-mapper/collection-item-mapper.component.ts index 776b82f9b4c..74b77f505eb 100644 --- a/src/app/collection-page/collection-item-mapper/collection-item-mapper.component.ts +++ b/src/app/collection-page/collection-item-mapper/collection-item-mapper.component.ts @@ -120,7 +120,7 @@ export class CollectionItemMapperComponent implements OnInit { this.collectionName$ = this.collectionRD$.pipe( map((rd: RemoteData) => { - return this.dsoNameService.getName(rd.payload); + return this.dsoNameService.getName(rd.payload, true); }) ); this.searchOptions$ = this.searchConfigService.paginatedSearchOptions; diff --git a/src/app/core/breadcrumbs/dso-name.service.spec.ts b/src/app/core/breadcrumbs/dso-name.service.spec.ts index 81c75913340..412090edf5a 100644 --- a/src/app/core/breadcrumbs/dso-name.service.spec.ts +++ b/src/app/core/breadcrumbs/dso-name.service.spec.ts @@ -72,13 +72,28 @@ describe(`DSONameService`, () => { service = new DSONameService({ instant: (a) => a } as any); }); + describe(`getHitHighlights with escapeHTML`, () => { + const item = Object.assign(new Item(), { + metadata: { 'dc.title': [{ value: 'Title ' }] }, + }); + + it(`should escape the title`, () => { + expect(service.getHitHighlights({}, item, true)).toBe('Title <img src="x">'); + }); + + it(`should escape a highlighted title but keep its tags`, () => { + const hitHighlights = { 'dc.title': [{ value: 'Title ' }] }; + expect(service.getHitHighlights({ hitHighlights }, item, true)).toBe('Title <img src="x">'); + }); + }); + describe(`getName`, () => { it(`should use the Person factory for Person entities`, () => { spyOn((service as any).factories, 'Person').and.returnValue('Bingo!'); const result = service.getName(mockPerson); - expect((service as any).factories.Person).toHaveBeenCalledWith(mockPerson); + expect((service as any).factories.Person).toHaveBeenCalledWith(mockPerson, undefined); expect(result).toBe('Bingo!'); }); @@ -87,7 +102,7 @@ describe(`DSONameService`, () => { const result = service.getName(mockOrgUnit); - expect((service as any).factories.OrgUnit).toHaveBeenCalledWith(mockOrgUnit); + expect((service as any).factories.OrgUnit).toHaveBeenCalledWith(mockOrgUnit, undefined); expect(result).toBe('Bingo!'); }); @@ -96,7 +111,7 @@ describe(`DSONameService`, () => { const result = service.getName(mockEPerson); - expect((service as any).factories.EPerson).toHaveBeenCalledWith(mockEPerson); + expect((service as any).factories.EPerson).toHaveBeenCalledWith(mockEPerson, undefined); expect(result).toBe('Bingo!'); }); @@ -105,7 +120,7 @@ describe(`DSONameService`, () => { const result = service.getName(mockDSO); - expect((service as any).factories.Default).toHaveBeenCalledWith(mockDSO); + expect((service as any).factories.Default).toHaveBeenCalledWith(mockDSO, undefined); expect(result).toBe('Bingo!'); }); }); @@ -119,9 +134,9 @@ describe(`DSONameService`, () => { it(`should return 'person.familyName, person.givenName'`, () => { const result = (service as any).factories.Person(mockPerson); expect(result).toBe(mockPersonName); - expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.familyName'); - expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.givenName'); - expect(mockPerson.firstMetadataValue).not.toHaveBeenCalledWith('dc.title'); + expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.familyName', undefined, undefined); + expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.givenName', undefined, undefined); + expect(mockPerson.firstMetadataValue).not.toHaveBeenCalledWith('dc.title', undefined, undefined); }); }); @@ -133,9 +148,9 @@ describe(`DSONameService`, () => { it(`should return dc.title`, () => { const result = (service as any).factories.Person(mockPerson); expect(result).toBe(mockPersonName); - expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.familyName'); - expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.givenName'); - expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('dc.title'); + expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.familyName', undefined, undefined); + expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.givenName', undefined, undefined); + expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('dc.title', undefined, undefined); }); }); }); @@ -149,8 +164,8 @@ describe(`DSONameService`, () => { it(`should return 'eperson.firstname' and 'eperson.lastname'`, () => { const result = (service as any).factories.EPerson(mockEPerson); expect(result).toBe(mockEPersonName); - expect(mockEPerson.firstMetadataValue).toHaveBeenCalledWith('eperson.firstname'); - expect(mockEPerson.firstMetadataValue).toHaveBeenCalledWith('eperson.lastname'); + expect(mockEPerson.firstMetadataValue).toHaveBeenCalledWith('eperson.firstname', undefined, undefined); + expect(mockEPerson.firstMetadataValue).toHaveBeenCalledWith('eperson.lastname', undefined, undefined); }); }); @@ -162,8 +177,8 @@ describe(`DSONameService`, () => { it(`should return 'eperson.firstname'`, () => { const result = (service as any).factories.EPerson(mockEPersonFirst); expect(result).toBe(mockEPersonNameFirst); - expect(mockEPersonFirst.firstMetadataValue).toHaveBeenCalledWith('eperson.firstname'); - expect(mockEPersonFirst.firstMetadataValue).toHaveBeenCalledWith('eperson.lastname'); + expect(mockEPersonFirst.firstMetadataValue).toHaveBeenCalledWith('eperson.firstname', undefined, undefined); + expect(mockEPersonFirst.firstMetadataValue).toHaveBeenCalledWith('eperson.lastname', undefined, undefined); }); }); }); @@ -177,7 +192,7 @@ describe(`DSONameService`, () => { it(`should return 'organization.legalName'`, () => { const result = (service as any).factories.OrgUnit(mockOrgUnit); expect(result).toBe(mockOrgUnitName); - expect(mockOrgUnit.firstMetadataValue).toHaveBeenCalledWith('organization.legalName'); + expect(mockOrgUnit.firstMetadataValue).toHaveBeenCalledWith('organization.legalName', undefined, undefined); }); }); @@ -189,7 +204,7 @@ describe(`DSONameService`, () => { it(`should return 'dc.title'`, () => { const result = (service as any).factories.Default(mockDSO); expect(result).toBe(mockDSOName); - expect(mockDSO.firstMetadataValue).toHaveBeenCalledWith('dc.title'); + expect(mockDSO.firstMetadataValue).toHaveBeenCalledWith('dc.title', undefined, undefined); }); }); }); diff --git a/src/app/core/breadcrumbs/dso-name.service.ts b/src/app/core/breadcrumbs/dso-name.service.ts index 8e4fb771c64..75dde53e5b7 100644 --- a/src/app/core/breadcrumbs/dso-name.service.ts +++ b/src/app/core/breadcrumbs/dso-name.service.ts @@ -27,9 +27,9 @@ export class DSONameService { * With only two exceptions those solutions seem overkill for now. */ private readonly factories = { - EPerson: (dso: DSpaceObject): string => { - const firstName = dso.firstMetadataValue('eperson.firstname'); - const lastName = dso.firstMetadataValue('eperson.lastname'); + EPerson: (dso: DSpaceObject, escapeHTML?: boolean): string => { + const firstName = dso.firstMetadataValue('eperson.firstname', undefined, escapeHTML); + const lastName = dso.firstMetadataValue('eperson.lastname', undefined, escapeHTML); if (isEmpty(firstName) && isEmpty(lastName)) { return this.translateService.instant('dso.name.unnamed'); } else if (isEmpty(firstName) || isEmpty(lastName)) { @@ -38,32 +38,33 @@ export class DSONameService { return `${firstName} ${lastName}`; } }, - Person: (dso: DSpaceObject): string => { - const familyName = dso.firstMetadataValue('person.familyName'); - const givenName = dso.firstMetadataValue('person.givenName'); + Person: (dso: DSpaceObject, escapeHTML?: boolean): string => { + const familyName = dso.firstMetadataValue('person.familyName', undefined, escapeHTML); + const givenName = dso.firstMetadataValue('person.givenName', undefined, escapeHTML); if (isEmpty(familyName) && isEmpty(givenName)) { - return dso.firstMetadataValue('dc.title') || this.translateService.instant('dso.name.unnamed'); + return dso.firstMetadataValue('dc.title', undefined, escapeHTML) || this.translateService.instant('dso.name.unnamed'); } else if (isEmpty(familyName) || isEmpty(givenName)) { return familyName || givenName; } else { return `${familyName}, ${givenName}`; } }, - OrgUnit: (dso: DSpaceObject): string => { - return dso.firstMetadataValue('organization.legalName') || this.translateService.instant('dso.name.untitled'); + OrgUnit: (dso: DSpaceObject, escapeHTML?: boolean): string => { + return dso.firstMetadataValue('organization.legalName', undefined, escapeHTML); }, - Default: (dso: DSpaceObject): string => { + Default: (dso: DSpaceObject, escapeHTML?: boolean): string => { // If object doesn't have dc.title metadata use name property - return dso.firstMetadataValue('dc.title') || dso.name || this.translateService.instant('dso.name.untitled'); - } + return dso.firstMetadataValue('dc.title', undefined, escapeHTML) || dso.name || this.translateService.instant('dso.name.untitled'); + }, }; /** * Get the name for the given {@link DSpaceObject} * * @param dso The {@link DSpaceObject} you want a name for + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute */ - getName(dso: DSpaceObject | undefined): string { + getName(dso: DSpaceObject | undefined, escapeHTML?: boolean): string { if (dso) { const types = dso.getRenderTypes(); const match = types @@ -72,10 +73,10 @@ export class DSONameService { let name; if (hasValue(match)) { - name = this.factories[match](dso); + name = this.factories[match](dso, escapeHTML); } if (isEmpty(name)) { - name = this.factories.Default(dso); + name = this.factories.Default(dso, escapeHTML); } return name; } else { @@ -88,27 +89,28 @@ export class DSONameService { * * @param object * @param dso + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * * @returns {string} html embedded hit highlight. */ - getHitHighlights(object: any, dso: DSpaceObject): string { + getHitHighlights(object: any, dso: DSpaceObject, escapeHTML?: boolean): string { const types = dso.getRenderTypes(); const entityType = types .filter((type) => typeof type === 'string') .find((type: string) => (['Person', 'OrgUnit']).includes(type)) as string; if (entityType === 'Person') { - const familyName = this.firstMetadataValue(object, dso, 'person.familyName'); - const givenName = this.firstMetadataValue(object, dso, 'person.givenName'); + const familyName = this.firstMetadataValue(object, dso, 'person.familyName', escapeHTML); + const givenName = this.firstMetadataValue(object, dso, 'person.givenName', escapeHTML); if (isEmpty(familyName) && isEmpty(givenName)) { - return this.firstMetadataValue(object, dso, 'dc.title') || dso.name; + return this.firstMetadataValue(object, dso, 'dc.title', escapeHTML) || dso.name; } else if (isEmpty(familyName) || isEmpty(givenName)) { return familyName || givenName; } return `${familyName}, ${givenName}`; } else if (entityType === 'OrgUnit') { - return this.firstMetadataValue(object, dso, 'organization.legalName') || this.translateService.instant('dso.name.untitled'); + return this.firstMetadataValue(object, dso, 'organization.legalName', escapeHTML); } - return this.firstMetadataValue(object, dso, 'dc.title') || dso.name || this.translateService.instant('dso.name.untitled'); + return this.firstMetadataValue(object, dso, 'dc.title', escapeHTML) || dso.name || this.translateService.instant('dso.name.untitled'); } /** @@ -117,11 +119,12 @@ export class DSONameService { * @param object * @param dso * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * * @returns {string} the first matching string value, or `undefined`. */ - firstMetadataValue(object: any, dso: DSpaceObject, keyOrKeys: string | string[]): string { - return Metadata.firstValue([object.hitHighlights, dso.metadata], keyOrKeys); + firstMetadataValue(object: any, dso: DSpaceObject, keyOrKeys: string | string[], escapeHTML?: boolean): string { + return Metadata.firstValue(dso.metadata, keyOrKeys, object.hitHighlights, undefined, escapeHTML); } } diff --git a/src/app/core/shared/dspace-object.model.ts b/src/app/core/shared/dspace-object.model.ts index 6f5d45544df..b54150b1b7b 100644 --- a/src/app/core/shared/dspace-object.model.ts +++ b/src/app/core/shared/dspace-object.model.ts @@ -108,33 +108,36 @@ export class DSpaceObject extends ListableObject implements CacheableObject { * Gets all matching metadata in this DSpaceObject. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. - * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param {MetadataValueFilter} valueFilter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {MetadataValue[]} the matching values or an empty array. */ - allMetadata(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): MetadataValue[] { - return Metadata.all(this.metadata, keyOrKeys, valueFilter); + allMetadata(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter, escapeHTML?: boolean): MetadataValue[] { + return Metadata.all(this.metadata, keyOrKeys, undefined, valueFilter, escapeHTML); } /** * Like [[allMetadata]], but only returns string values. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. - * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param {MetadataValueFilter} valueFilter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string[]} the matching string values or an empty array. */ - allMetadataValues(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string[] { - return Metadata.allValues(this.metadata, keyOrKeys, valueFilter); + allMetadataValues(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter, escapeHTML?: boolean): string[] { + return Metadata.allValues(this.metadata, keyOrKeys, undefined, valueFilter, escapeHTML); } /** * Gets the first matching MetadataValue object in this DSpaceObject, or `undefined`. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. - * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param {MetadataValueFilter} valueFilter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {MetadataValue} the first matching value, or `undefined`. */ - firstMetadata(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): MetadataValue { - return Metadata.first(this.metadata, keyOrKeys, valueFilter); + firstMetadata(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter, escapeHTML?: boolean): MetadataValue { + return Metadata.first(this.metadata, keyOrKeys, undefined, valueFilter, escapeHTML); } /** @@ -142,26 +145,27 @@ export class DSpaceObject extends ListableObject implements CacheableObject { * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. * @param {MetadataValueFilter} valueFilter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string} the first matching string value, or `undefined`. */ - firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): string { - return Metadata.firstValue(this.metadata, keyOrKeys, valueFilter); + firstMetadataValue(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter, escapeHTML?: boolean): string { + return Metadata.firstValue(this.metadata, keyOrKeys, undefined, valueFilter, escapeHTML); } /** * Checks for a matching metadata value in this DSpaceObject. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. - * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param {MetadataValueFilter} valueFilter The value filter to use. If unspecified, no filtering will be done. * @returns {boolean} whether a match is found. */ hasMetadata(keyOrKeys: string | string[], valueFilter?: MetadataValueFilter): boolean { - return Metadata.has(this.metadata, keyOrKeys, valueFilter); + return Metadata.has(this.metadata, keyOrKeys, undefined, valueFilter); } /** * Find metadata on a specific field and order all of them using their "place" property. - * @param key + * @param keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. */ findMetadataSortedByPlace(keyOrKeys: string | string[]): MetadataValue[] { return this.allMetadata(keyOrKeys).sort((a: MetadataValue, b: MetadataValue) => { diff --git a/src/app/core/shared/metadata.utils.spec.ts b/src/app/core/shared/metadata.utils.spec.ts index 812e65bcbae..ff06cf89625 100644 --- a/src/app/core/shared/metadata.utils.spec.ts +++ b/src/app/core/shared/metadata.utils.spec.ts @@ -44,11 +44,11 @@ const multiViewModelList = [ { key: 'foo', ...bar, order: 0 } ]; -const testMethod = (fn, resultKind, mapOrMaps, keyOrKeys, expected, filter?) => { +const testMethod = (fn, resultKind, mapOrMaps, keyOrKeys, hitHighlights, expected, filter?) => { const keys = keyOrKeys instanceof Array ? keyOrKeys : [keyOrKeys]; describe('and key' + (keys.length === 1 ? (' ' + keys[0]) : ('s ' + JSON.stringify(keys))) + ' with ' + (isUndefined(filter) ? 'no filter' : 'filter ' + JSON.stringify(filter)), () => { - const result = fn(mapOrMaps, keys, filter); + const result = fn(mapOrMaps, keys, hitHighlights, filter); let shouldReturn; if (resultKind === 'boolean') { shouldReturn = expected; @@ -70,107 +70,107 @@ describe('Metadata', () => { describe('all method', () => { - const testAll = (mapOrMaps, keyOrKeys, expected, filter?: MetadataValueFilter) => - testMethod(Metadata.all, 'value', mapOrMaps, keyOrKeys, expected, filter); + const testAll = (mapOrMaps, keyOrKeys, hitHighlights, expected, filter?: MetadataValueFilter) => + testMethod(Metadata.all, 'value', mapOrMaps, keyOrKeys, hitHighlights, expected, filter); describe('with emptyMap', () => { - testAll({}, 'foo', []); - testAll({}, '*', []); + testAll({}, 'foo', undefined, []); + testAll({}, '*', undefined, []); }); describe('with singleMap', () => { - testAll(singleMap, 'foo', []); - testAll(singleMap, '*', [dcTitle0]); - testAll(singleMap, '*', [], { value: 'baz' }); - testAll(singleMap, 'dc.title', [dcTitle0]); - testAll(singleMap, 'dc.*', [dcTitle0]); + testAll(singleMap, 'foo', undefined, []); + testAll(singleMap, '*', undefined, [dcTitle0]); + testAll(singleMap, '*', undefined, [], { value: 'baz' }); + testAll(singleMap, 'dc.title', undefined, [dcTitle0]); + testAll(singleMap, 'dc.*', undefined, [dcTitle0]); }); describe('with multiMap', () => { - testAll(multiMap, 'foo', [bar]); - testAll(multiMap, '*', [dcDescription, dcAbstract, dcTitle1, dcTitle2, bar]); - testAll(multiMap, 'dc.title', [dcTitle1, dcTitle2]); - testAll(multiMap, 'dc.*', [dcDescription, dcAbstract, dcTitle1, dcTitle2]); - testAll(multiMap, ['dc.title', 'dc.*'], [dcTitle1, dcTitle2, dcDescription, dcAbstract]); + testAll(multiMap, 'foo', undefined, [bar]); + testAll(multiMap, '*', undefined, [dcDescription, dcAbstract, dcTitle1, dcTitle2, bar]); + testAll(multiMap, 'dc.title', undefined, [dcTitle1, dcTitle2]); + testAll(multiMap, 'dc.*', undefined, [dcDescription, dcAbstract, dcTitle1, dcTitle2]); + testAll(multiMap, ['dc.title', 'dc.*'], undefined, [dcTitle1, dcTitle2, dcDescription, dcAbstract]); }); describe('with [ singleMap, multiMap ]', () => { - testAll([singleMap, multiMap], 'foo', [bar]); - testAll([singleMap, multiMap], '*', [dcTitle0]); - testAll([singleMap, multiMap], 'dc.title', [dcTitle0]); - testAll([singleMap, multiMap], 'dc.*', [dcTitle0]); + testAll(multiMap, 'foo', singleMap, [bar]); + testAll(multiMap, '*', singleMap, [dcTitle0]); + testAll(multiMap, 'dc.title', singleMap, [dcTitle0]); + testAll(multiMap, 'dc.*', singleMap, [dcTitle0]); }); describe('with [ multiMap, singleMap ]', () => { - testAll([multiMap, singleMap], 'foo', [bar]); - testAll([multiMap, singleMap], '*', [dcDescription, dcAbstract, dcTitle1, dcTitle2, bar]); - testAll([multiMap, singleMap], 'dc.title', [dcTitle1, dcTitle2]); - testAll([multiMap, singleMap], 'dc.*', [dcDescription, dcAbstract, dcTitle1, dcTitle2]); - testAll([multiMap, singleMap], ['dc.title', 'dc.*'], [dcTitle1, dcTitle2, dcDescription, dcAbstract]); + testAll(singleMap, 'foo', multiMap, [bar]); + testAll(singleMap, '*', multiMap, [dcDescription, dcAbstract, dcTitle1, dcTitle2, bar]); + testAll(singleMap, 'dc.title', multiMap, [dcTitle1, dcTitle2]); + testAll(singleMap, 'dc.*', multiMap, [dcDescription, dcAbstract, dcTitle1, dcTitle2]); + testAll(singleMap, ['dc.title', 'dc.*'], multiMap, [dcTitle1, dcTitle2, dcDescription, dcAbstract]); }); describe('with regexTestMap', () => { - testAll(regexTestMap, 'foo.bar.*', []); + testAll(regexTestMap, 'foo.bar.*', undefined, []); }); }); describe('allValues method', () => { - const testAllValues = (mapOrMaps, keyOrKeys, expected) => - testMethod(Metadata.allValues, 'string', mapOrMaps, keyOrKeys, expected); + const testAllValues = (mapOrMaps, keyOrKeys, hitHighlights, expected) => + testMethod(Metadata.allValues, 'string', mapOrMaps, keyOrKeys, hitHighlights, expected); describe('with emptyMap', () => { - testAllValues({}, '*', []); + testAllValues({}, '*', undefined, []); }); describe('with singleMap', () => { - testAllValues([singleMap, multiMap], '*', [dcTitle0.value]); + testAllValues(multiMap, '*', singleMap, [dcTitle0.value]); }); describe('with [ multiMap, singleMap ]', () => { - testAllValues([multiMap, singleMap], '*', [dcDescription.value, dcAbstract.value, dcTitle1.value, dcTitle2.value, bar.value]); + testAllValues(singleMap, '*', multiMap, [dcDescription.value, dcAbstract.value, dcTitle1.value, dcTitle2.value, bar.value]); }); }); describe('first method', () => { - const testFirst = (mapOrMaps, keyOrKeys, expected) => - testMethod(Metadata.first, 'value', mapOrMaps, keyOrKeys, expected); + const testFirst = (mapOrMaps, keyOrKeys, hitHighlights, expected) => + testMethod(Metadata.first, 'value', mapOrMaps, keyOrKeys, hitHighlights, expected); describe('with emptyMap', () => { - testFirst({}, '*', undefined); + testFirst({}, '*', undefined, undefined); }); describe('with singleMap', () => { - testFirst(singleMap, '*', dcTitle0); + testFirst(singleMap, '*', undefined, dcTitle0); }); describe('with [ multiMap, singleMap ]', () => { - testFirst([multiMap, singleMap], '*', dcDescription); + testFirst(singleMap, '*', multiMap, dcDescription); }); }); describe('firstValue method', () => { - const testFirstValue = (mapOrMaps, keyOrKeys, expected) => - testMethod(Metadata.firstValue, 'value', mapOrMaps, keyOrKeys, expected); + const testFirstValue = (mapOrMaps, keyOrKeys, hitHighlights, expected) => + testMethod(Metadata.firstValue, 'value', mapOrMaps, keyOrKeys, hitHighlights, expected); describe('with emptyMap', () => { - testFirstValue({}, '*', undefined); + testFirstValue({}, '*', undefined, undefined); }); describe('with singleMap', () => { - testFirstValue(singleMap, '*', dcTitle0.value); + testFirstValue(singleMap, '*', undefined, dcTitle0.value); }); describe('with [ multiMap, singleMap ]', () => { - testFirstValue([multiMap, singleMap], '*', dcDescription.value); + testFirstValue(singleMap, '*', multiMap, dcDescription.value); }); }); describe('has method', () => { - const testHas = (mapOrMaps, keyOrKeys, expected, filter?: MetadataValueFilter) => - testMethod(Metadata.has, 'boolean', mapOrMaps, keyOrKeys, expected, filter); + const testHas = (mapOrMaps, keyOrKeys, hitHighlights, expected, filter?: MetadataValueFilter) => + testMethod(Metadata.has, 'boolean', mapOrMaps, keyOrKeys, hitHighlights, expected, filter); describe('with emptyMap', () => { - testHas({}, '*', false); + testHas({}, '*', undefined, false); }); describe('with singleMap', () => { - testHas(singleMap, '*', true); - testHas(singleMap, '*', false, { value: 'baz' }); + testHas(singleMap, '*', undefined, true); + testHas(singleMap, '*', undefined, false, { value: 'baz' }); }); describe('with [ multiMap, singleMap ]', () => { - testHas([multiMap, singleMap], '*', true); + testHas(singleMap, '*', multiMap, true); }); }); @@ -249,4 +249,25 @@ describe('Metadata', () => { }); + describe('with escapeHTML', () => { + const htmlTitle = { 'dc.title': [mdValue('A & B ')] }; + const htmlHighlight = { 'dc.title': [mdValue('A & B ')] }; + + it('should escape metadata values', () => { + expect(Metadata.firstValue(htmlTitle, 'dc.title', undefined, undefined, true)) + .toEqual('A & B <img src="x">'); + }); + + it('should escape hit highlights but keep their tags', () => { + expect(Metadata.firstValue(htmlTitle, 'dc.title', htmlHighlight, undefined, true)) + .toEqual('A & B <img src="x">'); + expect(Metadata.allValues(htmlTitle, 'dc.title', htmlHighlight, undefined, true)) + .toEqual(['A & B <img src="x">']); + }); + + it('should return the values unchanged without escapeHTML', () => { + expect(Metadata.firstValue(htmlTitle, 'dc.title', htmlHighlight)).toEqual('A & B '); + }); + }); + }); diff --git a/src/app/core/shared/metadata.utils.ts b/src/app/core/shared/metadata.utils.ts index e48b2b0c442..9afb4e757ad 100644 --- a/src/app/core/shared/metadata.utils.ts +++ b/src/app/core/shared/metadata.utils.ts @@ -1,4 +1,6 @@ -import { isEmpty, isNotEmpty, isNotUndefined, isUndefined } from '../../shared/empty.util'; +import escape from 'lodash/escape'; + +import { isNotEmpty, isNotUndefined, isUndefined } from '../../shared/empty.util'; import { MetadataMapInterface, MetadataValue, @@ -26,65 +28,91 @@ export class Metadata { /** * Gets all matching metadata in the map(s). * - * @param {MetadataMapInterface|MetadataMapInterface[]} mapOrMaps The source map(s). When multiple maps are given, they will be - * checked in order, and only values from the first with at least one match will be returned. + * @param metadata The metadata values. * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see above. + * @param hitHighlights The search hit highlights. * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {MetadataValue[]} the matching values or an empty array. */ - public static all(mapOrMaps: MetadataMapInterface | MetadataMapInterface[], keyOrKeys: string | string[], - filter?: MetadataValueFilter): MetadataValue[] { - const mdMaps: MetadataMapInterface[] = mapOrMaps instanceof Array ? mapOrMaps : [mapOrMaps]; + public static all(metadata: MetadataMapInterface, keyOrKeys: string | string[], hitHighlights?: MetadataMapInterface, filter?: MetadataValueFilter, escapeHTML?: boolean): MetadataValue[] { const matches: MetadataValue[] = []; - for (const mdMap of mdMaps) { - for (const mdKey of Metadata.resolveKeys(mdMap, keyOrKeys)) { - const candidates = mdMap[mdKey]; - if (candidates) { - for (const candidate of candidates) { + if (isNotEmpty(hitHighlights)) { + for (const mdKey of Metadata.resolveKeys(hitHighlights, keyOrKeys)) { + if (hitHighlights[mdKey]) { + for (const candidate of hitHighlights[mdKey]) { if (Metadata.valueMatches(candidate as MetadataValue, filter)) { - matches.push(candidate as MetadataValue); + matches.push(escapeHTML ? Metadata.escapeHighlight(candidate as MetadataValue) : candidate as MetadataValue); } } } } - if (!isEmpty(matches)) { + if (isNotEmpty(matches)) { return matches; } } + for (const mdKey of Metadata.resolveKeys(metadata, keyOrKeys)) { + if (metadata[mdKey]) { + for (const candidate of metadata[mdKey]) { + if (Metadata.valueMatches(candidate as MetadataValue, filter)) { + if (escapeHTML) { + matches.push(Object.assign(new MetadataValue(), candidate, { + value: escape(candidate.value), + })); + } else { + matches.push(candidate as MetadataValue); + } + } + } + } + } return matches; } /** * Like [[Metadata.all]], but only returns string values. * - * @param {MetadataMapInterface|MetadataMapInterface[]} mapOrMaps The source map(s). When multiple maps are given, they will be - * checked in order, and only values from the first with at least one match will be returned. + * @param metadata The metadata values. * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see above. + * @param hitHighlights The search hit highlights. * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string[]} the matching string values or an empty array. */ - public static allValues(mapOrMaps: MetadataMapInterface | MetadataMapInterface[], keyOrKeys: string | string[], - filter?: MetadataValueFilter): string[] { - return Metadata.all(mapOrMaps, keyOrKeys, filter).map((mdValue) => mdValue.value); + public static allValues(metadata: MetadataMapInterface, keyOrKeys: string | string[], hitHighlights?: MetadataMapInterface, filter?: MetadataValueFilter, escapeHTML?: boolean): string[] { + return Metadata.all(metadata, keyOrKeys, hitHighlights, filter, escapeHTML).map((mdValue) => mdValue.value); } /** * Gets the first matching MetadataValue object in the map(s), or `undefined`. * - * @param {MetadataMapInterface|MetadataMapInterface[]} mapOrMaps The source map(s). + * @param metadata The metadata values. * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see above. + * @param hitHighlights The search hit highlights. * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {MetadataValue} the first matching value, or `undefined`. */ - public static first(mdMapOrMaps: MetadataMapInterface | MetadataMapInterface[], keyOrKeys: string | string[], - filter?: MetadataValueFilter): MetadataValue { - const mdMaps: MetadataMapInterface[] = mdMapOrMaps instanceof Array ? mdMapOrMaps : [mdMapOrMaps]; - for (const mdMap of mdMaps) { - for (const key of Metadata.resolveKeys(mdMap, keyOrKeys)) { - const values: MetadataValue[] = mdMap[key] as MetadataValue[]; + public static first(metadata: MetadataMapInterface, keyOrKeys: string | string[], hitHighlights?: MetadataMapInterface, filter?: MetadataValueFilter, escapeHTML?: boolean): MetadataValue { + if (isNotEmpty(hitHighlights)) { + for (const key of Metadata.resolveKeys(hitHighlights, keyOrKeys)) { + const values: MetadataValue[] = hitHighlights[key] as MetadataValue[]; if (values) { - return values.find((value: MetadataValue) => Metadata.valueMatches(value, filter)); + const result: MetadataValue = values.find((value: MetadataValue) => Metadata.valueMatches(value, filter)); + return escapeHTML && result ? Metadata.escapeHighlight(result) : result; + } + } + } + for (const key of Metadata.resolveKeys(metadata, keyOrKeys)) { + const values: MetadataValue[] = metadata[key] as MetadataValue[]; + if (values) { + const result: MetadataValue = values.find((value: MetadataValue) => Metadata.valueMatches(value, filter)); + if (escapeHTML) { + return Object.assign(new MetadataValue(), result, { + value: escape(result.value), + }); } + return result; } } } @@ -92,28 +120,29 @@ export class Metadata { /** * Like [[Metadata.first]], but only returns a string value, or `undefined`. * - * @param {MetadataMapInterface|MetadataMapInterface[]} mapOrMaps The source map(s). + * @param metadata The metadata values. * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see above. + * @param hitHighlights The search hit highlights. * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string} the first matching string value, or `undefined`. */ - public static firstValue(mdMapOrMaps: MetadataMapInterface | MetadataMapInterface[], keyOrKeys: string | string[], - filter?: MetadataValueFilter): string { - const value = Metadata.first(mdMapOrMaps, keyOrKeys, filter); + public static firstValue(metadata: MetadataMapInterface, keyOrKeys: string | string[], hitHighlights?: MetadataMapInterface, filter?: MetadataValueFilter, escapeHTML?: boolean): string { + const value = Metadata.first(metadata, keyOrKeys, hitHighlights, filter, escapeHTML); return isUndefined(value) ? undefined : value.value; } /** * Checks for a matching metadata value in the given map(s). * - * @param {MetadataMapInterface|MetadataMapInterface[]} mapOrMaps The source map(s). + * @param metadata The metadata values. * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see above. + * @param hitHighlights The search hit highlights. * @param {MetadataValueFilter} filter The value filter to use. If unspecified, no filtering will be done. * @returns {boolean} whether a match is found. */ - public static has(mdMapOrMaps: MetadataMapInterface | MetadataMapInterface[], keyOrKeys: string | string[], - filter?: MetadataValueFilter): boolean { - return isNotUndefined(Metadata.first(mdMapOrMaps, keyOrKeys, filter)); + public static has(metadata: MetadataMapInterface, keyOrKeys: string | string[], hitHighlights?: MetadataMapInterface, filter?: MetadataValueFilter): boolean { + return isNotUndefined(Metadata.first(metadata, keyOrKeys, hitHighlights, filter)); } /** @@ -233,4 +262,14 @@ export class Metadata { mdMap[key] = [Object.assign(new MetadataValue(), { value: value })]; } } + + /** + * Escapes a hit highlight for `[innerHTML]`. Solr returns the stored value unescaped, so only the `` tags it + * puts around the matched words are kept. + */ + private static escapeHighlight(highlight: MetadataValue): MetadataValue { + return Object.assign(new MetadataValue(), highlight, { + value: escape(highlight.value).replace(/<(\/?)em>/g, '<$1em>'), + }); + } } diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.spec.ts index 55948428f16..05cd7db7aa2 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.spec.ts @@ -4,7 +4,10 @@ import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote- import { buildPaginatedList } from '../../../../../core/data/paginated-list.model'; import { PageInfo } from '../../../../../core/shared/page-info.model'; import { JournalVolumeSearchResultGridElementComponent } from './journal-volume-search-result-grid-element.component'; -import { getEntityGridElementTestComponent } from '../../../../../shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec'; +import { + getEntityGridElementTestComponent, + mockItemWithHtmlDescription +} from '../../../../../shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec'; const mockItemWithMetadata: ItemSearchResult = new ItemSearchResult(); mockItemWithMetadata.hitHighlights = {}; @@ -46,4 +49,4 @@ mockItemWithoutMetadata.indexableObject = Object.assign(new Item(), { } }); -describe('JournalVolumeSearchResultGridElementComponent', getEntityGridElementTestComponent(JournalVolumeSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['date', 'description'])); +describe('JournalVolumeSearchResultGridElementComponent', getEntityGridElementTestComponent(JournalVolumeSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['date', 'description'], undefined, mockItemWithHtmlDescription)); diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html index 3730a78755c..ba6e559f618 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html +++ b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html @@ -26,10 +26,10 @@

- {{firstMetadataValue('creativework.editor')}} + {{firstMetadataValue('creativework.editor', false)}} , - {{firstMetadataValue('creativework.publisher')}} + {{firstMetadataValue('creativework.publisher', false)}}

diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.spec.ts index 44e6be0b12a..ed7f3d70cc1 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.spec.ts @@ -4,7 +4,10 @@ import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote- import { buildPaginatedList } from '../../../../../core/data/paginated-list.model'; import { PageInfo } from '../../../../../core/shared/page-info.model'; import { JournalSearchResultGridElementComponent } from './journal-search-result-grid-element.component'; -import { getEntityGridElementTestComponent } from '../../../../../shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec'; +import { + getEntityGridElementTestComponent, + mockItemWithHtmlDescription +} from '../../../../../shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec'; const mockItemWithMetadata: ItemSearchResult = new ItemSearchResult(); mockItemWithMetadata.hitHighlights = {}; @@ -52,4 +55,4 @@ mockItemWithoutMetadata.indexableObject = Object.assign(new Item(), { } }); -describe('JournalSearchResultGridElementComponent', getEntityGridElementTestComponent(JournalSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['editor', 'publisher', 'description'])); +describe('JournalSearchResultGridElementComponent', getEntityGridElementTestComponent(JournalSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['editor', 'publisher', 'description'], undefined, mockItemWithHtmlDescription)); diff --git a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html index 28ab7f33b45..00bcfe5aef1 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html +++ b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html @@ -33,10 +33,10 @@

class="item-location card-text"> {{firstMetadataValue('organization.address.addressCountry')}} + class="item-country">{{firstMetadataValue('organization.address.addressCountry', false)}} , - {{firstMetadataValue('organization.address.addressLocality')}} + {{firstMetadataValue('organization.address.addressLocality', false)}}

diff --git a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.spec.ts b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.spec.ts index 2cc64cf7b10..14c49301931 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.spec.ts @@ -4,7 +4,10 @@ import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote- import { buildPaginatedList } from '../../../../../core/data/paginated-list.model'; import { PageInfo } from '../../../../../core/shared/page-info.model'; import { ProjectSearchResultGridElementComponent } from './project-search-result-grid-element.component'; -import { getEntityGridElementTestComponent } from '../../../../../shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec'; +import { + getEntityGridElementTestComponent, + mockItemWithHtmlDescription +} from '../../../../../shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec'; const mockItemWithMetadata: ItemSearchResult = new ItemSearchResult(); mockItemWithMetadata.hitHighlights = {}; @@ -40,4 +43,4 @@ mockItemWithoutMetadata.indexableObject = Object.assign(new Item(), { } }); -describe('ProjectSearchResultGridElementComponent', getEntityGridElementTestComponent(ProjectSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['description'])); +describe('ProjectSearchResultGridElementComponent', getEntityGridElementTestComponent(ProjectSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['description'], undefined, mockItemWithHtmlDescription)); diff --git a/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.spec.ts b/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.spec.ts index 42e3aa372ed..8aaa5cbb2fc 100644 --- a/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.spec.ts @@ -53,6 +53,28 @@ const mockItemWithoutMetadata: ItemSearchResult = Object.assign( } }) }); +const htmlDescription = 'Read more here'; +const mockItemWithHtmlDescription: ItemSearchResult = Object.assign( + new ItemSearchResult(), + { + indexableObject: Object.assign(new Item(), { + bundles: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.description': [ + { + language: 'en_US', + value: htmlDescription + } + ] + } + }) + }); const environmentUseThumbs = { browseBy: { @@ -122,6 +144,19 @@ describe('OrgUnitSearchResultListElementComponent', () => { }); }); + describe('When the item has HTML markup in its org unit description', () => { + beforeEach(() => { + orgUnitListElementComponent.object = mockItemWithHtmlDescription; + fixture.detectChanges(); + }); + + it('should render the markup as text, not as elements', () => { + const orgUnitDescriptionField = fixture.debugElement.query(By.css('span.item-list-org-unit-description')); + expect(orgUnitDescriptionField.query(By.css('a, img'))).toBeNull(); + expect(orgUnitDescriptionField.nativeElement.textContent.trim()).toEqual(htmlDescription); + }); + }); + describe('When the item has no org unit description', () => { beforeEach(() => { orgUnitListElementComponent.object = mockItemWithoutMetadata; diff --git a/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html b/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html index f7eb2692ac0..c5aea7a46af 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html +++ b/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html @@ -1,12 +1,12 @@ - + + [ngbTooltip]="mdRepresentation.hasMetadata(['dc.description']) ? descTemplate : null"> diff --git a/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html b/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html index cbc68ef7cf9..1b58919cef5 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html +++ b/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html @@ -2,8 +2,8 @@ - - ; + + ; diff --git a/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html index acc9173bf7d..4c1f9266d6b 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html +++ b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html @@ -1,12 +1,12 @@ - + - \ No newline at end of file + [innerHTML]="dsoNameService.getName(mdRepresentation, true)" + [ngbTooltip]="dsoNameService.getName(mdRepresentation, true).length > 0 ? descTemplate : null"> + diff --git a/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.ts b/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.ts index 76a56182923..d07dcf27a50 100644 --- a/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.ts +++ b/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.ts @@ -62,7 +62,7 @@ export class OrgUnitSearchResultListSubmissionElementComponent extends SearchRes if (this.useNameVariants) { const defaultValue = this.dso ? this.dsoNameService.getName(this.dso) : undefined; - const alternatives = this.allMetadataValues(this.alternativeField); + const alternatives = this.allMetadataValues(this.alternativeField, false); this.allSuggestions = [defaultValue, ...alternatives]; this.relationshipService.getNameVariant(this.listID, this.dso.uuid) diff --git a/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-suggestions/org-unit-input-suggestions.component.html b/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-suggestions/org-unit-input-suggestions.component.html index 7415b84f859..12a589dcbaa 100644 --- a/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-suggestions/org-unit-input-suggestions.component.html +++ b/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-suggestions/org-unit-input-suggestions.component.html @@ -20,7 +20,7 @@ diff --git a/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-search-result-list-submission-element.component.ts b/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-search-result-list-submission-element.component.ts index c9826e440be..7b9ec69b8b7 100644 --- a/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-search-result-list-submission-element.component.ts +++ b/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-search-result-list-submission-element.component.ts @@ -56,7 +56,7 @@ export class PersonSearchResultListSubmissionElementComponent extends SearchResu ngOnInit() { super.ngOnInit(); const defaultValue = this.dso ? this.dsoNameService.getName(this.dso) : undefined; - const alternatives = this.allMetadataValues(this.alternativeField); + const alternatives = this.allMetadataValues(this.alternativeField, false); this.allSuggestions = [defaultValue, ...alternatives]; this.relationshipService.getNameVariant(this.listID, this.dso.uuid) diff --git a/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-suggestions/person-input-suggestions.component.html b/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-suggestions/person-input-suggestions.component.html index 1241fd65ffc..b9d9307eaad 100644 --- a/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-suggestions/person-input-suggestions.component.html +++ b/src/app/entity-groups/research-entities/submission/item-list-elements/person/person-suggestions/person-input-suggestions.component.html @@ -21,7 +21,7 @@ diff --git a/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.ts b/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.ts index d94abfaa9f8..644dab9e1cc 100644 --- a/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.ts +++ b/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.ts @@ -105,7 +105,7 @@ export class ItemCollectionMapperComponent implements OnInit { this.itemName$ = this.itemRD$.pipe( filter((rd: RemoteData) => hasValue(rd)), map((rd: RemoteData) => { - return this.dsoNameService.getName(rd.payload); + return this.dsoNameService.getName(rd.payload, true); }) ); this.searchOptions$ = this.searchConfigService.paginatedSearchOptions; diff --git a/src/app/item-page/full/full-item-page.component.html b/src/app/item-page/full/full-item-page.component.html index 6a6e1f31573..774eebeec6e 100644 --- a/src/app/item-page/full/full-item-page.component.html +++ b/src/app/item-page/full/full-item-page.component.html @@ -47,7 +47,7 @@ {{mdEntry.key}} - + diff --git a/src/app/item-page/simple/field-components/clarin-description-item-field/clarin-description-item-field.component.spec.ts b/src/app/item-page/simple/field-components/clarin-description-item-field/clarin-description-item-field.component.spec.ts index 9eb04c1b3ae..dcc190ccd71 100644 --- a/src/app/item-page/simple/field-components/clarin-description-item-field/clarin-description-item-field.component.spec.ts +++ b/src/app/item-page/simple/field-components/clarin-description-item-field/clarin-description-item-field.component.spec.ts @@ -36,4 +36,20 @@ describe('ClarinDescriptionItemFieldComponent', () => { it('should create', () => { expect(component).toBeTruthy(); }); + + it('should show markup in the description as text and keep URLs as links', () => { + component.item = Object.assign(new Item(), { + metadata: { + 'dc.description': [{ language: null, value: 'Bold See https://example.org' }] + } + }); + component.fields = ['dc.description']; + component.ngOnInit(); + fixture.detectChanges(); + + const element: HTMLElement = fixture.nativeElement; + expect(element.querySelector('b, img')).toBeNull(); + expect(element.textContent).toContain('Bold See https://example.org'); + expect(element.querySelector('a').getAttribute('href')).toEqual('https://example.org'); + }); }); diff --git a/src/app/request-copy/grant-deny-request-copy/grant-deny-request-copy.component.ts b/src/app/request-copy/grant-deny-request-copy/grant-deny-request-copy.component.ts index b130c23abed..f9a8d24c84a 100644 --- a/src/app/request-copy/grant-deny-request-copy/grant-deny-request-copy.component.ts +++ b/src/app/request-copy/grant-deny-request-copy/grant-deny-request-copy.component.ts @@ -77,7 +77,7 @@ export class GrantDenyRequestCopyComponent implements OnInit { ); this.itemName$ = this.itemRD$.pipe( getFirstSucceededRemoteDataPayload(), - map((item) => this.nameService.getName(item)), + map((item) => this.nameService.getName(item, true)), ); this.itemUrl$ = this.itemRD$.pipe( getFirstSucceededRemoteDataPayload(), diff --git a/src/app/shared/clarin-shared-util.spec.ts b/src/app/shared/clarin-shared-util.spec.ts index 8404d87990a..2c9f9ad7f73 100644 --- a/src/app/shared/clarin-shared-util.spec.ts +++ b/src/app/shared/clarin-shared-util.spec.ts @@ -1,6 +1,23 @@ -import { buildAuthoritySearchFilter, convertMetadataFieldIntoSearchType } from './clarin-shared-util'; +import { buildAuthoritySearchFilter, convertMetadataFieldIntoSearchType, makeLinks } from './clarin-shared-util'; describe('clarin-shared-util', () => { + describe('makeLinks', () => { + it('turns URLs into links', () => { + expect(makeLinks('See https://example.org/a?b=1&c=2 now')) + .toBe('See https://example.org/a?b=1&c=2 now'); + }); + + it('escapes markup in the text', () => { + expect(makeLinks('Read here')) + .toBe('Read <a href="https://evil.example/">here</a><img src="x">'); + }); + + it('keeps empty values', () => { + expect(makeLinks(undefined)).toBeUndefined(); + expect(makeLinks('')).toBe(''); + }); + }); + describe('buildAuthoritySearchFilter', () => { it('uses the authority operator and key when an authority is present', () => { expect(buildAuthoritySearchFilter('publisher', { value: 'ACME Press', authority: '02mhbdp94' })) diff --git a/src/app/shared/clarin-shared-util.ts b/src/app/shared/clarin-shared-util.ts index 1afe3c21adb..44acd742ed0 100644 --- a/src/app/shared/clarin-shared-util.ts +++ b/src/app/shared/clarin-shared-util.ts @@ -1,4 +1,5 @@ import { DomSanitizer } from '@angular/platform-browser'; +import escape from 'lodash/escape'; import { getFirstSucceededRemoteDataPayload } from '../core/shared/operators'; import { ConfigurationDataService } from '../core/data/configuration-data.service'; import { isEmpty, isNull, isUndefined } from './empty.util'; @@ -92,9 +93,13 @@ export function loadItemAuthors(item, itemAuthors, baseUrl, fields) { } export function makeLinks(text: string): string { - // Use a regular expression to find URLs and convert them into clickable links - const regex = /(?:https?|ftp):\/\/[^\s)]+|www\.[^\s)]+/g; - return text?.replace(regex, (url) => `${url}`); + if (!text) { + return text; + } + // Split the text into plain parts and URLs (the odd parts). Everything is escaped, so the links are the only HTML. + return text.split(/((?:https?|ftp):\/\/[^\s)"<>]+|www\.[^\s)"<>]+)/) + .map((part, i) => i % 2 === 0 ? escape(part) : `${escape(part)}`) + .join(''); } /** diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.spec.ts index 646125eae5a..a1b9e98fc06 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.spec.ts @@ -196,6 +196,11 @@ describe('DsDynamicAutocompleteComponent test suite', () => { it('should format object values using display fallback', () => { expect(autComp.formatter({ display: 'Alumu-Tesu' })).toEqual('Alumu-Tesu'); }); + + it('should escape markup in the suggestions', () => { + const suggestion: any = Object.assign(new VocabularyEntry(), { display: 'A & B ', value: 1 }); + expect(autComp.suggestionFormatter(suggestion)).toEqual('A & B <img src="x">'); + }); }); }); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.ts index a0d82c4875a..79dacd98128 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.component.ts @@ -1,6 +1,7 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, TemplateRef, ViewChild } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { NgbTypeahead, NgbTypeaheadSelectItemEvent } from '@ng-bootstrap/ng-bootstrap'; +import escape from 'lodash/escape'; import { BehaviorSubject, Observable, of as observableOf } from 'rxjs'; import { PageInfo } from '../../../../../../core/shared/page-info.model'; import { VocabularyService } from '../../../../../../core/submission/vocabularies/vocabulary.service'; @@ -213,7 +214,7 @@ export class DsDynamicAutocompleteComponent extends DsDynamicTagComponent implem return DsDynamicAutocompleteService.pretifyLanguageSuggestion(suggestion, this.translateService); } // @ts-ignore - return suggestion.display; + return escape(suggestion.display); }; /** diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.service.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.service.ts index 2c051ca0ac1..abade67ae9c 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.service.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/autocomplete/ds-dynamic-autocomplete.service.ts @@ -1,3 +1,4 @@ +import escape from 'lodash/escape'; import { take } from 'rxjs/operators'; import {isEmpty } from '../../../../../empty.util'; import {TranslateService} from '@ngx-translate/core'; @@ -25,7 +26,7 @@ export class DsDynamicAutocompleteService { .pipe(take(1)) .subscribe( pn => { projectName = pn; }); - return (fundingCode + ': ').bold() + fundingProjectCode + '
' + (projectName + ': ').bold() + fundingName; + return (fundingCode + ': ').bold() + escape(fundingProjectCode) + '
' + (projectName + ': ').bold() + escape(fundingName); } static pretifyLanguageSuggestion(suggestion, translateService: TranslateService) { @@ -34,7 +35,7 @@ export class DsDynamicAutocompleteService { // fetch language message const languageMessage = translateService.instant('autocomplete.suggestion.language.title'); - return (isoMessage + ': ').bold() + suggestion?.value + '
' + (languageMessage + ': ').bold() + - suggestion?.display; + return (isoMessage + ': ').bold() + escape(suggestion?.value) + '
' + (languageMessage + ': ').bold() + + escape(suggestion?.display); } } diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts index 5faf02eac05..ed6ee822a1f 100644 --- a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts @@ -33,6 +33,11 @@ export class ItemDetailPreviewFieldComponent { */ @Input() metadata: string | string[]; + /** + * Escape HTML in the metadata value + */ + @Input() escapeMetadataHTML: boolean; + /** * The placeholder if there are no value to show */ @@ -50,6 +55,6 @@ export class ItemDetailPreviewFieldComponent { * @returns {string[]} the matching string values or an empty array. */ allMetadataValues(keyOrKeys: string | string[]): string[] { - return Metadata.allValues([this.object.hitHighlights, this.item.metadata], keyOrKeys); + return Metadata.allValues(this.item.metadata, keyOrKeys, this.object.hitHighlights, undefined, this.escapeMetadataHTML); } } diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html index c2f5299d4bc..9fa82b534d6 100644 --- a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html @@ -40,6 +40,7 @@ [object]="object" [label]="('item.page.abstract' | translate)" [metadata]="'dc.description.abstract'" + [escapeMetadataHTML]="false" [separator]="separator" [placeholder]="('mydspace.results.no-abstract' | translate)"> , K ext * Gets all matching metadata string values from hitHighlights or dso metadata, preferring hitHighlights. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string[]} the matching string values or an empty array. */ - allMetadataValues(keyOrKeys: string | string[]): string[] { - return Metadata.allValues([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + allMetadataValues(keyOrKeys: string | string[], escapeHTML = true): string[] { + return Metadata.allValues(this.dso.metadata, keyOrKeys, this.object.hitHighlights, undefined, escapeHTML); } /** * Gets the first matching metadata string value from hitHighlights or dso metadata, preferring hitHighlights. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string} the first matching string value, or `undefined`. */ - firstMetadataValue(keyOrKeys: string | string[]): string { - return Metadata.firstValue([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + firstMetadataValue(keyOrKeys: string | string[], escapeHTML = true): string { + return Metadata.firstValue(this.dso.metadata, keyOrKeys, this.object.hitHighlights, undefined, escapeHTML); } } diff --git a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.html b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.html index 7e2f093a32e..6bccb042caf 100644 --- a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.html +++ b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.html @@ -23,15 +23,15 @@

- {{firstMetadataValue('dc.date.issued')}} + {{firstMetadataValue('dc.date.issued', false)}} ,

- +

- +

diff --git a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec.ts b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec.ts index 083b8779b6a..7f488f06a4d 100644 --- a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec.ts +++ b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.spec.ts @@ -26,25 +26,27 @@ import { TruncatableService } from '../../../../truncatable/truncatable.service' import { TruncatePipe } from '../../../../utils/truncate.pipe'; import { DsLangPipe } from '../../../../utils/ds-lang.pipe'; import { ItemSearchResultGridElementComponent } from './item-search-result-grid-element.component'; +import { MetadataValue } from '../../../../../core/shared/metadata.models'; const mockItemWithMetadata: ItemSearchResult = new ItemSearchResult(); -mockItemWithMetadata.hitHighlights = {}; const mockItemWithAbstractOnly: ItemSearchResult = new ItemSearchResult(); mockItemWithAbstractOnly.hitHighlights = {}; const dcTitle = 'This is just another title'; +mockItemWithMetadata.hitHighlights = { + 'dc.title': [ + Object.assign(new MetadataValue(), { + value: dcTitle, + }), + ], +}; mockItemWithMetadata.indexableObject = Object.assign(new Item(), { - hitHighlights: { - 'dc.title': [{ - value: dcTitle - }], - }, bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), metadata: { 'dc.title': [ { language: 'en_US', - value: dcTitle - } + value: 'This is just another title', + }, ], 'dc.contributor.author': [ { @@ -83,6 +85,26 @@ mockItemWithAbstractOnly.indexableObject = Object.assign(new Item(), { ] } }); +const htmlDescription = 'Read more here'; +export const mockItemWithHtmlDescription: ItemSearchResult = new ItemSearchResult(); +mockItemWithHtmlDescription.hitHighlights = {}; +mockItemWithHtmlDescription.indexableObject = Object.assign(new Item(), { + bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: dcTitle + } + ], + 'dc.description': [ + { + language: 'en_US', + value: htmlDescription + } + ] + } +}); const mockPerson: ItemSearchResult = Object.assign(new ItemSearchResult(), { hitHighlights: { 'person.familyName': [{ @@ -206,7 +228,7 @@ mockItemWithoutMetadata.indexableObject = Object.assign(new Item(), { } }); -describe('ItemGridElementComponent', getEntityGridElementTestComponent(ItemSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['authors', 'date', 'abstract'], mockItemWithAbstractOnly)); +describe('ItemGridElementComponent', getEntityGridElementTestComponent(ItemSearchResultGridElementComponent, mockItemWithMetadata, mockItemWithoutMetadata, ['authors', 'date', 'abstract'], mockItemWithAbstractOnly, mockItemWithHtmlDescription)); /** * Create test cases for a grid component of an entity. @@ -216,6 +238,8 @@ describe('ItemGridElementComponent', getEntityGridElementTestComponent(ItemSearc * @param fieldsToCheck A list of fields to check. The tests expect to find html elements with class ".item-${field}", so make sure they exist in the html template of the grid element. * For example: If one of the fields to check is labeled "authors", the html template should contain at least one element with class ".item-authors" that's * present when the author metadata is available. + * @param searchResultWithHtmlDescription An optional ItemSearchResult containing an item whose dc.description is HTML markup, + * which must be rendered as text in the ".item-abstract" or ".item-description" field */ export function getEntityGridElementTestComponent( component, @@ -223,6 +247,7 @@ export function getEntityGridElementTestComponent( searchResultWithoutMetadata: ItemSearchResult, fieldsToCheck: string[], searchResultWithAbstractOnly?: ItemSearchResult, + searchResultWithHtmlDescription?: ItemSearchResult, ) { return () => { let comp; @@ -284,6 +309,22 @@ export function getEntityGridElementTestComponent( }); } + if (searchResultWithHtmlDescription) { + describe('when the item has HTML markup in dc.description', () => { + beforeEach(() => { + comp.object = searchResultWithHtmlDescription; + fixture.detectChanges(); + }); + + it('should render the markup as text, not as elements', () => { + const descriptionField = fixture.debugElement.query(By.css('.item-abstract, .item-description')); + expect(descriptionField.query(By.css('a, img'))).toBeNull(); + expect(descriptionField.nativeElement.textContent.trim()) + .toEqual(searchResultWithHtmlDescription.indexableObject.firstMetadataValue('dc.description')); + }); + }); + } + fieldsToCheck.forEach((field) => { describe(`when the item has "${field}" metadata`, () => { beforeEach(() => { diff --git a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.ts b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.ts index 7d237e3f792..479cb692cd4 100644 --- a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.ts +++ b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component.ts @@ -42,6 +42,6 @@ export class ItemSearchResultGridElementComponent extends SearchResultGridElemen ngOnInit(): void { super.ngOnInit(); this.itemPageRoute = getItemPageRoute(this.dso); - this.dsoTitle = this.dsoNameService.getHitHighlights(this.object, this.dso); + this.dsoTitle = this.dsoNameService.getHitHighlights(this.object, this.dso, true); } } diff --git a/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts b/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts index 4c3431bb55d..928b4e34778 100644 --- a/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts +++ b/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts @@ -47,20 +47,22 @@ export class SearchResultGridElementComponent, K exten * Gets all matching metadata string values from hitHighlights or dso metadata, preferring hitHighlights. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string[]} the matching string values or an empty array. */ - allMetadataValues(keyOrKeys: string | string[]): string[] { - return Metadata.allValues([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + allMetadataValues(keyOrKeys: string | string[], escapeHTML = true): string[] { + return Metadata.allValues(this.dso.metadata, keyOrKeys, this.object.hitHighlights, undefined, escapeHTML); } /** * Gets the first matching metadata string value from hitHighlights or dso metadata, preferring hitHighlights. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute * @returns {string} the first matching string value, or `undefined`. */ - firstMetadataValue(keyOrKeys: string | string[]): string { - return Metadata.firstValue([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + firstMetadataValue(keyOrKeys: string | string[], escapeHTML = true): string { + return Metadata.firstValue(this.dso.metadata, keyOrKeys, this.object.hitHighlights, undefined, escapeHTML); } private isCollapsed(): Observable { diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html index b4fade662b8..5098be9e4cf 100644 --- a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html @@ -14,16 +14,16 @@

( + [innerHTML]="item.firstMetadataValue('dc.publisher', undefined, true) + ', '"> ) + [innerHTML]="item.firstMetadataValue('dc.date.issued', undefined, true) || ('mydspace.results.no-date' | translate)">) {{'mydspace.results.no-authors' | translate}} + *ngFor="let author of item.allMetadataValues(['dc.contributor.author', 'dc.creator', 'dc.contributor.*'], undefined, true); let last=last;"> ; @@ -33,8 +33,8 @@

- + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts index be94eb85aad..414476a18a9 100644 --- a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts @@ -59,7 +59,7 @@ export class ItemListPreviewComponent implements OnInit { ngOnInit(): void { this.showThumbnails = this.appConfig.browseBy.showThumbnails; - this.dsoTitle = this.dsoNameService.getHitHighlights(this.object, this.item); + this.dsoTitle = this.dsoNameService.getHitHighlights(this.object, this.item, true); } diff --git a/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.html b/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.html index fb3518fe1cf..f8702e8ce60 100644 --- a/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.html +++ b/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.html @@ -23,22 +23,22 @@ [innerHTML]="dsoTitle"> - - ( - , - ) + + ( + , + ) - - + + ; -
+
+ [innerHTML]="abstract">
diff --git a/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.spec.ts b/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.spec.ts index 06fff63d181..6fa5c1a3558 100644 --- a/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.spec.ts +++ b/src/app/shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component.spec.ts @@ -71,6 +71,41 @@ const mockItemWithAbstractOnly: ItemSearchResult = Object.assign(new ItemSearchR } }) }); +const htmlDescription = 'Read more here'; +const mockItemWithHtmlDescription: ItemSearchResult = Object.assign(new ItemSearchResult(), { + indexableObject: + Object.assign(new Item(), { + bundles: observableOf({}), + metadata: { + 'dc.description': [ + { + language: 'en_US', + value: htmlDescription + } + ] + } + }) +}); +const htmlAuthor = 'Smith '; +const mockItemWithHtmlAuthor: ItemSearchResult = Object.assign(new ItemSearchResult(), { + hitHighlights: { + 'dc.contributor.author': [{ + value: 'Smith ' + }], + }, + indexableObject: + Object.assign(new Item(), { + bundles: observableOf({}), + metadata: { + 'dc.contributor.author': [ + { + language: 'en_US', + value: htmlAuthor + } + ] + } + }) +}); const mockItemWithoutMetadata: ItemSearchResult = Object.assign(new ItemSearchResult(), { indexableObject: Object.assign(new Item(), { @@ -247,6 +282,20 @@ describe('ItemSearchResultListElementComponent', () => { }); }); + describe('When a highlighted author has HTML markup', () => { + beforeEach(() => { + publicationListElementComponent.object = mockItemWithHtmlAuthor; + fixture.detectChanges(); + }); + + it('should keep the highlight and render the markup as text', () => { + const itemAuthorField = fixture.debugElement.query(By.css('span.item-list-authors')); + expect(itemAuthorField.query(By.css('em'))).not.toBeNull(); + expect(itemAuthorField.query(By.css('img'))).toBeNull(); + expect(itemAuthorField.nativeElement.textContent).toContain(htmlAuthor); + }); + }); + describe('When the item has no author', () => { beforeEach(() => { publicationListElementComponent.object = mockItemWithoutMetadata; @@ -317,6 +366,24 @@ describe('ItemSearchResultListElementComponent', () => { const abstractField = fixture.debugElement.query(By.css('div.item-list-abstract')); expect(abstractField).not.toBeNull(); }); + + it('should show the dc.description text unchanged', () => { + const abstractField = fixture.debugElement.query(By.css('div.item-list-abstract')); + expect(abstractField.nativeElement.textContent.trim()).toEqual('This is the abstract'); + }); + }); + + describe('When the item has HTML markup in dc.description', () => { + beforeEach(() => { + publicationListElementComponent.object = mockItemWithHtmlDescription; + fixture.detectChanges(); + }); + + it('should render the markup as text, not as elements', () => { + const abstractField = fixture.debugElement.query(By.css('div.item-list-abstract')); + expect(abstractField.query(By.css('a, img'))).toBeNull(); + expect(abstractField.nativeElement.textContent.trim()).toEqual(htmlDescription); + }); }); describe('When the item has no abstract', () => { diff --git a/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts b/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts index 1d65dd8b128..258a6072780 100644 --- a/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts +++ b/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts @@ -33,7 +33,7 @@ export class SearchResultListElementComponent, K exten ngOnInit(): void { if (hasValue(this.object)) { this.dso = this.object.indexableObject; - this.dsoTitle = this.dsoNameService.getHitHighlights(this.object, this.dso); + this.dsoTitle = this.dsoNameService.getHitHighlights(this.object, this.dso, true); } } @@ -41,12 +41,14 @@ export class SearchResultListElementComponent, K exten * Gets all matching metadata string values from hitHighlights or dso metadata. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute. Defaults to `true` because we + * always use `[innerHTML]` in the templates to render metadata due to the hit highlights. * @returns {string[]} the matching string values or an empty array. */ - allMetadataValues(keyOrKeys: string | string[]): string[] { - let dsoMetadata: string[] = Metadata.allValues([this.dso.metadata], keyOrKeys); - let highlights: string[] = Metadata.allValues([this.object.hitHighlights], keyOrKeys); - let removedHighlights: string[] = highlights.map(str => str.replace(/<\/?em>/g, '')); + allMetadataValues(keyOrKeys: string | string[], escapeHTML = true): string[] { + const dsoMetadata: string[] = Metadata.allValues(this.dso.metadata, keyOrKeys, undefined, undefined, escapeHTML); + const highlights: string[] = Metadata.allValues({}, keyOrKeys, this.object.hitHighlights, undefined, escapeHTML); + const removedHighlights: string[] = highlights.map(str => str.replace(/<\/?em>/g, '')); for (let i = 0; i < removedHighlights.length; i++) { let index = dsoMetadata.indexOf(removedHighlights[i]); if (index !== -1) { @@ -60,10 +62,12 @@ export class SearchResultListElementComponent, K exten * Gets the first matching metadata string value from hitHighlights or dso metadata, preferring hitHighlights. * * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @param escapeHTML Whether the HTML is used inside a `[innerHTML]` attribute. Defaults to `true` because we + * always use `[innerHTML]` in the templates to render metadata due to the hit highlights. * @returns {string} the first matching string value, or `undefined`. */ - firstMetadataValue(keyOrKeys: string | string[]): string { - return Metadata.firstValue([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + firstMetadataValue(keyOrKeys: string | string[], escapeHTML = true): string { + return Metadata.firstValue(this.dso.metadata, keyOrKeys, this.object.hitHighlights, undefined, escapeHTML); } /** diff --git a/src/app/shared/object-list/sidebar-search-list-element/sidebar-search-list-element.component.ts b/src/app/shared/object-list/sidebar-search-list-element/sidebar-search-list-element.component.ts index 2ec5cee7a6e..e31dddee290 100644 --- a/src/app/shared/object-list/sidebar-search-list-element/sidebar-search-list-element.component.ts +++ b/src/app/shared/object-list/sidebar-search-list-element/sidebar-search-list-element.component.ts @@ -113,7 +113,7 @@ export class SidebarSearchListElementComponent, K exte !parentRD.hasSucceeded) { return observableOf(accumulatedNames); } - const parentName = this.dsoNameService.getName(parentRD.payload); + const parentName = this.dsoNameService.getName(parentRD.payload, true); const newAccumulatedNames = hasValue(parentName) ? [parentName, ...accumulatedNames] : accumulatedNames; diff --git a/src/app/shared/utils/emphasize.pipe.spec.ts b/src/app/shared/utils/emphasize.pipe.spec.ts new file mode 100644 index 00000000000..66be839a673 --- /dev/null +++ b/src/app/shared/utils/emphasize.pipe.spec.ts @@ -0,0 +1,13 @@ +import { EmphasizePipe } from './emphasize.pipe'; + +describe('EmphasizePipe', () => { + const pipe = new EmphasizePipe(); + + it('should wrap the matches in tags', () => { + expect(pipe.transform('Smith, Sam', 's')).toEqual('Smith, Sam'); + }); + + it('should escape markup in the value', () => { + expect(pipe.transform('Smith & Co ', 'smi')).toEqual('Smith & Co <img src="x">'); + }); +}); diff --git a/src/app/shared/utils/emphasize.pipe.ts b/src/app/shared/utils/emphasize.pipe.ts index 613074a308c..11536b7b532 100644 --- a/src/app/shared/utils/emphasize.pipe.ts +++ b/src/app/shared/utils/emphasize.pipe.ts @@ -1,4 +1,5 @@ import { Pipe, PipeTransform } from '@angular/core'; +import escape from 'lodash/escape'; @Pipe({ name: 'dsEmphasize' }) /** @@ -40,9 +41,11 @@ export class EmphasizePipe implements PipeTransform { * @returns {any} Transformed haystack with the needle emphasized */ transform(haystack, needle): any { - const escaped = this.escapeRegExp(needle); - const reg = new RegExp(escaped, 'gi'); - return haystack.replace(reg, '$&'); + const reg = new RegExp('(' + this.escapeRegExp(needle) + ')', 'gi'); + // The matches are the odd parts. Everything is escaped, so the tags are the only HTML. + return haystack.split(reg) + .map((part, i) => i % 2 === 0 ? escape(part) : '' + escape(part) + '') + .join(''); } /**