drupal.js 18 KB

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