drupal.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. switch (key.charAt(0)) {
  164. // Escaped only.
  165. case '@':
  166. args[key] = Drupal.checkPlain(args[key]);
  167. break;
  168. // Pass-through.
  169. case '!':
  170. break;
  171. // Escaped and placeholder.
  172. case '%':
  173. default:
  174. args[key] = Drupal.theme('placeholder', args[key]);
  175. break;
  176. }
  177. str = str.replace(key, args[key]);
  178. }
  179. return str;
  180. };
  181. /**
  182. * Translate strings to the page language or a given language.
  183. *
  184. * See the documentation of the server-side t() function for further details.
  185. *
  186. * @param str
  187. * A string containing the English string to translate.
  188. * @param args
  189. * An object of replacements pairs to make after translation. Incidences
  190. * of any key in this array are replaced with the corresponding value.
  191. * See Drupal.formatString().
  192. *
  193. * @param options
  194. * - 'context' (defaults to the empty context): The context the source string
  195. * belongs to.
  196. *
  197. * @return
  198. * The translated string.
  199. */
  200. Drupal.t = function (str, args, options) {
  201. options = options || {};
  202. options.context = options.context || '';
  203. // Fetch the localized version of the string.
  204. if (Drupal.locale.strings && Drupal.locale.strings[options.context] && Drupal.locale.strings[options.context][str]) {
  205. str = Drupal.locale.strings[options.context][str];
  206. }
  207. if (args) {
  208. str = Drupal.formatString(str, args);
  209. }
  210. return str;
  211. };
  212. /**
  213. * Format a string containing a count of items.
  214. *
  215. * This function ensures that the string is pluralized correctly. Since Drupal.t() is
  216. * called by this function, make sure not to pass already-localized strings to it.
  217. *
  218. * See the documentation of the server-side format_plural() function for further details.
  219. *
  220. * @param count
  221. * The item count to display.
  222. * @param singular
  223. * The string for the singular case. Please make sure it is clear this is
  224. * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
  225. * Do not use @count in the singular string.
  226. * @param plural
  227. * The string for the plural case. Please make sure it is clear this is plural,
  228. * to ease translation. Use @count in place of the item count, as in "@count
  229. * new comments".
  230. * @param args
  231. * An object of replacements pairs to make after translation. Incidences
  232. * of any key in this array are replaced with the corresponding value.
  233. * See Drupal.formatString().
  234. * Note that you do not need to include @count in this array.
  235. * This replacement is done automatically for the plural case.
  236. * @param options
  237. * The options to pass to the Drupal.t() function.
  238. * @return
  239. * A translated string.
  240. */
  241. Drupal.formatPlural = function (count, singular, plural, args, options) {
  242. var args = args || {};
  243. args['@count'] = count;
  244. // Determine the index of the plural form.
  245. var index = Drupal.locale.pluralFormula ? Drupal.locale.pluralFormula(args['@count']) : ((args['@count'] == 1) ? 0 : 1);
  246. if (index == 0) {
  247. return Drupal.t(singular, args, options);
  248. }
  249. else if (index == 1) {
  250. return Drupal.t(plural, args, options);
  251. }
  252. else {
  253. args['@count[' + index + ']'] = args['@count'];
  254. delete args['@count'];
  255. return Drupal.t(plural.replace('@count', '@count[' + index + ']'), args, options);
  256. }
  257. };
  258. /**
  259. * Returns the passed in URL as an absolute URL.
  260. *
  261. * @param url
  262. * The URL string to be normalized to an absolute URL.
  263. *
  264. * @return
  265. * The normalized, absolute URL.
  266. *
  267. * @see https://github.com/angular/angular.js/blob/v1.4.4/src/ng/urlUtils.js
  268. * @see https://grack.com/blog/2009/11/17/absolutizing-url-in-javascript
  269. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L53
  270. */
  271. Drupal.absoluteUrl = function (url) {
  272. var urlParsingNode = document.createElement('a');
  273. // Decode the URL first; this is required by IE <= 6. Decoding non-UTF-8
  274. // strings may throw an exception.
  275. try {
  276. url = decodeURIComponent(url);
  277. } catch (e) {}
  278. urlParsingNode.setAttribute('href', url);
  279. // IE <= 7 normalizes the URL when assigned to the anchor node similar to
  280. // the other browsers.
  281. return urlParsingNode.cloneNode(false).href;
  282. };
  283. /**
  284. * Returns true if the URL is within Drupal's base path.
  285. *
  286. * @param url
  287. * The URL string to be tested.
  288. *
  289. * @return
  290. * Boolean true if local.
  291. *
  292. * @see https://github.com/jquery/jquery-ui/blob/1.11.4/ui/tabs.js#L58
  293. */
  294. Drupal.urlIsLocal = function (url) {
  295. // Always use browser-derived absolute URLs in the comparison, to avoid
  296. // attempts to break out of the base path using directory traversal.
  297. var absoluteUrl = Drupal.absoluteUrl(url);
  298. var protocol = location.protocol;
  299. // Consider URLs that match this site's base URL but use HTTPS instead of HTTP
  300. // as local as well.
  301. if (protocol === 'http:' && absoluteUrl.indexOf('https:') === 0) {
  302. protocol = 'https:';
  303. }
  304. var baseUrl = protocol + '//' + location.host + Drupal.settings.basePath.slice(0, -1);
  305. // Decoding non-UTF-8 strings may throw an exception.
  306. try {
  307. absoluteUrl = decodeURIComponent(absoluteUrl);
  308. } catch (e) {}
  309. try {
  310. baseUrl = decodeURIComponent(baseUrl);
  311. } catch (e) {}
  312. // The given URL matches the site's base URL, or has a path under the site's
  313. // base URL.
  314. return absoluteUrl === baseUrl || absoluteUrl.indexOf(baseUrl + '/') === 0;
  315. };
  316. /**
  317. * Generate the themed representation of a Drupal object.
  318. *
  319. * All requests for themed output must go through this function. It examines
  320. * the request and routes it to the appropriate theme function. If the current
  321. * theme does not provide an override function, the generic theme function is
  322. * called.
  323. *
  324. * For example, to retrieve the HTML for text that should be emphasized and
  325. * displayed as a placeholder inside a sentence, call
  326. * Drupal.theme('placeholder', text).
  327. *
  328. * @param func
  329. * The name of the theme function to call.
  330. * @param ...
  331. * Additional arguments to pass along to the theme function.
  332. * @return
  333. * Any data the theme function returns. This could be a plain HTML string,
  334. * but also a complex object.
  335. */
  336. Drupal.theme = function (func) {
  337. var args = Array.prototype.slice.apply(arguments, [1]);
  338. return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
  339. };
  340. /**
  341. * Freeze the current body height (as minimum height). Used to prevent
  342. * unnecessary upwards scrolling when doing DOM manipulations.
  343. */
  344. Drupal.freezeHeight = function () {
  345. Drupal.unfreezeHeight();
  346. $('<div id="freeze-height"></div>').css({
  347. position: 'absolute',
  348. top: '0px',
  349. left: '0px',
  350. width: '1px',
  351. height: $('body').css('height')
  352. }).appendTo('body');
  353. };
  354. /**
  355. * Unfreeze the body height.
  356. */
  357. Drupal.unfreezeHeight = function () {
  358. $('#freeze-height').remove();
  359. };
  360. /**
  361. * Encodes a Drupal path for use in a URL.
  362. *
  363. * For aesthetic reasons slashes are not escaped.
  364. */
  365. Drupal.encodePath = function (item, uri) {
  366. uri = uri || location.href;
  367. return encodeURIComponent(item).replace(/%2F/g, '/');
  368. };
  369. /**
  370. * Get the text selection in a textarea.
  371. */
  372. Drupal.getSelection = function (element) {
  373. if (typeof element.selectionStart != 'number' && document.selection) {
  374. // The current selection.
  375. var range1 = document.selection.createRange();
  376. var range2 = range1.duplicate();
  377. // Select all text.
  378. range2.moveToElementText(element);
  379. // Now move 'dummy' end point to end point of original range.
  380. range2.setEndPoint('EndToEnd', range1);
  381. // Now we can calculate start and end points.
  382. var start = range2.text.length - range1.text.length;
  383. var end = start + range1.text.length;
  384. return { 'start': start, 'end': end };
  385. }
  386. return { 'start': element.selectionStart, 'end': element.selectionEnd };
  387. };
  388. /**
  389. * Add a global variable which determines if the window is being unloaded.
  390. *
  391. * This is primarily used by Drupal.displayAjaxError().
  392. */
  393. Drupal.beforeUnloadCalled = false;
  394. $(window).bind('beforeunload pagehide', function () {
  395. Drupal.beforeUnloadCalled = true;
  396. });
  397. /**
  398. * Displays a JavaScript error from an Ajax response when appropriate to do so.
  399. */
  400. Drupal.displayAjaxError = function (message) {
  401. // Skip displaying the message if the user deliberately aborted (for example,
  402. // by reloading the page or navigating to a different page) while the Ajax
  403. // request was still ongoing. See, for example, the discussion at
  404. // http://stackoverflow.com/questions/699941/handle-ajax-error-when-a-user-clicks-refresh.
  405. if (!Drupal.beforeUnloadCalled) {
  406. alert(message);
  407. }
  408. };
  409. /**
  410. * Build an error message from an Ajax response.
  411. */
  412. Drupal.ajaxError = function (xmlhttp, uri, customMessage) {
  413. var statusCode, statusText, pathText, responseText, readyStateText, message;
  414. if (xmlhttp.status) {
  415. statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status});
  416. }
  417. else {
  418. statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally.");
  419. }
  420. statusCode += "\n" + Drupal.t("Debugging information follows.");
  421. pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} );
  422. statusText = '';
  423. // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined.
  424. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that
  425. // and the test causes an exception. So we need to catch the exception here.
  426. try {
  427. statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)});
  428. }
  429. catch (e) {}
  430. responseText = '';
  431. // Again, we don't have a way to know for sure whether accessing
  432. // xmlhttp.responseText is going to throw an exception. So we'll catch it.
  433. try {
  434. responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } );
  435. } catch (e) {}
  436. // Make the responseText more readable by stripping HTML tags and newlines.
  437. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,"");
  438. responseText = responseText.replace(/[\n]+\s+/g,"\n");
  439. // We don't need readyState except for status == 0.
  440. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : "";
  441. // Additional message beyond what the xmlhttp object provides.
  442. customMessage = customMessage ? ("\n" + Drupal.t("CustomMessage: !customMessage", {'!customMessage': customMessage})) : "";
  443. message = statusCode + pathText + statusText + customMessage + responseText + readyStateText;
  444. return message;
  445. };
  446. // Class indicating that JS is enabled; used for styling purpose.
  447. $('html').addClass('js');
  448. // 'js enabled' cookie.
  449. document.cookie = 'has_js=1; path=/';
  450. /**
  451. * Additions to jQuery.support.
  452. */
  453. $(function () {
  454. /**
  455. * Boolean indicating whether or not position:fixed is supported.
  456. */
  457. if (jQuery.support.positionFixed === undefined) {
  458. var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body);
  459. jQuery.support.positionFixed = el[0].offsetTop === 10;
  460. el.remove();
  461. }
  462. });
  463. //Attach all behaviors.
  464. $(function () {
  465. Drupal.attachBehaviors(document, Drupal.settings);
  466. });
  467. /**
  468. * The default themes.
  469. */
  470. Drupal.theme.prototype = {
  471. /**
  472. * Formats text for emphasized display in a placeholder inside a sentence.
  473. *
  474. * @param str
  475. * The text to format (plain-text).
  476. * @return
  477. * The formatted text (html).
  478. */
  479. placeholder: function (str) {
  480. return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
  481. }
  482. };
  483. })(jQuery);