MediaWiki  master
FSFileBackend.php
Go to the documentation of this file.
1 <?php
44 
63  protected $basePath;
64 
66  protected $containerPaths = [];
67 
69  protected $fileMode;
71  protected $dirMode;
72 
74  protected $fileOwner;
75 
77  protected $isWindows;
79  protected $currentUser;
80 
82  protected $hadWarningErrors = [];
83 
94  public function __construct( array $config ) {
95  parent::__construct( $config );
96 
97  $this->isWindows = ( strtoupper( substr( PHP_OS, 0, 3 ) ) === 'WIN' );
98  // Remove any possible trailing slash from directories
99  if ( isset( $config['basePath'] ) ) {
100  $this->basePath = rtrim( $config['basePath'], '/' ); // remove trailing slash
101  } else {
102  $this->basePath = null; // none; containers must have explicit paths
103  }
104 
105  if ( isset( $config['containerPaths'] ) ) {
106  $this->containerPaths = (array)$config['containerPaths'];
107  foreach ( $this->containerPaths as &$path ) {
108  $path = rtrim( $path, '/' ); // remove trailing slash
109  }
110  }
111 
112  $this->fileMode = $config['fileMode'] ?? 0644;
113  $this->dirMode = $config['directoryMode'] ?? 0777;
114  if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
115  $this->fileOwner = $config['fileOwner'];
116  // cache this, assuming it doesn't change
117  $this->currentUser = posix_getpwuid( posix_getuid() )['name'];
118  }
119  }
120 
121  public function getFeatures() {
122  if ( $this->isWindows && version_compare( PHP_VERSION, '7.1', 'lt' ) ) {
123  // PHP before 7.1 used 8-bit code page for filesystem paths on Windows;
124  // See https://www.php.net/manual/en/migration71.windows-support.php
125  return 0;
126  } else {
128  }
129  }
130 
131  protected function resolveContainerPath( $container, $relStoragePath ) {
132  // Check that container has a root directory
133  if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
134  // Check for sane relative paths (assume the base paths are OK)
135  if ( $this->isLegalRelPath( $relStoragePath ) ) {
136  return $relStoragePath;
137  }
138  }
139 
140  return null;
141  }
142 
149  protected function isLegalRelPath( $path ) {
150  // Check for file names longer than 255 chars
151  if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
152  return false;
153  }
154  if ( $this->isWindows ) { // NTFS
155  return !preg_match( '![:*?"<>|]!', $path );
156  } else {
157  return true;
158  }
159  }
160 
169  protected function containerFSRoot( $shortCont, $fullCont ) {
170  if ( isset( $this->containerPaths[$shortCont] ) ) {
171  return $this->containerPaths[$shortCont];
172  } elseif ( isset( $this->basePath ) ) {
173  return "{$this->basePath}/{$fullCont}";
174  }
175 
176  return null; // no container base path defined
177  }
178 
185  protected function resolveToFSPath( $storagePath ) {
186  list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
187  if ( $relPath === null ) {
188  return null; // invalid
189  }
190  list( , $shortCont, ) = FileBackend::splitStoragePath( $storagePath );
191  $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
192  if ( $relPath != '' ) {
193  $fsPath .= "/{$relPath}";
194  }
195 
196  return $fsPath;
197  }
198 
199  public function isPathUsableInternal( $storagePath ) {
200  $fsPath = $this->resolveToFSPath( $storagePath );
201  if ( $fsPath === null ) {
202  return false; // invalid
203  }
204  $parentDir = dirname( $fsPath );
205 
206  if ( file_exists( $fsPath ) ) {
207  $ok = is_file( $fsPath ) && is_writable( $fsPath );
208  } else {
209  $ok = is_dir( $parentDir ) && is_writable( $parentDir );
210  }
211 
212  if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
213  $ok = false;
214  trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
215  }
216 
217  return $ok;
218  }
219 
220  protected function doCreateInternal( array $params ) {
221  $status = $this->newStatus();
222 
223  $dest = $this->resolveToFSPath( $params['dst'] );
224  if ( $dest === null ) {
225  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
226 
227  return $status;
228  }
229 
230  if ( !empty( $params['async'] ) ) { // deferred
231  $tempFile = TempFSFile::factory( 'create_', 'tmp', $this->tmpDirectory );
232  if ( !$tempFile ) {
233  $status->fatal( 'backend-fail-create', $params['dst'] );
234 
235  return $status;
236  }
237  $this->trapWarnings();
238  $bytes = file_put_contents( $tempFile->getPath(), $params['content'] );
239  $this->untrapWarnings();
240  if ( $bytes === false ) {
241  $status->fatal( 'backend-fail-create', $params['dst'] );
242 
243  return $status;
244  }
245  $cmd = implode( ' ', [
246  $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
247  escapeshellarg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
248  escapeshellarg( $this->cleanPathSlashes( $dest ) )
249  ] );
250  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
251  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
252  $status->fatal( 'backend-fail-create', $params['dst'] );
253  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
254  }
255  };
256  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
257  $tempFile->bind( $status->value );
258  } else { // immediate write
259  $this->trapWarnings();
260  $bytes = file_put_contents( $dest, $params['content'] );
261  $this->untrapWarnings();
262  if ( $bytes === false ) {
263  $status->fatal( 'backend-fail-create', $params['dst'] );
264 
265  return $status;
266  }
267  $this->chmod( $dest );
268  }
269 
270  return $status;
271  }
272 
273  protected function doStoreInternal( array $params ) {
274  $status = $this->newStatus();
275 
276  $dest = $this->resolveToFSPath( $params['dst'] );
277  if ( $dest === null ) {
278  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
279 
280  return $status;
281  }
282 
283  if ( !empty( $params['async'] ) ) { // deferred
284  $cmd = implode( ' ', [
285  $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
286  escapeshellarg( $this->cleanPathSlashes( $params['src'] ) ),
287  escapeshellarg( $this->cleanPathSlashes( $dest ) )
288  ] );
289  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
290  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
291  $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
292  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
293  }
294  };
295  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
296  } else { // immediate write
297  $this->trapWarnings();
298  $ok = copy( $params['src'], $dest );
299  $this->untrapWarnings();
300  // In some cases (at least over NFS), copy() returns true when it fails
301  if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
302  if ( $ok ) { // PHP bug
303  unlink( $dest ); // remove broken file
304  trigger_error( __METHOD__ . ": copy() failed but returned true." );
305  }
306  $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
307 
308  return $status;
309  }
310  $this->chmod( $dest );
311  }
312 
313  return $status;
314  }
315 
316  protected function doCopyInternal( array $params ) {
317  $status = $this->newStatus();
318 
319  $source = $this->resolveToFSPath( $params['src'] );
320  if ( $source === null ) {
321  $status->fatal( 'backend-fail-invalidpath', $params['src'] );
322 
323  return $status;
324  }
325 
326  $dest = $this->resolveToFSPath( $params['dst'] );
327  if ( $dest === null ) {
328  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
329 
330  return $status;
331  }
332 
333  if ( !is_file( $source ) ) {
334  if ( empty( $params['ignoreMissingSource'] ) ) {
335  $status->fatal( 'backend-fail-copy', $params['src'] );
336  }
337 
338  return $status; // do nothing; either OK or bad status
339  }
340 
341  if ( !empty( $params['async'] ) ) { // deferred
342  $cmd = implode( ' ', [
343  $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
344  escapeshellarg( $this->cleanPathSlashes( $source ) ),
345  escapeshellarg( $this->cleanPathSlashes( $dest ) )
346  ] );
347  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
348  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
349  $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
350  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
351  }
352  };
353  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
354  } else { // immediate write
355  $this->trapWarnings();
356  $ok = ( $source === $dest ) ? true : copy( $source, $dest );
357  $this->untrapWarnings();
358  // In some cases (at least over NFS), copy() returns true when it fails
359  if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
360  if ( $ok ) { // PHP bug
361  $this->trapWarnings();
362  unlink( $dest ); // remove broken file
363  $this->untrapWarnings();
364  trigger_error( __METHOD__ . ": copy() failed but returned true." );
365  }
366  $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
367 
368  return $status;
369  }
370  $this->chmod( $dest );
371  }
372 
373  return $status;
374  }
375 
376  protected function doMoveInternal( array $params ) {
377  $status = $this->newStatus();
378 
379  $source = $this->resolveToFSPath( $params['src'] );
380  if ( $source === null ) {
381  $status->fatal( 'backend-fail-invalidpath', $params['src'] );
382 
383  return $status;
384  }
385 
386  $dest = $this->resolveToFSPath( $params['dst'] );
387  if ( $dest === null ) {
388  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
389 
390  return $status;
391  }
392 
393  if ( !is_file( $source ) ) {
394  if ( empty( $params['ignoreMissingSource'] ) ) {
395  $status->fatal( 'backend-fail-move', $params['src'] );
396  }
397 
398  return $status; // do nothing; either OK or bad status
399  }
400 
401  if ( !empty( $params['async'] ) ) { // deferred
402  $cmd = implode( ' ', [
403  $this->isWindows ? 'MOVE /Y' : 'mv', // (overwrite)
404  escapeshellarg( $this->cleanPathSlashes( $source ) ),
405  escapeshellarg( $this->cleanPathSlashes( $dest ) )
406  ] );
407  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
408  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
409  $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
410  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
411  }
412  };
413  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
414  } else { // immediate write
415  $this->trapWarnings();
416  $ok = ( $source === $dest ) ? true : rename( $source, $dest );
417  $this->untrapWarnings();
418  clearstatcache(); // file no longer at source
419  if ( !$ok ) {
420  $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
421 
422  return $status;
423  }
424  }
425 
426  return $status;
427  }
428 
429  protected function doDeleteInternal( array $params ) {
430  $status = $this->newStatus();
431 
432  $source = $this->resolveToFSPath( $params['src'] );
433  if ( $source === null ) {
434  $status->fatal( 'backend-fail-invalidpath', $params['src'] );
435 
436  return $status;
437  }
438 
439  if ( !is_file( $source ) ) {
440  if ( empty( $params['ignoreMissingSource'] ) ) {
441  $status->fatal( 'backend-fail-delete', $params['src'] );
442  }
443 
444  return $status; // do nothing; either OK or bad status
445  }
446 
447  if ( !empty( $params['async'] ) ) { // deferred
448  $cmd = implode( ' ', [
449  $this->isWindows ? 'DEL' : 'unlink',
450  escapeshellarg( $this->cleanPathSlashes( $source ) )
451  ] );
452  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
453  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
454  $status->fatal( 'backend-fail-delete', $params['src'] );
455  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
456  }
457  };
458  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
459  } else { // immediate write
460  $this->trapWarnings();
461  $ok = unlink( $source );
462  $this->untrapWarnings();
463  if ( !$ok ) {
464  $status->fatal( 'backend-fail-delete', $params['src'] );
465 
466  return $status;
467  }
468  }
469 
470  return $status;
471  }
472 
479  protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
480  $status = $this->newStatus();
481  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
482  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
483  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
484  $existed = is_dir( $dir ); // already there?
485  // Create the directory and its parents as needed...
486  $this->trapWarnings();
487  if ( !$existed && !mkdir( $dir, $this->dirMode, true ) && !is_dir( $dir ) ) {
488  $this->logger->error( __METHOD__ . ": cannot create directory $dir" );
489  $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
490  } elseif ( !is_writable( $dir ) ) {
491  $this->logger->error( __METHOD__ . ": directory $dir is read-only" );
492  $status->fatal( 'directoryreadonlyerror', $params['dir'] );
493  } elseif ( !is_readable( $dir ) ) {
494  $this->logger->error( __METHOD__ . ": directory $dir is not readable" );
495  $status->fatal( 'directorynotreadableerror', $params['dir'] );
496  }
497  $this->untrapWarnings();
498  // Respect any 'noAccess' or 'noListing' flags...
499  if ( is_dir( $dir ) && !$existed ) {
500  $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
501  }
502 
503  return $status;
504  }
505 
506  protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
507  $status = $this->newStatus();
508  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
509  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
510  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
511  // Seed new directories with a blank index.html, to prevent crawling...
512  if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
513  $this->trapWarnings();
514  $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
515  $this->untrapWarnings();
516  if ( $bytes === false ) {
517  $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
518  }
519  }
520  // Add a .htaccess file to the root of the container...
521  if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
522  $this->trapWarnings();
523  $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
524  $this->untrapWarnings();
525  if ( $bytes === false ) {
526  $storeDir = "mwstore://{$this->name}/{$shortCont}";
527  $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
528  }
529  }
530 
531  return $status;
532  }
533 
534  protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
535  $status = $this->newStatus();
536  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
537  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
538  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
539  // Unseed new directories with a blank index.html, to allow crawling...
540  if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
541  $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
542  $this->trapWarnings();
543  if ( $exists && !unlink( "{$dir}/index.html" ) ) { // reverse secure()
544  $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
545  }
546  $this->untrapWarnings();
547  }
548  // Remove the .htaccess file from the root of the container...
549  if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
550  $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
551  $this->trapWarnings();
552  if ( $exists && !unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
553  $storeDir = "mwstore://{$this->name}/{$shortCont}";
554  $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
555  }
556  $this->untrapWarnings();
557  }
558 
559  return $status;
560  }
561 
562  protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
563  $status = $this->newStatus();
564  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
565  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
566  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
567  $this->trapWarnings();
568  if ( is_dir( $dir ) ) {
569  rmdir( $dir ); // remove directory if empty
570  }
571  $this->untrapWarnings();
572 
573  return $status;
574  }
575 
576  protected function doGetFileStat( array $params ) {
577  $source = $this->resolveToFSPath( $params['src'] );
578  if ( $source === null ) {
579  return false; // invalid storage path
580  }
581 
582  $this->trapWarnings(); // don't trust 'false' if there were errors
583  $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
584  $hadError = $this->untrapWarnings();
585 
586  if ( $stat ) {
587  $ct = new ConvertibleTimestamp( $stat['mtime'] );
588 
589  return [
590  'mtime' => $ct->getTimestamp( TS_MW ),
591  'size' => $stat['size']
592  ];
593  } elseif ( !$hadError ) {
594  return false; // file does not exist
595  } else {
596  return null; // failure
597  }
598  }
599 
600  protected function doClearCache( array $paths = null ) {
601  clearstatcache(); // clear the PHP file stat cache
602  }
603 
604  protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
605  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
606  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
607  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
608 
609  $this->trapWarnings(); // don't trust 'false' if there were errors
610  $exists = is_dir( $dir );
611  $hadError = $this->untrapWarnings();
612 
613  return $hadError ? null : $exists;
614  }
615 
623  public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
624  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
625  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
626  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
627  $exists = is_dir( $dir );
628  if ( !$exists ) {
629  $this->logger->warning( __METHOD__ . "() given directory does not exist: '$dir'\n" );
630 
631  return []; // nothing under this dir
632  } elseif ( !is_readable( $dir ) ) {
633  $this->logger->warning( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
634 
635  return null; // bad permissions?
636  }
637 
638  return new FSFileBackendDirList( $dir, $params );
639  }
640 
648  public function getFileListInternal( $fullCont, $dirRel, array $params ) {
649  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
650  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
651  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
652  $exists = is_dir( $dir );
653  if ( !$exists ) {
654  $this->logger->warning( __METHOD__ . "() given directory does not exist: '$dir'\n" );
655 
656  return []; // nothing under this dir
657  } elseif ( !is_readable( $dir ) ) {
658  $this->logger->warning( __METHOD__ . "() given directory is unreadable: '$dir'\n" );
659 
660  return null; // bad permissions?
661  }
662 
663  return new FSFileBackendFileList( $dir, $params );
664  }
665 
666  protected function doGetLocalReferenceMulti( array $params ) {
667  $fsFiles = []; // (path => FSFile)
668 
669  foreach ( $params['srcs'] as $src ) {
670  $source = $this->resolveToFSPath( $src );
671  if ( $source === null || !is_file( $source ) ) {
672  $fsFiles[$src] = null; // invalid path or file does not exist
673  } else {
674  $fsFiles[$src] = new FSFile( $source );
675  }
676  }
677 
678  return $fsFiles;
679  }
680 
681  protected function doGetLocalCopyMulti( array $params ) {
682  $tmpFiles = []; // (path => TempFSFile)
683 
684  foreach ( $params['srcs'] as $src ) {
685  $source = $this->resolveToFSPath( $src );
686  if ( $source === null ) {
687  $tmpFiles[$src] = null; // invalid path
688  } else {
689  // Create a new temporary file with the same extension...
691  $tmpFile = TempFSFile::factory( 'localcopy_', $ext, $this->tmpDirectory );
692  if ( !$tmpFile ) {
693  $tmpFiles[$src] = null;
694  } else {
695  $tmpPath = $tmpFile->getPath();
696  // Copy the source file over the temp file
697  $this->trapWarnings();
698  $ok = copy( $source, $tmpPath );
699  $this->untrapWarnings();
700  if ( !$ok ) {
701  $tmpFiles[$src] = null;
702  } else {
703  $this->chmod( $tmpPath );
704  $tmpFiles[$src] = $tmpFile;
705  }
706  }
707  }
708  }
709 
710  return $tmpFiles;
711  }
712 
713  protected function directoriesAreVirtual() {
714  return false;
715  }
716 
722  protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
723  $statuses = [];
724 
725  $pipes = [];
726  foreach ( $fileOpHandles as $index => $fileOpHandle ) {
727  $pipes[$index] = popen( "{$fileOpHandle->cmd} 2>&1", 'r' );
728  }
729 
730  $errs = [];
731  foreach ( $pipes as $index => $pipe ) {
732  // Result will be empty on success in *NIX. On Windows,
733  // it may be something like " 1 file(s) [copied|moved].".
734  $errs[$index] = stream_get_contents( $pipe );
735  fclose( $pipe );
736  }
737 
738  foreach ( $fileOpHandles as $index => $fileOpHandle ) {
739  $status = $this->newStatus();
740  $function = $fileOpHandle->call;
741  $function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
742  $statuses[$index] = $status;
743  if ( $status->isOK() && $fileOpHandle->chmodPath ) {
744  $this->chmod( $fileOpHandle->chmodPath );
745  }
746  }
747 
748  clearstatcache(); // files changed
749  return $statuses;
750  }
751 
758  protected function chmod( $path ) {
759  $this->trapWarnings();
760  $ok = chmod( $path, $this->fileMode );
761  $this->untrapWarnings();
762 
763  return $ok;
764  }
765 
771  protected function indexHtmlPrivate() {
772  return '';
773  }
774 
780  protected function htaccessPrivate() {
781  return "Deny from all\n";
782  }
783 
790  protected function cleanPathSlashes( $path ) {
791  return $this->isWindows ? strtr( $path, '/', '\\' ) : $path;
792  }
793 
797  protected function trapWarnings() {
798  $this->hadWarningErrors[] = false; // push to stack
799  set_error_handler( [ $this, 'handleWarning' ], E_WARNING );
800  }
801 
807  protected function untrapWarnings() {
808  restore_error_handler(); // restore previous handler
809  return array_pop( $this->hadWarningErrors ); // pop from stack
810  }
811 
818  public function handleWarning( $errno, $errstr ) {
819  $this->logger->error( $errstr ); // more detailed error logging
820  $this->hadWarningErrors[count( $this->hadWarningErrors ) - 1] = true;
821 
822  return true; // suppress from PHP handler
823  }
824 }
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
untrapWarnings()
Stop listening for E_WARNING errors and return true if any happened.
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
doDirectoryExists( $fullCont, $dirRel, array $params)
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
doDeleteInternal(array $params)
int $fileMode
File permission mode.
doMoveInternal(array $params)
doGetFileStat(array $params)
containerFSRoot( $shortCont, $fullCont)
Given the short (unresolved) and full (resolved) name of a container, return the file system path of ...
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
isLegalRelPath( $path)
Sanity check a relative file system path for validity.
doSecureInternal( $fullCont, $dirRel, array $params)
handleWarning( $errno, $errstr)
$source
doExecuteOpHandlesInternal(array $fileOpHandles)
doGetLocalCopyMulti(array $params)
array $containerPaths
Map of container names to root paths for custom container paths.
getFileListInternal( $fullCont, $dirRel, array $params)
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
doPrepareInternal( $fullCont, $dirRel, array $params)
__construct(array $config)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition: hooks.txt:780
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition: hooks.txt:1263
static factory( $prefix, $extension='', $tmpDirectory=null)
Make a new temporary file on the file system.
Definition: TempFSFile.php:55
indexHtmlPrivate()
Return the text of an index.html file to hide directory listings.
$params
const ATTR_UNICODE_PATHS
doStoreInternal(array $params)
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
htaccessPrivate()
Return the text of a .htaccess file to make a directory private.
newStatus(... $args)
Yields the result of the status wrapper callback on either:
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
doCopyInternal(array $params)
Base class for all backends using particular storage medium.
trapWarnings()
Listen for E_WARNING errors and track whether any happen.
string $basePath
Directory holding the container directories.
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
doCreateInternal(array $params)
doCleanInternal( $fullCont, $dirRel, array $params)
Class representing a non-directory file on the file system.
Definition: FSFile.php:29
isPathUsableInternal( $storagePath)
int $dirMode
File permission mode.
copy(array $params, array $opts=[])
Performs a single copy operation.
doPublishInternal( $fullCont, $dirRel, array $params)
if(!is_readable( $file)) $ext
Definition: router.php:48
string $currentUser
OS username running this script.
doGetLocalReferenceMulti(array $params)
getDirectoryListInternal( $fullCont, $dirRel, array $params)
resolveToFSPath( $storagePath)
Get the absolute file system path for a storage path.
Class for a file system (FS) based file backend.
cleanPathSlashes( $path)
Clean up directory separators for the given OS.
resolveContainerPath( $container, $relStoragePath)
array $hadWarningErrors
chmod( $path)
Chmod a file, suppressing the warnings.
doClearCache(array $paths=null)
string $fileOwner
Required OS username to own files.