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.
 
 
 

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