MediaWiki  1.34.0
FSFileBackend.php
Go to the documentation of this file.
1 <?php
43 use Wikimedia\AtEase\AtEase;
44 use Wikimedia\Timestamp\ConvertibleTimestamp;
45 
64  protected $basePath;
65 
67  protected $containerPaths;
68 
70  protected $dirMode;
72  protected $fileMode;
74  protected $fileOwner;
75 
77  protected $isWindows;
79  protected $currentUser;
80 
82  private $warningTrapStack = [];
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  $this->containerPaths = [];
106  foreach ( ( $config['containerPaths'] ?? [] ) as $container => $path ) {
107  $this->containerPaths[$container] = rtrim( $path, '/' ); // remove trailing slash
108  }
109 
110  $this->fileMode = $config['fileMode'] ?? 0644;
111  $this->dirMode = $config['directoryMode'] ?? 0777;
112  if ( isset( $config['fileOwner'] ) && function_exists( 'posix_getuid' ) ) {
113  $this->fileOwner = $config['fileOwner'];
114  // cache this, assuming it doesn't change
115  $this->currentUser = posix_getpwuid( posix_getuid() )['name'];
116  }
117  }
118 
119  public function getFeatures() {
120  if ( $this->isWindows && version_compare( PHP_VERSION, '7.1', 'lt' ) ) {
121  // PHP before 7.1 used 8-bit code page for filesystem paths on Windows;
122  // See https://www.php.net/manual/en/migration71.windows-support.php
123  return 0;
124  } else {
126  }
127  }
128 
129  protected function resolveContainerPath( $container, $relStoragePath ) {
130  // Check that container has a root directory
131  if ( isset( $this->containerPaths[$container] ) || isset( $this->basePath ) ) {
132  // Check for sane relative paths (assume the base paths are OK)
133  if ( $this->isLegalRelPath( $relStoragePath ) ) {
134  return $relStoragePath;
135  }
136  }
137 
138  return null; // invalid
139  }
140 
147  protected function isLegalRelPath( $path ) {
148  // Check for file names longer than 255 chars
149  if ( preg_match( '![^/]{256}!', $path ) ) { // ext3/NTFS
150  return false;
151  }
152  if ( $this->isWindows ) { // NTFS
153  return !preg_match( '![:*?"<>|]!', $path );
154  } else {
155  return true;
156  }
157  }
158 
167  protected function containerFSRoot( $shortCont, $fullCont ) {
168  if ( isset( $this->containerPaths[$shortCont] ) ) {
169  return $this->containerPaths[$shortCont];
170  } elseif ( isset( $this->basePath ) ) {
171  return "{$this->basePath}/{$fullCont}";
172  }
173 
174  return null; // no container base path defined
175  }
176 
183  protected function resolveToFSPath( $storagePath ) {
184  list( $fullCont, $relPath ) = $this->resolveStoragePathReal( $storagePath );
185  if ( $relPath === null ) {
186  return null; // invalid
187  }
188  list( , $shortCont, ) = FileBackend::splitStoragePath( $storagePath );
189  $fsPath = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
190  if ( $relPath != '' ) {
191  $fsPath .= "/{$relPath}";
192  }
193 
194  return $fsPath;
195  }
196 
197  public function isPathUsableInternal( $storagePath ) {
198  $fsPath = $this->resolveToFSPath( $storagePath );
199  if ( $fsPath === null ) {
200  return false; // invalid
201  }
202  $parentDir = dirname( $fsPath );
203 
204  if ( file_exists( $fsPath ) ) {
205  $ok = is_file( $fsPath ) && is_writable( $fsPath );
206  } else {
207  $ok = is_dir( $parentDir ) && is_writable( $parentDir );
208  }
209 
210  if ( $this->fileOwner !== null && $this->currentUser !== $this->fileOwner ) {
211  $ok = false;
212  trigger_error( __METHOD__ . ": PHP process owner is not '{$this->fileOwner}'." );
213  }
214 
215  return $ok;
216  }
217 
218  protected function doCreateInternal( array $params ) {
219  $status = $this->newStatus();
220 
221  $dest = $this->resolveToFSPath( $params['dst'] );
222  if ( $dest === null ) {
223  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
224 
225  return $status;
226  }
227 
228  if ( !empty( $params['async'] ) ) { // deferred
229  $tempFile = $this->stageContentAsTempFile( $params );
230  if ( !$tempFile ) {
231  $status->fatal( 'backend-fail-create', $params['dst'] );
232 
233  return $status;
234  }
235  $cmd = implode( ' ', [
236  $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
237  escapeshellarg( $this->cleanPathSlashes( $tempFile->getPath() ) ),
238  escapeshellarg( $this->cleanPathSlashes( $dest ) )
239  ] );
240  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
241  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
242  $status->fatal( 'backend-fail-create', $params['dst'] );
243  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
244  }
245  };
246  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
247  $tempFile->bind( $status->value );
248  } else { // immediate write
249  $this->trapWarnings();
250  $bytes = file_put_contents( $dest, $params['content'] );
251  $this->untrapWarnings();
252  if ( $bytes === false ) {
253  $status->fatal( 'backend-fail-create', $params['dst'] );
254 
255  return $status;
256  }
257  $this->chmod( $dest );
258  }
259 
260  return $status;
261  }
262 
263  protected function doStoreInternal( array $params ) {
264  $status = $this->newStatus();
265 
266  $dest = $this->resolveToFSPath( $params['dst'] );
267  if ( $dest === null ) {
268  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
269 
270  return $status;
271  }
272 
273  if ( !empty( $params['async'] ) ) { // deferred
274  $cmd = implode( ' ', [
275  $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
276  escapeshellarg( $this->cleanPathSlashes( $params['src'] ) ),
277  escapeshellarg( $this->cleanPathSlashes( $dest ) )
278  ] );
279  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
280  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
281  $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
282  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
283  }
284  };
285  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
286  } else { // immediate write
287  $this->trapWarnings();
288  $ok = copy( $params['src'], $dest );
289  $this->untrapWarnings();
290  // In some cases (at least over NFS), copy() returns true when it fails
291  if ( !$ok || ( filesize( $params['src'] ) !== filesize( $dest ) ) ) {
292  if ( $ok ) { // PHP bug
293  unlink( $dest ); // remove broken file
294  trigger_error( __METHOD__ . ": copy() failed but returned true." );
295  }
296  $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
297 
298  return $status;
299  }
300  $this->chmod( $dest );
301  }
302 
303  return $status;
304  }
305 
306  protected function doCopyInternal( array $params ) {
307  $status = $this->newStatus();
308 
309  $source = $this->resolveToFSPath( $params['src'] );
310  if ( $source === null ) {
311  $status->fatal( 'backend-fail-invalidpath', $params['src'] );
312 
313  return $status;
314  }
315 
316  $dest = $this->resolveToFSPath( $params['dst'] );
317  if ( $dest === null ) {
318  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
319 
320  return $status;
321  }
322 
323  if ( !is_file( $source ) ) {
324  if ( empty( $params['ignoreMissingSource'] ) ) {
325  $status->fatal( 'backend-fail-copy', $params['src'] );
326  }
327 
328  return $status; // do nothing; either OK or bad status
329  }
330 
331  if ( !empty( $params['async'] ) ) { // deferred
332  $cmd = implode( ' ', [
333  $this->isWindows ? 'COPY /B /Y' : 'cp', // (binary, overwrite)
334  escapeshellarg( $this->cleanPathSlashes( $source ) ),
335  escapeshellarg( $this->cleanPathSlashes( $dest ) )
336  ] );
337  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
338  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
339  $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
340  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
341  }
342  };
343  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd, $dest );
344  } else { // immediate write
345  $this->trapWarnings();
346  $ok = ( $source === $dest ) ? true : copy( $source, $dest );
347  $this->untrapWarnings();
348  // In some cases (at least over NFS), copy() returns true when it fails
349  if ( !$ok || ( filesize( $source ) !== filesize( $dest ) ) ) {
350  if ( $ok ) { // PHP bug
351  $this->trapWarnings();
352  unlink( $dest ); // remove broken file
353  $this->untrapWarnings();
354  trigger_error( __METHOD__ . ": copy() failed but returned true." );
355  }
356  $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
357 
358  return $status;
359  }
360  $this->chmod( $dest );
361  }
362 
363  return $status;
364  }
365 
366  protected function doMoveInternal( array $params ) {
367  $status = $this->newStatus();
368 
369  $fsSrcPath = $this->resolveToFSPath( $params['src'] );
370  if ( $fsSrcPath === null ) {
371  $status->fatal( 'backend-fail-invalidpath', $params['src'] );
372 
373  return $status;
374  }
375 
376  $fsDstPath = $this->resolveToFSPath( $params['dst'] );
377  if ( $fsDstPath === null ) {
378  $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
379 
380  return $status;
381  }
382 
383  if ( $fsSrcPath === $fsDstPath ) {
384  return $status; // no-op
385  }
386 
387  $ignoreMissing = !empty( $params['ignoreMissingSource'] );
388 
389  if ( !empty( $params['async'] ) ) { // deferred
390  // https://manpages.debian.org/buster/coreutils/mv.1.en.html
391  // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/move
392  $encSrc = escapeshellarg( $this->cleanPathSlashes( $fsSrcPath ) );
393  $encDst = escapeshellarg( $this->cleanPathSlashes( $fsDstPath ) );
394  if ( $this->isWindows ) {
395  $writeCmd = "MOVE /Y $encSrc $encDst";
396  $cmd = $ignoreMissing ? "IF EXIST $encSrc $writeCmd" : $writeCmd;
397  } else {
398  $writeCmd = "mv -f $encSrc $encDst";
399  $cmd = $ignoreMissing ? "test -f $encSrc && $writeCmd" : $writeCmd;
400  }
401  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
402  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
403  $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
404  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
405  }
406  };
407  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
408  } else { // immediate write
409  // Use rename() here since (a) this clears xattrs, (b) any threads still reading the
410  // old inode are unaffected since it writes to a new inode, and (c) this is fast and
411  // atomic within a file system volume (as is normally the case)
412  $this->trapWarnings( '/: No such file or directory$/' );
413  $moved = rename( $fsSrcPath, $fsDstPath );
414  $hadError = $this->untrapWarnings();
415  if ( $hadError || ( !$moved && !$ignoreMissing ) ) {
416  $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
417 
418  return $status;
419  }
420  }
421 
422  return $status;
423  }
424 
425  protected function doDeleteInternal( array $params ) {
426  $status = $this->newStatus();
427 
428  $fsSrcPath = $this->resolveToFSPath( $params['src'] );
429  if ( $fsSrcPath === null ) {
430  $status->fatal( 'backend-fail-invalidpath', $params['src'] );
431 
432  return $status;
433  }
434 
435  $ignoreMissing = !empty( $params['ignoreMissingSource'] );
436 
437  if ( !empty( $params['async'] ) ) { // deferred
438  // https://manpages.debian.org/buster/coreutils/rm.1.en.html
439  // https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/del
440  $encSrc = escapeshellarg( $this->cleanPathSlashes( $fsSrcPath ) );
441  if ( $this->isWindows ) {
442  $writeCmd = "DEL /Q $encSrc";
443  $cmd = $ignoreMissing ? "IF EXIST $encSrc $writeCmd" : $writeCmd;
444  } else {
445  $cmd = $ignoreMissing ? "rm -f $encSrc" : "rm $encSrc";
446  }
447  $handler = function ( $errors, StatusValue $status, array $params, $cmd ) {
448  if ( $errors !== '' && !( $this->isWindows && $errors[0] === " " ) ) {
449  $status->fatal( 'backend-fail-delete', $params['src'] );
450  trigger_error( "$cmd\n$errors", E_USER_WARNING ); // command output
451  }
452  };
453  $status->value = new FSFileOpHandle( $this, $params, $handler, $cmd );
454  } else { // immediate write
455  $this->trapWarnings( '/: No such file or directory$/' );
456  $deleted = unlink( $fsSrcPath );
457  $hadError = $this->untrapWarnings();
458  if ( $hadError || ( !$deleted && !$ignoreMissing ) ) {
459  $status->fatal( 'backend-fail-delete', $params['src'] );
460 
461  return $status;
462  }
463  }
464 
465  return $status;
466  }
467 
474  protected function doPrepareInternal( $fullCont, $dirRel, array $params ) {
475  $status = $this->newStatus();
476  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
477  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
478  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
479  $existed = is_dir( $dir ); // already there?
480  // Create the directory and its parents as needed...
481  AtEase::suppressWarnings();
482  if ( !$existed && !mkdir( $dir, $this->dirMode, true ) && !is_dir( $dir ) ) {
483  $this->logger->error( __METHOD__ . ": cannot create directory $dir" );
484  $status->fatal( 'directorycreateerror', $params['dir'] ); // fails on races
485  } elseif ( !is_writable( $dir ) ) {
486  $this->logger->error( __METHOD__ . ": directory $dir is read-only" );
487  $status->fatal( 'directoryreadonlyerror', $params['dir'] );
488  } elseif ( !is_readable( $dir ) ) {
489  $this->logger->error( __METHOD__ . ": directory $dir is not readable" );
490  $status->fatal( 'directorynotreadableerror', $params['dir'] );
491  }
492  AtEase::restoreWarnings();
493  // Respect any 'noAccess' or 'noListing' flags...
494  if ( is_dir( $dir ) && !$existed ) {
495  $status->merge( $this->doSecureInternal( $fullCont, $dirRel, $params ) );
496  }
497 
498  return $status;
499  }
500 
501  protected function doSecureInternal( $fullCont, $dirRel, array $params ) {
502  $status = $this->newStatus();
503  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
504  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
505  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
506  // Seed new directories with a blank index.html, to prevent crawling...
507  if ( !empty( $params['noListing'] ) && !file_exists( "{$dir}/index.html" ) ) {
508  $this->trapWarnings();
509  $bytes = file_put_contents( "{$dir}/index.html", $this->indexHtmlPrivate() );
510  $this->untrapWarnings();
511  if ( $bytes === false ) {
512  $status->fatal( 'backend-fail-create', $params['dir'] . '/index.html' );
513  }
514  }
515  // Add a .htaccess file to the root of the container...
516  if ( !empty( $params['noAccess'] ) && !file_exists( "{$contRoot}/.htaccess" ) ) {
517  AtEase::suppressWarnings();
518  $bytes = file_put_contents( "{$contRoot}/.htaccess", $this->htaccessPrivate() );
519  AtEase::restoreWarnings();
520  if ( $bytes === false ) {
521  $storeDir = "mwstore://{$this->name}/{$shortCont}";
522  $status->fatal( 'backend-fail-create', "{$storeDir}/.htaccess" );
523  }
524  }
525 
526  return $status;
527  }
528 
529  protected function doPublishInternal( $fullCont, $dirRel, array $params ) {
530  $status = $this->newStatus();
531  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
532  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
533  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
534  // Unseed new directories with a blank index.html, to allow crawling...
535  if ( !empty( $params['listing'] ) && is_file( "{$dir}/index.html" ) ) {
536  $exists = ( file_get_contents( "{$dir}/index.html" ) === $this->indexHtmlPrivate() );
537  if ( $exists && !$this->unlink( "{$dir}/index.html" ) ) { // reverse secure()
538  $status->fatal( 'backend-fail-delete', $params['dir'] . '/index.html' );
539  }
540  }
541  // Remove the .htaccess file from the root of the container...
542  if ( !empty( $params['access'] ) && is_file( "{$contRoot}/.htaccess" ) ) {
543  $exists = ( file_get_contents( "{$contRoot}/.htaccess" ) === $this->htaccessPrivate() );
544  if ( $exists && !$this->unlink( "{$contRoot}/.htaccess" ) ) { // reverse secure()
545  $storeDir = "mwstore://{$this->name}/{$shortCont}";
546  $status->fatal( 'backend-fail-delete', "{$storeDir}/.htaccess" );
547  }
548  }
549 
550  return $status;
551  }
552 
553  protected function doCleanInternal( $fullCont, $dirRel, array $params ) {
554  $status = $this->newStatus();
555  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
556  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
557  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
558  AtEase::suppressWarnings();
559  rmdir( $dir ); // remove directory if empty
560  AtEase::restoreWarnings();
561 
562  return $status;
563  }
564 
565  protected function doGetFileStat( array $params ) {
566  $source = $this->resolveToFSPath( $params['src'] );
567  if ( $source === null ) {
568  return self::$RES_ERROR; // invalid storage path
569  }
570 
571  $this->trapWarnings(); // don't trust 'false' if there were errors
572  $stat = is_file( $source ) ? stat( $source ) : false; // regular files only
573  $hadError = $this->untrapWarnings();
574 
575  if ( is_array( $stat ) ) {
576  $ct = new ConvertibleTimestamp( $stat['mtime'] );
577 
578  return [
579  'mtime' => $ct->getTimestamp( TS_MW ),
580  'size' => $stat['size']
581  ];
582  }
583 
584  return $hadError ? self::$RES_ERROR : self::$RES_ABSENT;
585  }
586 
587  protected function doClearCache( array $paths = null ) {
588  clearstatcache(); // clear the PHP file stat cache
589  }
590 
591  protected function doDirectoryExists( $fullCont, $dirRel, array $params ) {
592  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
593  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
594  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
595 
596  $this->trapWarnings(); // don't trust 'false' if there were errors
597  $exists = is_dir( $dir );
598  $hadError = $this->untrapWarnings();
599 
600  return $hadError ? self::$RES_ERROR : $exists;
601  }
602 
610  public function getDirectoryListInternal( $fullCont, $dirRel, array $params ) {
611  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
612  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
613  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
614 
615  $this->trapWarnings(); // don't trust 'false' if there were errors
616  $exists = is_dir( $dir );
617  $isReadable = $exists ? is_readable( $dir ) : false;
618  $hadError = $this->untrapWarnings();
619 
620  if ( $isReadable ) {
621  return new FSFileBackendDirList( $dir, $params );
622  } elseif ( $exists ) {
623  $this->logger->warning( __METHOD__ . ": given directory is unreadable: '$dir'" );
624 
625  return self::$RES_ERROR; // bad permissions?
626  } elseif ( $hadError ) {
627  $this->logger->warning( __METHOD__ . ": given directory was unreachable: '$dir'" );
628 
629  return self::$RES_ERROR;
630  } else {
631  $this->logger->info( __METHOD__ . ": given directory does not exist: '$dir'" );
632 
633  return []; // nothing under this dir
634  }
635  }
636 
644  public function getFileListInternal( $fullCont, $dirRel, array $params ) {
645  list( , $shortCont, ) = FileBackend::splitStoragePath( $params['dir'] );
646  $contRoot = $this->containerFSRoot( $shortCont, $fullCont ); // must be valid
647  $dir = ( $dirRel != '' ) ? "{$contRoot}/{$dirRel}" : $contRoot;
648 
649  $this->trapWarnings(); // don't trust 'false' if there were errors
650  $exists = is_dir( $dir );
651  $isReadable = $exists ? is_readable( $dir ) : false;
652  $hadError = $this->untrapWarnings();
653 
654  if ( $exists && $isReadable ) {
655  return new FSFileBackendFileList( $dir, $params );
656  } elseif ( $exists ) {
657  $this->logger->warning( __METHOD__ . ": given directory is unreadable: '$dir'\n" );
658 
659  return self::$RES_ERROR; // bad permissions?
660  } elseif ( $hadError ) {
661  $this->logger->warning( __METHOD__ . ": given directory was unreachable: '$dir'\n" );
662 
663  return self::$RES_ERROR;
664  } else {
665  $this->logger->info( __METHOD__ . ": given directory does not exist: '$dir'\n" );
666 
667  return []; // nothing under this dir
668  }
669  }
670 
671  protected function doGetLocalReferenceMulti( array $params ) {
672  $fsFiles = []; // (path => FSFile)
673 
674  foreach ( $params['srcs'] as $src ) {
675  $source = $this->resolveToFSPath( $src );
676  if ( $source === null ) {
677  $fsFiles[$src] = self::$RES_ERROR; // invalid path
678  continue;
679  }
680 
681  $this->trapWarnings(); // don't trust 'false' if there were errors
682  $isFile = is_file( $source ); // regular files only
683  $hadError = $this->untrapWarnings();
684 
685  if ( $isFile ) {
686  $fsFiles[$src] = new FSFile( $source );
687  } elseif ( $hadError ) {
688  $fsFiles[$src] = self::$RES_ERROR;
689  } else {
690  $fsFiles[$src] = self::$RES_ABSENT;
691  }
692  }
693 
694  return $fsFiles;
695  }
696 
697  protected function doGetLocalCopyMulti( array $params ) {
698  $tmpFiles = []; // (path => TempFSFile)
699 
700  foreach ( $params['srcs'] as $src ) {
701  $source = $this->resolveToFSPath( $src );
702  if ( $source === null ) {
703  $tmpFiles[$src] = self::$RES_ERROR; // invalid path
704  continue;
705  }
706  // Create a new temporary file with the same extension...
708  $tmpFile = $this->tmpFileFactory->newTempFSFile( 'localcopy_', $ext );
709  if ( !$tmpFile ) {
710  $tmpFiles[$src] = self::$RES_ERROR;
711  continue;
712  }
713 
714  $tmpPath = $tmpFile->getPath();
715  // Copy the source file over the temp file
716  $this->trapWarnings(); // don't trust 'false' if there were errors
717  $isFile = is_file( $source ); // regular files only
718  $copySuccess = $isFile ? copy( $source, $tmpPath ) : false;
719  $hadError = $this->untrapWarnings();
720 
721  if ( $copySuccess ) {
722  $this->chmod( $tmpPath );
723  $tmpFiles[$src] = $tmpFile;
724  } elseif ( $hadError ) {
725  $tmpFiles[$src] = self::$RES_ERROR; // copy failed
726  } else {
727  $tmpFiles[$src] = self::$RES_ABSENT;
728  }
729  }
730 
731  return $tmpFiles;
732  }
733 
734  protected function directoriesAreVirtual() {
735  return false;
736  }
737 
743  protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
744  $statuses = [];
745 
746  $pipes = [];
747  $octalPermissions = '0' . decoct( $this->fileMode );
748  foreach ( $fileOpHandles as $index => $fileOpHandle ) {
749  $cmd = "{$fileOpHandle->cmd} 2>&1";
750  // Add a post-operation chmod command for permissions cleanup if applicable
751  if (
752  !$this->isWindows &&
753  $fileOpHandle->chmodPath !== null &&
754  strlen( $octalPermissions ) == 4
755  ) {
756  $encPath = escapeshellarg( $fileOpHandle->chmodPath );
757  $cmd .= " && chmod $octalPermissions $encPath 2>/dev/null";
758  }
759  $pipes[$index] = popen( $cmd, 'r' );
760  }
761 
762  $errs = [];
763  foreach ( $pipes as $index => $pipe ) {
764  // Result will be empty on success in *NIX. On Windows,
765  // it may be something like " 1 file(s) [copied|moved].".
766  $errs[$index] = stream_get_contents( $pipe );
767  fclose( $pipe );
768  }
769 
770  foreach ( $fileOpHandles as $index => $fileOpHandle ) {
771  $status = $this->newStatus();
772  $function = $fileOpHandle->call;
773  $function( $errs[$index], $status, $fileOpHandle->params, $fileOpHandle->cmd );
774  $statuses[$index] = $status;
775  }
776 
777  clearstatcache(); // files changed
778 
779  return $statuses;
780  }
781 
788  protected function chmod( $path ) {
789  if ( $this->isWindows ) {
790  return true;
791  }
792 
793  AtEase::suppressWarnings();
794  $ok = chmod( $path, $this->fileMode );
795  AtEase::restoreWarnings();
796 
797  return $ok;
798  }
799 
806  protected function unlink( $path ) {
807  AtEase::suppressWarnings();
808  $ok = unlink( $path );
809  AtEase::restoreWarnings();
810 
811  return $ok;
812  }
813 
818  protected function stageContentAsTempFile( array $params ) {
819  $content = $params['content'];
820  $tempFile = $this->tmpFileFactory->newTempFSFile( 'create_', 'tmp' );
821  if ( !$tempFile ) {
822  return null;
823  }
824 
825  AtEase::suppressWarnings();
826  $tmpPath = $tempFile->getPath();
827  if ( file_put_contents( $tmpPath, $content ) === false ) {
828  $tempFile = null;
829  }
830  AtEase::restoreWarnings();
831 
832  return $tempFile;
833  }
834 
840  protected function indexHtmlPrivate() {
841  return '';
842  }
843 
849  protected function htaccessPrivate() {
850  return "Deny from all\n";
851  }
852 
859  protected function cleanPathSlashes( $path ) {
860  return $this->isWindows ? strtr( $path, '/', '\\' ) : $path;
861  }
862 
868  protected function trapWarnings( $regexIgnore = null ) {
869  $this->warningTrapStack[] = false;
870  set_error_handler( function ( $errno, $errstr ) use ( $regexIgnore ) {
871  if ( $regexIgnore === null || !preg_match( $regexIgnore, $errstr ) ) {
872  $this->logger->error( $errstr );
873  $this->warningTrapStack[count( $this->warningTrapStack ) - 1] = true;
874  }
875  return true; // suppress from PHP handler
876  }, E_WARNING );
877  }
878 
884  protected function untrapWarnings() {
885  restore_error_handler();
886 
887  return array_pop( $this->warningTrapStack );
888  }
889 }
FileBackend\splitStoragePath
static splitStoragePath( $storagePath)
Split a storage path into a backend name, a container name, and a relative file path.
Definition: FileBackend.php:1520
FSFileBackend\__construct
__construct(array $config)
Definition: FSFileBackend.php:94
FSFileBackend\doCleanInternal
doCleanInternal( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:553
FSFileOpHandle
Definition: FSFileOpHandle.php:25
StatusValue
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: StatusValue.php:42
FSFileBackend\doStoreInternal
doStoreInternal(array $params)
Definition: FSFileBackend.php:263
FSFileBackend\doClearCache
doClearCache(array $paths=null)
Clears any additional stat caches for storage paths.
Definition: FSFileBackend.php:587
FSFileBackend\doPublishInternal
doPublishInternal( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:529
FSFileBackend\$currentUser
string $currentUser
OS username running this script.
Definition: FSFileBackend.php:79
FSFileBackend\doPrepareInternal
doPrepareInternal( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:474
FileBackend\extensionFromPath
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
Definition: FileBackend.php:1579
FSFileBackend\$dirMode
int $dirMode
Directory permission mode.
Definition: FSFileBackend.php:70
FSFileBackend\htaccessPrivate
htaccessPrivate()
Return the text of a .htaccess file to make a directory private.
Definition: FSFileBackend.php:849
FSFileBackend\doGetFileStat
doGetFileStat(array $params)
Definition: FSFileBackend.php:565
FSFileBackend\directoriesAreVirtual
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
Definition: FSFileBackend.php:734
FSFileBackend\$fileOwner
string $fileOwner
Required OS username to own files.
Definition: FSFileBackend.php:74
FileBackendStore\$RES_ERROR
static null $RES_ERROR
Idiom for "no result due to I/O errors" (since 1.34)
Definition: FileBackendStore.php:65
FSFileBackend\doGetLocalReferenceMulti
doGetLocalReferenceMulti(array $params)
Definition: FSFileBackend.php:671
FSFileBackend\$basePath
string $basePath
Directory holding the container directories.
Definition: FSFileBackend.php:64
FSFileBackend\doDirectoryExists
doDirectoryExists( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:591
FSFileBackend\getDirectoryListInternal
getDirectoryListInternal( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:610
FSFileBackend\getFeatures
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
Definition: FSFileBackend.php:119
FSFileBackendFileList
Definition: FSFileBackendFileList.php:22
FSFileBackend\stageContentAsTempFile
stageContentAsTempFile(array $params)
Definition: FSFileBackend.php:818
FSFileBackend\containerFSRoot
containerFSRoot( $shortCont, $fullCont)
Given the short (unresolved) and full (resolved) name of a container, return the file system path of ...
Definition: FSFileBackend.php:167
FSFileBackend\unlink
unlink( $path)
Unlink a file, suppressing the warnings.
Definition: FSFileBackend.php:806
FSFileBackendDirList
Definition: FSFileBackendDirList.php:22
FileBackend\ATTR_UNICODE_PATHS
const ATTR_UNICODE_PATHS
Definition: FileBackend.php:132
FSFileBackend\$warningTrapStack
bool[] $warningTrapStack
Map of (stack index => whether a warning happened)
Definition: FSFileBackend.php:82
FSFileBackend\doSecureInternal
doSecureInternal( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:501
FSFileBackend\doExecuteOpHandlesInternal
doExecuteOpHandlesInternal(array $fileOpHandles)
Definition: FSFileBackend.php:743
FSFileBackend\$containerPaths
array $containerPaths
Map of container names to root paths for custom container paths.
Definition: FSFileBackend.php:67
FSFileBackend\resolveToFSPath
resolveToFSPath( $storagePath)
Get the absolute file system path for a storage path.
Definition: FSFileBackend.php:183
FSFileBackend\doDeleteInternal
doDeleteInternal(array $params)
Definition: FSFileBackend.php:425
$content
$content
Definition: router.php:78
FSFileBackend\$fileMode
int $fileMode
File permission mode.
Definition: FSFileBackend.php:72
FSFileBackend\resolveContainerPath
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
Definition: FSFileBackend.php:129
FileBackendStore\resolveStoragePathReal
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
Definition: FileBackendStore.php:1624
FileBackendStore
Base class for all backends using particular storage medium.
Definition: FileBackendStore.php:40
FileBackendStore\$RES_ABSENT
static false $RES_ABSENT
Idiom for "no result due to missing file" (since 1.34)
Definition: FileBackendStore.php:63
FSFile
Class representing a non-directory file on the file system.
Definition: FSFile.php:32
FileBackend\newStatus
newStatus(... $args)
Yields the result of the status wrapper callback on either:
Definition: FileBackend.php:1670
FSFileBackend\$isWindows
bool $isWindows
Whether the OS is Windows (otherwise assumed Unix-like)
Definition: FSFileBackend.php:77
$status
return $status
Definition: SyntaxHighlight.php:347
FSFileBackend
Class for a file system (FS) based file backend.
Definition: FSFileBackend.php:62
FSFileBackend\indexHtmlPrivate
indexHtmlPrivate()
Return the text of an index.html file to hide directory listings.
Definition: FSFileBackend.php:840
FSFileBackend\cleanPathSlashes
cleanPathSlashes( $path)
Clean up directory separators for the given OS.
Definition: FSFileBackend.php:859
$path
$path
Definition: NoLocalSettings.php:25
FSFileBackend\doCreateInternal
doCreateInternal(array $params)
Definition: FSFileBackend.php:218
FSFileBackend\chmod
chmod( $path)
Chmod a file, suppressing the warnings.
Definition: FSFileBackend.php:788
$source
$source
Definition: mwdoc-filter.php:34
FSFileBackend\isLegalRelPath
isLegalRelPath( $path)
Sanity check a relative file system path for validity.
Definition: FSFileBackend.php:147
FSFileBackend\isPathUsableInternal
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path in the backend.
Definition: FSFileBackend.php:197
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
FileBackend\copy
copy(array $params, array $opts=[])
Performs a single copy operation.
Definition: FileBackend.php:538
FSFileBackend\untrapWarnings
untrapWarnings()
Stop listening for E_WARNING errors and get whether any happened.
Definition: FSFileBackend.php:884
FSFileBackend\doGetLocalCopyMulti
doGetLocalCopyMulti(array $params)
Definition: FSFileBackend.php:697
FSFileBackend\doCopyInternal
doCopyInternal(array $params)
Definition: FSFileBackend.php:306
FSFileBackend\trapWarnings
trapWarnings( $regexIgnore=null)
Listen for E_WARNING errors and track whether any that happen.
Definition: FSFileBackend.php:868
FSFileBackend\getFileListInternal
getFileListInternal( $fullCont, $dirRel, array $params)
Definition: FSFileBackend.php:644
FSFileBackend\doMoveInternal
doMoveInternal(array $params)
Definition: FSFileBackend.php:366