2
0

core_utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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.collectActions = collectActions;
  27. exports.encodeToXmlString = encodeToXmlString;
  28. exports.escapePDFName = escapePDFName;
  29. exports.getArrayLookupTableFactory = getArrayLookupTableFactory;
  30. exports.getInheritableProperty = getInheritableProperty;
  31. exports.getLookupTableFactory = getLookupTableFactory;
  32. exports.isWhiteSpace = isWhiteSpace;
  33. exports.log2 = log2;
  34. exports.parseXFAPath = parseXFAPath;
  35. exports.readInt8 = readInt8;
  36. exports.readUint16 = readUint16;
  37. exports.readUint32 = readUint32;
  38. exports.recoverJsURL = recoverJsURL;
  39. exports.toRomanNumerals = toRomanNumerals;
  40. exports.validateCSSFont = validateCSSFont;
  41. exports.XRefParseException = exports.XRefEntryException = exports.ParserEOFException = exports.MissingDataException = void 0;
  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. function getInheritableProperty({
  97. dict,
  98. key,
  99. getArray = false,
  100. stopWhenFound = true
  101. }) {
  102. let values;
  103. const visited = new _primitives.RefSet();
  104. while (dict instanceof _primitives.Dict && !(dict.objId && visited.has(dict.objId))) {
  105. if (dict.objId) {
  106. visited.put(dict.objId);
  107. }
  108. const value = getArray ? dict.getArray(key) : dict.get(key);
  109. if (value !== undefined) {
  110. if (stopWhenFound) {
  111. return value;
  112. }
  113. if (!values) {
  114. values = [];
  115. }
  116. values.push(value);
  117. }
  118. dict = dict.get("Parent");
  119. }
  120. return values;
  121. }
  122. 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"];
  123. function toRomanNumerals(number, lowerCase = false) {
  124. (0, _util.assert)(Number.isInteger(number) && number > 0, "The number should be a positive integer.");
  125. const romanBuf = [];
  126. let pos;
  127. while (number >= 1000) {
  128. number -= 1000;
  129. romanBuf.push("M");
  130. }
  131. pos = number / 100 | 0;
  132. number %= 100;
  133. romanBuf.push(ROMAN_NUMBER_MAP[pos]);
  134. pos = number / 10 | 0;
  135. number %= 10;
  136. romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]);
  137. romanBuf.push(ROMAN_NUMBER_MAP[20 + number]);
  138. const romanStr = romanBuf.join("");
  139. return lowerCase ? romanStr.toLowerCase() : romanStr;
  140. }
  141. function log2(x) {
  142. if (x <= 0) {
  143. return 0;
  144. }
  145. return Math.ceil(Math.log2(x));
  146. }
  147. function readInt8(data, offset) {
  148. return data[offset] << 24 >> 24;
  149. }
  150. function readUint16(data, offset) {
  151. return data[offset] << 8 | data[offset + 1];
  152. }
  153. function readUint32(data, offset) {
  154. return (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
  155. }
  156. function isWhiteSpace(ch) {
  157. return ch === 0x20 || ch === 0x09 || ch === 0x0d || ch === 0x0a;
  158. }
  159. function parseXFAPath(path) {
  160. const positionPattern = /(.+)\[(\d+)\]$/;
  161. return path.split(".").map(component => {
  162. const m = component.match(positionPattern);
  163. if (m) {
  164. return {
  165. name: m[1],
  166. pos: parseInt(m[2], 10)
  167. };
  168. }
  169. return {
  170. name: component,
  171. pos: 0
  172. };
  173. });
  174. }
  175. function escapePDFName(str) {
  176. const buffer = [];
  177. let start = 0;
  178. for (let i = 0, ii = str.length; i < ii; i++) {
  179. const char = str.charCodeAt(i);
  180. 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) {
  181. if (start < i) {
  182. buffer.push(str.substring(start, i));
  183. }
  184. buffer.push(`#${char.toString(16)}`);
  185. start = i + 1;
  186. }
  187. }
  188. if (buffer.length === 0) {
  189. return str;
  190. }
  191. if (start < str.length) {
  192. buffer.push(str.substring(start, str.length));
  193. }
  194. return buffer.join("");
  195. }
  196. function _collectJS(entry, xref, list, parents) {
  197. if (!entry) {
  198. return;
  199. }
  200. let parent = null;
  201. if ((0, _primitives.isRef)(entry)) {
  202. if (parents.has(entry)) {
  203. return;
  204. }
  205. parent = entry;
  206. parents.put(parent);
  207. entry = xref.fetch(entry);
  208. }
  209. if (Array.isArray(entry)) {
  210. for (const element of entry) {
  211. _collectJS(element, xref, list, parents);
  212. }
  213. } else if (entry instanceof _primitives.Dict) {
  214. if ((0, _primitives.isName)(entry.get("S"), "JavaScript") && entry.has("JS")) {
  215. const js = entry.get("JS");
  216. let code;
  217. if ((0, _primitives.isStream)(js)) {
  218. code = js.getString();
  219. } else {
  220. code = js;
  221. }
  222. code = (0, _util.stringToPDFString)(code);
  223. if (code) {
  224. list.push(code);
  225. }
  226. }
  227. _collectJS(entry.getRaw("Next"), xref, list, parents);
  228. }
  229. if (parent) {
  230. parents.remove(parent);
  231. }
  232. }
  233. function collectActions(xref, dict, eventType) {
  234. const actions = Object.create(null);
  235. const additionalActionsDicts = getInheritableProperty({
  236. dict,
  237. key: "AA",
  238. stopWhenFound: false
  239. });
  240. if (additionalActionsDicts) {
  241. for (let i = additionalActionsDicts.length - 1; i >= 0; i--) {
  242. const additionalActions = additionalActionsDicts[i];
  243. if (!(additionalActions instanceof _primitives.Dict)) {
  244. continue;
  245. }
  246. for (const key of additionalActions.getKeys()) {
  247. const action = eventType[key];
  248. if (!action) {
  249. continue;
  250. }
  251. const actionDict = additionalActions.getRaw(key);
  252. const parents = new _primitives.RefSet();
  253. const list = [];
  254. _collectJS(actionDict, xref, list, parents);
  255. if (list.length > 0) {
  256. actions[action] = list;
  257. }
  258. }
  259. }
  260. }
  261. if (dict.has("A")) {
  262. const actionDict = dict.get("A");
  263. const parents = new _primitives.RefSet();
  264. const list = [];
  265. _collectJS(actionDict, xref, list, parents);
  266. if (list.length > 0) {
  267. actions.Action = list;
  268. }
  269. }
  270. return (0, _util.objectSize)(actions) > 0 ? actions : null;
  271. }
  272. const XMLEntities = {
  273. 0x3c: "&lt;",
  274. 0x3e: "&gt;",
  275. 0x26: "&amp;",
  276. 0x22: "&quot;",
  277. 0x27: "&apos;"
  278. };
  279. function encodeToXmlString(str) {
  280. const buffer = [];
  281. let start = 0;
  282. for (let i = 0, ii = str.length; i < ii; i++) {
  283. const char = str.codePointAt(i);
  284. if (0x20 <= char && char <= 0x7e) {
  285. const entity = XMLEntities[char];
  286. if (entity) {
  287. if (start < i) {
  288. buffer.push(str.substring(start, i));
  289. }
  290. buffer.push(entity);
  291. start = i + 1;
  292. }
  293. } else {
  294. if (start < i) {
  295. buffer.push(str.substring(start, i));
  296. }
  297. buffer.push(`&#x${char.toString(16).toUpperCase()};`);
  298. if (char > 0xd7ff && (char < 0xe000 || char > 0xfffd)) {
  299. i++;
  300. }
  301. start = i + 1;
  302. }
  303. }
  304. if (buffer.length === 0) {
  305. return str;
  306. }
  307. if (start < str.length) {
  308. buffer.push(str.substring(start, str.length));
  309. }
  310. return buffer.join("");
  311. }
  312. function validateCSSFont(cssFontInfo) {
  313. const DEFAULT_CSS_FONT_OBLIQUE = "14";
  314. const DEFAULT_CSS_FONT_WEIGHT = "400";
  315. const CSS_FONT_WEIGHT_VALUES = new Set(["100", "200", "300", "400", "500", "600", "700", "800", "900", "1000", "normal", "bold", "bolder", "lighter"]);
  316. const {
  317. fontFamily,
  318. fontWeight,
  319. italicAngle
  320. } = cssFontInfo;
  321. if (/^".*"$/.test(fontFamily)) {
  322. if (/[^\\]"/.test(fontFamily.slice(1, fontFamily.length - 1))) {
  323. (0, _util.warn)(`XFA - FontFamily contains some unescaped ": ${fontFamily}.`);
  324. return false;
  325. }
  326. } else if (/^'.*'$/.test(fontFamily)) {
  327. if (/[^\\]'/.test(fontFamily.slice(1, fontFamily.length - 1))) {
  328. (0, _util.warn)(`XFA - FontFamily contains some unescaped ': ${fontFamily}.`);
  329. return false;
  330. }
  331. } else {
  332. for (const ident of fontFamily.split(/[ \t]+/)) {
  333. if (/^(\d|(-(\d|-)))/.test(ident) || !/^[\w-\\]+$/.test(ident)) {
  334. (0, _util.warn)(`XFA - FontFamily contains some invalid <custom-ident>: ${fontFamily}.`);
  335. return false;
  336. }
  337. }
  338. }
  339. const weight = fontWeight ? fontWeight.toString() : "";
  340. cssFontInfo.fontWeight = CSS_FONT_WEIGHT_VALUES.has(weight) ? weight : DEFAULT_CSS_FONT_WEIGHT;
  341. const angle = parseFloat(italicAngle);
  342. cssFontInfo.italicAngle = isNaN(angle) || angle < -90 || angle > 90 ? DEFAULT_CSS_FONT_OBLIQUE : italicAngle.toString();
  343. return true;
  344. }
  345. function recoverJsURL(str) {
  346. const URL_OPEN_METHODS = ["app.launchURL", "window.open", "xfa.host.gotoURL"];
  347. const regex = new RegExp("^\\s*(" + URL_OPEN_METHODS.join("|").split(".").join("\\.") + ")\\((?:'|\")([^'\"]*)(?:'|\")(?:,\\s*(\\w+)\\)|\\))", "i");
  348. const jsUrl = regex.exec(str);
  349. if (jsUrl && jsUrl[2]) {
  350. const url = jsUrl[2];
  351. let newWindow = false;
  352. if (jsUrl[3] === "true" && jsUrl[1] === "app.launchURL") {
  353. newWindow = true;
  354. }
  355. return {
  356. url,
  357. newWindow
  358. };
  359. }
  360. return null;
  361. }