core_utils.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2021 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.MissingDataException = exports.DocStats = void 0;
  27. exports.collectActions = collectActions;
  28. exports.encodeToXmlString = encodeToXmlString;
  29. exports.escapePDFName = escapePDFName;
  30. exports.getArrayLookupTableFactory = getArrayLookupTableFactory;
  31. exports.getInheritableProperty = getInheritableProperty;
  32. exports.getLookupTableFactory = getLookupTableFactory;
  33. exports.isWhiteSpace = isWhiteSpace;
  34. exports.log2 = log2;
  35. exports.parseXFAPath = parseXFAPath;
  36. exports.readInt8 = readInt8;
  37. exports.readUint16 = readUint16;
  38. exports.readUint32 = readUint32;
  39. exports.recoverJsURL = recoverJsURL;
  40. exports.toRomanNumerals = toRomanNumerals;
  41. exports.validateCSSFont = validateCSSFont;
  42. var _util = require("../shared/util.js");
  43. var _primitives = require("./primitives.js");
  44. function getLookupTableFactory(initializer) {
  45. let lookup;
  46. return function () {
  47. if (initializer) {
  48. lookup = Object.create(null);
  49. initializer(lookup);
  50. initializer = null;
  51. }
  52. return lookup;
  53. };
  54. }
  55. function getArrayLookupTableFactory(initializer) {
  56. let lookup;
  57. return function () {
  58. if (initializer) {
  59. let arr = initializer();
  60. initializer = null;
  61. lookup = Object.create(null);
  62. for (let i = 0, ii = arr.length; i < ii; i += 2) {
  63. lookup[arr[i]] = arr[i + 1];
  64. }
  65. arr = null;
  66. }
  67. return lookup;
  68. };
  69. }
  70. class MissingDataException extends _util.BaseException {
  71. constructor(begin, end) {
  72. super(`Missing data [${begin}, ${end})`, "MissingDataException");
  73. this.begin = begin;
  74. this.end = end;
  75. }
  76. }
  77. exports.MissingDataException = MissingDataException;
  78. class ParserEOFException extends _util.BaseException {
  79. constructor(msg) {
  80. super(msg, "ParserEOFException");
  81. }
  82. }
  83. exports.ParserEOFException = ParserEOFException;
  84. class XRefEntryException extends _util.BaseException {
  85. constructor(msg) {
  86. super(msg, "XRefEntryException");
  87. }
  88. }
  89. exports.XRefEntryException = XRefEntryException;
  90. class XRefParseException extends _util.BaseException {
  91. constructor(msg) {
  92. super(msg, "XRefParseException");
  93. }
  94. }
  95. exports.XRefParseException = XRefParseException;
  96. class DocStats {
  97. constructor(handler) {
  98. this._handler = handler;
  99. this._streamTypes = new Set();
  100. this._fontTypes = new Set();
  101. }
  102. _send() {
  103. const streamTypes = Object.create(null),
  104. fontTypes = Object.create(null);
  105. for (const type of this._streamTypes) {
  106. streamTypes[type] = true;
  107. }
  108. for (const type of this._fontTypes) {
  109. fontTypes[type] = true;
  110. }
  111. this._handler.send("DocStats", {
  112. streamTypes,
  113. fontTypes
  114. });
  115. }
  116. addStreamType(type) {
  117. if (this._streamTypes.has(type)) {
  118. return;
  119. }
  120. this._streamTypes.add(type);
  121. this._send();
  122. }
  123. addFontType(type) {
  124. if (this._fontTypes.has(type)) {
  125. return;
  126. }
  127. this._fontTypes.add(type);
  128. this._send();
  129. }
  130. }
  131. exports.DocStats = DocStats;
  132. function getInheritableProperty({
  133. dict,
  134. key,
  135. getArray = false,
  136. stopWhenFound = true
  137. }) {
  138. let values;
  139. const visited = new _primitives.RefSet();
  140. while (dict instanceof _primitives.Dict && !(dict.objId && visited.has(dict.objId))) {
  141. if (dict.objId) {
  142. visited.put(dict.objId);
  143. }
  144. const value = getArray ? dict.getArray(key) : dict.get(key);
  145. if (value !== undefined) {
  146. if (stopWhenFound) {
  147. return value;
  148. }
  149. if (!values) {
  150. values = [];
  151. }
  152. values.push(value);
  153. }
  154. dict = dict.get("Parent");
  155. }
  156. return values;
  157. }
  158. const ROMAN_NUMBER_MAP = ["", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM", "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC", "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"];
  159. function toRomanNumerals(number, lowerCase = false) {
  160. (0, _util.assert)(Number.isInteger(number) && number > 0, "The number should be a positive integer.");
  161. const romanBuf = [];
  162. let pos;
  163. while (number >= 1000) {
  164. number -= 1000;
  165. romanBuf.push("M");
  166. }
  167. pos = number / 100 | 0;
  168. number %= 100;
  169. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  170. pos = number / 10 | 0;
  171. number %= 10;
  172. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  173. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  174. const romanStr = romanBuf.join("");
  175. return lowerCase ? romanStr.toLowerCase() : romanStr;
  176. }
  177. function log2(x) {
  178. if (x <= 0) {
  179. return 0;
  180. }
  181. return Math.ceil(Math.log2(x));
  182. }
  183. function readInt8(data, offset) {
  184. return data[offset] << 24 >> 24;
  185. }
  186. function readUint16(data, offset) {
  187. return data[offset] << 8 | data[offset + 1];
  188. }
  189. function readUint32(data, offset) {
  190. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  191. }
  192. function isWhiteSpace(ch) {
  193. return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a;
  194. }
  195. function parseXFAPath(path) {
  196. const positionPattern = /(.+)\[(\d+)\]$/;
  197. return path.split(".").map(component => {
  198. const m = component.match(positionPattern);
  199. if (m) {
  200. return {
  201. name: m[1],
  202. pos: parseInt(m[2], 10)
  203. };
  204. }
  205. return {
  206. name: component,
  207. pos: 0
  208. };
  209. });
  210. }
  211. function escapePDFName(str) {
  212. const buffer = [];
  213. let start = 0;
  214. for (let i = 0, ii = str.length; i < ii; i++) {
  215. const char = str.charCodeAt(i);
  216. if (char < 0x21 || char > 0x7e || char === 0x23 || char === 0x28 || char === 0x29 || char === 0x3c || char === 0x3e || char === 0x5b || char === 0x5d || char === 0x7b || char === 0x7d || char === 0x2f || char === 0x25) {
  217. if (start < i) {
  218. buffer.push(str.substring(start, i));
  219. }
  220. buffer.push(`#${char.toString(16)}`);
  221. start = i + 1;
  222. }
  223. }
  224. if (buffer.length === 0) {
  225. return str;
  226. }
  227. if (start < str.length) {
  228. buffer.push(str.substring(start, str.length));
  229. }
  230. return buffer.join("");
  231. }
  232. function _collectJS(entry, xref, list, parents) {
  233. if (!entry) {
  234. return;
  235. }
  236. let parent = null;
  237. if ((0, _primitives.isRef)(entry)) {
  238. if (parents.has(entry)) {
  239. return;
  240. }
  241. parent = entry;
  242. parents.put(parent);
  243. entry = xref.fetch(entry);
  244. }
  245. if (Array.isArray(entry)) {
  246. for (const element of entry) {
  247. _collectJS(element, xref, list, parents);
  248. }
  249. } else if (entry instanceof _primitives.Dict) {
  250. if ((0, _primitives.isName)(entry.get("S"), "JavaScript") && entry.has("JS")) {
  251. const js = entry.get("JS");
  252. let code;
  253. if ((0, _primitives.isStream)(js)) {
  254. code = js.getString();
  255. } else {
  256. code = js;
  257. }
  258. code = (0, _util.stringToPDFString)(code);
  259. if (code) {
  260. list.push(code);
  261. }
  262. }
  263. _collectJS(entry.getRaw("Next"), xref, list, parents);
  264. }
  265. if (parent) {
  266. parents.remove(parent);
  267. }
  268. }
  269. function collectActions(xref, dict, eventType) {
  270. const actions = Object.create(null);
  271. const additionalActionsDicts = getInheritableProperty({
  272. dict,
  273. key: "AA",
  274. stopWhenFound: false
  275. });
  276. if (additionalActionsDicts) {
  277. for (let i = additionalActionsDicts.length - 1; i >= 0; i--) {
  278. const additionalActions = additionalActionsDicts[i];
  279. if (!(additionalActions instanceof _primitives.Dict)) {
  280. continue;
  281. }
  282. for (const key of additionalActions.getKeys()) {
  283. const action = eventType[key];
  284. if (!action) {
  285. continue;
  286. }
  287. const actionDict = additionalActions.getRaw(key);
  288. const parents = new _primitives.RefSet();
  289. const list = [];
  290. _collectJS(actionDict, xref, list, parents);
  291. if (list.length > 0) {
  292. actions[action] = list;
  293. }
  294. }
  295. }
  296. }
  297. if (dict.has("A")) {
  298. const actionDict = dict.get("A");
  299. const parents = new _primitives.RefSet();
  300. const list = [];
  301. _collectJS(actionDict, xref, list, parents);
  302. if (list.length > 0) {
  303. actions.Action = list;
  304. }
  305. }
  306. return (0, _util.objectSize)(actions) > 0 ? actions : null;
  307. }
  308. const XMLEntities = {
  309. 0x3c: "&lt;",
  310. 0x3e: "&gt;",
  311. 0x26: "&amp;",
  312. 0x22: "&quot;",
  313. 0x27: "&apos;"
  314. };
  315. function encodeToXmlString(str) {
  316. const buffer = [];
  317. let start = 0;
  318. for (let i = 0, ii = str.length; i < ii; i++) {
  319. const char = str.codePointAt(i);
  320. if (0x20 <= char && char <= 0x7e) {
  321. const entity = XMLEntities[char];
  322. if (entity) {
  323. if (start < i) {
  324. buffer.push(str.substring(start, i));
  325. }
  326. buffer.push(entity);
  327. start = i + 1;
  328. }
  329. } else {
  330. if (start < i) {
  331. buffer.push(str.substring(start, i));
  332. }
  333. buffer.push(`&#x${char.toString(16).toUpperCase()};`);
  334. if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
  335. i++;
  336. }
  337. start = i + 1;
  338. }
  339. }
  340. if (buffer.length === 0) {
  341. return str;
  342. }
  343. if (start < str.length) {
  344. buffer.push(str.substring(start, str.length));
  345. }
  346. return buffer.join("");
  347. }
  348. function validateCSSFont(cssFontInfo) {
  349. const DEFAULT_CSS_FONT_OBLIQUE = "14";
  350. const DEFAULT_CSS_FONT_WEIGHT = "400";
  351. const CSS_FONT_WEIGHT_VALUES = new Set(["100", "200", "300", "400", "500", "600", "700", "800", "900", "1000", "normal", "bold", "bolder", "lighter"]);
  352. const {
  353. fontFamily,
  354. fontWeight,
  355. italicAngle
  356. } = cssFontInfo;
  357. if (/^".*"$/.test(fontFamily)) {
  358. if (/[^\\]"/.test(fontFamily.slice(1, fontFamily.length - 1))) {
  359. (0, _util.warn)(`XFA - FontFamily contains some unescaped ": ${fontFamily}.`);
  360. return false;
  361. }
  362. } else if (/^'.*'$/.test(fontFamily)) {
  363. if (/[^\\]'/.test(fontFamily.slice(1, fontFamily.length - 1))) {
  364. (0, _util.warn)(`XFA - FontFamily contains some unescaped ': ${fontFamily}.`);
  365. return false;
  366. }
  367. } else {
  368. for (const ident of fontFamily.split(/[ \t]+/)) {
  369. if (/^(\d|(-(\d|-)))/.test(ident) || !/^[\w-\\]+$/.test(ident)) {
  370. (0, _util.warn)(`XFA - FontFamily contains some invalid <custom-ident>: ${fontFamily}.`);
  371. return false;
  372. }
  373. }
  374. }
  375. const weight = fontWeight ? fontWeight.toString() : "";
  376. cssFontInfo.fontWeight = CSS_FONT_WEIGHT_VALUES.has(weight) ? weight : DEFAULT_CSS_FONT_WEIGHT;
  377. const angle = parseFloat(italicAngle);
  378. cssFontInfo.italicAngle = isNaN(angle) || angle < -90 || angle > 90 ? DEFAULT_CSS_FONT_OBLIQUE : italicAngle.toString();
  379. return true;
  380. }
  381. function recoverJsURL(str) {
  382. const URL_OPEN_METHODS = ["app.launchURL", "window.open", "xfa.host.gotoURL"];
  383. const regex = new RegExp("^\\s*(" + URL_OPEN_METHODS.join("|").split(".").join("\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i");
  384. const jsUrl = regex.exec(str);
  385. if (jsUrl && jsUrl[2]) {
  386. const url = jsUrl[2];
  387. let newWindow = false;
  388. if (jsUrl[3] === "true" && jsUrl[1] === "app.launchURL") {
  389. newWindow = true;
  390. }
  391. return {
  392. url,
  393. newWindow
  394. };
  395. }
  396. return null;
  397. }