Debian Codegraph @

closure-library/closure/goog/html/safehtmlformatter.js

raw
1 // Copyright 2016 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15
16 goog.provide('goog.html.SafeHtmlFormatter');
17
18 goog.require('goog.asserts');
19 goog.require('goog.dom.tags');
20 goog.require('goog.html.SafeHtml');
21 goog.require('goog.string');
22
23
24
25 /**
26 * Formatter producing SafeHtml from a plain text format and HTML fragments.
27 *
28 * Example usage:
29 *
30 * var formatter = new goog.html.SafeHtmlFormatter();
31 * var safeHtml = formatter.format(
32 * formatter.startTag('b') +
33 * 'User input:' +
34 * formatter.endTag('b') +
35 * ' ' +
36 * formatter.text(userInput));
37 *
38 * The most common usage is with goog.getMsg:
39 *
40 * var MSG_USER_INPUT = goog.getMsg(
41 * '{$startLink}Learn more{$endLink} about {$userInput}', {
42 * 'startLink': formatter.startTag('a', {'href': url}),
43 * 'endLink': formatter.endTag('a'),
44 * 'userInput': formatter.text(userInput)
45 * });
46 * var safeHtml = formatter.format(MSG_USER_INPUT);
47 *
48 * The formatting string should be constant with all variables processed by
49 * formatter.text().
50 *
51 * @constructor
52 * @struct
53 * @final
54 */
55 goog.html.SafeHtmlFormatter = function() {
56 /**
57 * Mapping from a marker to a replacement.
58 * @private {!Object<string, !goog.html.SafeHtmlFormatter.Replacement>}
59 */
60 this.replacements_ = {};
61
62 /** @private {number} Number of stored replacements. */
63 this.replacementsCount_ = 0;
64 };
65
66
67 /**
68 * @typedef {?{
69 * startTag: (string|undefined),
70 * attributes: (string|undefined),
71 * endTag: (string|undefined),
72 * html: (string|undefined)
73 * }}
74 */
75 goog.html.SafeHtmlFormatter.Replacement;
76
77
78 /**
79 * Formats a plain text string with markers holding HTML fragments to SafeHtml.
80 * @param {string} format Plain text format, will be HTML-escaped.
81 * @return {!goog.html.SafeHtml}
82 */
83 goog.html.SafeHtmlFormatter.prototype.format = function(format) {
84 var openedTags = [];
85 var marker = goog.string.htmlEscape(goog.html.SafeHtmlFormatter.MARKER_);
86 var html = goog.string.htmlEscape(format).replace(
87 new RegExp('\\{' + marker + '[\\w&#;]+\\}', 'g'),
88 goog.bind(this.replaceFormattingString_, this, openedTags));
89 goog.asserts.assert(openedTags.length == 0,
90 'Expected no unclosed tags, got <' + openedTags.join('>, <') + '>.');
91 return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse(
92 html, null);
93 };
94
95
96 /**
97 * Replaces found formatting strings with saved tags.
98 * @param {!Array<string>} openedTags The tags opened so far, modified by this
99 * function.
100 * @param {string} match
101 * @return {string}
102 * @private
103 */
104 goog.html.SafeHtmlFormatter.prototype.replaceFormattingString_ =
105 function(openedTags, match) {
106 var replacement = this.replacements_[match];
107 if (!replacement) {
108 // Someone included a string looking like our internal marker in the format.
109 return match;
110 }
111 var result = '';
112 if (replacement.startTag) {
113 result += '<' + replacement.startTag + replacement.attributes + '>';
114 if (goog.asserts.ENABLE_ASSERTS) {
115 if (!goog.dom.tags.isVoidTag(replacement.startTag.toLowerCase())) {
116 openedTags.push(replacement.startTag.toLowerCase());
117 }
118 }
119 }
120 if (replacement.html) {
121 result += replacement.html;
122 }
123 if (replacement.endTag) {
124 result += '</' + replacement.endTag + '>';
125 if (goog.asserts.ENABLE_ASSERTS) {
126 var lastTag = openedTags.pop();
127 goog.asserts.assert(lastTag == replacement.endTag.toLowerCase(),
128 'Expected </' + lastTag + '>, got </' + replacement.endTag + '>.');
129 }
130 }
131 return result;
132 };
133
134
135 /**
136 * Saves a start tag and returns its marker.
137 * @param {string} tagName
138 * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes
139 * Mapping from attribute names to their values. Only attribute names
140 * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes
141 * the attribute to be omitted.
142 * @return {string} Marker.
143 * @throws {Error} If invalid tag name, attribute name, or attribute value is
144 * provided. This function accepts the same tags and attributes as
145 * {@link goog.html.SafeHtml.create}.
146 */
147 goog.html.SafeHtmlFormatter.prototype.startTag = function(
148 tagName, opt_attributes) {
149 goog.html.SafeHtml.verifyTagName(tagName);
150 return this.storeReplacement_({
151 startTag: tagName,
152 attributes: goog.html.SafeHtml.stringifyAttributes(tagName, opt_attributes)
153 });
154 };
155
156
157 /**
158 * Saves an end tag and returns its marker.
159 * @param {string} tagName
160 * @return {string} Marker.
161 * @throws {Error} If invalid tag name, attribute name, or attribute value is
162 * provided. This function accepts the same tags and attributes as
163 * {@link goog.html.SafeHtml.create}.
164 */
165 goog.html.SafeHtmlFormatter.prototype.endTag = function(tagName) {
166 goog.html.SafeHtml.verifyTagName(tagName);
167 return this.storeReplacement_({endTag: tagName});
168 };
169
170
171 /**
172 * Escapes a text, saves it and returns its marker.
173 *
174 * Wrapping any user input to .text() prevents the attacker with access to
175 * the random number generator to duplicate tags used elsewhere in the format.
176 *
177 * @param {string} text
178 * @return {string} Marker.
179 */
180 goog.html.SafeHtmlFormatter.prototype.text = function(text) {
181 return this.storeReplacement_({html: goog.string.htmlEscape(text)});
182 };
183
184
185 /**
186 * Saves SafeHtml and returns its marker.
187 * @param {!goog.html.SafeHtml} safeHtml
188 * @return {string} Marker.
189 */
190 goog.html.SafeHtmlFormatter.prototype.safeHtml = function(safeHtml) {
191 return this.storeReplacement_({
192 html: goog.html.SafeHtml.unwrap(safeHtml)
193 });
194 };
195
196
197 /** @private @const {string} Marker used for replacements. */
198 goog.html.SafeHtmlFormatter.MARKER_ = 'SafeHtmlFormatter:';
199
200
201 /**
202 * Stores a replacement and returns its marker.
203 * @param {!goog.html.SafeHtmlFormatter.Replacement} replacement
204 * @return {string} Marker.
205 * @private
206 */
207 goog.html.SafeHtmlFormatter.prototype.storeReplacement_ = function(
208 replacement) {
209 this.replacementsCount_++;
210 var marker = '{' + goog.html.SafeHtmlFormatter.MARKER_ +
211 this.replacementsCount_ + '_' + goog.string.getRandomString() + '}';
212 this.replacements_[goog.string.htmlEscape(marker)] = replacement;
213 return marker;
214 };