MediaWiki  1.29.1
GenerateFancyCaptchas.php
Go to the documentation of this file.
1 <?php
24 if ( getenv( 'MW_INSTALL_PATH' ) ) {
25  $IP = getenv( 'MW_INSTALL_PATH' );
26 } else {
27  $IP = __DIR__ . '/../../..';
28 }
29 
30 require_once ( "$IP/maintenance/Maintenance.php" );
31 
38  public function __construct() {
39  parent::__construct();
40 
41  // See captcha.py for argument usage
42  $this->addOption( "wordlist", 'A list of words', true, true );
43  $this->addOption( "font", "The font to use", true, true );
44  $this->addOption( "font-size", "The font size ", false, true );
45  $this->addOption( "blacklist", "A blacklist of words that should not be used", false, true );
46  $this->addOption( "fill", "Fill the captcha container to N files", true, true );
47  $this->addOption( "verbose", "Show debugging information" );
48  $this->addOption(
49  "oldcaptcha",
50  "Whether to use captcha-old.py which doesn't have OCR fighting improvements"
51  );
52  $this->addOption( "delete", "Delete the old captches" );
53  $this->mDescription = "Generate new fancy captchas and move them into storage";
54 
55  $this->requireExtension( "FancyCaptcha" );
56  }
57 
58  public function execute() {
59  global $wgCaptchaSecret, $wgCaptchaDirectoryLevels;
60 
61  $totalTime = -microtime( true );
62 
63  $instance = ConfirmEditHooks::getInstance();
64  if ( !( $instance instanceof FancyCaptcha ) ) {
65  $this->error( "\$wgCaptchaClass is not FancyCaptcha.\n", 1 );
66  }
67  $backend = $instance->getBackend();
68 
69  $deleteOldCaptchas = $this->getOption( 'delete' );
70 
71  $countGen = (int)$this->getOption( 'fill' );
72  if ( !$deleteOldCaptchas ) {
73  $countAct = $instance->getCaptchaCount();
74  $this->output( "Current number of captchas is $countAct.\n" );
75  $countGen -= $countAct;
76  }
77 
78  if ( $countGen <= 0 ) {
79  $this->output( "No need to generate anymore captchas.\n" );
80  return;
81  }
82 
83  $tmpDir = wfTempDir() . '/mw-fancycaptcha-' . time() . '-' . wfRandomString( 6 );
84  if ( !wfMkdirParents( $tmpDir ) ) {
85  $this->error( "Could not create temp directory.\n", 1 );
86  }
87 
88  $e = null; // exception
89  try {
90  $captchaScript = 'captcha.py';
91 
92  if ( $this->hasOption( 'oldcaptcha' ) ) {
93  $captchaScript = 'captcha-old.py';
94  }
95 
96  $cmd = sprintf( "python %s --key %s --output %s --count %s --dirs %s",
97  wfEscapeShellArg( dirname( __DIR__ ) . '/' . $captchaScript ),
98  wfEscapeShellArg( $wgCaptchaSecret ),
99  wfEscapeShellArg( $tmpDir ),
100  wfEscapeShellArg( $countGen ),
101  wfEscapeShellArg( $wgCaptchaDirectoryLevels )
102  );
103  foreach ( [ 'wordlist', 'font', 'font-size', 'blacklist', 'verbose' ] as $par ) {
104  if ( $this->hasOption( $par ) ) {
105  $cmd .= " --$par " . wfEscapeShellArg( $this->getOption( $par ) );
106  }
107  }
108 
109  $this->output( "Generating $countGen new captchas.." );
110  $retVal = 1;
111  $captchaTime = -microtime( true );
112  wfShellExec( $cmd, $retVal, [], [ 'time' => 0 ] );
113  if ( $retVal != 0 ) {
114  wfRecursiveRemoveDir( $tmpDir );
115  $this->error( "Could not run generation script.\n", 1 );
116  }
117 
118  $captchaTime += microtime( true );
119  $this->output( " Done.\n" );
120 
121  $this->output(
122  sprintf(
123  "\nGenerated %d captchas in %.1f seconds\n",
124  $countGen,
125  $captchaTime
126  )
127  );
128 
129  $filesToDelete = [];
130  if ( $deleteOldCaptchas ) {
131  $this->output( "Getting a list of old captchas to delete..." );
132  $path = $backend->getRootStoragePath() . '/captcha-render';
133  foreach ( $backend->getFileList( [ 'dir' => $path ] ) as $file ) {
134  $filesToDelete[] = [
135  'op' => 'delete',
136  'src' => $path . '/' . $file,
137  ];
138  }
139  $this->output( " Done.\n" );
140  }
141 
142  $this->output( "Copying the new captchas to storage..." );
143 
144  $storeTime = -microtime( true );
145  $iter = new RecursiveIteratorIterator(
146  new RecursiveDirectoryIterator(
147  $tmpDir,
148  FilesystemIterator::SKIP_DOTS
149  ),
150  RecursiveIteratorIterator::LEAVES_ONLY
151  );
152 
153  $captchasGenerated = iterator_count( $iter );
154  $filesToStore = [];
158  foreach ( $iter as $fileInfo ) {
159  if ( !$fileInfo->isFile() ) {
160  continue;
161  }
162  list( $salt, $hash ) = $instance->hashFromImageName( $fileInfo->getBasename() );
163  $dest = $instance->imagePath( $salt, $hash );
164  $backend->prepare( [ 'dir' => dirname( $dest ) ] );
165  $filesToStore[] = [
166  'op' => 'store',
167  'src' => $fileInfo->getPathname(),
168  'dst' => $dest,
169  ];
170  }
171 
172  $ret = $backend->doQuickOperations( $filesToStore );
173 
174  $storeTime += microtime( true );
175 
176  if ( $ret->isOK() ) {
177  $this->output( " Done.\n" );
178  $this->output(
179  sprintf(
180  "\nCopied %d captchas to storage in %.1f seconds\n",
181  $ret->successCount,
182  $storeTime
183  )
184  );
185  if ( $ret->failCount ) {
186  $this->output( sprintf( "\nFailed to copy %d captchas\n", $ret->failCount ) );
187  }
188  if ( $ret->successCount + $ret->failCount !== $captchasGenerated ) {
189  $this->output(
190  sprintf( "Internal error: captchasGenerated: %d, successCount: %d, failCount: %d\n",
191  $captchasGenerated, $ret->successCount, $ret->failCount
192  )
193  );
194  }
195  } else {
196  $this->output( "Errored.\n" );
197  $this->output( implode( "\n", Status::wrap( $ret )->getWikiText( null, null, 'en' ) ) );
198  }
199 
200  if ( $deleteOldCaptchas ) {
201  $numOriginalFiles = count( $filesToDelete );
202  $this->output( "Deleting {$numOriginalFiles} old captchas...\n" );
203  $deleteTime = -microtime( true );
204  $ret = $backend->doQuickOperations( $filesToDelete );
205 
206  $deleteTime += microtime( true );
207  if ( $ret->isOK() ) {
208 
209  $this->output( "Done.\n" );
210  $this->output(
211  sprintf(
212  "\nDeleted %d old captchas in %.1f seconds\n",
213  $numOriginalFiles,
214  $deleteTime
215  )
216  );
217  } else {
218  $this->output( "Errored.\n" );
219  $this->output( implode( "\n", Status::wrap( $ret )->getWikiText( null, null, 'en' ) ) );
220  }
221 
222  }
223  } catch ( Exception $e ) {
224  wfRecursiveRemoveDir( $tmpDir );
225  throw $e;
226  }
227 
228  $this->output( "Removing temporary files..." );
229  wfRecursiveRemoveDir( $tmpDir );
230  $this->output( " Done.\n" );
231 
232  $totalTime += microtime( true );
233  $this->output(
234  sprintf(
235  "\nWhole captchas generation process took %.1f seconds\n",
236  $totalTime
237  )
238  );
239  }
240 }
241 
242 $maintClass = "GenerateFancyCaptchas";
243 require_once ( RUN_MAINTENANCE_IF_MAIN );
wfMkdirParents
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
Definition: GlobalFunctions.php:2080
captcha-old.count
count
Definition: captcha-old.py:225
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
ConfirmEditHooks\getInstance
static getInstance()
Get the global Captcha instance.
Definition: ConfirmEditHooks.php:13
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Status\wrap
static wrap( $sv)
Succinct helper method to wrap a StatusValue.
Definition: Status.php:55
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:215
$IP
$IP
Definition: update.php:3
Maintenance\requireExtension
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
Definition: Maintenance.php:529
$maintClass
$maintClass
Definition: GenerateFancyCaptchas.php:242
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2122
FancyCaptcha
FancyCaptcha for displaying captchas precomputed by captcha.py.
Definition: FancyCaptcha.class.php:9
wfEscapeShellArg
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
Definition: GlobalFunctions.php:2195
GenerateFancyCaptchas\execute
execute()
Do the actual work.
Definition: GenerateFancyCaptchas.php:58
GenerateFancyCaptchas
Maintenance script to generate fancy captchas using a python script and copy them into storage.
Definition: GenerateFancyCaptchas.php:37
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1956
GenerateFancyCaptchas\__construct
__construct()
Default constructor.
Definition: GenerateFancyCaptchas.php:38
wfTempDir
wfTempDir()
Tries to get the system directory for temporary files.
Definition: GlobalFunctions.php:2061
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:250
wfRecursiveRemoveDir
wfRecursiveRemoveDir( $dir)
Remove a directory and all its content.
Definition: GlobalFunctions.php:2123
$path
$path
Definition: NoLocalSettings.php:26
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:392
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:373
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:236
wfShellExec
wfShellExec( $cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
Definition: GlobalFunctions.php:2297
wfRandomString
wfRandomString( $length=32)
Get a random string containing a number of pseudo-random hex characters.
Definition: GlobalFunctions.php:336