SpecialBotPasswords.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. <?php
  2. /**
  3. * Implements Special:BotPasswords
  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. /**
  26. * Let users manage bot passwords
  27. *
  28. * @ingroup SpecialPage
  29. */
  30. class SpecialBotPasswords extends FormSpecialPage {
  31. /** @var int Central user ID */
  32. private $userId = 0;
  33. /** @var BotPassword|null Bot password being edited, if any */
  34. private $botPassword = null;
  35. /** @var string Operation being performed: create, update, delete */
  36. private $operation = null;
  37. /** @var string New password set, for communication between onSubmit() and onSuccess() */
  38. private $password = null;
  39. /** @var Psr\Log\LoggerInterface */
  40. private $logger = null;
  41. public function __construct() {
  42. parent::__construct( 'BotPasswords', 'editmyprivateinfo' );
  43. $this->logger = LoggerFactory::getInstance( 'authentication' );
  44. }
  45. /**
  46. * @return bool
  47. */
  48. public function isListed() {
  49. return $this->getConfig()->get( 'EnableBotPasswords' );
  50. }
  51. protected function getLoginSecurityLevel() {
  52. return $this->getName();
  53. }
  54. /**
  55. * Main execution point
  56. * @param string|null $par
  57. */
  58. function execute( $par ) {
  59. $this->getOutput()->disallowUserJs();
  60. $this->requireLogin();
  61. $this->addHelpLink( 'Manual:Bot_passwords' );
  62. $par = trim( $par );
  63. if ( strlen( $par ) === 0 ) {
  64. $par = null;
  65. } elseif ( strlen( $par ) > BotPassword::APPID_MAXLENGTH ) {
  66. throw new ErrorPageError( 'botpasswords', 'botpasswords-bad-appid',
  67. [ htmlspecialchars( $par ) ] );
  68. }
  69. parent::execute( $par );
  70. }
  71. protected function checkExecutePermissions( User $user ) {
  72. parent::checkExecutePermissions( $user );
  73. if ( !$this->getConfig()->get( 'EnableBotPasswords' ) ) {
  74. throw new ErrorPageError( 'botpasswords', 'botpasswords-disabled' );
  75. }
  76. $this->userId = CentralIdLookup::factory()->centralIdFromLocalUser( $this->getUser() );
  77. if ( !$this->userId ) {
  78. throw new ErrorPageError( 'botpasswords', 'botpasswords-no-central-id' );
  79. }
  80. }
  81. protected function getFormFields() {
  82. $fields = [];
  83. if ( $this->par !== null ) {
  84. $this->botPassword = BotPassword::newFromCentralId( $this->userId, $this->par );
  85. if ( !$this->botPassword ) {
  86. $this->botPassword = BotPassword::newUnsaved( [
  87. 'centralId' => $this->userId,
  88. 'appId' => $this->par,
  89. ] );
  90. }
  91. $sep = BotPassword::getSeparator();
  92. $fields[] = [
  93. 'type' => 'info',
  94. 'label-message' => 'username',
  95. 'default' => $this->getUser()->getName() . $sep . $this->par
  96. ];
  97. if ( $this->botPassword->isSaved() ) {
  98. $fields['resetPassword'] = [
  99. 'type' => 'check',
  100. 'label-message' => 'botpasswords-label-resetpassword',
  101. ];
  102. if ( $this->botPassword->isInvalid() ) {
  103. $fields['resetPassword']['default'] = true;
  104. }
  105. }
  106. $lang = $this->getLanguage();
  107. $showGrants = MWGrants::getValidGrants();
  108. $fields['grants'] = [
  109. 'type' => 'checkmatrix',
  110. 'label-message' => 'botpasswords-label-grants',
  111. 'help-message' => 'botpasswords-help-grants',
  112. 'columns' => [
  113. $this->msg( 'botpasswords-label-grants-column' )->escaped() => 'grant'
  114. ],
  115. 'rows' => array_combine(
  116. array_map( 'MWGrants::getGrantsLink', $showGrants ),
  117. $showGrants
  118. ),
  119. 'default' => array_map(
  120. function ( $g ) {
  121. return "grant-$g";
  122. },
  123. $this->botPassword->getGrants()
  124. ),
  125. 'tooltips' => array_combine(
  126. array_map( 'MWGrants::getGrantsLink', $showGrants ),
  127. array_map(
  128. function ( $rights ) use ( $lang ) {
  129. return $lang->semicolonList( array_map( 'User::getRightDescription', $rights ) );
  130. },
  131. array_intersect_key( MWGrants::getRightsByGrant(), array_flip( $showGrants ) )
  132. )
  133. ),
  134. 'force-options-on' => array_map(
  135. function ( $g ) {
  136. return "grant-$g";
  137. },
  138. MWGrants::getHiddenGrants()
  139. ),
  140. ];
  141. $fields['restrictions'] = [
  142. 'class' => HTMLRestrictionsField::class,
  143. 'required' => true,
  144. 'default' => $this->botPassword->getRestrictions(),
  145. ];
  146. } else {
  147. $linkRenderer = $this->getLinkRenderer();
  148. $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
  149. $dbr = BotPassword::getDB( DB_REPLICA );
  150. $res = $dbr->select(
  151. 'bot_passwords',
  152. [ 'bp_app_id', 'bp_password' ],
  153. [ 'bp_user' => $this->userId ],
  154. __METHOD__
  155. );
  156. foreach ( $res as $row ) {
  157. try {
  158. $password = $passwordFactory->newFromCiphertext( $row->bp_password );
  159. $passwordInvalid = $password instanceof InvalidPassword;
  160. unset( $password );
  161. } catch ( PasswordError $ex ) {
  162. $passwordInvalid = true;
  163. }
  164. $text = $linkRenderer->makeKnownLink(
  165. $this->getPageTitle( $row->bp_app_id ),
  166. $row->bp_app_id
  167. );
  168. if ( $passwordInvalid ) {
  169. $text .= $this->msg( 'word-separator' )->escaped()
  170. . $this->msg( 'botpasswords-label-needsreset' )->parse();
  171. }
  172. $fields[] = [
  173. 'section' => 'existing',
  174. 'type' => 'info',
  175. 'raw' => true,
  176. 'default' => $text,
  177. ];
  178. }
  179. $fields['appId'] = [
  180. 'section' => 'createnew',
  181. 'type' => 'textwithbutton',
  182. 'label-message' => 'botpasswords-label-appid',
  183. 'buttondefault' => $this->msg( 'botpasswords-label-create' )->text(),
  184. 'buttonflags' => [ 'progressive', 'primary' ],
  185. 'required' => true,
  186. 'size' => BotPassword::APPID_MAXLENGTH,
  187. 'maxlength' => BotPassword::APPID_MAXLENGTH,
  188. 'validation-callback' => function ( $v ) {
  189. $v = trim( $v );
  190. return $v !== '' && strlen( $v ) <= BotPassword::APPID_MAXLENGTH;
  191. },
  192. ];
  193. $fields[] = [
  194. 'type' => 'hidden',
  195. 'default' => 'new',
  196. 'name' => 'op',
  197. ];
  198. }
  199. return $fields;
  200. }
  201. protected function alterForm( HTMLForm $form ) {
  202. $form->setId( 'mw-botpasswords-form' );
  203. $form->setTableId( 'mw-botpasswords-table' );
  204. $form->addPreText( $this->msg( 'botpasswords-summary' )->parseAsBlock() );
  205. $form->suppressDefaultSubmit();
  206. if ( $this->par !== null ) {
  207. if ( $this->botPassword->isSaved() ) {
  208. $form->setWrapperLegendMsg( 'botpasswords-editexisting' );
  209. $form->addButton( [
  210. 'name' => 'op',
  211. 'value' => 'update',
  212. 'label-message' => 'botpasswords-label-update',
  213. 'flags' => [ 'primary', 'progressive' ],
  214. ] );
  215. $form->addButton( [
  216. 'name' => 'op',
  217. 'value' => 'delete',
  218. 'label-message' => 'botpasswords-label-delete',
  219. 'flags' => [ 'destructive' ],
  220. ] );
  221. } else {
  222. $form->setWrapperLegendMsg( 'botpasswords-createnew' );
  223. $form->addButton( [
  224. 'name' => 'op',
  225. 'value' => 'create',
  226. 'label-message' => 'botpasswords-label-create',
  227. 'flags' => [ 'primary', 'progressive' ],
  228. ] );
  229. }
  230. $form->addButton( [
  231. 'name' => 'op',
  232. 'value' => 'cancel',
  233. 'label-message' => 'botpasswords-label-cancel'
  234. ] );
  235. }
  236. }
  237. public function onSubmit( array $data ) {
  238. $op = $this->getRequest()->getVal( 'op', '' );
  239. switch ( $op ) {
  240. case 'new':
  241. $this->getOutput()->redirect( $this->getPageTitle( $data['appId'] )->getFullURL() );
  242. return false;
  243. case 'create':
  244. $this->operation = 'insert';
  245. return $this->save( $data );
  246. case 'update':
  247. $this->operation = 'update';
  248. return $this->save( $data );
  249. case 'delete':
  250. $this->operation = 'delete';
  251. $bp = BotPassword::newFromCentralId( $this->userId, $this->par );
  252. if ( $bp ) {
  253. $bp->delete();
  254. $this->logger->info(
  255. "Bot password {op} for {user}@{app_id}",
  256. [
  257. 'app_id' => $this->par,
  258. 'user' => $this->getUser()->getName(),
  259. 'centralId' => $this->userId,
  260. 'op' => 'delete',
  261. 'client_ip' => $this->getRequest()->getIP()
  262. ]
  263. );
  264. }
  265. return Status::newGood();
  266. case 'cancel':
  267. $this->getOutput()->redirect( $this->getPageTitle()->getFullURL() );
  268. return false;
  269. }
  270. return false;
  271. }
  272. private function save( array $data ) {
  273. $bp = BotPassword::newUnsaved( [
  274. 'centralId' => $this->userId,
  275. 'appId' => $this->par,
  276. 'restrictions' => $data['restrictions'],
  277. 'grants' => array_merge(
  278. MWGrants::getHiddenGrants(),
  279. // @phan-suppress-next-next-line PhanTypeMismatchArgumentInternal See phan issue #3163,
  280. // it's probably failing to infer the type of $data['grants']
  281. preg_replace( '/^grant-/', '', $data['grants'] )
  282. )
  283. ] );
  284. if ( $this->operation === 'insert' || !empty( $data['resetPassword'] ) ) {
  285. $this->password = BotPassword::generatePassword( $this->getConfig() );
  286. $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
  287. $password = $passwordFactory->newFromPlaintext( $this->password );
  288. } else {
  289. $password = null;
  290. }
  291. if ( $bp->save( $this->operation, $password ) ) {
  292. $this->logger->info(
  293. "Bot password {op} for {user}@{app_id}",
  294. [
  295. 'op' => $this->operation,
  296. 'user' => $this->getUser()->getName(),
  297. 'app_id' => $this->par,
  298. 'centralId' => $this->userId,
  299. 'restrictions' => $data['restrictions'],
  300. 'grants' => $bp->getGrants(),
  301. 'client_ip' => $this->getRequest()->getIP()
  302. ]
  303. );
  304. return Status::newGood();
  305. } else {
  306. // Messages: botpasswords-insert-failed, botpasswords-update-failed
  307. return Status::newFatal( "botpasswords-{$this->operation}-failed", $this->par );
  308. }
  309. }
  310. public function onSuccess() {
  311. $out = $this->getOutput();
  312. $username = $this->getUser()->getName();
  313. switch ( $this->operation ) {
  314. case 'insert':
  315. $out->setPageTitle( $this->msg( 'botpasswords-created-title' )->text() );
  316. $out->addWikiMsg( 'botpasswords-created-body', $this->par, $username );
  317. break;
  318. case 'update':
  319. $out->setPageTitle( $this->msg( 'botpasswords-updated-title' )->text() );
  320. $out->addWikiMsg( 'botpasswords-updated-body', $this->par, $username );
  321. break;
  322. case 'delete':
  323. $out->setPageTitle( $this->msg( 'botpasswords-deleted-title' )->text() );
  324. $out->addWikiMsg( 'botpasswords-deleted-body', $this->par, $username );
  325. $this->password = null;
  326. break;
  327. }
  328. if ( $this->password !== null ) {
  329. $sep = BotPassword::getSeparator();
  330. $out->addWikiMsg(
  331. 'botpasswords-newpassword',
  332. htmlspecialchars( $username . $sep . $this->par ),
  333. htmlspecialchars( $this->password ),
  334. htmlspecialchars( $username ),
  335. htmlspecialchars( $this->par . $sep . $this->password )
  336. );
  337. $this->password = null;
  338. }
  339. $out->addReturnTo( $this->getPageTitle() );
  340. }
  341. protected function getGroupName() {
  342. return 'users';
  343. }
  344. protected function getDisplayFormat() {
  345. return 'ooui';
  346. }
  347. }