drupal.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'locale': {} };
  2. // Allow other JavaScript libraries to use $.
  3. jQuery.noConflict();
  4. (function ($) {
  5. /**
  6. * Override jQuery.fn.init to guard against XSS attacks.
  7. *
  8. * See http://bugs.jquery.com/ticket/9521
  9. */
  10. var jquery_init = $.fn.init;
  11. $.fn.init = function (selector, context, rootjQuery) {
  12. // If the string contains a "#" before a "<", treat it as invalid HTML.
  13. if (selector && typeof selector === 'string') {
  14. var hash_position = selector.indexOf('#');
  15. if (hash_position >= 0) {
  16. var bracket_position = selector.indexOf('<');
  17. if (bracket_position > hash_position) {
  18. throw 'Syntax error, unrecognized expression: ' + selector;
  19. }
  20. }
  21. }
  22. return jquery_init.call(this, selector, context, rootjQuery);
  23. };
  24. $.fn.init.prototype = jquery_init.prototype;
  25. /**
  26. * Pre-filter Ajax requests to guard against XSS attacks.
  27. *
  28. * See https://github.com/jquery/jquery/issues/2432
  29. */
  30. if ($.ajaxPrefilter) {
  31. // For newer versions of jQuery, use an Ajax prefilter to prevent
  32. // auto-executing script tags from untrusted domains. This is similar to the
  33. // fix that is built in to jQuery 3.0 and higher.
  34. $.ajaxPrefilter(function (s) {
  35. if (s.crossDomain) {
  36. s.contents.script = false;
  37. }
  38. });
  39. }
  40. else if ($.httpData) {
  41. // For the version of jQuery that ships with Drupal core, override
  42. // jQuery.httpData to prevent auto-detecting "script" data types from
  43. // untrusted domains.
  44. var jquery_httpData = $.httpData;
  45. $.httpData = function (xhr, type, s) {
  46. // @todo Consider backporting code from newer jQuery versions to check for
  47. // a cross-domain request here, rather than using Drupal.urlIsLocal() to
  48. // block scripts from all URLs that are not on the same site.
  49. if (!type && !Drupal.urlIsLocal(s.url)) {
  50. var content_type = xhr.getResponseHeader('content-type') || '';
  51. if (content_type.indexOf('javascript') >= 0) {
  52. // Default to a safe data type.
  53. type = 'text';
  54. }
  55. }
  56. return jquery_httpData.call(this, xhr, type, s);
  57. };
  58. $.httpData.prototype = jquery_httpData.prototype;
  59. }
  60. /**
  61. * Attach all registered behaviors to a page element.
  62. *
  63. * Behaviors are event-triggered actions that attach to page elements, enhancing
  64. * default non-JavaScript UIs. Behaviors are registered in the Drupal.behaviors
  65. * object using the method 'attach' and optionally also 'detach' as follows:
  66. * @code
  67. * Drupal.behaviors.behaviorName = {
  68. * attach: function (context, settings) {
  69. * ...
  70. * },
  71. * detach: function (context, settings, trigger) {
  72. * ...
  73. * }
  74. * };
  75. * @endcode
  76. *
  77. * Drupal.attachBehaviors is added below to the jQuery ready event and so
  78. * runs on initial page load. Developers implementing AHAH/Ajax in their
  79. * solutions should also call this function after new page content has been
  80. * loaded, feeding in an element to be processed, in order to attach all
  81. * behaviors to the new content.
  82. *
  83. * Behaviors should use
  84. * @code
  85. * $(selector).once('behavior-name', function () {
  86. * ...
  87. * });
  88. * @endcode
  89. * to ensure the behavior is attached only once to a given element. (Doing so
  90. * enables the reprocessing of given elements, which may be needed on occasion
  91. * despite the ability to limit behavior attachment to a particular element.)
  92. *
  93. * @param context
  94. * An element to attach behaviors to. If none is given, the document element
  95. * is used.
  96. * @param settings
  97. * An object containing settings for the current context. If none given, the
  98. * global Drupal.settings object is used.
  99. */
  100. Drupal.attachBehaviors = function (context, settings) {
  101. context = context || document;
  102. settings = settings || Drupal.settings;
  103. // Execute all of them.
  104. $.each(Drupal.behaviors, function () {
  105. if ($.isFunction(this.attach)) {
  106. this.attach(context, settings);
  107. }
  108. });
  109. };
  110. /**
  111. * Detach registered behaviors from a page element.
  112. *
  113. * Developers implementing AHAH/Ajax in their solutions should call this
  114. * function before page content is about to be removed, feeding in an element
  115. * to be processed, in order to allow special behaviors to detach from the
  116. * content.
  117. *
  118. * Such implementations should look for the class name that was added in their
  119. * corresponding Drupal.behaviors.behaviorName.attach implementation, i.e.
  120. * behaviorName-processed, to ensure the behavior is detached only from
  121. * previously processed elements.
  122. *
  123. * @param context
  124. * An element to detach behaviors from. If none is given, the document element
  125. * is used.
  126. * @param settings
  127. * An object containing settings for the current context. If none given, the
  128. * global Drupal.settings object is used.
  129. * @param trigger
  130. * A string containing what's causing the behaviors to be detached. The
  131. * possible triggers are:
  132. * - unload: (default) The context element is being removed from the DOM.
  133. * - move: The element is about to be moved within the DOM (for example,
  134. * during a tabledrag row swap). After the move is completed,
  135. * Drupal.attachBehaviors() is called, so that the behavior can undo
  136. * whatever it did in response to the move. Many behaviors won't need to
  137. * do anything simply in response to the element being moved, but because
  138. * IFRAME elements reload their "src" when being moved within the DOM,
  139. * behaviors bound to IFRAME elements (like WYSIWYG editors) may need to
  140. * take some action.
  141. * - serialize: When an Ajax form is submitted, this is called with the
  142. * form as the context. This provides every behavior within the form an
  143. * opportunity to ensure that the field elements have correct content
  144. * in them before the form is serialized. The canonical use-case is so
  145. * that WYSIWYG editors can update the hidden textarea to which they are
  146. * bound.
  147. *
  148. * @see Drupal.attachBehaviors
  149. */
  150. Drupal.detachBehaviors = function (context, settings, trigger) {
  151. context = context || document;
  152. settings = settings || Drupal.settings;
  153. trigger = trigger || 'unload';
  154. // Execute all of them.
  155. $.each(Drupal.behaviors, function () {
  156. if ($.isFunction(this.detach)) {
  157. this.detach(context, settings, trigger);
  158. }
  159. });
  160. };
  161. /**
  162. * Encode special characters in a plain-text string for display as HTML.
  163. *
  164. * @ingroup sanitization
  165. */
  166. Drupal.checkPlain = function (str) {
  167. var character, regex,
  168. replace = { '&': '&amp;', "'": '&#39;', '"': '&quot;', '<': '&lt;', '>': '&gt;' };
  169. str = String(str);
  170. for (character in replace) {
  171. if (replace.hasOwnProperty(character)) {
  172. regex = new RegExp(character, 'g');
  173. str = str.replace(regex, replace[character]);
  174. }
  175. }
  176. return str;
  177. };
  178. /**
  179. * Replace placeholders with sanitized values in a string.
  180. *
  181. * @param str
  182. * A string with placeholders.
  183. * @param args
  184. * An object of replacements pairs to make. Incidences of any key in this
  185. * array are replaced with the corresponding value. Based on the first
  186. * character of the key, the value is escaped and/or themed:
  187. * - !variable: inserted as is
  188. * - @variable: escape plain text to HTML (Drupal.checkPlain)
  189. * - %variable: escape text and theme as a placeholder for user-submitted
  190. * content (checkPlain + Drupal.theme('placeholder'))
  191. *
  192. * @see Drupal.t()
  193. * @ingroup sanitization
  194. */
  195. Drupal.formatString = function(str, args) {
  196. // Transform arguments before inserting them.
  197. for (var key in args) {
  198. if (args.hasOwnProperty(key)) {
  199. switch (key.charAt(0)) {
  200. // Escaped only.
  201. case '@':
  202. args[key] = Drupal.checkPlain(args[key]);
  203. break;
  204. // Pass-through.
  205. case '!':
  206. break;
  207. // Escaped and placeholder.
  208. default:
  209. args[key] = Drupal.theme('placeholder', args[key]);
  210. break;
  211. }
  212. }
  213. }
  214. return Drupal.stringReplace(str, args, null);
  215. };
  216. /**
  217. * Replace substring.
  218. *
  219. * The longest keys will be tried first. Once a substring has been replaced,
  220. * its new value will not be searched again.
  221. *
  222. * @param {String} str
  223. * A string with placeholders.
  224. * @param {Object} args
  225. * Key-value pairs.
  226. * @param {Array|null} keys
  227. * Array of keys from the "args". Internal use only.
  228. *
  229. * @return {String}
  230. * Returns the replaced string.
  231. */
  232. Drupal.stringReplace = function (str, args, keys) {
  233. if (str.length === 0) {
  234. return str;
  235. }
  236. // If the array of keys is not passed then collect the keys from the args.
  237. if (!$.isArray(keys)) {
  238. keys = [];
  239. for (var k in args) {
  240. if (args.hasOwnProperty(k)) {
  241. keys.push(k);
  242. }
  243. }
  244. // Order the keys by the character length. The shortest one is the first.
  245. keys.sort(function (a, b) { return a.length - b.length; });
  246. }
  247. if (keys.length === 0) {
  248. return str;
  249. }
  250. // Take next longest one from the end.
  251. var key = keys.pop();
  252. var fragments = str.split(key);
  253. if (keys.length) {
  254. for (var i = 0; i < fragments.length; i++) {
  255. // Process each fragment with a copy of remaining keys.
  256. fragments[i] = Drupal.stringReplace(fragments[i], args, keys.slice(0));
  257. }
  258. }
  259. return fragments.join(args[key]);
  260. };
  261. /**
  262. * Translate strings to the page language or a given language.
  263. *
  264. * See the documentation of the server-side t() function for further details.
  265. *
  266. * @param str
  267. * A string containing the English string to translate.
  268. * @param args
  269. * An object of replacements pairs to make after translation. Incidences
  270. * of any key in this array are replaced with the corresponding value.
  271. * See Drupal.formatString().
  272. *
  273. * @param options
  274. * - 'context' (defaults to the empty context): The context the source string
  275. * belongs to.
  276. *
  277. * @return
  278. * The translated string.
  279. */
  280. Drupal.t = function (str, args, options) {
  281. options = options || {};
  282. options.context = options.context || '';
  283. // Fetch the localized version of the string.
  284. if (Drupal.locale.strings && Drupal.locale.strings[options.context] && Drupal.locale.strings[options.context][str]) {
  285. str = Drupal.locale.strings[options.context][str];
  286. }
  287. if (args) {
  288. str = Drupal.formatString(str, args);
  289. }
  290. return str;
  291. };
  292. /**
  293. * Format a string containing a count of items.
  294. *
  295. * This function ensures that the string is pluralized correctly. Since Drupal.t() is
  296. * called by this function, make sure not to pass already-localized strings to it.
  297. *
  298. * See the documentation of the server-side format_plural() function for further details.
  299. *
  300. * @param count
  301. * The item count to display.
  302. * @param singular
  303. * The string for the singular case. Please make sure it is clear this is
  304. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  305. * Do not use @count in the singular string.
  306. * @param plural
  307. * The string for the plural case. Please make sure it is clear this is plural,
  308. * to ease translation. Use @count in place of the item count, as in "@count
  309. * new comments".
  310. * @param args
  311. * An object of replacements pairs to make after translation. Incidences
  312. * of any key in this array are replaced with the corresponding value.
  313. * See Drupal.formatString().
  314. * Note that you do not need to include @count in this array.
  315. * This replacement is done automatically for the plural case.
  316. * @param options
  317. * The options to pass to the Drupal.t() function.
  318. * @return
  319. * A translated string.
  320. */
  321. Drupal.formatPlural = function (count, singular, plural, args, options) {
  322. args = args || {};
  323. args['@count'] = count;
  324. // Determine the index of the plural form.
  325. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);
  326. if (index == 0) {
  327. return Drupal.t(singular, args, options);
  328. }
  329. else if (index == 1) {
  330. return Drupal.t(plural, args, options);
  331. }
  332. else {
  333. args['@count[' + index + ']'] = args['@count'];
  334. delete args['@count'];
  335. return Drupal.t(plural.replace('@count', '@count[' + index + ']'), args, options);
  336. }
  337. };
  338. /**
  339. * Returns the passed in URL as an absolute URL.
  340. *
  341. * @param url
  342. * The URL string to be normalized to an absolute URL.
  343. *
  344. * @return
  345. * The normalized, absolute URL.
  346. *
  347. * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
  348. * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
  349. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
  350. */
  351. Drupal.absoluteUrl = function (url) {
  352. var urlParsingNode = document.createElement('a');
  353. // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
  354. // strings may throw an exception.
  355. try {
  356. url = decodeURIComponent(url);
  357. } catch (e) {}
  358. urlParsingNode.setAttribute('href', url);
  359. // IE <= 7 normalizes the URL when assigned to the anchor node similar to
  360. // the other browsers.
  361. return urlParsingNode.cloneNode(false).href;
  362. };
  363. /**
  364. * Returns true if the URL is within Drupal's base path.
  365. *
  366. * @param url
  367. * The URL string to be tested.
  368. *
  369. * @return
  370. * Boolean true if local.
  371. *
  372. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
  373. */
  374. Drupal.urlIsLocal = function (url) {
  375. // Always use browser-derived absolute URLs in the comparison, to avoid
  376. // attempts to break out of the base path using directory traversal.
  377. var absoluteUrl = Drupal.absoluteUrl(url);
  378. var protocol = location.protocol;
  379. // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
  380. // as local as well.
  381. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
  382. protocol = 'https:';
  383. }
  384. var baseUrl = protocol + '//' + location.host + Drupal.settings.basePath.slice(0, -1);
  385. // Decoding non-UTF-8 strings may throw an exception.
  386. try {
  387. absoluteUrl = decodeURIComponent(absoluteUrl);
  388. } catch (e) {}
  389. try {
  390. baseUrl = decodeURIComponent(baseUrl);
  391. } catch (e) {}
  392. // The given URL matches the site's base URL, or has a path under the site's
  393. // base URL.
  394. return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
  395. };
  396. /**
  397. * Sanitizes a URL for use with jQuery.ajax().
  398. *
  399. * @param url
  400. * The URL string to be sanitized.
  401. *
  402. * @return
  403. * The sanitized URL.
  404. */
  405. Drupal.sanitizeAjaxUrl = function (url) {
  406. var regex = /\=\?(&|$)/;
  407. while (url.match(regex)) {
  408. url = url.replace(regex, '');
  409. }
  410. return url;
  411. }
  412. /**
  413. * Generate the themed representation of a Drupal object.
  414. *
  415. * All requests for themed output must go through this function. It examines
  416. * the request and routes it to the appropriate theme function. If the current
  417. * theme does not provide an override function, the generic theme function is
  418. * called.
  419. *
  420. * For example, to retrieve the HTML for text that should be emphasized and
  421. * displayed as a placeholder inside a sentence, call
  422. * Drupal.theme('placeholder', text).
  423. *
  424. * @param func
  425. * The name of the theme function to call.
  426. * @param ...
  427. * Additional arguments to pass along to the theme function.
  428. * @return
  429. * Any data the theme function returns. This could be a plain HTML string,
  430. * but also a complex object.
  431. */
  432. Drupal.theme = function (func) {
  433. var args = Array.prototype.slice.apply(arguments, [1]);
  434. return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
  435. };
  436. /**
  437. * Freeze the current body height (as minimum height). Used to prevent
  438. * unnecessary upwards scrolling when doing DOM manipulations.
  439. */
  440. Drupal.freezeHeight = function () {
  441. Drupal.unfreezeHeight();
  442. $('<div id="freeze-height"></div>').css({
  443. position: 'absolute',
  444. top: '0px',
  445. left: '0px',
  446. width: '1px',
  447. height: $('body').css('height')
  448. }).appendTo('body');
  449. };
  450. /**
  451. * Unfreeze the body height.
  452. */
  453. Drupal.unfreezeHeight = function () {
  454. $('#freeze-height').remove();
  455. };
  456. /**
  457. * Encodes a Drupal path for use in a URL.
  458. *
  459. * For aesthetic reasons slashes are not escaped.
  460. */
  461. Drupal.encodePath = function (item, uri) {
  462. uri = uri || location.href;
  463. return encodeURIComponent(item).replace(/%2F/g, '/');
  464. };
  465. /**
  466. * Get the text selection in a textarea.
  467. */
  468. Drupal.getSelection = function (element) {
  469. if (typeof element.selectionStart != 'number' && document.selection) {
  470. // The current selection.
  471. var range1 = document.selection.createRange();
  472. var range2 = range1.duplicate();
  473. // Select all text.
  474. range2.moveToElementText(element);
  475. // Now move 'dummy' end point to end point of original range.
  476. range2.setEndPoint('EndToEnd', range1);
  477. // Now we can calculate start and end points.
  478. var start = range2.text.length - range1.text.length;
  479. var end = start + range1.text.length;
  480. return { 'start': start, 'end': end };
  481. }
  482. return { 'start': element.selectionStart, 'end': element.selectionEnd };
  483. };
  484. /**
  485. * Add a global variable which determines if the window is being unloaded.
  486. *
  487. * This is primarily used by Drupal.displayAjaxError().
  488. */
  489. Drupal.beforeUnloadCalled = false;
  490. $(window).bind('beforeunload pagehide', function () {
  491. Drupal.beforeUnloadCalled = true;
  492. });
  493. /**
  494. * Displays a JavaScript error from an Ajax response when appropriate to do so.
  495. */
  496. Drupal.displayAjaxError = function (message) {
  497. // Skip displaying the message if the user deliberately aborted (for example,
  498. // by reloading the page or navigating to a different page) while the Ajax
  499. // request was still ongoing. See, for example, the discussion at
  500. // http://stackoverflow.com/questions/699941/handle-ajax-error-when-a-user-clicks-refresh.
  501. if (!Drupal.beforeUnloadCalled) {
  502. alert(message);
  503. }
  504. };
  505. /**
  506. * Build an error message from an Ajax response.
  507. */
  508. Drupal.ajaxError = function (xmlhttp, uri, customMessage) {
  509. var statusCode, statusText, pathText, responseText, readyStateText, message;
  510. if (xmlhttp.status) {
  511. statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status});
  512. }
  513. else {
  514. statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally.");
  515. }
  516. statusCode += "\n" + Drupal.t("Debugging information follows.");
  517. pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} );
  518. statusText = '';
  519. // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined.
  520. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that
  521. // and the test causes an exception. So we need to catch the exception here.
  522. try {
  523. statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)});
  524. }
  525. catch (e) {}
  526. responseText = '';
  527. // Again, we don't have a way to know for sure whether accessing
  528. // xmlhttp.responseText is going to throw an exception. So we'll catch it.
  529. try {
  530. responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } );
  531. } catch (e) {}
  532. // Make the responseText more readable by stripping HTML tags and newlines.
  533. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,"");
  534. responseText = responseText.replace(/[\n]+\s+/g,"\n");
  535. // We don't need readyState except for status == 0.
  536. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : "";
  537. // Additional message beyond what the xmlhttp object provides.
  538. customMessage = customMessage ? ("\n" + Drupal.t("CustomMessage: !customMessage", {'!customMessage': customMessage})) : "";
  539. message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
  540. return message;
  541. };
  542. // Class indicating that JS is enabled; used for styling purpose.
  543. $('html').addClass('js');
  544. // 'js enabled' cookie.
  545. document.cookie = 'has_js=1; path=/';
  546. /**
  547. * Additions to jQuery.support.
  548. */
  549. $(function () {
  550. /**
  551. * Boolean indicating whether or not position:fixed is supported.
  552. */
  553. if (jQuery.support.positionFixed === undefined) {
  554. var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body);
  555. jQuery.support.positionFixed = el[0].offsetTop === 10;
  556. el.remove();
  557. }
  558. });
  559. //Attach all behaviors.
  560. $(function () {
  561. Drupal.attachBehaviors(document, Drupal.settings);
  562. });
  563. /**
  564. * The default themes.
  565. */
  566. Drupal.theme.prototype = {
  567. /**
  568. * Formats text for emphasized display in a placeholder inside a sentence.
  569. *
  570. * @param str
  571. * The text to format (plain-text).
  572. * @return
  573. * The formatted text (html).
  574. */
  575. placeholder: function (str) {
  576. return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
  577. }
  578. };
  579. })(jQuery);