Maintenance.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. <?php
  2. /**
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License along
  14. * with this program; if not, write to the Free Software Foundation, Inc.,
  15. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. * http://www.gnu.org/copyleft/gpl.html
  17. *
  18. * @file
  19. * @ingroup Maintenance
  20. * @defgroup Maintenance Maintenance
  21. */
  22. // Bail on old versions of PHP, or if composer has not been run yet to install
  23. // dependencies.
  24. require_once __DIR__ . '/../includes/PHPVersionCheck.php';
  25. wfEntryPointCheck( 'cli' );
  26. /**
  27. * @defgroup MaintenanceArchive Maintenance archives
  28. * @ingroup Maintenance
  29. */
  30. // Define this so scripts can easily find doMaintenance.php
  31. define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
  32. define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
  33. $maintClass = false;
  34. use MediaWiki\Logger\LoggerFactory;
  35. use MediaWiki\MediaWikiServices;
  36. /**
  37. * Abstract maintenance class for quickly writing and churning out
  38. * maintenance scripts with minimal effort. All that _must_ be defined
  39. * is the execute() method. See docs/maintenance.txt for more info
  40. * and a quick demo of how to use it.
  41. *
  42. * @author Chad Horohoe <chad@anyonecanedit.org>
  43. * @since 1.16
  44. * @ingroup Maintenance
  45. */
  46. abstract class Maintenance {
  47. /**
  48. * Constants for DB access type
  49. * @see Maintenance::getDbType()
  50. */
  51. const DB_NONE = 0;
  52. const DB_STD = 1;
  53. const DB_ADMIN = 2;
  54. // Const for getStdin()
  55. const STDIN_ALL = 'all';
  56. // This is the desired params
  57. protected $mParams = [];
  58. // Array of mapping short parameters to long ones
  59. protected $mShortParamsMap = [];
  60. // Array of desired args
  61. protected $mArgList = [];
  62. // This is the list of options that were actually passed
  63. protected $mOptions = [];
  64. // This is the list of arguments that were actually passed
  65. protected $mArgs = [];
  66. // Name of the script currently running
  67. protected $mSelf;
  68. // Special vars for params that are always used
  69. protected $mQuiet = false;
  70. protected $mDbUser, $mDbPass;
  71. // A description of the script, children should change this via addDescription()
  72. protected $mDescription = '';
  73. // Have we already loaded our user input?
  74. protected $mInputLoaded = false;
  75. /**
  76. * Batch size. If a script supports this, they should set
  77. * a default with setBatchSize()
  78. *
  79. * @var int
  80. */
  81. protected $mBatchSize = null;
  82. // Generic options added by addDefaultParams()
  83. private $mGenericParameters = [];
  84. // Generic options which might or not be supported by the script
  85. private $mDependantParameters = [];
  86. /**
  87. * Used by getDB() / setDB()
  88. * @var Database
  89. */
  90. private $mDb = null;
  91. /** @var float UNIX timestamp */
  92. private $lastReplicationWait = 0.0;
  93. /**
  94. * Used when creating separate schema files.
  95. * @var resource
  96. */
  97. public $fileHandle;
  98. /**
  99. * Accessible via getConfig()
  100. *
  101. * @var Config
  102. */
  103. private $config;
  104. /**
  105. * @see Maintenance::requireExtension
  106. * @var array
  107. */
  108. private $requiredExtensions = [];
  109. /**
  110. * Used to read the options in the order they were passed.
  111. * Useful for option chaining (Ex. dumpBackup.php). It will
  112. * be an empty array if the options are passed in through
  113. * loadParamsAndArgs( $self, $opts, $args ).
  114. *
  115. * This is an array of arrays where
  116. * 0 => the option and 1 => parameter value.
  117. *
  118. * @var array
  119. */
  120. public $orderedOptions = [];
  121. /**
  122. * Default constructor. Children should call this *first* if implementing
  123. * their own constructors
  124. */
  125. public function __construct() {
  126. // Setup $IP, using MW_INSTALL_PATH if it exists
  127. global $IP;
  128. $IP = strval( getenv( 'MW_INSTALL_PATH' ) ) !== ''
  129. ? getenv( 'MW_INSTALL_PATH' )
  130. : realpath( __DIR__ . '/..' );
  131. $this->addDefaultParams();
  132. register_shutdown_function( [ $this, 'outputChanneled' ], false );
  133. }
  134. /**
  135. * Should we execute the maintenance script, or just allow it to be included
  136. * as a standalone class? It checks that the call stack only includes this
  137. * function and "requires" (meaning was called from the file scope)
  138. *
  139. * @return bool
  140. */
  141. public static function shouldExecute() {
  142. global $wgCommandLineMode;
  143. if ( !function_exists( 'debug_backtrace' ) ) {
  144. // If someone has a better idea...
  145. return $wgCommandLineMode;
  146. }
  147. $bt = debug_backtrace();
  148. $count = count( $bt );
  149. if ( $count < 2 ) {
  150. return false; // sanity
  151. }
  152. if ( $bt[0]['class'] !== 'Maintenance' || $bt[0]['function'] !== 'shouldExecute' ) {
  153. return false; // last call should be to this function
  154. }
  155. $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
  156. for ( $i = 1; $i < $count; $i++ ) {
  157. if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
  158. return false; // previous calls should all be "requires"
  159. }
  160. }
  161. return true;
  162. }
  163. /**
  164. * Do the actual work. All child classes will need to implement this
  165. */
  166. abstract public function execute();
  167. /**
  168. * Add a parameter to the script. Will be displayed on --help
  169. * with the associated description
  170. *
  171. * @param string $name The name of the param (help, version, etc)
  172. * @param string $description The description of the param to show on --help
  173. * @param bool $required Is the param required?
  174. * @param bool $withArg Is an argument required with this option?
  175. * @param string $shortName Character to use as short name
  176. * @param bool $multiOccurrence Can this option be passed multiple times?
  177. */
  178. protected function addOption( $name, $description, $required = false,
  179. $withArg = false, $shortName = false, $multiOccurrence = false
  180. ) {
  181. $this->mParams[$name] = [
  182. 'desc' => $description,
  183. 'require' => $required,
  184. 'withArg' => $withArg,
  185. 'shortName' => $shortName,
  186. 'multiOccurrence' => $multiOccurrence
  187. ];
  188. if ( $shortName !== false ) {
  189. $this->mShortParamsMap[$shortName] = $name;
  190. }
  191. }
  192. /**
  193. * Checks to see if a particular param exists.
  194. * @param string $name The name of the param
  195. * @return bool
  196. */
  197. protected function hasOption( $name ) {
  198. return isset( $this->mOptions[$name] );
  199. }
  200. /**
  201. * Get an option, or return the default.
  202. *
  203. * If the option was added to support multiple occurrences,
  204. * this will return an array.
  205. *
  206. * @param string $name The name of the param
  207. * @param mixed $default Anything you want, default null
  208. * @return mixed
  209. */
  210. protected function getOption( $name, $default = null ) {
  211. if ( $this->hasOption( $name ) ) {
  212. return $this->mOptions[$name];
  213. } else {
  214. // Set it so we don't have to provide the default again
  215. $this->mOptions[$name] = $default;
  216. return $this->mOptions[$name];
  217. }
  218. }
  219. /**
  220. * Add some args that are needed
  221. * @param string $arg Name of the arg, like 'start'
  222. * @param string $description Short description of the arg
  223. * @param bool $required Is this required?
  224. */
  225. protected function addArg( $arg, $description, $required = true ) {
  226. $this->mArgList[] = [
  227. 'name' => $arg,
  228. 'desc' => $description,
  229. 'require' => $required
  230. ];
  231. }
  232. /**
  233. * Remove an option. Useful for removing options that won't be used in your script.
  234. * @param string $name The option to remove.
  235. */
  236. protected function deleteOption( $name ) {
  237. unset( $this->mParams[$name] );
  238. }
  239. /**
  240. * Set the description text.
  241. * @param string $text The text of the description
  242. */
  243. protected function addDescription( $text ) {
  244. $this->mDescription = $text;
  245. }
  246. /**
  247. * Does a given argument exist?
  248. * @param int $argId The integer value (from zero) for the arg
  249. * @return bool
  250. */
  251. protected function hasArg( $argId = 0 ) {
  252. return isset( $this->mArgs[$argId] );
  253. }
  254. /**
  255. * Get an argument.
  256. * @param int $argId The integer value (from zero) for the arg
  257. * @param mixed $default The default if it doesn't exist
  258. * @return mixed
  259. */
  260. protected function getArg( $argId = 0, $default = null ) {
  261. return $this->hasArg( $argId ) ? $this->mArgs[$argId] : $default;
  262. }
  263. /**
  264. * Set the batch size.
  265. * @param int $s The number of operations to do in a batch
  266. */
  267. protected function setBatchSize( $s = 0 ) {
  268. $this->mBatchSize = $s;
  269. // If we support $mBatchSize, show the option.
  270. // Used to be in addDefaultParams, but in order for that to
  271. // work, subclasses would have to call this function in the constructor
  272. // before they called parent::__construct which is just weird
  273. // (and really wasn't done).
  274. if ( $this->mBatchSize ) {
  275. $this->addOption( 'batch-size', 'Run this many operations ' .
  276. 'per batch, default: ' . $this->mBatchSize, false, true );
  277. if ( isset( $this->mParams['batch-size'] ) ) {
  278. // This seems a little ugly...
  279. $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
  280. }
  281. }
  282. }
  283. /**
  284. * Get the script's name
  285. * @return string
  286. */
  287. public function getName() {
  288. return $this->mSelf;
  289. }
  290. /**
  291. * Return input from stdin.
  292. * @param int $len The number of bytes to read. If null, just return the handle.
  293. * Maintenance::STDIN_ALL returns the full length
  294. * @return mixed
  295. */
  296. protected function getStdin( $len = null ) {
  297. if ( $len == Maintenance::STDIN_ALL ) {
  298. return file_get_contents( 'php://stdin' );
  299. }
  300. $f = fopen( 'php://stdin', 'rt' );
  301. if ( !$len ) {
  302. return $f;
  303. }
  304. $input = fgets( $f, $len );
  305. fclose( $f );
  306. return rtrim( $input );
  307. }
  308. /**
  309. * @return bool
  310. */
  311. public function isQuiet() {
  312. return $this->mQuiet;
  313. }
  314. /**
  315. * Throw some output to the user. Scripts can call this with no fears,
  316. * as we handle all --quiet stuff here
  317. * @param string $out The text to show to the user
  318. * @param mixed $channel Unique identifier for the channel. See function outputChanneled.
  319. */
  320. protected function output( $out, $channel = null ) {
  321. if ( $this->mQuiet ) {
  322. return;
  323. }
  324. if ( $channel === null ) {
  325. $this->cleanupChanneled();
  326. print $out;
  327. } else {
  328. $out = preg_replace( '/\n\z/', '', $out );
  329. $this->outputChanneled( $out, $channel );
  330. }
  331. }
  332. /**
  333. * Throw an error to the user. Doesn't respect --quiet, so don't use
  334. * this for non-error output
  335. * @param string $err The error to display
  336. * @param int $die If > 0, go ahead and die out using this int as the code
  337. */
  338. protected function error( $err, $die = 0 ) {
  339. $this->outputChanneled( false );
  340. if ( PHP_SAPI == 'cli' ) {
  341. fwrite( STDERR, $err . "\n" );
  342. } else {
  343. print $err;
  344. }
  345. $die = intval( $die );
  346. if ( $die > 0 ) {
  347. die( $die );
  348. }
  349. }
  350. private $atLineStart = true;
  351. private $lastChannel = null;
  352. /**
  353. * Clean up channeled output. Output a newline if necessary.
  354. */
  355. public function cleanupChanneled() {
  356. if ( !$this->atLineStart ) {
  357. print "\n";
  358. $this->atLineStart = true;
  359. }
  360. }
  361. /**
  362. * Message outputter with channeled message support. Messages on the
  363. * same channel are concatenated, but any intervening messages in another
  364. * channel start a new line.
  365. * @param string $msg The message without trailing newline
  366. * @param string $channel Channel identifier or null for no
  367. * channel. Channel comparison uses ===.
  368. */
  369. public function outputChanneled( $msg, $channel = null ) {
  370. if ( $msg === false ) {
  371. $this->cleanupChanneled();
  372. return;
  373. }
  374. // End the current line if necessary
  375. if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
  376. print "\n";
  377. }
  378. print $msg;
  379. $this->atLineStart = false;
  380. if ( $channel === null ) {
  381. // For unchanneled messages, output trailing newline immediately
  382. print "\n";
  383. $this->atLineStart = true;
  384. }
  385. $this->lastChannel = $channel;
  386. }
  387. /**
  388. * Does the script need different DB access? By default, we give Maintenance
  389. * scripts normal rights to the DB. Sometimes, a script needs admin rights
  390. * access for a reason and sometimes they want no access. Subclasses should
  391. * override and return one of the following values, as needed:
  392. * Maintenance::DB_NONE - For no DB access at all
  393. * Maintenance::DB_STD - For normal DB access, default
  394. * Maintenance::DB_ADMIN - For admin DB access
  395. * @return int
  396. */
  397. public function getDbType() {
  398. return Maintenance::DB_STD;
  399. }
  400. /**
  401. * Add the default parameters to the scripts
  402. */
  403. protected function addDefaultParams() {
  404. # Generic (non script dependant) options:
  405. $this->addOption( 'help', 'Display this help message', false, false, 'h' );
  406. $this->addOption( 'quiet', 'Whether to supress non-error output', false, false, 'q' );
  407. $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
  408. $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
  409. $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
  410. $this->addOption(
  411. 'memory-limit',
  412. 'Set a specific memory limit for the script, '
  413. . '"max" for no limit or "default" to avoid changing it'
  414. );
  415. $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
  416. "http://en.wikipedia.org. This is sometimes necessary because " .
  417. "server name detection may fail in command line scripts.", false, true );
  418. $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
  419. # Save generic options to display them separately in help
  420. $this->mGenericParameters = $this->mParams;
  421. # Script dependant options:
  422. // If we support a DB, show the options
  423. if ( $this->getDbType() > 0 ) {
  424. $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
  425. $this->addOption( 'dbpass', 'The password to use for this script', false, true );
  426. }
  427. # Save additional script dependant options to display
  428. #  them separately in help
  429. $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
  430. }
  431. /**
  432. * @since 1.24
  433. * @return Config
  434. */
  435. public function getConfig() {
  436. if ( $this->config === null ) {
  437. $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
  438. }
  439. return $this->config;
  440. }
  441. /**
  442. * @since 1.24
  443. * @param Config $config
  444. */
  445. public function setConfig( Config $config ) {
  446. $this->config = $config;
  447. }
  448. /**
  449. * Indicate that the specified extension must be
  450. * loaded before the script can run.
  451. *
  452. * This *must* be called in the constructor.
  453. *
  454. * @since 1.28
  455. * @param string $name
  456. */
  457. protected function requireExtension( $name ) {
  458. $this->requiredExtensions[] = $name;
  459. }
  460. /**
  461. * Verify that the required extensions are installed
  462. *
  463. * @since 1.28
  464. */
  465. public function checkRequiredExtensions() {
  466. $registry = ExtensionRegistry::getInstance();
  467. $missing = [];
  468. foreach ( $this->requiredExtensions as $name ) {
  469. if ( !$registry->isLoaded( $name ) ) {
  470. $missing[] = $name;
  471. }
  472. }
  473. if ( $missing ) {
  474. $joined = implode( ', ', $missing );
  475. $msg = "The following extensions are required to be installed "
  476. . "for this script to run: $joined. Please enable them and then try again.";
  477. $this->error( $msg, 1 );
  478. }
  479. }
  480. /**
  481. * Set triggers like when to try to run deferred updates
  482. * @since 1.28
  483. */
  484. public function setAgentAndTriggers() {
  485. if ( function_exists( 'posix_getpwuid' ) ) {
  486. $agent = posix_getpwuid( posix_geteuid() )['name'];
  487. } else {
  488. $agent = 'sysadmin';
  489. }
  490. $agent .= '@' . wfHostname();
  491. $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  492. // Add a comment for easy SHOW PROCESSLIST interpretation
  493. $lbFactory->setAgentName(
  494. mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
  495. );
  496. self::setLBFactoryTriggers( $lbFactory );
  497. }
  498. /**
  499. * @param LBFactory $LBFactory
  500. * @since 1.28
  501. */
  502. public static function setLBFactoryTriggers( LBFactory $LBFactory ) {
  503. // Hook into period lag checks which often happen in long-running scripts
  504. $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  505. $lbFactory->setWaitForReplicationListener(
  506. __METHOD__,
  507. function () {
  508. global $wgCommandLineMode;
  509. // Check config in case of JobRunner and unit tests
  510. if ( $wgCommandLineMode ) {
  511. DeferredUpdates::tryOpportunisticExecute( 'run' );
  512. }
  513. }
  514. );
  515. // Check for other windows to run them. A script may read or do a few writes
  516. // to the master but mostly be writing to something else, like a file store.
  517. $lbFactory->getMainLB()->setTransactionListener(
  518. __METHOD__,
  519. function ( $trigger ) {
  520. global $wgCommandLineMode;
  521. // Check config in case of JobRunner and unit tests
  522. if ( $wgCommandLineMode && $trigger === IDatabase::TRIGGER_COMMIT ) {
  523. DeferredUpdates::tryOpportunisticExecute( 'run' );
  524. }
  525. }
  526. );
  527. }
  528. /**
  529. * Run a child maintenance script. Pass all of the current arguments
  530. * to it.
  531. * @param string $maintClass A name of a child maintenance class
  532. * @param string $classFile Full path of where the child is
  533. * @return Maintenance
  534. */
  535. public function runChild( $maintClass, $classFile = null ) {
  536. // Make sure the class is loaded first
  537. if ( !class_exists( $maintClass ) ) {
  538. if ( $classFile ) {
  539. require_once $classFile;
  540. }
  541. if ( !class_exists( $maintClass ) ) {
  542. $this->error( "Cannot spawn child: $maintClass" );
  543. }
  544. }
  545. /**
  546. * @var $child Maintenance
  547. */
  548. $child = new $maintClass();
  549. $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
  550. if ( !is_null( $this->mDb ) ) {
  551. $child->setDB( $this->mDb );
  552. }
  553. return $child;
  554. }
  555. /**
  556. * Do some sanity checking and basic setup
  557. */
  558. public function setup() {
  559. global $IP, $wgCommandLineMode, $wgRequestTime;
  560. # Abort if called from a web server
  561. if ( isset( $_SERVER ) && isset( $_SERVER['REQUEST_METHOD'] ) ) {
  562. $this->error( 'This script must be run from the command line', true );
  563. }
  564. if ( $IP === null ) {
  565. $this->error( "\$IP not set, aborting!\n" .
  566. '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
  567. }
  568. # Make sure we can handle script parameters
  569. if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
  570. $this->error( 'Cannot get command line arguments, register_argc_argv is set to false', true );
  571. }
  572. // Send PHP warnings and errors to stderr instead of stdout.
  573. // This aids in diagnosing problems, while keeping messages
  574. // out of redirected output.
  575. if ( ini_get( 'display_errors' ) ) {
  576. ini_set( 'display_errors', 'stderr' );
  577. }
  578. $this->loadParamsAndArgs();
  579. $this->maybeHelp();
  580. # Set the memory limit
  581. # Note we need to set it again later in cache LocalSettings changed it
  582. $this->adjustMemoryLimit();
  583. # Set max execution time to 0 (no limit). PHP.net says that
  584. # "When running PHP from the command line the default setting is 0."
  585. # But sometimes this doesn't seem to be the case.
  586. ini_set( 'max_execution_time', 0 );
  587. $wgRequestTime = microtime( true );
  588. # Define us as being in MediaWiki
  589. define( 'MEDIAWIKI', true );
  590. $wgCommandLineMode = true;
  591. # Turn off output buffering if it's on
  592. while ( ob_get_level() > 0 ) {
  593. ob_end_flush();
  594. }
  595. $this->validateParamsAndArgs();
  596. }
  597. /**
  598. * Normally we disable the memory_limit when running admin scripts.
  599. * Some scripts may wish to actually set a limit, however, to avoid
  600. * blowing up unexpectedly. We also support a --memory-limit option,
  601. * to allow sysadmins to explicitly set one if they'd prefer to override
  602. * defaults (or for people using Suhosin which yells at you for trying
  603. * to disable the limits)
  604. * @return string
  605. */
  606. public function memoryLimit() {
  607. $limit = $this->getOption( 'memory-limit', 'max' );
  608. $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
  609. return $limit;
  610. }
  611. /**
  612. * Adjusts PHP's memory limit to better suit our needs, if needed.
  613. */
  614. protected function adjustMemoryLimit() {
  615. $limit = $this->memoryLimit();
  616. if ( $limit == 'max' ) {
  617. $limit = -1; // no memory limit
  618. }
  619. if ( $limit != 'default' ) {
  620. ini_set( 'memory_limit', $limit );
  621. }
  622. }
  623. /**
  624. * Activate the profiler (assuming $wgProfiler is set)
  625. */
  626. protected function activateProfiler() {
  627. global $wgProfiler, $wgProfileLimit, $wgTrxProfilerLimits;
  628. $output = $this->getOption( 'profiler' );
  629. if ( !$output ) {
  630. return;
  631. }
  632. if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
  633. $class = $wgProfiler['class'];
  634. /** @var Profiler $profiler */
  635. $profiler = new $class(
  636. [ 'sampling' => 1, 'output' => [ $output ] ]
  637. + $wgProfiler
  638. + [ 'threshold' => $wgProfileLimit ]
  639. );
  640. $profiler->setTemplated( true );
  641. Profiler::replaceStubInstance( $profiler );
  642. }
  643. $trxProfiler = Profiler::instance()->getTransactionProfiler();
  644. $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
  645. $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
  646. }
  647. /**
  648. * Clear all params and arguments.
  649. */
  650. public function clearParamsAndArgs() {
  651. $this->mOptions = [];
  652. $this->mArgs = [];
  653. $this->mInputLoaded = false;
  654. }
  655. /**
  656. * Load params and arguments from a given array
  657. * of command-line arguments
  658. *
  659. * @since 1.27
  660. * @param array $argv
  661. */
  662. public function loadWithArgv( $argv ) {
  663. $options = [];
  664. $args = [];
  665. $this->orderedOptions = [];
  666. # Parse arguments
  667. for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
  668. if ( $arg == '--' ) {
  669. # End of options, remainder should be considered arguments
  670. $arg = next( $argv );
  671. while ( $arg !== false ) {
  672. $args[] = $arg;
  673. $arg = next( $argv );
  674. }
  675. break;
  676. } elseif ( substr( $arg, 0, 2 ) == '--' ) {
  677. # Long options
  678. $option = substr( $arg, 2 );
  679. if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
  680. $param = next( $argv );
  681. if ( $param === false ) {
  682. $this->error( "\nERROR: $option parameter needs a value after it\n" );
  683. $this->maybeHelp( true );
  684. }
  685. $this->setParam( $options, $option, $param );
  686. } else {
  687. $bits = explode( '=', $option, 2 );
  688. if ( count( $bits ) > 1 ) {
  689. $option = $bits[0];
  690. $param = $bits[1];
  691. } else {
  692. $param = 1;
  693. }
  694. $this->setParam( $options, $option, $param );
  695. }
  696. } elseif ( $arg == '-' ) {
  697. # Lonely "-", often used to indicate stdin or stdout.
  698. $args[] = $arg;
  699. } elseif ( substr( $arg, 0, 1 ) == '-' ) {
  700. # Short options
  701. $argLength = strlen( $arg );
  702. for ( $p = 1; $p < $argLength; $p++ ) {
  703. $option = $arg[$p];
  704. if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
  705. $option = $this->mShortParamsMap[$option];
  706. }
  707. if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
  708. $param = next( $argv );
  709. if ( $param === false ) {
  710. $this->error( "\nERROR: $option parameter needs a value after it\n" );
  711. $this->maybeHelp( true );
  712. }
  713. $this->setParam( $options, $option, $param );
  714. } else {
  715. $this->setParam( $options, $option, 1 );
  716. }
  717. }
  718. } else {
  719. $args[] = $arg;
  720. }
  721. }
  722. $this->mOptions = $options;
  723. $this->mArgs = $args;
  724. $this->loadSpecialVars();
  725. $this->mInputLoaded = true;
  726. }
  727. /**
  728. * Helper function used solely by loadParamsAndArgs
  729. * to prevent code duplication
  730. *
  731. * This sets the param in the options array based on
  732. * whether or not it can be specified multiple times.
  733. *
  734. * @since 1.27
  735. * @param array $options
  736. * @param string $option
  737. * @param mixed $value
  738. */
  739. private function setParam( &$options, $option, $value ) {
  740. $this->orderedOptions[] = [ $option, $value ];
  741. if ( isset( $this->mParams[$option] ) ) {
  742. $multi = $this->mParams[$option]['multiOccurrence'];
  743. } else {
  744. $multi = false;
  745. }
  746. $exists = array_key_exists( $option, $options );
  747. if ( $multi && $exists ) {
  748. $options[$option][] = $value;
  749. } elseif ( $multi ) {
  750. $options[$option] = [ $value ];
  751. } elseif ( !$exists ) {
  752. $options[$option] = $value;
  753. } else {
  754. $this->error( "\nERROR: $option parameter given twice\n" );
  755. $this->maybeHelp( true );
  756. }
  757. }
  758. /**
  759. * Process command line arguments
  760. * $mOptions becomes an array with keys set to the option names
  761. * $mArgs becomes a zero-based array containing the non-option arguments
  762. *
  763. * @param string $self The name of the script, if any
  764. * @param array $opts An array of options, in form of key=>value
  765. * @param array $args An array of command line arguments
  766. */
  767. public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
  768. # If we were given opts or args, set those and return early
  769. if ( $self ) {
  770. $this->mSelf = $self;
  771. $this->mInputLoaded = true;
  772. }
  773. if ( $opts ) {
  774. $this->mOptions = $opts;
  775. $this->mInputLoaded = true;
  776. }
  777. if ( $args ) {
  778. $this->mArgs = $args;
  779. $this->mInputLoaded = true;
  780. }
  781. # If we've already loaded input (either by user values or from $argv)
  782. # skip on loading it again. The array_shift() will corrupt values if
  783. # it's run again and again
  784. if ( $this->mInputLoaded ) {
  785. $this->loadSpecialVars();
  786. return;
  787. }
  788. global $argv;
  789. $this->mSelf = $argv[0];
  790. $this->loadWithArgv( array_slice( $argv, 1 ) );
  791. }
  792. /**
  793. * Run some validation checks on the params, etc
  794. */
  795. protected function validateParamsAndArgs() {
  796. $die = false;
  797. # Check to make sure we've got all the required options
  798. foreach ( $this->mParams as $opt => $info ) {
  799. if ( $info['require'] && !$this->hasOption( $opt ) ) {
  800. $this->error( "Param $opt required!" );
  801. $die = true;
  802. }
  803. }
  804. # Check arg list too
  805. foreach ( $this->mArgList as $k => $info ) {
  806. if ( $info['require'] && !$this->hasArg( $k ) ) {
  807. $this->error( 'Argument <' . $info['name'] . '> required!' );
  808. $die = true;
  809. }
  810. }
  811. if ( $die ) {
  812. $this->maybeHelp( true );
  813. }
  814. }
  815. /**
  816. * Handle the special variables that are global to all scripts
  817. */
  818. protected function loadSpecialVars() {
  819. if ( $this->hasOption( 'dbuser' ) ) {
  820. $this->mDbUser = $this->getOption( 'dbuser' );
  821. }
  822. if ( $this->hasOption( 'dbpass' ) ) {
  823. $this->mDbPass = $this->getOption( 'dbpass' );
  824. }
  825. if ( $this->hasOption( 'quiet' ) ) {
  826. $this->mQuiet = true;
  827. }
  828. if ( $this->hasOption( 'batch-size' ) ) {
  829. $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
  830. }
  831. }
  832. /**
  833. * Maybe show the help.
  834. * @param bool $force Whether to force the help to show, default false
  835. */
  836. protected function maybeHelp( $force = false ) {
  837. if ( !$force && !$this->hasOption( 'help' ) ) {
  838. return;
  839. }
  840. $screenWidth = 80; // TODO: Calculate this!
  841. $tab = " ";
  842. $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
  843. ksort( $this->mParams );
  844. $this->mQuiet = false;
  845. // Description ...
  846. if ( $this->mDescription ) {
  847. $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
  848. }
  849. $output = "\nUsage: php " . basename( $this->mSelf );
  850. // ... append parameters ...
  851. if ( $this->mParams ) {
  852. $output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
  853. }
  854. // ... and append arguments.
  855. if ( $this->mArgList ) {
  856. $output .= ' ';
  857. foreach ( $this->mArgList as $k => $arg ) {
  858. if ( $arg['require'] ) {
  859. $output .= '<' . $arg['name'] . '>';
  860. } else {
  861. $output .= '[' . $arg['name'] . ']';
  862. }
  863. if ( $k < count( $this->mArgList ) - 1 ) {
  864. $output .= ' ';
  865. }
  866. }
  867. }
  868. $this->output( "$output\n\n" );
  869. # TODO abstract some repetitive code below
  870. // Generic parameters
  871. $this->output( "Generic maintenance parameters:\n" );
  872. foreach ( $this->mGenericParameters as $par => $info ) {
  873. if ( $info['shortName'] !== false ) {
  874. $par .= " (-{$info['shortName']})";
  875. }
  876. $this->output(
  877. wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
  878. "\n$tab$tab" ) . "\n"
  879. );
  880. }
  881. $this->output( "\n" );
  882. $scriptDependantParams = $this->mDependantParameters;
  883. if ( count( $scriptDependantParams ) > 0 ) {
  884. $this->output( "Script dependant parameters:\n" );
  885. // Parameters description
  886. foreach ( $scriptDependantParams as $par => $info ) {
  887. if ( $info['shortName'] !== false ) {
  888. $par .= " (-{$info['shortName']})";
  889. }
  890. $this->output(
  891. wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
  892. "\n$tab$tab" ) . "\n"
  893. );
  894. }
  895. $this->output( "\n" );
  896. }
  897. // Script specific parameters not defined on construction by
  898. // Maintenance::addDefaultParams()
  899. $scriptSpecificParams = array_diff_key(
  900. # all script parameters:
  901. $this->mParams,
  902. # remove the Maintenance default parameters:
  903. $this->mGenericParameters,
  904. $this->mDependantParameters
  905. );
  906. if ( count( $scriptSpecificParams ) > 0 ) {
  907. $this->output( "Script specific parameters:\n" );
  908. // Parameters description
  909. foreach ( $scriptSpecificParams as $par => $info ) {
  910. if ( $info['shortName'] !== false ) {
  911. $par .= " (-{$info['shortName']})";
  912. }
  913. $this->output(
  914. wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
  915. "\n$tab$tab" ) . "\n"
  916. );
  917. }
  918. $this->output( "\n" );
  919. }
  920. // Print arguments
  921. if ( count( $this->mArgList ) > 0 ) {
  922. $this->output( "Arguments:\n" );
  923. // Arguments description
  924. foreach ( $this->mArgList as $info ) {
  925. $openChar = $info['require'] ? '<' : '[';
  926. $closeChar = $info['require'] ? '>' : ']';
  927. $this->output(
  928. wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
  929. $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
  930. );
  931. }
  932. $this->output( "\n" );
  933. }
  934. die( 1 );
  935. }
  936. /**
  937. * Handle some last-minute setup here.
  938. */
  939. public function finalSetup() {
  940. global $wgCommandLineMode, $wgShowSQLErrors, $wgServer;
  941. global $wgDBadminuser, $wgDBadminpassword;
  942. global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
  943. # Turn off output buffering again, it might have been turned on in the settings files
  944. if ( ob_get_level() ) {
  945. ob_end_flush();
  946. }
  947. # Same with these
  948. $wgCommandLineMode = true;
  949. # Override $wgServer
  950. if ( $this->hasOption( 'server' ) ) {
  951. $wgServer = $this->getOption( 'server', $wgServer );
  952. }
  953. # If these were passed, use them
  954. if ( $this->mDbUser ) {
  955. $wgDBadminuser = $this->mDbUser;
  956. }
  957. if ( $this->mDbPass ) {
  958. $wgDBadminpassword = $this->mDbPass;
  959. }
  960. if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
  961. $wgDBuser = $wgDBadminuser;
  962. $wgDBpassword = $wgDBadminpassword;
  963. if ( $wgDBservers ) {
  964. /**
  965. * @var $wgDBservers array
  966. */
  967. foreach ( $wgDBservers as $i => $server ) {
  968. $wgDBservers[$i]['user'] = $wgDBuser;
  969. $wgDBservers[$i]['password'] = $wgDBpassword;
  970. }
  971. }
  972. if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
  973. $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
  974. $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
  975. }
  976. MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
  977. }
  978. // Per-script profiling; useful for debugging
  979. $this->activateProfiler();
  980. $this->afterFinalSetup();
  981. $wgShowSQLErrors = true;
  982. MediaWiki\suppressWarnings();
  983. set_time_limit( 0 );
  984. MediaWiki\restoreWarnings();
  985. $this->adjustMemoryLimit();
  986. }
  987. /**
  988. * Execute a callback function at the end of initialisation
  989. */
  990. protected function afterFinalSetup() {
  991. if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
  992. call_user_func( MW_CMDLINE_CALLBACK );
  993. }
  994. }
  995. /**
  996. * Potentially debug globals. Originally a feature only
  997. * for refreshLinks
  998. */
  999. public function globals() {
  1000. if ( $this->hasOption( 'globals' ) ) {
  1001. print_r( $GLOBALS );
  1002. }
  1003. }
  1004. /**
  1005. * Generic setup for most installs. Returns the location of LocalSettings
  1006. * @return string
  1007. */
  1008. public function loadSettings() {
  1009. global $wgCommandLineMode, $IP;
  1010. if ( isset( $this->mOptions['conf'] ) ) {
  1011. $settingsFile = $this->mOptions['conf'];
  1012. } elseif ( defined( "MW_CONFIG_FILE" ) ) {
  1013. $settingsFile = MW_CONFIG_FILE;
  1014. } else {
  1015. $settingsFile = "$IP/LocalSettings.php";
  1016. }
  1017. if ( isset( $this->mOptions['wiki'] ) ) {
  1018. $bits = explode( '-', $this->mOptions['wiki'] );
  1019. if ( count( $bits ) == 1 ) {
  1020. $bits[] = '';
  1021. }
  1022. define( 'MW_DB', $bits[0] );
  1023. define( 'MW_PREFIX', $bits[1] );
  1024. }
  1025. if ( !is_readable( $settingsFile ) ) {
  1026. $this->error( "A copy of your installation's LocalSettings.php\n" .
  1027. "must exist and be readable in the source directory.\n" .
  1028. "Use --conf to specify it.", true );
  1029. }
  1030. $wgCommandLineMode = true;
  1031. return $settingsFile;
  1032. }
  1033. /**
  1034. * Support function for cleaning up redundant text records
  1035. * @param bool $delete Whether or not to actually delete the records
  1036. * @author Rob Church <robchur@gmail.com>
  1037. */
  1038. public function purgeRedundantText( $delete = true ) {
  1039. # Data should come off the master, wrapped in a transaction
  1040. $dbw = $this->getDB( DB_MASTER );
  1041. $this->beginTransaction( $dbw, __METHOD__ );
  1042. # Get "active" text records from the revisions table
  1043. $cur = [];
  1044. $this->output( 'Searching for active text records in revisions table...' );
  1045. $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
  1046. foreach ( $res as $row ) {
  1047. $cur[] = $row->rev_text_id;
  1048. }
  1049. $this->output( "done.\n" );
  1050. # Get "active" text records from the archive table
  1051. $this->output( 'Searching for active text records in archive table...' );
  1052. $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
  1053. foreach ( $res as $row ) {
  1054. # old pre-MW 1.5 records can have null ar_text_id's.
  1055. if ( $row->ar_text_id !== null ) {
  1056. $cur[] = $row->ar_text_id;
  1057. }
  1058. }
  1059. $this->output( "done.\n" );
  1060. # Get the IDs of all text records not in these sets
  1061. $this->output( 'Searching for inactive text records...' );
  1062. $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
  1063. $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
  1064. $old = [];
  1065. foreach ( $res as $row ) {
  1066. $old[] = $row->old_id;
  1067. }
  1068. $this->output( "done.\n" );
  1069. # Inform the user of what we're going to do
  1070. $count = count( $old );
  1071. $this->output( "$count inactive items found.\n" );
  1072. # Delete as appropriate
  1073. if ( $delete && $count ) {
  1074. $this->output( 'Deleting...' );
  1075. $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
  1076. $this->output( "done.\n" );
  1077. }
  1078. # Done
  1079. $this->commitTransaction( $dbw, __METHOD__ );
  1080. }
  1081. /**
  1082. * Get the maintenance directory.
  1083. * @return string
  1084. */
  1085. protected function getDir() {
  1086. return __DIR__;
  1087. }
  1088. /**
  1089. * Returns a database to be used by current maintenance script. It can be set by setDB().
  1090. * If not set, wfGetDB() will be used.
  1091. * This function has the same parameters as wfGetDB()
  1092. *
  1093. * @param integer $db DB index (DB_REPLICA/DB_MASTER)
  1094. * @param array $groups; default: empty array
  1095. * @param string|bool $wiki; default: current wiki
  1096. * @return Database
  1097. */
  1098. protected function getDB( $db, $groups = [], $wiki = false ) {
  1099. if ( is_null( $this->mDb ) ) {
  1100. return wfGetDB( $db, $groups, $wiki );
  1101. } else {
  1102. return $this->mDb;
  1103. }
  1104. }
  1105. /**
  1106. * Sets database object to be returned by getDB().
  1107. *
  1108. * @param IDatabase $db Database object to be used
  1109. */
  1110. public function setDB( IDatabase $db ) {
  1111. $this->mDb = $db;
  1112. }
  1113. /**
  1114. * Begin a transcation on a DB
  1115. *
  1116. * This method makes it clear that begin() is called from a maintenance script,
  1117. * which has outermost scope. This is safe, unlike $dbw->begin() called in other places.
  1118. *
  1119. * @param IDatabase $dbw
  1120. * @param string $fname Caller name
  1121. * @since 1.27
  1122. */
  1123. protected function beginTransaction( IDatabase $dbw, $fname ) {
  1124. $dbw->begin( $fname );
  1125. }
  1126. /**
  1127. * Commit the transcation on a DB handle and wait for replica DBs to catch up
  1128. *
  1129. * This method makes it clear that commit() is called from a maintenance script,
  1130. * which has outermost scope. This is safe, unlike $dbw->commit() called in other places.
  1131. *
  1132. * @param IDatabase $dbw
  1133. * @param string $fname Caller name
  1134. * @return bool Whether the replica DB wait succeeded
  1135. * @since 1.27
  1136. */
  1137. protected function commitTransaction( IDatabase $dbw, $fname ) {
  1138. $dbw->commit( $fname );
  1139. try {
  1140. $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
  1141. $lbFactory->waitForReplication(
  1142. [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
  1143. );
  1144. $this->lastReplicationWait = microtime( true );
  1145. return true;
  1146. } catch ( DBReplicationWaitError $e ) {
  1147. return false;
  1148. }
  1149. }
  1150. /**
  1151. * Rollback the transcation on a DB handle
  1152. *
  1153. * This method makes it clear that rollback() is called from a maintenance script,
  1154. * which has outermost scope. This is safe, unlike $dbw->rollback() called in other places.
  1155. *
  1156. * @param IDatabase $dbw
  1157. * @param string $fname Caller name
  1158. * @since 1.27
  1159. */
  1160. protected function rollbackTransaction( IDatabase $dbw, $fname ) {
  1161. $dbw->rollback( $fname );
  1162. }
  1163. /**
  1164. * Lock the search index
  1165. * @param Database &$db
  1166. */
  1167. private function lockSearchindex( $db ) {
  1168. $write = [ 'searchindex' ];
  1169. $read = [
  1170. 'page',
  1171. 'revision',
  1172. 'text',
  1173. 'interwiki',
  1174. 'l10n_cache',
  1175. 'user',
  1176. 'page_restrictions'
  1177. ];
  1178. $db->lockTables( $read, $write, __CLASS__ . '::' . __METHOD__ );
  1179. }
  1180. /**
  1181. * Unlock the tables
  1182. * @param Database &$db
  1183. */
  1184. private function unlockSearchindex( $db ) {
  1185. $db->unlockTables( __CLASS__ . '::' . __METHOD__ );
  1186. }
  1187. /**
  1188. * Unlock and lock again
  1189. * Since the lock is low-priority, queued reads will be able to complete
  1190. * @param Database &$db
  1191. */
  1192. private function relockSearchindex( $db ) {
  1193. $this->unlockSearchindex( $db );
  1194. $this->lockSearchindex( $db );
  1195. }
  1196. /**
  1197. * Perform a search index update with locking
  1198. * @param int $maxLockTime The maximum time to keep the search index locked.
  1199. * @param string $callback The function that will update the function.
  1200. * @param Database $dbw
  1201. * @param array $results
  1202. */
  1203. public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
  1204. $lockTime = time();
  1205. # Lock searchindex
  1206. if ( $maxLockTime ) {
  1207. $this->output( " --- Waiting for lock ---" );
  1208. $this->lockSearchindex( $dbw );
  1209. $lockTime = time();
  1210. $this->output( "\n" );
  1211. }
  1212. # Loop through the results and do a search update
  1213. foreach ( $results as $row ) {
  1214. # Allow reads to be processed
  1215. if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
  1216. $this->output( " --- Relocking ---" );
  1217. $this->relockSearchindex( $dbw );
  1218. $lockTime = time();
  1219. $this->output( "\n" );
  1220. }
  1221. call_user_func( $callback, $dbw, $row );
  1222. }
  1223. # Unlock searchindex
  1224. if ( $maxLockTime ) {
  1225. $this->output( " --- Unlocking --" );
  1226. $this->unlockSearchindex( $dbw );
  1227. $this->output( "\n" );
  1228. }
  1229. }
  1230. /**
  1231. * Update the searchindex table for a given pageid
  1232. * @param Database $dbw A database write handle
  1233. * @param int $pageId The page ID to update.
  1234. * @return null|string
  1235. */
  1236. public function updateSearchIndexForPage( $dbw, $pageId ) {
  1237. // Get current revision
  1238. $rev = Revision::loadFromPageId( $dbw, $pageId );
  1239. $title = null;
  1240. if ( $rev ) {
  1241. $titleObj = $rev->getTitle();
  1242. $title = $titleObj->getPrefixedDBkey();
  1243. $this->output( "$title..." );
  1244. # Update searchindex
  1245. $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
  1246. $u->doUpdate();
  1247. $this->output( "\n" );
  1248. }
  1249. return $title;
  1250. }
  1251. /**
  1252. * Wrapper for posix_isatty()
  1253. * We default as considering stdin a tty (for nice readline methods)
  1254. * but treating stout as not a tty to avoid color codes
  1255. *
  1256. * @param mixed $fd File descriptor
  1257. * @return bool
  1258. */
  1259. public static function posix_isatty( $fd ) {
  1260. if ( !function_exists( 'posix_isatty' ) ) {
  1261. return !$fd;
  1262. } else {
  1263. return posix_isatty( $fd );
  1264. }
  1265. }
  1266. /**
  1267. * Prompt the console for input
  1268. * @param string $prompt What to begin the line with, like '> '
  1269. * @return string Response
  1270. */
  1271. public static function readconsole( $prompt = '> ' ) {
  1272. static $isatty = null;
  1273. if ( is_null( $isatty ) ) {
  1274. $isatty = self::posix_isatty( 0 /*STDIN*/ );
  1275. }
  1276. if ( $isatty && function_exists( 'readline' ) ) {
  1277. $resp = readline( $prompt );
  1278. if ( $resp === null ) {
  1279. // Workaround for https://github.com/facebook/hhvm/issues/4776
  1280. return false;
  1281. } else {
  1282. return $resp;
  1283. }
  1284. } else {
  1285. if ( $isatty ) {
  1286. $st = self::readlineEmulation( $prompt );
  1287. } else {
  1288. if ( feof( STDIN ) ) {
  1289. $st = false;
  1290. } else {
  1291. $st = fgets( STDIN, 1024 );
  1292. }
  1293. }
  1294. if ( $st === false ) {
  1295. return false;
  1296. }
  1297. $resp = trim( $st );
  1298. return $resp;
  1299. }
  1300. }
  1301. /**
  1302. * Emulate readline()
  1303. * @param string $prompt What to begin the line with, like '> '
  1304. * @return string
  1305. */
  1306. private static function readlineEmulation( $prompt ) {
  1307. $bash = Installer::locateExecutableInDefaultPaths( [ 'bash' ] );
  1308. if ( !wfIsWindows() && $bash ) {
  1309. $retval = false;
  1310. $encPrompt = wfEscapeShellArg( $prompt );
  1311. $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
  1312. $encCommand = wfEscapeShellArg( $command );
  1313. $line = wfShellExec( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
  1314. if ( $retval == 0 ) {
  1315. return $line;
  1316. } elseif ( $retval == 127 ) {
  1317. // Couldn't execute bash even though we thought we saw it.
  1318. // Shell probably spit out an error message, sorry :(
  1319. // Fall through to fgets()...
  1320. } else {
  1321. // EOF/ctrl+D
  1322. return false;
  1323. }
  1324. }
  1325. // Fallback... we'll have no editing controls, EWWW
  1326. if ( feof( STDIN ) ) {
  1327. return false;
  1328. }
  1329. print $prompt;
  1330. return fgets( STDIN, 1024 );
  1331. }
  1332. /**
  1333. * Call this to set up the autoloader to allow classes to be used from the
  1334. * tests directory.
  1335. */
  1336. public static function requireTestsAutoloader() {
  1337. require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
  1338. }
  1339. }
  1340. /**
  1341. * Fake maintenance wrapper, mostly used for the web installer/updater
  1342. */
  1343. class FakeMaintenance extends Maintenance {
  1344. protected $mSelf = "FakeMaintenanceScript";
  1345. public function execute() {
  1346. return;
  1347. }
  1348. }
  1349. /**
  1350. * Class for scripts that perform database maintenance and want to log the
  1351. * update in `updatelog` so we can later skip it
  1352. */
  1353. abstract class LoggedUpdateMaintenance extends Maintenance {
  1354. public function __construct() {
  1355. parent::__construct();
  1356. $this->addOption( 'force', 'Run the update even if it was completed already' );
  1357. $this->setBatchSize( 200 );
  1358. }
  1359. public function execute() {
  1360. $db = $this->getDB( DB_MASTER );
  1361. $key = $this->getUpdateKey();
  1362. if ( !$this->hasOption( 'force' )
  1363. && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
  1364. ) {
  1365. $this->output( "..." . $this->updateSkippedMessage() . "\n" );
  1366. return true;
  1367. }
  1368. if ( !$this->doDBUpdates() ) {
  1369. return false;
  1370. }
  1371. if ( $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, 'IGNORE' ) ) {
  1372. return true;
  1373. } else {
  1374. $this->output( $this->updatelogFailedMessage() . "\n" );
  1375. return false;
  1376. }
  1377. }
  1378. /**
  1379. * Message to show that the update was done already and was just skipped
  1380. * @return string
  1381. */
  1382. protected function updateSkippedMessage() {
  1383. $key = $this->getUpdateKey();
  1384. return "Update '{$key}' already logged as completed.";
  1385. }
  1386. /**
  1387. * Message to show that the update log was unable to log the completion of this update
  1388. * @return string
  1389. */
  1390. protected function updatelogFailedMessage() {
  1391. $key = $this->getUpdateKey();
  1392. return "Unable to log update '{$key}' as completed.";
  1393. }
  1394. /**
  1395. * Do the actual work. All child classes will need to implement this.
  1396. * Return true to log the update as done or false (usually on failure).
  1397. * @return bool
  1398. */
  1399. abstract protected function doDBUpdates();
  1400. /**
  1401. * Get the update key name to go in the update log table
  1402. * @return string
  1403. */
  1404. abstract protected function getUpdateKey();
  1405. }