drupal.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. * Generate the themed representation of a Drupal object.
  260. *
  261. * All requests for themed output must go through this function. It examines
  262. * the request and routes it to the appropriate theme function. If the current
  263. * theme does not provide an override function, the generic theme function is
  264. * called.
  265. *
  266. * For example, to retrieve the HTML for text that should be emphasized and
  267. * displayed as a placeholder inside a sentence, call
  268. * Drupal.theme('placeholder', text).
  269. *
  270. * @param func
  271. * The name of the theme function to call.
  272. * @param ...
  273. * Additional arguments to pass along to the theme function.
  274. * @return
  275. * Any data the theme function returns. This could be a plain HTML string,
  276. * but also a complex object.
  277. */
  278. Drupal.theme = function (func) {
  279. var args = Array.prototype.slice.apply(arguments, [1]);
  280. return (Drupal.theme[func] || Drupal.theme.prototype[func]).apply(this, args);
  281. };
  282. /**
  283. * Freeze the current body height (as minimum height). Used to prevent
  284. * unnecessary upwards scrolling when doing DOM manipulations.
  285. */
  286. Drupal.freezeHeight = function () {
  287. Drupal.unfreezeHeight();
  288. $('<div id="freeze-height"></div>').css({
  289. position: 'absolute',
  290. top: '0px',
  291. left: '0px',
  292. width: '1px',
  293. height: $('body').css('height')
  294. }).appendTo('body');
  295. };
  296. /**
  297. * Unfreeze the body height.
  298. */
  299. Drupal.unfreezeHeight = function () {
  300. $('#freeze-height').remove();
  301. };
  302. /**
  303. * Encodes a Drupal path for use in a URL.
  304. *
  305. * For aesthetic reasons slashes are not escaped.
  306. */
  307. Drupal.encodePath = function (item, uri) {
  308. uri = uri || location.href;
  309. return encodeURIComponent(item).replace(/%2F/g, '/');
  310. };
  311. /**
  312. * Get the text selection in a textarea.
  313. */
  314. Drupal.getSelection = function (element) {
  315. if (typeof element.selectionStart != 'number' && document.selection) {
  316. // The current selection.
  317. var range1 = document.selection.createRange();
  318. var range2 = range1.duplicate();
  319. // Select all text.
  320. range2.moveToElementText(element);
  321. // Now move 'dummy' end point to end point of original range.
  322. range2.setEndPoint('EndToEnd', range1);
  323. // Now we can calculate start and end points.
  324. var start = range2.text.length - range1.text.length;
  325. var end = start + range1.text.length;
  326. return { 'start': start, 'end': end };
  327. }
  328. return { 'start': element.selectionStart, 'end': element.selectionEnd };
  329. };
  330. /**
  331. * Build an error message from an Ajax response.
  332. */
  333. Drupal.ajaxError = function (xmlhttp, uri) {
  334. var statusCode, statusText, pathText, responseText, readyStateText, message;
  335. if (xmlhttp.status) {
  336. statusCode = "\n" + Drupal.t("An AJAX HTTP error occurred.") + "\n" + Drupal.t("HTTP Result Code: !status", {'!status': xmlhttp.status});
  337. }
  338. else {
  339. statusCode = "\n" + Drupal.t("An AJAX HTTP request terminated abnormally.");
  340. }
  341. statusCode += "\n" + Drupal.t("Debugging information follows.");
  342. pathText = "\n" + Drupal.t("Path: !uri", {'!uri': uri} );
  343. statusText = '';
  344. // In some cases, when statusCode == 0, xmlhttp.statusText may not be defined.
  345. // Unfortunately, testing for it with typeof, etc, doesn't seem to catch that
  346. // and the test causes an exception. So we need to catch the exception here.
  347. try {
  348. statusText = "\n" + Drupal.t("StatusText: !statusText", {'!statusText': $.trim(xmlhttp.statusText)});
  349. }
  350. catch (e) {}
  351. responseText = '';
  352. // Again, we don't have a way to know for sure whether accessing
  353. // xmlhttp.responseText is going to throw an exception. So we'll catch it.
  354. try {
  355. responseText = "\n" + Drupal.t("ResponseText: !responseText", {'!responseText': $.trim(xmlhttp.responseText) } );
  356. } catch (e) {}
  357. // Make the responseText more readable by stripping HTML tags and newlines.
  358. responseText = responseText.replace(/<("[^"]*"|'[^']*'|[^'">])*>/gi,"");
  359. responseText = responseText.replace(/[\n]+\s+/g,"\n");
  360. // We don't need readyState except for status == 0.
  361. readyStateText = xmlhttp.status == 0 ? ("\n" + Drupal.t("ReadyState: !readyState", {'!readyState': xmlhttp.readyState})) : "";
  362. message = statusCode + pathText + statusText + responseText + readyStateText;
  363. return message;
  364. };
  365. // Class indicating that JS is enabled; used for styling purpose.
  366. $('html').addClass('js');
  367. // 'js enabled' cookie.
  368. document.cookie = 'has_js=1; path=/';
  369. /**
  370. * Additions to jQuery.support.
  371. */
  372. $(function () {
  373. /**
  374. * Boolean indicating whether or not position:fixed is supported.
  375. */
  376. if (jQuery.support.positionFixed === undefined) {
  377. var el = $('<div style="position:fixed; top:10px" />').appendTo(document.body);
  378. jQuery.support.positionFixed = el[0].offsetTop === 10;
  379. el.remove();
  380. }
  381. });
  382. //Attach all behaviors.
  383. $(function () {
  384. Drupal.attachBehaviors(document, Drupal.settings);
  385. });
  386. /**
  387. * The default themes.
  388. */
  389. Drupal.theme.prototype = {
  390. /**
  391. * Formats text for emphasized display in a placeholder inside a sentence.
  392. *
  393. * @param str
  394. * The text to format (plain-text).
  395. * @return
  396. * The formatted text (html).
  397. */
  398. placeholder: function (str) {
  399. return '<em class="placeholder">' + Drupal.checkPlain(str) + '</em>';
  400. }
  401. };
  402. })(jQuery);