A Wikipedia user script to automate common TfD operations
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

709 lines
23 KiB

  1. // Templates for discussion clerk script by [[User:The Earwig]]
  2. // Version: @TFDCLERK_VERSION_FULL@
  3. // Development and bug reports: https://github.com/earwig/tfdclerk
  4. // To install, add:
  5. // importScript("User:The Earwig/tfdclerk.js"); // [[User:The Earwig/tfdclerk.js]]
  6. // to [[Special:MyPage/common.js]] or [[Special:MyPage/skin.js]]
  7. /*
  8. Copyright (C) 2015 Ben Kurtovic <ben.kurtovic@gmail.com>
  9. Permission is hereby granted, free of charge, to any person obtaining a copy
  10. of this software and associated documentation files (the "Software"), to deal
  11. in the Software without restriction, including without limitation the rights to
  12. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  13. of the Software, and to permit persons to whom the Software is furnished to do
  14. so, subject to the following conditions:
  15. The above copyright notice and this permission notice shall be included in all
  16. copies or substantial portions of the Software.
  17. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. SOFTWARE.
  24. */
  25. // <nowiki>
  26. var dependencies = [
  27. "mediawiki.api",
  28. "mediawiki.ui",
  29. "mediawiki.util",
  30. "jquery.ui.core"
  31. ];
  32. var is_tfd_page = function() {
  33. return mw.config.get("wgAction") == "view" &&
  34. mw.config.get("wgIsProbablyEditable") == true &&
  35. mw.config.get("wgRevisionId") == mw.config.get("wgCurRevisionId") &&
  36. mw.config.get("wgNamespaceNumber") == 4 && (
  37. mw.config.get("wgTitle") == "Templates for discussion" ||
  38. mw.config.get("wgTitle").indexOf("Templates for discussion/Log/2") == 0);
  39. };
  40. if (is_tfd_page()) {
  41. mw.loader.using(dependencies, function() {
  42. /* Main script starts here */
  43. TFDClerk = {
  44. version: "@TFDCLERK_VERSION@",
  45. script_url: "https://en.wikipedia.org/wiki/User:The_Earwig/tfdclerk.js",
  46. author_url: "https://en.wikipedia.org/wiki/User_talk:The_Earwig",
  47. github_url: "https://github.com/earwig/tfdclerk",
  48. tfds: [],
  49. _api: new mw.Api(),
  50. _sysop: $.inArray("sysop", mw.config.get("wgUserGroups")) >= 0
  51. // TODO: access time?
  52. };
  53. TFD = function(id, head) {
  54. this.id = id;
  55. this.head = head;
  56. this.box = null;
  57. this._guard = false;
  58. this._submit_blockers = [];
  59. this._wikitext = undefined;
  60. this._wikitext_callbacks = [];
  61. };
  62. TFDClerk.api_get = function(tfd, params, done, fail, always) {
  63. TFDClerk._api.get(params)
  64. .done(function(data) {
  65. if (done)
  66. done.call(tfd, data);
  67. })
  68. .fail(function(error) {
  69. if (fail)
  70. fail.call(tfd, error);
  71. else
  72. tfd._error("API query failure", error);
  73. })
  74. .always(function() {
  75. if (always)
  76. always.call(tfd);
  77. });
  78. };
  79. TFDClerk.install = function() {
  80. $("h4").each(function(i, elem) {
  81. var head = $(elem);
  82. if (head.next().hasClass("tfd-closed"))
  83. return;
  84. if (head.find(".mw-editsection").length == 0)
  85. return;
  86. var tfd = new TFD(TFDClerk.tfds.length, head);
  87. TFDClerk.tfds.push(tfd);
  88. tfd.add_hooks();
  89. });
  90. };
  91. Date.prototype.toDatePickerFormat = function() {
  92. return this.toISOString().slice(0, 10);
  93. }
  94. Date.prototype.toLogDateFormat = function() {
  95. if (isNaN(this.valueOf()))
  96. return null;
  97. var months = [
  98. "January", "February", "March", "April", "May", "June", "July",
  99. "August", "September", "October", "November", "December"];
  100. var month = months[this.getUTCMonth()];
  101. return this.getUTCFullYear() + " " + month + " " + this.getUTCDate();
  102. }
  103. TFD.prototype._block_submit = function(reason) {
  104. if (this._submit_blockers.indexOf(reason) < 0)
  105. this._submit_blockers.push(reason);
  106. this.box.find(".tfdclerk-submit").prop("disabled", true);
  107. };
  108. TFD.prototype._unblock_submit = function(reason) {
  109. var index = this._submit_blockers.indexOf(reason);
  110. if (index >= 0)
  111. this._submit_blockers.splice(index, 1);
  112. if (this._submit_blockers.length == 0)
  113. this.box.find(".tfdclerk-submit").prop("disabled", false);
  114. };
  115. TFD.prototype._error = function(msg, extra) {
  116. var elem = $("<span/>", {
  117. html: "<strong>Error:</strong> " + (extra ? msg + ": " : msg),
  118. style: "color: #A00;"
  119. });
  120. if (extra)
  121. elem.append($("<span/>", {
  122. text: extra,
  123. style: "font-family: monospace;"
  124. }));
  125. var contact = $("<a/>", {
  126. href: TFDClerk.author_url,
  127. title: TFDClerk.author_url.split("/").pop().replace(/_/g, " "),
  128. text: "contact me"
  129. }), file_bug = $("<a/>", {
  130. href: TFDClerk.github_url,
  131. title: TFDClerk.github_url.split("/").splice(-2).join("/"),
  132. text: "file a bug report"
  133. });
  134. elem.append($("<br/>"))
  135. .append($("<small/>", {
  136. html: "This may be caused by an edit conflict or other " +
  137. "intermittent problem. Try refreshing the page. If the error " +
  138. "persists, you can " + contact.prop("outerHTML") + " or " +
  139. file_bug.prop("outerHTML") + "."
  140. }));
  141. elem.insertAfter(this.box.find("h5"));
  142. this._block_submit("error");
  143. };
  144. TFD.prototype._get_discussion_page = function() {
  145. var url = this.head.find(".mw-editsection a").first().prop("href");
  146. var match = url.match(/title=(.*?)(\&|$)/);
  147. return match ? match[1] : null;
  148. };
  149. TFD.prototype._get_section_number = function() {
  150. var url = this.head.find(".mw-editsection a").first().prop("href");
  151. var match = url.match(/section=(.*?)(\&|$)/);
  152. return match ? match[1] : null;
  153. };
  154. TFD.prototype._with_content = function(callback) {
  155. var title = this._get_discussion_page(),
  156. section = this._get_section_number();
  157. if (title === null || section === null)
  158. return this._error("couldn't find discussion section");
  159. if (this._wikitext !== undefined) {
  160. if (this._wikitext === null)
  161. this._wikitext_callbacks.push(callback);
  162. else
  163. callback.call(this, this._wikitext);
  164. return;
  165. }
  166. this._wikitext = null;
  167. TFDClerk.api_get(this, {
  168. action: "query",
  169. prop: "revisions",
  170. rvprop: "content",
  171. indexpageids: "",
  172. rvsection: section,
  173. titles: title
  174. }, function(data) {
  175. var pageid = data.query.pageids[0];
  176. var content = data.query.pages[pageid].revisions[0]["*"];
  177. this._wikitext = content;
  178. callback.call(this, content);
  179. for (var i in this._wikitext_callbacks)
  180. this._wikitext_callbacks[i].call(this, content);
  181. }, null, function() {
  182. this._wikitext_callbacks = [];
  183. });
  184. };
  185. TFD.prototype._remove_option_box = function() {
  186. this.box.remove();
  187. this.box = null;
  188. this._guard = false;
  189. this._submit_blockers = [];
  190. };
  191. TFD.prototype._add_option_box = function(verb, title, callback, options) {
  192. var self = this;
  193. this.box = $("<div/>", {
  194. id: "tfdclerk-" + verb + "-box-" + this.id,
  195. addClass: "tfdclerk-" + verb + "-box"
  196. })
  197. .css("position", "relative")
  198. .css("border", "1px solid #AAA")
  199. .css("color", "#000")
  200. .css("background-color", "#F9F9F9")
  201. .css("margin", "0.5em 0")
  202. .css("padding", "1em")
  203. .append($("<div/>")
  204. .css("position", "absolute")
  205. .css("right", "1em")
  206. .css("top", "0.5em")
  207. .css("font-size", "75%")
  208. .css("color", "#777")
  209. .append($("<a/>", {
  210. href: TFDClerk.script_url,
  211. title: "tfdclerk.js",
  212. text: "tfdclerk.js"
  213. }))
  214. .append($("<span/>", {text: " version " + TFDClerk.version})))
  215. .append($("<h5/>", {
  216. text: title,
  217. style: "margin: 0; padding: 0 0 0.25em 0;"
  218. }));
  219. options.call(this);
  220. this.box.append($("<button/>", {
  221. text: verb.charAt(0).toUpperCase() + verb.slice(1),
  222. addClass: "tfdclerk-submit mw-ui-button mw-ui-progressive",
  223. style: "margin-right: 0.5em;",
  224. disabled: this._submit_blockers.length > 0,
  225. click: function() {
  226. self._block_submit("submitting");
  227. self.box.find(".tfdclerk-cancel").prop("disabled", true);
  228. callback.call(self);
  229. }
  230. }))
  231. .append($("<button/>", {
  232. text: "Cancel",
  233. addClass: "tfdclerk-cancel mw-ui-button",
  234. click: function() { self._remove_option_box(); }
  235. }))
  236. .insertAfter(this.head);
  237. };
  238. TFD.prototype._add_option_table = function(options) {
  239. var table = $("<table/>", {style: "border-spacing: 0;"});
  240. $.each(options, function(i, opt) {
  241. table.append($("<tr/>")
  242. .append(
  243. $("<td/>", {
  244. style: "padding-bottom: 0.75em; padding-right: 0.5em;"
  245. }).append(opt[0]))
  246. .append(
  247. $("<td/>", {
  248. style: "padding-bottom: 0.75em;"
  249. }).append(opt[1]))
  250. );
  251. });
  252. this.box.append(table);
  253. };
  254. TFD.prototype._build_loading_node = function(node, text) {
  255. return $("<" + node + "/>", {
  256. text: text + "...",
  257. style: "font-style: italic; color: #777;"
  258. });
  259. };
  260. TFD.prototype._do_close = function() {
  261. // TODO
  262. // rough mockup:
  263. // - post-submit ui updates
  264. // - result options -> result string
  265. // - disable comments box
  266. // - collapse/disable/fix actions
  267. // - add progress info area
  268. // - "Closing discussion..."
  269. // - add discussion close tags with result and comment, optional nac
  270. // - " done ([[diff]])"
  271. // - interface for closing each template
  272. // - replace gray buttons with progressive refresh button
  273. };
  274. TFD.prototype._do_relist = function() {
  275. // TODO
  276. // rough mockup:
  277. // - post-submit ui updates
  278. // - date input box -> link to new discussion log page
  279. // - disable comments box
  280. // - add progress info area
  281. // - "Adding discussion to new date..."
  282. // - add discussion to new date, plus relist template
  283. // - " done ([[diff]])"
  284. // - "Removing discussion from old date..."
  285. // - replace contents of section with {{relisted}}
  286. // - " done ([[diff]])"
  287. // - "Updating discussion link on template(s):\n* [[Template:A]]..."
  288. // - update |link param of {{template for discussion}}
  289. // - " done ([[diff]])"
  290. // - replace gray buttons with progressive refresh button
  291. };
  292. TFD.prototype._is_merge = function() {
  293. return this.head.nextUntil("h4").filter("p").first().find("b")
  294. .text() == "Propose merging";
  295. };
  296. TFD.prototype._get_close_action_choices = function() {
  297. // TODO
  298. return [{
  299. id: "none",
  300. name: "Do nothing",
  301. help: "The script will not modify this template or pages related to " +
  302. "it. You will need to carry out the closure yourself.",
  303. on_select: null,
  304. on_close: null,
  305. default: true
  306. }, {
  307. id: "holding-cell",
  308. name: "Move to holding cell",
  309. help: "The script will add {{being deleted}} to the template and " +
  310. "add an entry to the holding cell ([[WP:TFD/H]]).",
  311. on_select: null,
  312. on_close: null
  313. }];
  314. };
  315. TFD.prototype._on_close_result_change = function() {
  316. this._unblock_submit("no-close-result");
  317. // TODO: possibly disable/enable individual close actions
  318. };
  319. TFD.prototype._build_close_results = function() {
  320. if (this._is_merge())
  321. var choices = ["Merge", "Do not merge", "No consensus", "Other"];
  322. else
  323. var choices = ["Delete", "Keep", "Redirect", "No consensus", "Other"];
  324. var self = this;
  325. var elems = $("<div/>");
  326. $("<label/>").append($("<input/>", {
  327. name: "result-speedy",
  328. type: "checkbox",
  329. value: "true"
  330. })).append($("<span/>", {
  331. text: "Speedy",
  332. style: "margin: 0 1.25em 0 0.25em;"
  333. })).appendTo(elems);
  334. $.each(choices, function(i, choice) {
  335. $("<label/>").append($("<input/>", {
  336. name: "result",
  337. type: "radio",
  338. value: choice.toLowerCase(),
  339. change: function() { self._on_close_result_change(); }
  340. })).append($("<span/>", {
  341. text: choice,
  342. style: "margin: 0 1.25em 0 0.25em;"
  343. })).appendTo(elems);
  344. });
  345. var other = elems.children().last();
  346. other.find("span").css("margin", "0 0.25em");
  347. other.append($("<input/>", {
  348. name: "result-other",
  349. type: "text"
  350. }));
  351. this._block_submit("no-close-result");
  352. return elems;
  353. };
  354. TFD.prototype._on_backlink_summary = function(page, tlinfo, ntrans, nmtrans,
  355. nlinks) {
  356. tlinfo.empty().append($("<li/>").append($("<a/>", {
  357. href: mw.util.getUrl("Special:WhatLinksHere/" + page, {
  358. namespace: "",
  359. hidelinks: 1,
  360. hideredirs: 1,
  361. hidetrans: 0
  362. }),
  363. title: "Transclusions of " + page,
  364. text: ntrans + " transclusions"
  365. })));
  366. if (ntrans != 0)
  367. tlinfo.append($("<li/>").append($("<a/>", {
  368. href: mw.util.getUrl("Special:WhatLinksHere/" + page, {
  369. namespace: 0,
  370. hidelinks: 1,
  371. hideredirs: 1,
  372. hidetrans: 0
  373. }),
  374. title: "Mainspace transclusions of " + page,
  375. text: nmtrans + " in mainspace"
  376. })));
  377. if (nlinks != 0)
  378. tlinfo.append($("<li/>").append($("<a/>", {
  379. href: mw.util.getUrl("Special:WhatLinksHere/" + page, {
  380. namespace: "",
  381. hidelinks: 0,
  382. hideredirs: 0,
  383. hidetrans: 1
  384. }),
  385. title: "Mainspace links to " + page,
  386. text: nlinks + " mainspace links"
  387. })));
  388. };
  389. TFD.prototype._load_backlink_summary = function(page, tlinfo) {
  390. var limit = TFDClerk._sysop ? 5000 : 500;
  391. TFDClerk.api_get(this, {
  392. action: "query",
  393. list: "embeddedin|backlinks",
  394. eititle: page,
  395. eilimit: limit,
  396. bltitle: page,
  397. blnamespace: "0|10",
  398. bllimit: limit,
  399. blredirect: ""
  400. }, function(data) {
  401. var ntrans = data.query.embeddedin.length;
  402. var nmtrans = data.query.embeddedin.filter(function(pg) {
  403. return pg.ns == 0;
  404. }).length;
  405. var nlinks = data.query.backlinks.reduce(function(acc, pg) {
  406. var c = 0;
  407. if (pg.ns == 0)
  408. c++;
  409. if (pg.redirlinks)
  410. c += pg.redirlinks.filter(function(rl) {
  411. return rl.ns == 0;
  412. }).length;
  413. return acc + c;
  414. }, 0);
  415. if (data["continue"]) {
  416. if (data["continue"].eicontinue) {
  417. ntrans += "+";
  418. nmtrans += "+";
  419. }
  420. if (data["continue"].blcontinue)
  421. nlinks += "+";
  422. }
  423. this._on_backlink_summary(page, tlinfo, ntrans, nmtrans, nlinks);
  424. });
  425. };
  426. TFD.prototype._build_close_action_entry = function(page) {
  427. var self = this;
  428. var redlink = this.head.nextUntil("h4").filter("ul").first()
  429. .find("a").filter(function() { return $(this).text() == page; })
  430. .hasClass("new");
  431. var tlinfo = $("<ul/>", {style: "display: inline;"})
  432. .append(this._build_loading_node("li", "Fetching transclusions"));
  433. this._load_backlink_summary(page, tlinfo);
  434. var select_extra = $("<span/>");
  435. var help = $("<abbr/>", {text: "?"});
  436. var select = $("<select/>", {
  437. disabled: redlink,
  438. change: function() {
  439. var option = select.find("option:selected");
  440. help.prop("title", option.data("help"));
  441. if (option.data("select"))
  442. option.data("select").call(self, select_extra);
  443. }
  444. });
  445. $.each(this._get_close_action_choices(), function(i, choice) {
  446. select.append($("<option/>", {
  447. value: choice.id,
  448. text: choice.name,
  449. selected: choice.default
  450. }).data({
  451. help: choice.help,
  452. select: choice.on_select,
  453. close: choice.on_close
  454. }));
  455. if (choice.default)
  456. help.prop("title", choice.help);
  457. });
  458. return $("<li/>").append($("<a/>", {
  459. href: mw.util.getUrl(page),
  460. title: page,
  461. text: page,
  462. addClass: redlink ? "new" : "",
  463. style: "font-weight: bold;"
  464. })).append($("<span/>", {text: ": "}))
  465. .append(select)
  466. .append(select_extra)
  467. .append($("<span/>", {text: " ("}))
  468. .append(help)
  469. .append($("<span/>", {text: ") ("}))
  470. .append($("<div/>", {addClass: "hlist", style: "display: inline;"})
  471. .append(tlinfo))
  472. .append($("<span/>", {text: ")"}));
  473. };
  474. TFD.prototype._add_close_actions = function() {
  475. this._block_submit("add-close-actions");
  476. this._with_content(function(content) {
  477. var regex = /\*\s*\{\{tfd links\|(.*?)(\||\}\})/gi,
  478. match = regex.exec(content);
  479. if (match === null)
  480. return this._error("no templates found in section");
  481. var list = $("<ul/>", {style: "margin: 0 0 0 1em;"});
  482. do {
  483. var page = "Template:" + match[1];
  484. this._build_close_action_entry(page).appendTo(list);
  485. } while ((match = regex.exec(content)) !== null);
  486. this.box.find(".tfdclerk-actions").empty().append(list);
  487. this._unblock_submit("add-close-actions");
  488. });
  489. };
  490. TFD.prototype._get_relist_date = function() {
  491. return new Date(this.box.find(".tfdclerk-date").val()).toLogDateFormat();
  492. };
  493. TFD.prototype._on_date_change = function() {
  494. var date = this._get_relist_date();
  495. var title = "Wikipedia:Templates for discussion/Log/" + date;
  496. var info = this.box.find(".tfdclerk-discussion-info");
  497. info.empty();
  498. if (mw.config.get("wgTitle") == "Templates for discussion")
  499. var this_date = this.head.prevAll().filter("h3").first().find("a")
  500. .prop("title").split("/Log/")[1];
  501. else
  502. var this_date = mw.config.get("wgTitle").split("/Log/")[1];
  503. if (date == null || date == this_date) {
  504. this._block_submit("bad-date");
  505. info.append($("<span/>", {
  506. text: date == this_date ? "Same as current date" : "Invalid date",
  507. style: "color: #A00;"
  508. }));
  509. return;
  510. }
  511. this._unblock_submit("bad-date");
  512. this._block_submit("checking-discussion");
  513. info.append(this._build_loading_node("span", "Checking discussion"));
  514. TFDClerk.api_get(this, {
  515. action: "query",
  516. indexpageids: "",
  517. titles: title
  518. }, function(data) {
  519. this._unblock_submit("checking-discussion");
  520. info.empty().append($("<span/>", {text: "Log: "})).append($("<a/>", {
  521. href: mw.util.getUrl(title),
  522. title: title,
  523. text: date,
  524. addClass: data.query.pageids[0] < 0 ? "new" : ""
  525. }));
  526. if (date == (new Date().toLogDateFormat()))
  527. info.append($("<span/>", {text: " (today)"}));
  528. });
  529. };
  530. TFD.prototype.close = function() {
  531. if (this._guard)
  532. return;
  533. this._guard = true;
  534. this._add_option_box("close", "Closing discussion", this._do_close,
  535. function() {
  536. this._add_option_table([
  537. [
  538. $("<span/>", {text: "Result:"}),
  539. this._build_close_results()
  540. ],
  541. [
  542. $("<label/>", {
  543. for: "tfdclerk-comments-" + this.id,
  544. text: "Comments:"
  545. }),
  546. $("<textarea/>", {
  547. id: "tfdclerk-comments-" + this.id,
  548. name: "comments",
  549. rows: 2,
  550. cols: 60,
  551. placeholder: "Optional. Do not sign."
  552. })
  553. ],
  554. [
  555. $("<span/>", {text: "Actions:"}),
  556. $("<div/>", {addClass: "tfdclerk-actions"})
  557. .append(this._build_loading_node("span", "Fetching")),
  558. ]
  559. ]);
  560. this._add_close_actions();
  561. });
  562. };
  563. TFD.prototype.relist = function() {
  564. var self = this;
  565. if (this._guard)
  566. return;
  567. this._guard = true;
  568. this._add_option_box("relist", "Relisting discussion", this._do_relist,
  569. function() {
  570. this._add_option_table([
  571. [
  572. $("<label/>", {
  573. for: "tfdclerk-date-" + this.id,
  574. text: "New date:"
  575. }),
  576. $("<input/>", {
  577. id: "tfdclerk-date-" + this.id,
  578. addClass: "tfdclerk-date",
  579. name: "date",
  580. type: "date",
  581. value: new Date().toDatePickerFormat(),
  582. change: function() { self._on_date_change(); }
  583. }).add($("<span/>", {
  584. addClass: "tfdclerk-discussion-info",
  585. style: "margin-left: 0.5em; vertical-align: middle;"
  586. }))
  587. ],
  588. [
  589. $("<label/>", {
  590. for: "tfdclerk-comments-" + this.id,
  591. text: "Comments:"
  592. }),
  593. $("<textarea/>", {
  594. id: "tfdclerk-comments-" + this.id,
  595. name: "comments",
  596. rows: 2,
  597. cols: 60,
  598. placeholder: "Optional. Do not sign."
  599. })
  600. ]
  601. ]);
  602. this._on_date_change();
  603. });
  604. };
  605. TFD.prototype._build_hook = function(verb, callback) {
  606. var self = this;
  607. return $("<span/>", {style: "margin-left: 1em;"})
  608. .append($("<span/>", {addClass: "mw-editsection-bracket", text: "["}))
  609. .append($("<a/>", {
  610. href: "#",
  611. text: verb,
  612. title: "tfdclerk: " + verb + " discussion",
  613. click: function() {
  614. callback.call(self);
  615. return false;
  616. }
  617. }))
  618. .append($("<span/>", {addClass: "mw-editsection-bracket", text: "]"}));
  619. };
  620. TFD.prototype.add_hooks = function() {
  621. $("<span/>", {addClass: "tfdclerk-hooks"})
  622. .append(this._build_hook("close", this.close))
  623. .append(this._build_hook("relist", this.relist))
  624. .appendTo(this.head.find(".mw-editsection"));
  625. };
  626. $(TFDClerk.install);
  627. /* Main script ends here */
  628. });
  629. }
  630. // </nowiki>