ChangesListSpecialPage.php 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. <?php
  2. /**
  3. * Special page which uses a ChangesList to show query results.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. * @ingroup SpecialPage
  22. */
  23. use MediaWiki\Logger\LoggerFactory;
  24. use MediaWiki\MediaWikiServices;
  25. use Wikimedia\Rdbms\DBQueryTimeoutError;
  26. use Wikimedia\Rdbms\IResultWrapper;
  27. use Wikimedia\Rdbms\FakeResultWrapper;
  28. use Wikimedia\Rdbms\IDatabase;
  29. /**
  30. * Special page which uses a ChangesList to show query results.
  31. * @todo Way too many public functions, most of them should be protected
  32. *
  33. * @ingroup SpecialPage
  34. */
  35. abstract class ChangesListSpecialPage extends SpecialPage {
  36. /**
  37. * Maximum length of a tag description in UTF-8 characters.
  38. * Longer descriptions will be truncated.
  39. */
  40. const TAG_DESC_CHARACTER_LIMIT = 120;
  41. /**
  42. * Preference name for saved queries. Subclasses that use saved queries should override this.
  43. * @var string
  44. */
  45. protected static $savedQueriesPreferenceName;
  46. /**
  47. * Preference name for 'days'. Subclasses should override this.
  48. * @var string
  49. */
  50. protected static $daysPreferenceName;
  51. /**
  52. * Preference name for 'limit'. Subclasses should override this.
  53. * @var string
  54. */
  55. protected static $limitPreferenceName;
  56. /**
  57. * Preference name for collapsing the active filter display. Subclasses should override this.
  58. * @var string
  59. */
  60. protected static $collapsedPreferenceName;
  61. /** @var string */
  62. protected $rcSubpage;
  63. /** @var FormOptions */
  64. protected $rcOptions;
  65. // Order of both groups and filters is significant; first is top-most priority,
  66. // descending from there.
  67. // 'showHideSuffix' is a shortcut to and avoid spelling out
  68. // details specific to subclasses here.
  69. /**
  70. * Definition information for the filters and their groups
  71. *
  72. * The value is $groupDefinition, a parameter to the ChangesListFilterGroup constructor.
  73. * However, priority is dynamically added for the core groups, to ease maintenance.
  74. *
  75. * Groups are displayed to the user in the structured UI. However, if necessary,
  76. * all of the filters in a group can be configured to only display on the
  77. * unstuctured UI, in which case you don't need a group title.
  78. *
  79. * @var array $filterGroupDefinitions
  80. */
  81. private $filterGroupDefinitions;
  82. // Same format as filterGroupDefinitions, but for a single group (reviewStatus)
  83. // that is registered conditionally.
  84. private $legacyReviewStatusFilterGroupDefinition;
  85. // Single filter group registered conditionally
  86. private $reviewStatusFilterGroupDefinition;
  87. // Single filter group registered conditionally
  88. private $hideCategorizationFilterDefinition;
  89. /**
  90. * Filter groups, and their contained filters
  91. * This is an associative array (with group name as key) of ChangesListFilterGroup objects.
  92. *
  93. * @var array $filterGroups
  94. */
  95. protected $filterGroups = [];
  96. public function __construct( $name, $restriction ) {
  97. parent::__construct( $name, $restriction );
  98. $nonRevisionTypes = [ RC_LOG ];
  99. Hooks::run( 'SpecialWatchlistGetNonRevisionTypes', [ &$nonRevisionTypes ] );
  100. $this->filterGroupDefinitions = [
  101. [
  102. 'name' => 'registration',
  103. 'title' => 'rcfilters-filtergroup-registration',
  104. 'class' => ChangesListBooleanFilterGroup::class,
  105. 'filters' => [
  106. [
  107. 'name' => 'hideliu',
  108. // rcshowhideliu-show, rcshowhideliu-hide,
  109. // wlshowhideliu
  110. 'showHideSuffix' => 'showhideliu',
  111. 'default' => false,
  112. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  113. &$query_options, &$join_conds
  114. ) {
  115. $actorMigration = ActorMigration::newMigration();
  116. $actorQuery = $actorMigration->getJoin( 'rc_user' );
  117. $tables += $actorQuery['tables'];
  118. $join_conds += $actorQuery['joins'];
  119. $conds[] = $actorMigration->isAnon( $actorQuery['fields']['rc_user'] );
  120. },
  121. 'isReplacedInStructuredUi' => true,
  122. ],
  123. [
  124. 'name' => 'hideanons',
  125. // rcshowhideanons-show, rcshowhideanons-hide,
  126. // wlshowhideanons
  127. 'showHideSuffix' => 'showhideanons',
  128. 'default' => false,
  129. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  130. &$query_options, &$join_conds
  131. ) {
  132. $actorMigration = ActorMigration::newMigration();
  133. $actorQuery = $actorMigration->getJoin( 'rc_user' );
  134. $tables += $actorQuery['tables'];
  135. $join_conds += $actorQuery['joins'];
  136. $conds[] = $actorMigration->isNotAnon( $actorQuery['fields']['rc_user'] );
  137. },
  138. 'isReplacedInStructuredUi' => true,
  139. ]
  140. ],
  141. ],
  142. [
  143. 'name' => 'userExpLevel',
  144. 'title' => 'rcfilters-filtergroup-user-experience-level',
  145. 'class' => ChangesListStringOptionsFilterGroup::class,
  146. 'isFullCoverage' => true,
  147. 'filters' => [
  148. [
  149. 'name' => 'unregistered',
  150. 'label' => 'rcfilters-filter-user-experience-level-unregistered-label',
  151. 'description' => 'rcfilters-filter-user-experience-level-unregistered-description',
  152. 'cssClassSuffix' => 'user-unregistered',
  153. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  154. return !$rc->getAttribute( 'rc_user' );
  155. }
  156. ],
  157. [
  158. 'name' => 'registered',
  159. 'label' => 'rcfilters-filter-user-experience-level-registered-label',
  160. 'description' => 'rcfilters-filter-user-experience-level-registered-description',
  161. 'cssClassSuffix' => 'user-registered',
  162. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  163. return $rc->getAttribute( 'rc_user' );
  164. }
  165. ],
  166. [
  167. 'name' => 'newcomer',
  168. 'label' => 'rcfilters-filter-user-experience-level-newcomer-label',
  169. 'description' => 'rcfilters-filter-user-experience-level-newcomer-description',
  170. 'cssClassSuffix' => 'user-newcomer',
  171. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  172. $performer = $rc->getPerformer();
  173. return $performer && $performer->isLoggedIn() &&
  174. $performer->getExperienceLevel() === 'newcomer';
  175. }
  176. ],
  177. [
  178. 'name' => 'learner',
  179. 'label' => 'rcfilters-filter-user-experience-level-learner-label',
  180. 'description' => 'rcfilters-filter-user-experience-level-learner-description',
  181. 'cssClassSuffix' => 'user-learner',
  182. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  183. $performer = $rc->getPerformer();
  184. return $performer && $performer->isLoggedIn() &&
  185. $performer->getExperienceLevel() === 'learner';
  186. },
  187. ],
  188. [
  189. 'name' => 'experienced',
  190. 'label' => 'rcfilters-filter-user-experience-level-experienced-label',
  191. 'description' => 'rcfilters-filter-user-experience-level-experienced-description',
  192. 'cssClassSuffix' => 'user-experienced',
  193. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  194. $performer = $rc->getPerformer();
  195. return $performer && $performer->isLoggedIn() &&
  196. $performer->getExperienceLevel() === 'experienced';
  197. },
  198. ]
  199. ],
  200. 'default' => ChangesListStringOptionsFilterGroup::NONE,
  201. 'queryCallable' => [ $this, 'filterOnUserExperienceLevel' ],
  202. ],
  203. [
  204. 'name' => 'authorship',
  205. 'title' => 'rcfilters-filtergroup-authorship',
  206. 'class' => ChangesListBooleanFilterGroup::class,
  207. 'filters' => [
  208. [
  209. 'name' => 'hidemyself',
  210. 'label' => 'rcfilters-filter-editsbyself-label',
  211. 'description' => 'rcfilters-filter-editsbyself-description',
  212. // rcshowhidemine-show, rcshowhidemine-hide,
  213. // wlshowhidemine
  214. 'showHideSuffix' => 'showhidemine',
  215. 'default' => false,
  216. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  217. &$query_options, &$join_conds
  218. ) {
  219. $actorQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $ctx->getUser() );
  220. $tables += $actorQuery['tables'];
  221. $join_conds += $actorQuery['joins'];
  222. $conds[] = 'NOT(' . $actorQuery['conds'] . ')';
  223. },
  224. 'cssClassSuffix' => 'self',
  225. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  226. return $ctx->getUser()->equals( $rc->getPerformer() );
  227. },
  228. ],
  229. [
  230. 'name' => 'hidebyothers',
  231. 'label' => 'rcfilters-filter-editsbyother-label',
  232. 'description' => 'rcfilters-filter-editsbyother-description',
  233. 'default' => false,
  234. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  235. &$query_options, &$join_conds
  236. ) {
  237. $actorQuery = ActorMigration::newMigration()
  238. ->getWhere( $dbr, 'rc_user', $ctx->getUser(), false );
  239. $tables += $actorQuery['tables'];
  240. $join_conds += $actorQuery['joins'];
  241. $conds[] = $actorQuery['conds'];
  242. },
  243. 'cssClassSuffix' => 'others',
  244. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  245. return !$ctx->getUser()->equals( $rc->getPerformer() );
  246. },
  247. ]
  248. ]
  249. ],
  250. [
  251. 'name' => 'automated',
  252. 'title' => 'rcfilters-filtergroup-automated',
  253. 'class' => ChangesListBooleanFilterGroup::class,
  254. 'filters' => [
  255. [
  256. 'name' => 'hidebots',
  257. 'label' => 'rcfilters-filter-bots-label',
  258. 'description' => 'rcfilters-filter-bots-description',
  259. // rcshowhidebots-show, rcshowhidebots-hide,
  260. // wlshowhidebots
  261. 'showHideSuffix' => 'showhidebots',
  262. 'default' => false,
  263. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  264. &$query_options, &$join_conds
  265. ) {
  266. $conds['rc_bot'] = 0;
  267. },
  268. 'cssClassSuffix' => 'bot',
  269. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  270. return $rc->getAttribute( 'rc_bot' );
  271. },
  272. ],
  273. [
  274. 'name' => 'hidehumans',
  275. 'label' => 'rcfilters-filter-humans-label',
  276. 'description' => 'rcfilters-filter-humans-description',
  277. 'default' => false,
  278. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  279. &$query_options, &$join_conds
  280. ) {
  281. $conds['rc_bot'] = 1;
  282. },
  283. 'cssClassSuffix' => 'human',
  284. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  285. return !$rc->getAttribute( 'rc_bot' );
  286. },
  287. ]
  288. ]
  289. ],
  290. // significance (conditional)
  291. [
  292. 'name' => 'significance',
  293. 'title' => 'rcfilters-filtergroup-significance',
  294. 'class' => ChangesListBooleanFilterGroup::class,
  295. 'priority' => -6,
  296. 'filters' => [
  297. [
  298. 'name' => 'hideminor',
  299. 'label' => 'rcfilters-filter-minor-label',
  300. 'description' => 'rcfilters-filter-minor-description',
  301. // rcshowhideminor-show, rcshowhideminor-hide,
  302. // wlshowhideminor
  303. 'showHideSuffix' => 'showhideminor',
  304. 'default' => false,
  305. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  306. &$query_options, &$join_conds
  307. ) {
  308. $conds[] = 'rc_minor = 0';
  309. },
  310. 'cssClassSuffix' => 'minor',
  311. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  312. return $rc->getAttribute( 'rc_minor' );
  313. }
  314. ],
  315. [
  316. 'name' => 'hidemajor',
  317. 'label' => 'rcfilters-filter-major-label',
  318. 'description' => 'rcfilters-filter-major-description',
  319. 'default' => false,
  320. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  321. &$query_options, &$join_conds
  322. ) {
  323. $conds[] = 'rc_minor = 1';
  324. },
  325. 'cssClassSuffix' => 'major',
  326. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  327. return !$rc->getAttribute( 'rc_minor' );
  328. }
  329. ]
  330. ]
  331. ],
  332. [
  333. 'name' => 'lastRevision',
  334. 'title' => 'rcfilters-filtergroup-lastrevision',
  335. 'class' => ChangesListBooleanFilterGroup::class,
  336. 'priority' => -7,
  337. 'filters' => [
  338. [
  339. 'name' => 'hidelastrevision',
  340. 'label' => 'rcfilters-filter-lastrevision-label',
  341. 'description' => 'rcfilters-filter-lastrevision-description',
  342. 'default' => false,
  343. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  344. &$query_options, &$join_conds ) use ( $nonRevisionTypes ) {
  345. $conds[] = $dbr->makeList(
  346. [
  347. 'rc_this_oldid <> page_latest',
  348. 'rc_type' => $nonRevisionTypes,
  349. ],
  350. LIST_OR
  351. );
  352. },
  353. 'cssClassSuffix' => 'last',
  354. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  355. return $rc->getAttribute( 'rc_this_oldid' ) === $rc->getAttribute( 'page_latest' );
  356. }
  357. ],
  358. [
  359. 'name' => 'hidepreviousrevisions',
  360. 'label' => 'rcfilters-filter-previousrevision-label',
  361. 'description' => 'rcfilters-filter-previousrevision-description',
  362. 'default' => false,
  363. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  364. &$query_options, &$join_conds ) use ( $nonRevisionTypes ) {
  365. $conds[] = $dbr->makeList(
  366. [
  367. 'rc_this_oldid = page_latest',
  368. 'rc_type' => $nonRevisionTypes,
  369. ],
  370. LIST_OR
  371. );
  372. },
  373. 'cssClassSuffix' => 'previous',
  374. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  375. return $rc->getAttribute( 'rc_this_oldid' ) !== $rc->getAttribute( 'page_latest' );
  376. }
  377. ]
  378. ]
  379. ],
  380. // With extensions, there can be change types that will not be hidden by any of these.
  381. [
  382. 'name' => 'changeType',
  383. 'title' => 'rcfilters-filtergroup-changetype',
  384. 'class' => ChangesListBooleanFilterGroup::class,
  385. 'priority' => -8,
  386. 'filters' => [
  387. [
  388. 'name' => 'hidepageedits',
  389. 'label' => 'rcfilters-filter-pageedits-label',
  390. 'description' => 'rcfilters-filter-pageedits-description',
  391. 'default' => false,
  392. 'priority' => -2,
  393. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  394. &$query_options, &$join_conds
  395. ) {
  396. $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_EDIT );
  397. },
  398. 'cssClassSuffix' => 'src-mw-edit',
  399. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  400. return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_EDIT;
  401. },
  402. ],
  403. [
  404. 'name' => 'hidenewpages',
  405. 'label' => 'rcfilters-filter-newpages-label',
  406. 'description' => 'rcfilters-filter-newpages-description',
  407. 'default' => false,
  408. 'priority' => -3,
  409. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  410. &$query_options, &$join_conds
  411. ) {
  412. $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_NEW );
  413. },
  414. 'cssClassSuffix' => 'src-mw-new',
  415. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  416. return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_NEW;
  417. },
  418. ],
  419. // hidecategorization
  420. [
  421. 'name' => 'hidelog',
  422. 'label' => 'rcfilters-filter-logactions-label',
  423. 'description' => 'rcfilters-filter-logactions-description',
  424. 'default' => false,
  425. 'priority' => -5,
  426. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  427. &$query_options, &$join_conds
  428. ) {
  429. $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_LOG );
  430. },
  431. 'cssClassSuffix' => 'src-mw-log',
  432. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  433. return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_LOG;
  434. }
  435. ],
  436. ],
  437. ],
  438. ];
  439. $this->legacyReviewStatusFilterGroupDefinition = [
  440. [
  441. 'name' => 'legacyReviewStatus',
  442. 'title' => 'rcfilters-filtergroup-reviewstatus',
  443. 'class' => ChangesListBooleanFilterGroup::class,
  444. 'filters' => [
  445. [
  446. 'name' => 'hidepatrolled',
  447. // rcshowhidepatr-show, rcshowhidepatr-hide
  448. // wlshowhidepatr
  449. 'showHideSuffix' => 'showhidepatr',
  450. 'default' => false,
  451. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  452. &$query_options, &$join_conds
  453. ) {
  454. $conds['rc_patrolled'] = RecentChange::PRC_UNPATROLLED;
  455. },
  456. 'isReplacedInStructuredUi' => true,
  457. ],
  458. [
  459. 'name' => 'hideunpatrolled',
  460. 'default' => false,
  461. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  462. &$query_options, &$join_conds
  463. ) {
  464. $conds[] = 'rc_patrolled != ' . RecentChange::PRC_UNPATROLLED;
  465. },
  466. 'isReplacedInStructuredUi' => true,
  467. ],
  468. ],
  469. ]
  470. ];
  471. $this->reviewStatusFilterGroupDefinition = [
  472. [
  473. 'name' => 'reviewStatus',
  474. 'title' => 'rcfilters-filtergroup-reviewstatus',
  475. 'class' => ChangesListStringOptionsFilterGroup::class,
  476. 'isFullCoverage' => true,
  477. 'priority' => -5,
  478. 'filters' => [
  479. [
  480. 'name' => 'unpatrolled',
  481. 'label' => 'rcfilters-filter-reviewstatus-unpatrolled-label',
  482. 'description' => 'rcfilters-filter-reviewstatus-unpatrolled-description',
  483. 'cssClassSuffix' => 'reviewstatus-unpatrolled',
  484. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  485. return $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_UNPATROLLED;
  486. },
  487. ],
  488. [
  489. 'name' => 'manual',
  490. 'label' => 'rcfilters-filter-reviewstatus-manual-label',
  491. 'description' => 'rcfilters-filter-reviewstatus-manual-description',
  492. 'cssClassSuffix' => 'reviewstatus-manual',
  493. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  494. return $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_PATROLLED;
  495. },
  496. ],
  497. [
  498. 'name' => 'auto',
  499. 'label' => 'rcfilters-filter-reviewstatus-auto-label',
  500. 'description' => 'rcfilters-filter-reviewstatus-auto-description',
  501. 'cssClassSuffix' => 'reviewstatus-auto',
  502. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  503. return $rc->getAttribute( 'rc_patrolled' ) == RecentChange::PRC_AUTOPATROLLED;
  504. },
  505. ],
  506. ],
  507. 'default' => ChangesListStringOptionsFilterGroup::NONE,
  508. 'queryCallable' => function ( $specialPageClassName, $ctx, $dbr,
  509. &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selected
  510. ) {
  511. if ( $selected === [] ) {
  512. return;
  513. }
  514. $rcPatrolledValues = [
  515. 'unpatrolled' => RecentChange::PRC_UNPATROLLED,
  516. 'manual' => RecentChange::PRC_PATROLLED,
  517. 'auto' => RecentChange::PRC_AUTOPATROLLED,
  518. ];
  519. // e.g. rc_patrolled IN (0, 2)
  520. $conds['rc_patrolled'] = array_map( function ( $s ) use ( $rcPatrolledValues ) {
  521. return $rcPatrolledValues[ $s ];
  522. }, $selected );
  523. }
  524. ]
  525. ];
  526. $this->hideCategorizationFilterDefinition = [
  527. 'name' => 'hidecategorization',
  528. 'label' => 'rcfilters-filter-categorization-label',
  529. 'description' => 'rcfilters-filter-categorization-description',
  530. // rcshowhidecategorization-show, rcshowhidecategorization-hide.
  531. // wlshowhidecategorization
  532. 'showHideSuffix' => 'showhidecategorization',
  533. 'default' => false,
  534. 'priority' => -4,
  535. 'queryCallable' => function ( $specialClassName, $ctx, $dbr, &$tables, &$fields, &$conds,
  536. &$query_options, &$join_conds
  537. ) {
  538. $conds[] = 'rc_type != ' . $dbr->addQuotes( RC_CATEGORIZE );
  539. },
  540. 'cssClassSuffix' => 'src-mw-categorize',
  541. 'isRowApplicableCallable' => function ( $ctx, $rc ) {
  542. return $rc->getAttribute( 'rc_source' ) === RecentChange::SRC_CATEGORIZE;
  543. },
  544. ];
  545. }
  546. /**
  547. * Check if filters are in conflict and guaranteed to return no results.
  548. *
  549. * @return bool
  550. */
  551. protected function areFiltersInConflict() {
  552. $opts = $this->getOptions();
  553. /** @var ChangesListFilterGroup $group */
  554. foreach ( $this->getFilterGroups() as $group ) {
  555. if ( $group->getConflictingGroups() ) {
  556. wfLogWarning(
  557. $group->getName() .
  558. " specifies conflicts with other groups but these are not supported yet."
  559. );
  560. }
  561. /** @var ChangesListFilter $conflictingFilter */
  562. foreach ( $group->getConflictingFilters() as $conflictingFilter ) {
  563. if ( $conflictingFilter->activelyInConflictWithGroup( $group, $opts ) ) {
  564. return true;
  565. }
  566. }
  567. /** @var ChangesListFilter $filter */
  568. foreach ( $group->getFilters() as $filter ) {
  569. /** @var ChangesListFilter $conflictingFilter */
  570. foreach ( $filter->getConflictingFilters() as $conflictingFilter ) {
  571. if (
  572. $conflictingFilter->activelyInConflictWithFilter( $filter, $opts ) &&
  573. $filter->activelyInConflictWithFilter( $conflictingFilter, $opts )
  574. ) {
  575. return true;
  576. }
  577. }
  578. }
  579. }
  580. return false;
  581. }
  582. /**
  583. * @param string|null $subpage
  584. */
  585. public function execute( $subpage ) {
  586. $this->rcSubpage = $subpage;
  587. $this->considerActionsForDefaultSavedQuery( $subpage );
  588. $opts = $this->getOptions();
  589. try {
  590. $rows = $this->getRows();
  591. if ( $rows === false ) {
  592. $rows = new FakeResultWrapper( [] );
  593. }
  594. // Used by Structured UI app to get results without MW chrome
  595. if ( $this->getRequest()->getVal( 'action' ) === 'render' ) {
  596. $this->getOutput()->setArticleBodyOnly( true );
  597. }
  598. // Used by "live update" and "view newest" to check
  599. // if there's new changes with minimal data transfer
  600. if ( $this->getRequest()->getBool( 'peek' ) ) {
  601. $code = $rows->numRows() > 0 ? 200 : 204;
  602. $this->getOutput()->setStatusCode( $code );
  603. if ( $this->getUser()->isAnon() !==
  604. $this->getRequest()->getFuzzyBool( 'isAnon' )
  605. ) {
  606. $this->getOutput()->setStatusCode( 205 );
  607. }
  608. return;
  609. }
  610. $batch = new LinkBatch;
  611. foreach ( $rows as $row ) {
  612. $batch->add( NS_USER, $row->rc_user_text );
  613. $batch->add( NS_USER_TALK, $row->rc_user_text );
  614. $batch->add( $row->rc_namespace, $row->rc_title );
  615. if ( $row->rc_source === RecentChange::SRC_LOG ) {
  616. $formatter = LogFormatter::newFromRow( $row );
  617. foreach ( $formatter->getPreloadTitles() as $title ) {
  618. $batch->addObj( $title );
  619. }
  620. }
  621. }
  622. $batch->execute();
  623. $this->setHeaders();
  624. $this->outputHeader();
  625. $this->addModules();
  626. $this->webOutput( $rows, $opts );
  627. $rows->free();
  628. } catch ( DBQueryTimeoutError $timeoutException ) {
  629. MWExceptionHandler::logException( $timeoutException );
  630. $this->setHeaders();
  631. $this->outputHeader();
  632. $this->addModules();
  633. $this->getOutput()->setStatusCode( 500 );
  634. $this->webOutputHeader( 0, $opts );
  635. $this->outputTimeout();
  636. }
  637. if ( $this->getConfig()->get( 'EnableWANCacheReaper' ) ) {
  638. // Clean up any bad page entries for titles showing up in RC
  639. DeferredUpdates::addUpdate( new WANCacheReapUpdate(
  640. $this->getDB(),
  641. LoggerFactory::getInstance( 'objectcache' )
  642. ) );
  643. }
  644. $this->includeRcFiltersApp();
  645. }
  646. /**
  647. * Check whether or not the page should load defaults, and if so, whether
  648. * a default saved query is relevant to be redirected to. If it is relevant,
  649. * redirect properly with all necessary query parameters.
  650. *
  651. * @param string $subpage
  652. */
  653. protected function considerActionsForDefaultSavedQuery( $subpage ) {
  654. if ( !$this->isStructuredFilterUiEnabled() || $this->including() ) {
  655. return;
  656. }
  657. $knownParams = $this->getRequest()->getValues(
  658. ...array_keys( $this->getOptions()->getAllValues() )
  659. );
  660. // HACK: Temporarily until we can properly define "sticky" filters and parameters,
  661. // we need to exclude several parameters we know should not be counted towards preventing
  662. // the loading of defaults.
  663. $excludedParams = [ 'limit' => '', 'days' => '', 'enhanced' => '', 'from' => '' ];
  664. $knownParams = array_diff_key( $knownParams, $excludedParams );
  665. if (
  666. // If there are NO known parameters in the URL request
  667. // (that are not excluded) then we need to check into loading
  668. // the default saved query
  669. count( $knownParams ) === 0
  670. ) {
  671. // Get the saved queries data and parse it
  672. $savedQueries = FormatJson::decode(
  673. $this->getUser()->getOption( static::$savedQueriesPreferenceName ),
  674. true
  675. );
  676. if ( $savedQueries && isset( $savedQueries[ 'default' ] ) ) {
  677. // Only load queries that are 'version' 2, since those
  678. // have parameter representation
  679. if ( isset( $savedQueries[ 'version' ] ) && $savedQueries[ 'version' ] === '2' ) {
  680. $savedQueryDefaultID = $savedQueries[ 'default' ];
  681. $defaultQuery = $savedQueries[ 'queries' ][ $savedQueryDefaultID ][ 'data' ];
  682. // Build the entire parameter list
  683. $query = array_merge(
  684. $defaultQuery[ 'params' ],
  685. $defaultQuery[ 'highlights' ],
  686. [
  687. 'urlversion' => '2',
  688. ]
  689. );
  690. // Add to the query any parameters that we may have ignored before
  691. // but are still valid and requested in the URL
  692. $query = array_merge( $this->getRequest()->getValues(), $query );
  693. unset( $query[ 'title' ] );
  694. $this->getOutput()->redirect( $this->getPageTitle( $subpage )->getCanonicalURL( $query ) );
  695. } else {
  696. // There's a default, but the version is not 2, and the server can't
  697. // actually recognize the query itself. This happens if it is before
  698. // the conversion, so we need to tell the UI to reload saved query as
  699. // it does the conversion to version 2
  700. $this->getOutput()->addJsConfigVars(
  701. 'wgStructuredChangeFiltersDefaultSavedQueryExists',
  702. true
  703. );
  704. // Add the class that tells the frontend it is still loading
  705. // another query
  706. $this->getOutput()->addBodyClasses( 'mw-rcfilters-ui-loading' );
  707. }
  708. }
  709. }
  710. }
  711. /**
  712. * @see $wgRCLinkDays in DefaultSettings.php.
  713. * @see $wgRCFilterByAge in DefaultSettings.php.
  714. * @return int[]
  715. */
  716. protected function getLinkDays() {
  717. $linkDays = $this->getConfig()->get( 'RCLinkDays' );
  718. $filterByAge = $this->getConfig()->get( 'RCFilterByAge' );
  719. $maxAge = $this->getConfig()->get( 'RCMaxAge' );
  720. if ( $filterByAge ) {
  721. // Trim it to only links which are within $wgRCMaxAge.
  722. // Note that we allow one link higher than the max for things like
  723. // "age 56 days" being accessible through the "60 days" link.
  724. sort( $linkDays );
  725. $maxAgeDays = $maxAge / ( 3600 * 24 );
  726. foreach ( $linkDays as $i => $days ) {
  727. if ( $days >= $maxAgeDays ) {
  728. array_splice( $linkDays, $i + 1 );
  729. break;
  730. }
  731. }
  732. }
  733. return $linkDays;
  734. }
  735. /**
  736. * Include the modules and configuration for the RCFilters app.
  737. * Conditional on the user having the feature enabled.
  738. *
  739. * If it is disabled, add a <body> class marking that
  740. */
  741. protected function includeRcFiltersApp() {
  742. $out = $this->getOutput();
  743. if ( $this->isStructuredFilterUiEnabled() && !$this->including() ) {
  744. $jsData = $this->getStructuredFilterJsData();
  745. $messages = [];
  746. foreach ( $jsData['messageKeys'] as $key ) {
  747. $messages[$key] = $this->msg( $key )->plain();
  748. }
  749. $out->addBodyClasses( 'mw-rcfilters-enabled' );
  750. $collapsed = $this->getUser()->getBoolOption( static::$collapsedPreferenceName );
  751. if ( $collapsed ) {
  752. $out->addBodyClasses( 'mw-rcfilters-collapsed' );
  753. }
  754. // These config and message exports should be moved into a ResourceLoader data module (T201574)
  755. $out->addJsConfigVars( 'wgStructuredChangeFilters', $jsData['groups'] );
  756. $out->addJsConfigVars( 'wgStructuredChangeFiltersMessages', $messages );
  757. $out->addJsConfigVars( 'wgStructuredChangeFiltersCollapsedState', $collapsed );
  758. $out->addJsConfigVars(
  759. 'StructuredChangeFiltersDisplayConfig',
  760. [
  761. 'maxDays' => (int)$this->getConfig()->get( 'RCMaxAge' ) / ( 24 * 3600 ), // Translate to days
  762. 'limitArray' => $this->getConfig()->get( 'RCLinkLimits' ),
  763. 'limitDefault' => $this->getDefaultLimit(),
  764. 'daysArray' => $this->getLinkDays(),
  765. 'daysDefault' => $this->getDefaultDays(),
  766. ]
  767. );
  768. $out->addJsConfigVars(
  769. 'wgStructuredChangeFiltersSavedQueriesPreferenceName',
  770. static::$savedQueriesPreferenceName
  771. );
  772. $out->addJsConfigVars(
  773. 'wgStructuredChangeFiltersLimitPreferenceName',
  774. static::$limitPreferenceName
  775. );
  776. $out->addJsConfigVars(
  777. 'wgStructuredChangeFiltersDaysPreferenceName',
  778. static::$daysPreferenceName
  779. );
  780. $out->addJsConfigVars(
  781. 'wgStructuredChangeFiltersCollapsedPreferenceName',
  782. static::$collapsedPreferenceName
  783. );
  784. } else {
  785. $out->addBodyClasses( 'mw-rcfilters-disabled' );
  786. }
  787. }
  788. /**
  789. * Get essential data about getRcFiltersConfigVars() for change detection.
  790. *
  791. * @internal For use by Resources.php only.
  792. * @see ResourceLoaderModule::getDefinitionSummary() and ResourceLoaderModule::getVersionHash()
  793. * @param ResourceLoaderContext $context
  794. * @return array
  795. */
  796. public static function getRcFiltersConfigSummary( ResourceLoaderContext $context ) {
  797. return [
  798. // Reduce version computation by avoiding Message parsing
  799. 'RCFiltersChangeTags' => self::getChangeTagListSummary( $context ),
  800. 'StructuredChangeFiltersEditWatchlistUrl' =>
  801. SpecialPage::getTitleFor( 'EditWatchlist' )->getLocalURL()
  802. ];
  803. }
  804. /**
  805. * Get config vars to export with the mediawiki.rcfilters.filters.ui module.
  806. *
  807. * @internal For use by Resources.php only.
  808. * @param ResourceLoaderContext $context
  809. * @return array
  810. */
  811. public static function getRcFiltersConfigVars( ResourceLoaderContext $context ) {
  812. return [
  813. 'RCFiltersChangeTags' => self::getChangeTagList( $context ),
  814. 'StructuredChangeFiltersEditWatchlistUrl' =>
  815. SpecialPage::getTitleFor( 'EditWatchlist' )->getLocalURL()
  816. ];
  817. }
  818. /**
  819. * Get information about change tags, without parsing messages, for getRcFiltersConfigSummary().
  820. *
  821. * Message contents are the raw values (->plain()), because parsing messages is expensive.
  822. * Even though we're not parsing messages, building a data structure with the contents of
  823. * hundreds of i18n messages is still not cheap (see T223260#5370610), so the result of this
  824. * function is cached in WANCache for 24 hours.
  825. *
  826. * Returns an array of associative arrays with information about each tag:
  827. * - name: Tag name (string)
  828. * - labelMsg: Short description message (Message object)
  829. * - label: Short description message (raw message contents)
  830. * - descriptionMsg: Long description message (Message object)
  831. * - description: Long description message (raw message contents)
  832. * - cssClass: CSS class to use for RC entries with this tag
  833. * - hits: Number of RC entries that have this tag
  834. *
  835. * @param ResourceLoaderContext $context
  836. * @return array[] Information about each tag
  837. */
  838. protected static function getChangeTagListSummary( ResourceLoaderContext $context ) {
  839. $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
  840. return $cache->getWithSetCallback(
  841. $cache->makeKey( 'ChangesListSpecialPage-changeTagListSummary', $context->getLanguage() ),
  842. WANObjectCache::TTL_DAY,
  843. function ( $oldValue, &$ttl, array &$setOpts ) use ( $context ) {
  844. $explicitlyDefinedTags = array_fill_keys( ChangeTags::listExplicitlyDefinedTags(), 0 );
  845. $softwareActivatedTags = array_fill_keys( ChangeTags::listSoftwareActivatedTags(), 0 );
  846. $tagStats = ChangeTags::tagUsageStatistics();
  847. $tagHitCounts = array_merge( $explicitlyDefinedTags, $softwareActivatedTags, $tagStats );
  848. $result = [];
  849. foreach ( $tagHitCounts as $tagName => $hits ) {
  850. if (
  851. (
  852. // Only get active tags
  853. isset( $explicitlyDefinedTags[ $tagName ] ) ||
  854. isset( $softwareActivatedTags[ $tagName ] )
  855. ) &&
  856. // Only get tags with more than 0 hits
  857. $hits > 0
  858. ) {
  859. $labelMsg = ChangeTags::tagShortDescriptionMessage( $tagName, $context );
  860. if ( $labelMsg === false ) {
  861. // Tag is hidden, skip it
  862. continue;
  863. }
  864. $descriptionMsg = ChangeTags::tagLongDescriptionMessage( $tagName, $context );
  865. $result[] = [
  866. 'name' => $tagName,
  867. 'labelMsg' => $labelMsg,
  868. 'label' => $labelMsg->plain(),
  869. 'descriptionMsg' => $descriptionMsg,
  870. 'description' => $descriptionMsg ? $descriptionMsg->plain() : '',
  871. 'cssClass' => Sanitizer::escapeClass( 'mw-tag-' . $tagName ),
  872. 'hits' => $hits,
  873. ];
  874. }
  875. }
  876. return $result;
  877. }
  878. );
  879. }
  880. /**
  881. * Get information about change tags to export to JS via getRcFiltersConfigVars().
  882. *
  883. * This manipulates the label and description of each tag, which are parsed, stripped
  884. * and (in the case of description) truncated versions of these messages. Message
  885. * parsing is expensive, so to detect whether the tag list has changed, use
  886. * getChangeTagListSummary() instead.
  887. *
  888. * The result of this function is cached in WANCache for 24 hours.
  889. *
  890. * @param ResourceLoaderContext $context
  891. * @return array[] Same as getChangeTagListSummary(), with messages parsed, stripped and truncated
  892. */
  893. protected static function getChangeTagList( ResourceLoaderContext $context ) {
  894. $tags = self::getChangeTagListSummary( $context );
  895. $language = Language::factory( $context->getLanguage() );
  896. foreach ( $tags as &$tagInfo ) {
  897. $tagInfo['label'] = Sanitizer::stripAllTags( $tagInfo['labelMsg']->parse() );
  898. $tagInfo['description'] = $tagInfo['descriptionMsg'] ?
  899. $language->truncateForVisual(
  900. Sanitizer::stripAllTags( $tagInfo['descriptionMsg']->parse() ),
  901. self::TAG_DESC_CHARACTER_LIMIT
  902. ) :
  903. '';
  904. unset( $tagInfo['labelMsg'] );
  905. unset( $tagInfo['descriptionMsg'] );
  906. }
  907. // Instead of sorting by hit count (disabled for now), sort by display name
  908. usort( $tags, function ( $a, $b ) {
  909. return strcasecmp( $a['label'], $b['label'] );
  910. } );
  911. return $tags;
  912. }
  913. /**
  914. * Add the "no results" message to the output
  915. */
  916. protected function outputNoResults() {
  917. $this->getOutput()->addHTML(
  918. '<div class="mw-changeslist-empty">' .
  919. $this->msg( 'recentchanges-noresult' )->parse() .
  920. '</div>'
  921. );
  922. }
  923. /**
  924. * Add the "timeout" message to the output
  925. */
  926. protected function outputTimeout() {
  927. $this->getOutput()->addHTML(
  928. '<div class="mw-changeslist-empty mw-changeslist-timeout">' .
  929. $this->msg( 'recentchanges-timeout' )->parse() .
  930. '</div>'
  931. );
  932. }
  933. /**
  934. * Get the database result for this special page instance. Used by ApiFeedRecentChanges.
  935. *
  936. * @return bool|IResultWrapper Result or false
  937. */
  938. public function getRows() {
  939. $opts = $this->getOptions();
  940. $tables = [];
  941. $fields = [];
  942. $conds = [];
  943. $query_options = [];
  944. $join_conds = [];
  945. $this->buildQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
  946. return $this->doMainQuery( $tables, $fields, $conds, $query_options, $join_conds, $opts );
  947. }
  948. /**
  949. * Get the current FormOptions for this request
  950. *
  951. * @return FormOptions
  952. */
  953. public function getOptions() {
  954. if ( $this->rcOptions === null ) {
  955. $this->rcOptions = $this->setup( $this->rcSubpage );
  956. }
  957. return $this->rcOptions;
  958. }
  959. /**
  960. * Register all filters and their groups (including those from hooks), plus handle
  961. * conflicts and defaults.
  962. *
  963. * You might want to customize these in the same method, in subclasses. You can
  964. * call getFilterGroup to access a group, and (on the group) getFilter to access a
  965. * filter, then make necessary modfications to the filter or group (e.g. with
  966. * setDefault).
  967. */
  968. protected function registerFilters() {
  969. $this->registerFiltersFromDefinitions( $this->filterGroupDefinitions );
  970. // Make sure this is not being transcluded (we don't want to show this
  971. // information to all users just because the user that saves the edit can
  972. // patrol or is logged in)
  973. if ( !$this->including() && $this->getUser()->useRCPatrol() ) {
  974. $this->registerFiltersFromDefinitions( $this->legacyReviewStatusFilterGroupDefinition );
  975. $this->registerFiltersFromDefinitions( $this->reviewStatusFilterGroupDefinition );
  976. }
  977. $changeTypeGroup = $this->getFilterGroup( 'changeType' );
  978. if ( $this->getConfig()->get( 'RCWatchCategoryMembership' ) ) {
  979. $transformedHideCategorizationDef = $this->transformFilterDefinition(
  980. $this->hideCategorizationFilterDefinition
  981. );
  982. $transformedHideCategorizationDef['group'] = $changeTypeGroup;
  983. $hideCategorization = new ChangesListBooleanFilter(
  984. $transformedHideCategorizationDef
  985. );
  986. }
  987. Hooks::run( 'ChangesListSpecialPageStructuredFilters', [ $this ] );
  988. $this->registerFiltersFromDefinitions( [] );
  989. $userExperienceLevel = $this->getFilterGroup( 'userExpLevel' );
  990. $registered = $userExperienceLevel->getFilter( 'registered' );
  991. $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'newcomer' ) );
  992. $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'learner' ) );
  993. $registered->setAsSupersetOf( $userExperienceLevel->getFilter( 'experienced' ) );
  994. $categoryFilter = $changeTypeGroup->getFilter( 'hidecategorization' );
  995. $logactionsFilter = $changeTypeGroup->getFilter( 'hidelog' );
  996. $pagecreationFilter = $changeTypeGroup->getFilter( 'hidenewpages' );
  997. $significanceTypeGroup = $this->getFilterGroup( 'significance' );
  998. $hideMinorFilter = $significanceTypeGroup->getFilter( 'hideminor' );
  999. // categoryFilter is conditional; see registerFilters
  1000. if ( $categoryFilter !== null ) {
  1001. $hideMinorFilter->conflictsWith(
  1002. $categoryFilter,
  1003. 'rcfilters-hideminor-conflicts-typeofchange-global',
  1004. 'rcfilters-hideminor-conflicts-typeofchange',
  1005. 'rcfilters-typeofchange-conflicts-hideminor'
  1006. );
  1007. }
  1008. $hideMinorFilter->conflictsWith(
  1009. $logactionsFilter,
  1010. 'rcfilters-hideminor-conflicts-typeofchange-global',
  1011. 'rcfilters-hideminor-conflicts-typeofchange',
  1012. 'rcfilters-typeofchange-conflicts-hideminor'
  1013. );
  1014. $hideMinorFilter->conflictsWith(
  1015. $pagecreationFilter,
  1016. 'rcfilters-hideminor-conflicts-typeofchange-global',
  1017. 'rcfilters-hideminor-conflicts-typeofchange',
  1018. 'rcfilters-typeofchange-conflicts-hideminor'
  1019. );
  1020. }
  1021. /**
  1022. * Transforms filter definition to prepare it for constructor.
  1023. *
  1024. * See overrides of this method as well.
  1025. *
  1026. * @param array $filterDefinition Original filter definition
  1027. *
  1028. * @return array Transformed definition
  1029. */
  1030. protected function transformFilterDefinition( array $filterDefinition ) {
  1031. return $filterDefinition;
  1032. }
  1033. /**
  1034. * Register filters from a definition object
  1035. *
  1036. * Array specifying groups and their filters; see Filter and
  1037. * ChangesListFilterGroup constructors.
  1038. *
  1039. * There is light processing to simplify core maintenance.
  1040. * @param array $definition
  1041. * @phan-param array<int,array{class:string,filters:array}> $definition
  1042. */
  1043. protected function registerFiltersFromDefinitions( array $definition ) {
  1044. $autoFillPriority = -1;
  1045. foreach ( $definition as $groupDefinition ) {
  1046. if ( !isset( $groupDefinition['priority'] ) ) {
  1047. $groupDefinition['priority'] = $autoFillPriority;
  1048. } else {
  1049. // If it's explicitly specified, start over the auto-fill
  1050. $autoFillPriority = $groupDefinition['priority'];
  1051. }
  1052. $autoFillPriority--;
  1053. $className = $groupDefinition['class'];
  1054. unset( $groupDefinition['class'] );
  1055. foreach ( $groupDefinition['filters'] as &$filterDefinition ) {
  1056. $filterDefinition = $this->transformFilterDefinition( $filterDefinition );
  1057. }
  1058. $this->registerFilterGroup( new $className( $groupDefinition ) );
  1059. }
  1060. }
  1061. /**
  1062. * @return array The legacy show/hide toggle filters
  1063. */
  1064. protected function getLegacyShowHideFilters() {
  1065. $filters = [];
  1066. foreach ( $this->filterGroups as $group ) {
  1067. if ( $group instanceof ChangesListBooleanFilterGroup ) {
  1068. foreach ( $group->getFilters() as $key => $filter ) {
  1069. if ( $filter->displaysOnUnstructuredUi( $this ) ) {
  1070. $filters[ $key ] = $filter;
  1071. }
  1072. }
  1073. }
  1074. }
  1075. return $filters;
  1076. }
  1077. /**
  1078. * Register all the filters, including legacy hook-driven ones.
  1079. * Then create a FormOptions object with options as specified by the user
  1080. *
  1081. * @param string $parameters
  1082. *
  1083. * @return FormOptions
  1084. */
  1085. public function setup( $parameters ) {
  1086. $this->registerFilters();
  1087. $opts = $this->getDefaultOptions();
  1088. $opts = $this->fetchOptionsFromRequest( $opts );
  1089. // Give precedence to subpage syntax
  1090. if ( $parameters !== null ) {
  1091. $this->parseParameters( $parameters, $opts );
  1092. }
  1093. $this->validateOptions( $opts );
  1094. return $opts;
  1095. }
  1096. /**
  1097. * Get a FormOptions object containing the default options. By default, returns
  1098. * some basic options. The filters listed explicitly here are overriden in this
  1099. * method, in subclasses, but most filters (e.g. hideminor, userExpLevel filters,
  1100. * and more) are structured. Structured filters are overriden in registerFilters.
  1101. * not here.
  1102. *
  1103. * @return FormOptions
  1104. */
  1105. public function getDefaultOptions() {
  1106. $opts = new FormOptions();
  1107. $structuredUI = $this->isStructuredFilterUiEnabled();
  1108. // If urlversion=2 is set, ignore the filter defaults and set them all to false/empty
  1109. $useDefaults = $this->getRequest()->getInt( 'urlversion' ) !== 2;
  1110. /** @var ChangesListFilterGroup $filterGroup */
  1111. foreach ( $this->filterGroups as $filterGroup ) {
  1112. $filterGroup->addOptions( $opts, $useDefaults, $structuredUI );
  1113. }
  1114. $opts->add( 'namespace', '', FormOptions::STRING );
  1115. $opts->add( 'invert', false );
  1116. $opts->add( 'associated', false );
  1117. $opts->add( 'urlversion', 1 );
  1118. $opts->add( 'tagfilter', '' );
  1119. $opts->add( 'days', $this->getDefaultDays(), FormOptions::FLOAT );
  1120. $opts->add( 'limit', $this->getDefaultLimit(), FormOptions::INT );
  1121. $opts->add( 'from', '' );
  1122. return $opts;
  1123. }
  1124. /**
  1125. * Register a structured changes list filter group
  1126. *
  1127. * @param ChangesListFilterGroup $group
  1128. */
  1129. public function registerFilterGroup( ChangesListFilterGroup $group ) {
  1130. $groupName = $group->getName();
  1131. $this->filterGroups[$groupName] = $group;
  1132. }
  1133. /**
  1134. * Gets the currently registered filters groups
  1135. *
  1136. * @return array Associative array of ChangesListFilterGroup objects, with group name as key
  1137. */
  1138. protected function getFilterGroups() {
  1139. return $this->filterGroups;
  1140. }
  1141. /**
  1142. * Gets a specified ChangesListFilterGroup by name
  1143. *
  1144. * @param string $groupName Name of group
  1145. *
  1146. * @return ChangesListFilterGroup|null Group, or null if not registered
  1147. */
  1148. public function getFilterGroup( $groupName ) {
  1149. return $this->filterGroups[$groupName] ?? null;
  1150. }
  1151. // Currently, this intentionally only includes filters that display
  1152. // in the structured UI. This can be changed easily, though, if we want
  1153. // to include data on filters that use the unstructured UI. messageKeys is a
  1154. // special top-level value, with the value being an array of the message keys to
  1155. // send to the client.
  1156. /**
  1157. * Gets structured filter information needed by JS
  1158. *
  1159. * @return array Associative array
  1160. * * array $return['groups'] Group data
  1161. * * array $return['messageKeys'] Array of message keys
  1162. */
  1163. public function getStructuredFilterJsData() {
  1164. $output = [
  1165. 'groups' => [],
  1166. 'messageKeys' => [],
  1167. ];
  1168. usort( $this->filterGroups, function ( $a, $b ) {
  1169. return $b->getPriority() <=> $a->getPriority();
  1170. } );
  1171. foreach ( $this->filterGroups as $groupName => $group ) {
  1172. $groupOutput = $group->getJsData( $this );
  1173. if ( $groupOutput !== null ) {
  1174. $output['messageKeys'] = array_merge(
  1175. $output['messageKeys'],
  1176. $groupOutput['messageKeys']
  1177. );
  1178. unset( $groupOutput['messageKeys'] );
  1179. $output['groups'][] = $groupOutput;
  1180. }
  1181. }
  1182. return $output;
  1183. }
  1184. /**
  1185. * Fetch values for a FormOptions object from the WebRequest associated with this instance.
  1186. *
  1187. * Intended for subclassing, e.g. to add a backwards-compatibility layer.
  1188. *
  1189. * @param FormOptions $opts
  1190. * @return FormOptions
  1191. */
  1192. protected function fetchOptionsFromRequest( $opts ) {
  1193. $opts->fetchValuesFromRequest( $this->getRequest() );
  1194. return $opts;
  1195. }
  1196. /**
  1197. * Process $par and put options found in $opts. Used when including the page.
  1198. *
  1199. * @param string $par
  1200. * @param FormOptions $opts
  1201. */
  1202. public function parseParameters( $par, FormOptions $opts ) {
  1203. $stringParameterNameSet = [];
  1204. $hideParameterNameSet = [];
  1205. // URL parameters can be per-group, like 'userExpLevel',
  1206. // or per-filter, like 'hideminor'.
  1207. foreach ( $this->filterGroups as $filterGroup ) {
  1208. if ( $filterGroup instanceof ChangesListStringOptionsFilterGroup ) {
  1209. $stringParameterNameSet[$filterGroup->getName()] = true;
  1210. } elseif ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
  1211. foreach ( $filterGroup->getFilters() as $filter ) {
  1212. $hideParameterNameSet[$filter->getName()] = true;
  1213. }
  1214. }
  1215. }
  1216. $bits = preg_split( '/\s*,\s*/', trim( $par ) );
  1217. foreach ( $bits as $bit ) {
  1218. $m = [];
  1219. if ( isset( $hideParameterNameSet[$bit] ) ) {
  1220. // hidefoo => hidefoo=true
  1221. $opts[$bit] = true;
  1222. } elseif ( isset( $hideParameterNameSet["hide$bit"] ) ) {
  1223. // foo => hidefoo=false
  1224. $opts["hide$bit"] = false;
  1225. } elseif ( preg_match( '/^(.*)=(.*)$/', $bit, $m ) ) {
  1226. if ( isset( $stringParameterNameSet[$m[1]] ) ) {
  1227. $opts[$m[1]] = $m[2];
  1228. }
  1229. }
  1230. }
  1231. }
  1232. /**
  1233. * Validate a FormOptions object generated by getDefaultOptions() with values already populated.
  1234. *
  1235. * @param FormOptions $opts
  1236. */
  1237. public function validateOptions( FormOptions $opts ) {
  1238. $isContradictory = $this->fixContradictoryOptions( $opts );
  1239. $isReplaced = $this->replaceOldOptions( $opts );
  1240. if ( $isContradictory || $isReplaced ) {
  1241. $query = wfArrayToCgi( $this->convertParamsForLink( $opts->getChangedValues() ) );
  1242. $this->getOutput()->redirect( $this->getPageTitle()->getCanonicalURL( $query ) );
  1243. }
  1244. $opts->validateIntBounds( 'limit', 0, 5000 );
  1245. $opts->validateBounds( 'days', 0, $this->getConfig()->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
  1246. }
  1247. /**
  1248. * Fix invalid options by resetting pairs that should never appear together.
  1249. *
  1250. * @param FormOptions $opts
  1251. * @return bool True if any option was reset
  1252. */
  1253. private function fixContradictoryOptions( FormOptions $opts ) {
  1254. $fixed = $this->fixBackwardsCompatibilityOptions( $opts );
  1255. foreach ( $this->filterGroups as $filterGroup ) {
  1256. if ( $filterGroup instanceof ChangesListBooleanFilterGroup ) {
  1257. $filters = $filterGroup->getFilters();
  1258. if ( count( $filters ) === 1 ) {
  1259. // legacy boolean filters should not be considered
  1260. continue;
  1261. }
  1262. $allInGroupEnabled = array_reduce(
  1263. $filters,
  1264. function ( $carry, $filter ) use ( $opts ) {
  1265. return $carry && $opts[ $filter->getName() ];
  1266. },
  1267. /* initialValue */ count( $filters ) > 0
  1268. );
  1269. if ( $allInGroupEnabled ) {
  1270. foreach ( $filters as $filter ) {
  1271. $opts[ $filter->getName() ] = false;
  1272. }
  1273. $fixed = true;
  1274. }
  1275. }
  1276. }
  1277. return $fixed;
  1278. }
  1279. /**
  1280. * Fix a special case (hideanons=1 and hideliu=1) in a special way, for backwards
  1281. * compatibility.
  1282. *
  1283. * This is deprecated and may be removed.
  1284. *
  1285. * @param FormOptions $opts
  1286. * @return bool True if this change was mode
  1287. */
  1288. private function fixBackwardsCompatibilityOptions( FormOptions $opts ) {
  1289. if ( $opts['hideanons'] && $opts['hideliu'] ) {
  1290. $opts->reset( 'hideanons' );
  1291. if ( !$opts['hidebots'] ) {
  1292. $opts->reset( 'hideliu' );
  1293. $opts['hidehumans'] = 1;
  1294. }
  1295. return true;
  1296. }
  1297. return false;
  1298. }
  1299. /**
  1300. * Replace old options with their structured UI equivalents
  1301. *
  1302. * @param FormOptions $opts
  1303. * @return bool True if the change was made
  1304. */
  1305. public function replaceOldOptions( FormOptions $opts ) {
  1306. if ( !$this->isStructuredFilterUiEnabled() ) {
  1307. return false;
  1308. }
  1309. $changed = false;
  1310. // At this point 'hideanons' and 'hideliu' cannot be both true,
  1311. // because fixBackwardsCompatibilityOptions resets (at least) 'hideanons' in such case
  1312. if ( $opts[ 'hideanons' ] ) {
  1313. $opts->reset( 'hideanons' );
  1314. $opts[ 'userExpLevel' ] = 'registered';
  1315. $changed = true;
  1316. }
  1317. if ( $opts[ 'hideliu' ] ) {
  1318. $opts->reset( 'hideliu' );
  1319. $opts[ 'userExpLevel' ] = 'unregistered';
  1320. $changed = true;
  1321. }
  1322. if ( $this->getFilterGroup( 'legacyReviewStatus' ) ) {
  1323. if ( $opts[ 'hidepatrolled' ] ) {
  1324. $opts->reset( 'hidepatrolled' );
  1325. $opts[ 'reviewStatus' ] = 'unpatrolled';
  1326. $changed = true;
  1327. }
  1328. if ( $opts[ 'hideunpatrolled' ] ) {
  1329. $opts->reset( 'hideunpatrolled' );
  1330. $opts[ 'reviewStatus' ] = implode(
  1331. ChangesListStringOptionsFilterGroup::SEPARATOR,
  1332. [ 'manual', 'auto' ]
  1333. );
  1334. $changed = true;
  1335. }
  1336. }
  1337. return $changed;
  1338. }
  1339. /**
  1340. * Convert parameters values from true/false to 1/0
  1341. * so they are not omitted by wfArrayToCgi()
  1342. * T38524
  1343. *
  1344. * @param array $params
  1345. * @return array
  1346. */
  1347. protected function convertParamsForLink( $params ) {
  1348. foreach ( $params as &$value ) {
  1349. if ( $value === false ) {
  1350. $value = '0';
  1351. }
  1352. }
  1353. unset( $value );
  1354. return $params;
  1355. }
  1356. /**
  1357. * Sets appropriate tables, fields, conditions, etc. depending on which filters
  1358. * the user requested.
  1359. *
  1360. * @param array &$tables Array of tables; see IDatabase::select $table
  1361. * @param array &$fields Array of fields; see IDatabase::select $vars
  1362. * @param array &$conds Array of conditions; see IDatabase::select $conds
  1363. * @param array &$query_options Array of query options; see IDatabase::select $options
  1364. * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
  1365. * @param FormOptions $opts
  1366. */
  1367. protected function buildQuery( &$tables, &$fields, &$conds, &$query_options,
  1368. &$join_conds, FormOptions $opts
  1369. ) {
  1370. $dbr = $this->getDB();
  1371. $isStructuredUI = $this->isStructuredFilterUiEnabled();
  1372. /** @var ChangesListFilterGroup $filterGroup */
  1373. foreach ( $this->filterGroups as $filterGroup ) {
  1374. $filterGroup->modifyQuery( $dbr, $this, $tables, $fields, $conds,
  1375. $query_options, $join_conds, $opts, $isStructuredUI );
  1376. }
  1377. // Namespace filtering
  1378. if ( $opts[ 'namespace' ] !== '' ) {
  1379. $namespaces = explode( ';', $opts[ 'namespace' ] );
  1380. $namespaces = $this->expandSymbolicNamespaceFilters( $namespaces );
  1381. if ( $opts[ 'associated' ] ) {
  1382. $namespaceInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
  1383. $associatedNamespaces = array_map(
  1384. function ( $ns ) use ( $namespaceInfo ){
  1385. return $namespaceInfo->getAssociated( $ns );
  1386. },
  1387. array_filter(
  1388. $namespaces,
  1389. function ( $ns ) use ( $namespaceInfo ) {
  1390. return $namespaceInfo->hasTalkNamespace( $ns );
  1391. }
  1392. )
  1393. );
  1394. $namespaces = array_unique( array_merge( $namespaces, $associatedNamespaces ) );
  1395. }
  1396. if ( count( $namespaces ) === 1 ) {
  1397. $operator = $opts[ 'invert' ] ? '!=' : '=';
  1398. $value = $dbr->addQuotes( reset( $namespaces ) );
  1399. } else {
  1400. $operator = $opts[ 'invert' ] ? 'NOT IN' : 'IN';
  1401. sort( $namespaces );
  1402. $value = '(' . $dbr->makeList( $namespaces ) . ')';
  1403. }
  1404. $conds[] = "rc_namespace $operator $value";
  1405. }
  1406. // Calculate cutoff
  1407. $cutoff_unixtime = time() - $opts['days'] * 3600 * 24;
  1408. $cutoff = $dbr->timestamp( $cutoff_unixtime );
  1409. $fromValid = preg_match( '/^[0-9]{14}$/', $opts['from'] );
  1410. if ( $fromValid && $opts['from'] > wfTimestamp( TS_MW, $cutoff ) ) {
  1411. $cutoff = $dbr->timestamp( $opts['from'] );
  1412. } else {
  1413. $opts->reset( 'from' );
  1414. }
  1415. $conds[] = 'rc_timestamp >= ' . $dbr->addQuotes( $cutoff );
  1416. }
  1417. /**
  1418. * Process the query
  1419. *
  1420. * @param array $tables Array of tables; see IDatabase::select $table
  1421. * @param array $fields Array of fields; see IDatabase::select $vars
  1422. * @param array $conds Array of conditions; see IDatabase::select $conds
  1423. * @param array $query_options Array of query options; see IDatabase::select $options
  1424. * @param array $join_conds Array of join conditions; see IDatabase::select $join_conds
  1425. * @param FormOptions $opts
  1426. * @return bool|IResultWrapper Result or false
  1427. */
  1428. protected function doMainQuery( $tables, $fields, $conds,
  1429. $query_options, $join_conds, FormOptions $opts
  1430. ) {
  1431. $rcQuery = RecentChange::getQueryInfo();
  1432. $tables = array_merge( $tables, $rcQuery['tables'] );
  1433. $fields = array_merge( $rcQuery['fields'], $fields );
  1434. $join_conds = array_merge( $join_conds, $rcQuery['joins'] );
  1435. ChangeTags::modifyDisplayQuery(
  1436. $tables,
  1437. $fields,
  1438. $conds,
  1439. $join_conds,
  1440. $query_options,
  1441. ''
  1442. );
  1443. if ( !$this->runMainQueryHook( $tables, $fields, $conds, $query_options, $join_conds,
  1444. $opts )
  1445. ) {
  1446. return false;
  1447. }
  1448. $dbr = $this->getDB();
  1449. return $dbr->select(
  1450. $tables,
  1451. $fields,
  1452. $conds,
  1453. __METHOD__,
  1454. $query_options,
  1455. $join_conds
  1456. );
  1457. }
  1458. protected function runMainQueryHook( &$tables, &$fields, &$conds,
  1459. &$query_options, &$join_conds, $opts
  1460. ) {
  1461. return Hooks::run(
  1462. 'ChangesListSpecialPageQuery',
  1463. [ $this->getName(), &$tables, &$fields, &$conds, &$query_options, &$join_conds, $opts ]
  1464. );
  1465. }
  1466. /**
  1467. * Return a IDatabase object for reading
  1468. *
  1469. * @return IDatabase
  1470. */
  1471. protected function getDB() {
  1472. return wfGetDB( DB_REPLICA );
  1473. }
  1474. /**
  1475. * Send header output to the OutputPage object, only called if not using feeds
  1476. *
  1477. * @param int $rowCount Number of database rows
  1478. * @param FormOptions $opts
  1479. */
  1480. private function webOutputHeader( $rowCount, $opts ) {
  1481. if ( !$this->including() ) {
  1482. $this->outputFeedLinks();
  1483. $this->doHeader( $opts, $rowCount );
  1484. }
  1485. }
  1486. /**
  1487. * Send output to the OutputPage object, only called if not used feeds
  1488. *
  1489. * @param IResultWrapper $rows Database rows
  1490. * @param FormOptions $opts
  1491. */
  1492. public function webOutput( $rows, $opts ) {
  1493. $this->webOutputHeader( $rows->numRows(), $opts );
  1494. $this->outputChangesList( $rows, $opts );
  1495. }
  1496. /**
  1497. * Output feed links.
  1498. */
  1499. public function outputFeedLinks() {
  1500. // nothing by default
  1501. }
  1502. /**
  1503. * Build and output the actual changes list.
  1504. *
  1505. * @param IResultWrapper $rows Database rows
  1506. * @param FormOptions $opts
  1507. */
  1508. abstract public function outputChangesList( $rows, $opts );
  1509. /**
  1510. * Set the text to be displayed above the changes
  1511. *
  1512. * @param FormOptions $opts
  1513. * @param int $numRows Number of rows in the result to show after this header
  1514. */
  1515. public function doHeader( $opts, $numRows ) {
  1516. $this->setTopText( $opts );
  1517. // @todo Lots of stuff should be done here.
  1518. $this->setBottomText( $opts );
  1519. }
  1520. /**
  1521. * Send the text to be displayed before the options.
  1522. * Should use $this->getOutput()->addWikiTextAsInterface()
  1523. * or similar methods to print the text.
  1524. *
  1525. * @param FormOptions $opts
  1526. */
  1527. public function setTopText( FormOptions $opts ) {
  1528. // nothing by default
  1529. }
  1530. /**
  1531. * Send the text to be displayed after the options.
  1532. * Should use $this->getOutput()->addWikiTextAsInterface()
  1533. * or similar methods to print the text.
  1534. *
  1535. * @param FormOptions $opts
  1536. */
  1537. public function setBottomText( FormOptions $opts ) {
  1538. // nothing by default
  1539. }
  1540. /**
  1541. * Get options to be displayed in a form
  1542. * @todo This should handle options returned by getDefaultOptions().
  1543. * @todo Not called by anything in this class (but is in subclasses), should be
  1544. * called by something… doHeader() maybe?
  1545. *
  1546. * @param FormOptions $opts
  1547. * @return array
  1548. */
  1549. public function getExtraOptions( $opts ) {
  1550. return [];
  1551. }
  1552. /**
  1553. * Return the legend displayed within the fieldset
  1554. *
  1555. * @return string
  1556. */
  1557. public function makeLegend() {
  1558. $context = $this->getContext();
  1559. $user = $context->getUser();
  1560. # The legend showing what the letters and stuff mean
  1561. $legend = Html::openElement( 'dl' ) . "\n";
  1562. # Iterates through them and gets the messages for both letter and tooltip
  1563. $legendItems = $context->getConfig()->get( 'RecentChangesFlags' );
  1564. if ( !( $user->useRCPatrol() || $user->useNPPatrol() ) ) {
  1565. unset( $legendItems['unpatrolled'] );
  1566. }
  1567. foreach ( $legendItems as $key => $item ) { # generate items of the legend
  1568. $label = $item['legend'] ?? $item['title'];
  1569. $letter = $item['letter'];
  1570. $cssClass = $item['class'] ?? $key;
  1571. $legend .= Html::element( 'dt',
  1572. [ 'class' => $cssClass ], $context->msg( $letter )->text()
  1573. ) . "\n" .
  1574. Html::rawElement( 'dd',
  1575. [ 'class' => Sanitizer::escapeClass( 'mw-changeslist-legend-' . $key ) ],
  1576. $context->msg( $label )->parse()
  1577. ) . "\n";
  1578. }
  1579. # (+-123)
  1580. $legend .= Html::rawElement( 'dt',
  1581. [ 'class' => 'mw-plusminus-pos' ],
  1582. $context->msg( 'recentchanges-legend-plusminus' )->parse()
  1583. ) . "\n";
  1584. $legend .= Html::element(
  1585. 'dd',
  1586. [ 'class' => 'mw-changeslist-legend-plusminus' ],
  1587. $context->msg( 'recentchanges-label-plusminus' )->text()
  1588. ) . "\n";
  1589. $legend .= Html::closeElement( 'dl' ) . "\n";
  1590. $legendHeading = $this->isStructuredFilterUiEnabled() ?
  1591. $context->msg( 'rcfilters-legend-heading' )->parse() :
  1592. $context->msg( 'recentchanges-legend-heading' )->parse();
  1593. # Collapsible
  1594. $collapsedState = $this->getRequest()->getCookie( 'changeslist-state' );
  1595. $collapsedClass = $collapsedState === 'collapsed' ? ' mw-collapsed' : '';
  1596. $legend =
  1597. '<div class="mw-changeslist-legend mw-collapsible' . $collapsedClass . '">' .
  1598. $legendHeading .
  1599. '<div class="mw-collapsible-content">' . $legend . '</div>' .
  1600. '</div>';
  1601. return $legend;
  1602. }
  1603. /**
  1604. * Add page-specific modules.
  1605. */
  1606. protected function addModules() {
  1607. $out = $this->getOutput();
  1608. // Styles and behavior for the legend box (see makeLegend())
  1609. $out->addModuleStyles( [
  1610. 'mediawiki.interface.helpers.styles',
  1611. 'mediawiki.special.changeslist.legend',
  1612. 'mediawiki.special.changeslist',
  1613. ] );
  1614. $out->addModules( 'mediawiki.special.changeslist.legend.js' );
  1615. if ( $this->isStructuredFilterUiEnabled() && !$this->including() ) {
  1616. $out->addModules( 'mediawiki.rcfilters.filters.ui' );
  1617. $out->addModuleStyles( 'mediawiki.rcfilters.filters.base.styles' );
  1618. }
  1619. }
  1620. protected function getGroupName() {
  1621. return 'changes';
  1622. }
  1623. /**
  1624. * Filter on users' experience levels; this will not be called if nothing is
  1625. * selected.
  1626. *
  1627. * @param string $specialPageClassName Class name of current special page
  1628. * @param IContextSource $context Context, for e.g. user
  1629. * @param IDatabase $dbr Database, for addQuotes, makeList, and similar
  1630. * @param array &$tables Array of tables; see IDatabase::select $table
  1631. * @param array &$fields Array of fields; see IDatabase::select $vars
  1632. * @param array &$conds Array of conditions; see IDatabase::select $conds
  1633. * @param array &$query_options Array of query options; see IDatabase::select $options
  1634. * @param array &$join_conds Array of join conditions; see IDatabase::select $join_conds
  1635. * @param array $selectedExpLevels The allowed active values, sorted
  1636. * @param int $now Number of seconds since the UNIX epoch, or 0 if not given
  1637. * (optional)
  1638. */
  1639. public function filterOnUserExperienceLevel( $specialPageClassName, $context, $dbr,
  1640. &$tables, &$fields, &$conds, &$query_options, &$join_conds, $selectedExpLevels, $now = 0
  1641. ) {
  1642. global $wgLearnerEdits,
  1643. $wgExperiencedUserEdits,
  1644. $wgLearnerMemberSince,
  1645. $wgExperiencedUserMemberSince;
  1646. $LEVEL_COUNT = 5;
  1647. // If all levels are selected, don't filter
  1648. if ( count( $selectedExpLevels ) === $LEVEL_COUNT ) {
  1649. return;
  1650. }
  1651. // both 'registered' and 'unregistered', experience levels, if any, are included in 'registered'
  1652. if (
  1653. in_array( 'registered', $selectedExpLevels ) &&
  1654. in_array( 'unregistered', $selectedExpLevels )
  1655. ) {
  1656. return;
  1657. }
  1658. $actorMigration = ActorMigration::newMigration();
  1659. $actorQuery = $actorMigration->getJoin( 'rc_user' );
  1660. $tables += $actorQuery['tables'];
  1661. $join_conds += $actorQuery['joins'];
  1662. // 'registered' but not 'unregistered', experience levels, if any, are included in 'registered'
  1663. if (
  1664. in_array( 'registered', $selectedExpLevels ) &&
  1665. !in_array( 'unregistered', $selectedExpLevels )
  1666. ) {
  1667. $conds[] = $actorMigration->isNotAnon( $actorQuery['fields']['rc_user'] );
  1668. return;
  1669. }
  1670. if ( $selectedExpLevels === [ 'unregistered' ] ) {
  1671. $conds[] = $actorMigration->isAnon( $actorQuery['fields']['rc_user'] );
  1672. return;
  1673. }
  1674. $tables[] = 'user';
  1675. $join_conds['user'] = [ 'LEFT JOIN', $actorQuery['fields']['rc_user'] . ' = user_id' ];
  1676. if ( $now === 0 ) {
  1677. $now = time();
  1678. }
  1679. $secondsPerDay = 86400;
  1680. $learnerCutoff = $now - $wgLearnerMemberSince * $secondsPerDay;
  1681. $experiencedUserCutoff = $now - $wgExperiencedUserMemberSince * $secondsPerDay;
  1682. $aboveNewcomer = $dbr->makeList(
  1683. [
  1684. 'user_editcount >= ' . intval( $wgLearnerEdits ),
  1685. 'user_registration <= ' . $dbr->addQuotes( $dbr->timestamp( $learnerCutoff ) ),
  1686. ],
  1687. IDatabase::LIST_AND
  1688. );
  1689. $aboveLearner = $dbr->makeList(
  1690. [
  1691. 'user_editcount >= ' . intval( $wgExperiencedUserEdits ),
  1692. 'user_registration <= ' .
  1693. $dbr->addQuotes( $dbr->timestamp( $experiencedUserCutoff ) ),
  1694. ],
  1695. IDatabase::LIST_AND
  1696. );
  1697. $conditions = [];
  1698. if ( in_array( 'unregistered', $selectedExpLevels ) ) {
  1699. $selectedExpLevels = array_diff( $selectedExpLevels, [ 'unregistered' ] );
  1700. $conditions[] = $actorMigration->isAnon( $actorQuery['fields']['rc_user'] );
  1701. }
  1702. if ( $selectedExpLevels === [ 'newcomer' ] ) {
  1703. $conditions[] = "NOT ( $aboveNewcomer )";
  1704. } elseif ( $selectedExpLevels === [ 'learner' ] ) {
  1705. $conditions[] = $dbr->makeList(
  1706. [ $aboveNewcomer, "NOT ( $aboveLearner )" ],
  1707. IDatabase::LIST_AND
  1708. );
  1709. } elseif ( $selectedExpLevels === [ 'experienced' ] ) {
  1710. $conditions[] = $aboveLearner;
  1711. } elseif ( $selectedExpLevels === [ 'learner', 'newcomer' ] ) {
  1712. $conditions[] = "NOT ( $aboveLearner )";
  1713. } elseif ( $selectedExpLevels === [ 'experienced', 'newcomer' ] ) {
  1714. $conditions[] = $dbr->makeList(
  1715. [ "NOT ( $aboveNewcomer )", $aboveLearner ],
  1716. IDatabase::LIST_OR
  1717. );
  1718. } elseif ( $selectedExpLevels === [ 'experienced', 'learner' ] ) {
  1719. $conditions[] = $aboveNewcomer;
  1720. } elseif ( $selectedExpLevels === [ 'experienced', 'learner', 'newcomer' ] ) {
  1721. $conditions[] = $actorMigration->isNotAnon( $actorQuery['fields']['rc_user'] );
  1722. }
  1723. if ( count( $conditions ) > 1 ) {
  1724. $conds[] = $dbr->makeList( $conditions, IDatabase::LIST_OR );
  1725. } elseif ( count( $conditions ) === 1 ) {
  1726. $conds[] = reset( $conditions );
  1727. }
  1728. }
  1729. /**
  1730. * Check whether the structured filter UI is enabled
  1731. *
  1732. * @return bool
  1733. */
  1734. public function isStructuredFilterUiEnabled() {
  1735. if ( $this->getRequest()->getBool( 'rcfilters' ) ) {
  1736. return true;
  1737. }
  1738. return static::checkStructuredFilterUiEnabled( $this->getUser() );
  1739. }
  1740. /**
  1741. * Static method to check whether StructuredFilter UI is enabled for the given user
  1742. *
  1743. * @since 1.31
  1744. * @param User $user
  1745. * @return bool
  1746. */
  1747. public static function checkStructuredFilterUiEnabled( $user ) {
  1748. if ( $user instanceof Config ) {
  1749. wfDeprecated( __METHOD__ . ' with Config argument', '1.34' );
  1750. $user = func_get_arg( 1 );
  1751. }
  1752. return !$user->getOption( 'rcenhancedfilters-disable' );
  1753. }
  1754. /**
  1755. * Get the default value of the number of changes to display when loading
  1756. * the result set.
  1757. *
  1758. * @since 1.30
  1759. * @return int
  1760. */
  1761. public function getDefaultLimit() {
  1762. return $this->getUser()->getIntOption( static::$limitPreferenceName );
  1763. }
  1764. /**
  1765. * Get the default value of the number of days to display when loading
  1766. * the result set.
  1767. * Supports fractional values, and should be cast to a float.
  1768. *
  1769. * @since 1.30
  1770. * @return float
  1771. */
  1772. public function getDefaultDays() {
  1773. return floatval( $this->getUser()->getOption( static::$daysPreferenceName ) );
  1774. }
  1775. private function expandSymbolicNamespaceFilters( array $namespaces ) {
  1776. $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
  1777. $symbolicFilters = [
  1778. 'all-contents' => $nsInfo->getSubjectNamespaces(),
  1779. 'all-discussions' => $nsInfo->getTalkNamespaces(),
  1780. ];
  1781. $additionalNamespaces = [];
  1782. foreach ( $symbolicFilters as $name => $values ) {
  1783. if ( in_array( $name, $namespaces ) ) {
  1784. $additionalNamespaces = array_merge( $additionalNamespaces, $values );
  1785. }
  1786. }
  1787. $namespaces = array_diff( $namespaces, array_keys( $symbolicFilters ) );
  1788. $namespaces = array_merge( $namespaces, $additionalNamespaces );
  1789. return array_unique( $namespaces );
  1790. }
  1791. }