3 * OpenStack Swift based file backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 * @author Aaron Schulz
27 * @brief Class for an OpenStack Swift based file backend.
29 * This requires the SwiftCloudFiles MediaWiki extension, which includes
30 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
31 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
33 * Status messages should avoid mentioning the Swift account name.
34 * Likewise, error suppression should be used to avoid path disclosure.
36 * @ingroup FileBackend
39 class SwiftFileBackend
extends FileBackendStore
{
40 /** @var CF_Authentication */
41 protected $auth; // Swift authentication handler
42 protected $authTTL; // integer seconds
43 protected $swiftAnonUser; // string; username to handle unauthenticated requests
44 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
45 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
46 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
48 /** @var CF_Connection */
49 protected $conn; // Swift connection handle
50 protected $sessionStarted = 0; // integer UNIX timestamp
52 /** @var CloudFilesException */
53 protected $connException;
54 protected $connErrorTime = 0; // UNIX timestamp
59 /** @var ProcessCacheLRU */
60 protected $connContainerCache; // container object cache
63 * @see FileBackendStore::__construct()
64 * Additional $config params include:
65 * - swiftAuthUrl : Swift authentication server URL
66 * - swiftUser : Swift user used by MediaWiki (account:username)
67 * - swiftKey : Swift authentication key for the above user
68 * - swiftAuthTTL : Swift authentication TTL (seconds)
69 * - swiftAnonUser : Swift user used for end-user requests (account:username).
70 * If set, then views of public containers are assumed to go
71 * through this user. If not set, then public containers are
72 * accessible to unauthenticated requests via ".r:*" in the ACL.
73 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
74 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
75 * If files may likely change, this should probably not exceed
76 * a few days. For example, deletions may take this long to apply.
77 * If object purging is enabled, however, this is not an issue.
78 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
79 * - shardViaHashLevels : Map of container names to sharding config with:
80 * - base : base of hash characters, 16 or 36
81 * - levels : the number of hash levels (and digits)
82 * - repeat : hash subdirectories are prefixed with all the
83 * parent hash directory names (e.g. "a/ab/abc")
84 * - cacheAuthInfo : Whether to cache authentication tokens in APC/XCache.
85 * This is probably insecure in shared hosting environments.
87 public function __construct( array $config ) {
88 parent
::__construct( $config );
89 if ( !MWInit
::classExists( 'CF_Constants' ) ) {
90 throw new MWException( 'SwiftCloudFiles extension not installed.' );
93 $this->auth
= new CF_Authentication(
96 null, // account; unused
97 $config['swiftAuthUrl']
100 $this->authTTL
= isset( $config['swiftAuthTTL'] )
101 ?
$config['swiftAuthTTL']
102 : 5 * 60; // some sane number
103 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
104 ?
$config['swiftAnonUser']
106 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
107 ?
$config['shardViaHashLevels']
109 $this->swiftUseCDN
= isset( $config['swiftUseCDN'] )
110 ?
$config['swiftUseCDN']
112 $this->swiftCDNExpiry
= isset( $config['swiftCDNExpiry'] )
113 ?
$config['swiftCDNExpiry']
115 $this->swiftCDNPurgable
= isset( $config['swiftCDNPurgable'] )
116 ?
$config['swiftCDNPurgable']
118 // Cache container information to mask latency
119 $this->memCache
= wfGetMainCache();
120 // Process cache for container info
121 $this->connContainerCache
= new ProcessCacheLRU( 300 );
122 // Cache auth token information to avoid RTTs
123 if ( !empty( $config['cacheAuthInfo'] ) ) {
124 try { // look for APC, XCache, WinCache, ect...
125 $this->srvCache
= ObjectCache
::newAccelerator( array() );
126 } catch ( Exception
$e ) {}
128 $this->srvCache
= $this->srvCache ?
$this->srvCache
: new EmptyBagOStuff();
132 * @see FileBackendStore::resolveContainerPath()
135 protected function resolveContainerPath( $container, $relStoragePath ) {
136 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
137 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
138 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
139 return null; // too long for Swift
141 return $relStoragePath;
145 * @see FileBackendStore::isPathUsableInternal()
148 public function isPathUsableInternal( $storagePath ) {
149 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
150 if ( $rel === null ) {
151 return false; // invalid
155 $this->getContainer( $container );
156 return true; // container exists
157 } catch ( NoSuchContainerException
$e ) {
158 } catch ( CloudFilesException
$e ) { // some other exception?
159 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
166 * @see FileBackendStore::doCreateInternal()
169 protected function doCreateInternal( array $params ) {
170 $status = Status
::newGood();
172 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
173 if ( $dstRel === null ) {
174 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
178 // (a) Check the destination container and object
180 $dContObj = $this->getContainer( $dstCont );
181 if ( empty( $params['overwrite'] ) &&
182 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
184 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
187 } catch ( NoSuchContainerException
$e ) {
188 $status->fatal( 'backend-fail-create', $params['dst'] );
190 } catch ( CloudFilesException
$e ) { // some other exception?
191 $this->handleException( $e, $status, __METHOD__
, $params );
195 // (b) Get a SHA-1 hash of the object
196 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
198 // (c) Actually create the object
200 // Create a fresh CF_Object with no fields preloaded.
201 // We don't want to preserve headers, metadata, and such.
202 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
203 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
204 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
205 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
206 // The MD5 here will be checked within Swift against its own MD5.
207 $obj->set_etag( md5( $params['content'] ) );
208 // Use the same content type as StreamFile for security
209 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
210 if ( !strlen( $obj->content_type
) ) { // special case
211 $obj->content_type
= 'unknown/unknown';
213 if ( !empty( $params['async'] ) ) { // deferred
214 $handle = $obj->write_async( $params['content'] );
215 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $handle );
216 $status->value
->affectedObjects
[] = $obj;
217 } else { // actually write the object in Swift
218 $obj->write( $params['content'] );
219 $this->purgeCDNCache( array( $obj ) );
221 } catch ( CDNNotEnabledException
$e ) {
222 // CDN not enabled; nothing to see here
223 } catch ( BadContentTypeException
$e ) {
224 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
225 } catch ( CloudFilesException
$e ) { // some other exception?
226 $this->handleException( $e, $status, __METHOD__
, $params );
233 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
235 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
237 $cfOp->getLastResponse();
238 } catch ( BadContentTypeException
$e ) {
239 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
244 * @see FileBackendStore::doStoreInternal()
247 protected function doStoreInternal( array $params ) {
248 $status = Status
::newGood();
250 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
251 if ( $dstRel === null ) {
252 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
256 // (a) Check the destination container and object
258 $dContObj = $this->getContainer( $dstCont );
259 if ( empty( $params['overwrite'] ) &&
260 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
262 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
265 } catch ( NoSuchContainerException
$e ) {
266 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
268 } catch ( CloudFilesException
$e ) { // some other exception?
269 $this->handleException( $e, $status, __METHOD__
, $params );
273 // (b) Get a SHA-1 hash of the object
274 $sha1Hash = sha1_file( $params['src'] );
275 if ( $sha1Hash === false ) { // source doesn't exist?
276 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
279 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
281 // (c) Actually store the object
283 // Create a fresh CF_Object with no fields preloaded.
284 // We don't want to preserve headers, metadata, and such.
285 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
286 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
287 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
288 // The MD5 here will be checked within Swift against its own MD5.
289 $obj->set_etag( md5_file( $params['src'] ) );
290 // Use the same content type as StreamFile for security
291 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
292 if ( !strlen( $obj->content_type
) ) { // special case
293 $obj->content_type
= 'unknown/unknown';
295 if ( !empty( $params['async'] ) ) { // deferred
296 wfSuppressWarnings();
297 $fp = fopen( $params['src'], 'rb' );
300 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
302 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
303 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $handle );
304 $status->value
->resourcesToClose
[] = $fp;
305 $status->value
->affectedObjects
[] = $obj;
307 } else { // actually write the object in Swift
308 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
309 $this->purgeCDNCache( array( $obj ) );
311 } catch ( CDNNotEnabledException
$e ) {
312 // CDN not enabled; nothing to see here
313 } catch ( BadContentTypeException
$e ) {
314 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
315 } catch ( IOException
$e ) {
316 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
317 } catch ( CloudFilesException
$e ) { // some other exception?
318 $this->handleException( $e, $status, __METHOD__
, $params );
325 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
327 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
329 $cfOp->getLastResponse();
330 } catch ( BadContentTypeException
$e ) {
331 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
332 } catch ( IOException
$e ) {
333 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
338 * @see FileBackendStore::doCopyInternal()
341 protected function doCopyInternal( array $params ) {
342 $status = Status
::newGood();
344 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
345 if ( $srcRel === null ) {
346 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
350 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
351 if ( $dstRel === null ) {
352 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
356 // (a) Check the source/destination containers and destination object
358 $sContObj = $this->getContainer( $srcCont );
359 $dContObj = $this->getContainer( $dstCont );
360 if ( empty( $params['overwrite'] ) &&
361 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
363 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
366 } catch ( NoSuchContainerException
$e ) {
367 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
369 } catch ( CloudFilesException
$e ) { // some other exception?
370 $this->handleException( $e, $status, __METHOD__
, $params );
374 // (b) Actually copy the file to the destination
376 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
377 if ( !empty( $params['async'] ) ) { // deferred
378 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
379 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
380 $status->value
->affectedObjects
[] = $dstObj;
381 } else { // actually write the object in Swift
382 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
383 $this->purgeCDNCache( array( $dstObj ) );
385 } catch ( CDNNotEnabledException
$e ) {
386 // CDN not enabled; nothing to see here
387 } catch ( NoSuchObjectException
$e ) { // source object does not exist
388 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
389 } catch ( CloudFilesException
$e ) { // some other exception?
390 $this->handleException( $e, $status, __METHOD__
, $params );
397 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
399 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
401 $cfOp->getLastResponse();
402 } catch ( NoSuchObjectException
$e ) { // source object does not exist
403 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
408 * @see FileBackendStore::doMoveInternal()
411 protected function doMoveInternal( array $params ) {
412 $status = Status
::newGood();
414 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
415 if ( $srcRel === null ) {
416 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
420 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
421 if ( $dstRel === null ) {
422 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
426 // (a) Check the source/destination containers and destination object
428 $sContObj = $this->getContainer( $srcCont );
429 $dContObj = $this->getContainer( $dstCont );
430 if ( empty( $params['overwrite'] ) &&
431 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
433 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
436 } catch ( NoSuchContainerException
$e ) {
437 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
439 } catch ( CloudFilesException
$e ) { // some other exception?
440 $this->handleException( $e, $status, __METHOD__
, $params );
444 // (b) Actually move the file to the destination
446 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
447 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
448 if ( !empty( $params['async'] ) ) { // deferred
449 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
450 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $handle );
451 $status->value
->affectedObjects
[] = $srcObj;
452 $status->value
->affectedObjects
[] = $dstObj;
453 } else { // actually write the object in Swift
454 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
455 $this->purgeCDNCache( array( $srcObj, $dstObj ) );
457 } catch ( CDNNotEnabledException
$e ) {
458 // CDN not enabled; nothing to see here
459 } catch ( NoSuchObjectException
$e ) { // source object does not exist
460 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
461 } catch ( CloudFilesException
$e ) { // some other exception?
462 $this->handleException( $e, $status, __METHOD__
, $params );
469 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
471 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
473 $cfOp->getLastResponse();
474 } catch ( NoSuchObjectException
$e ) { // source object does not exist
475 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
480 * @see FileBackendStore::doDeleteInternal()
483 protected function doDeleteInternal( array $params ) {
484 $status = Status
::newGood();
486 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
487 if ( $srcRel === null ) {
488 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
493 $sContObj = $this->getContainer( $srcCont );
494 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
495 if ( !empty( $params['async'] ) ) { // deferred
496 $handle = $sContObj->delete_object_async( $srcRel );
497 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
498 $status->value
->affectedObjects
[] = $srcObj;
499 } else { // actually write the object in Swift
500 $sContObj->delete_object( $srcRel );
501 $this->purgeCDNCache( array( $srcObj ) );
503 } catch ( CDNNotEnabledException
$e ) {
504 // CDN not enabled; nothing to see here
505 } catch ( NoSuchContainerException
$e ) {
506 $status->fatal( 'backend-fail-delete', $params['src'] );
507 } catch ( NoSuchObjectException
$e ) {
508 if ( empty( $params['ignoreMissingSource'] ) ) {
509 $status->fatal( 'backend-fail-delete', $params['src'] );
511 } catch ( CloudFilesException
$e ) { // some other exception?
512 $this->handleException( $e, $status, __METHOD__
, $params );
519 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
521 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
523 $cfOp->getLastResponse();
524 } catch ( NoSuchContainerException
$e ) {
525 $status->fatal( 'backend-fail-delete', $params['src'] );
526 } catch ( NoSuchObjectException
$e ) {
527 if ( empty( $params['ignoreMissingSource'] ) ) {
528 $status->fatal( 'backend-fail-delete', $params['src'] );
534 * @see FileBackendStore::doPrepareInternal()
537 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
538 $status = Status
::newGood();
540 // (a) Check if container already exists
542 $contObj = $this->getContainer( $fullCont );
543 // NoSuchContainerException not thrown: container must exist
544 return $status; // already exists
545 } catch ( NoSuchContainerException
$e ) {
546 // NoSuchContainerException thrown: container does not exist
547 } catch ( CloudFilesException
$e ) { // some other exception?
548 $this->handleException( $e, $status, __METHOD__
, $params );
552 // (b) Create container as needed
554 $contObj = $this->createContainer( $fullCont );
555 if ( !empty( $params['noAccess'] ) ) {
556 // Make container private to end-users...
557 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
559 // Make container public to end-users...
560 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
562 if ( $this->swiftUseCDN
) { // Rackspace style CDN
563 $contObj->make_public( $this->swiftCDNExpiry
);
565 } catch ( CDNNotEnabledException
$e ) {
566 // CDN not enabled; nothing to see here
567 } catch ( CloudFilesException
$e ) { // some other exception?
568 $this->handleException( $e, $status, __METHOD__
, $params );
576 * @see FileBackendStore::doSecureInternal()
579 protected function doSecureInternal( $fullCont, $dir, array $params ) {
580 $status = Status
::newGood();
581 if ( empty( $params['noAccess'] ) ) {
582 return $status; // nothing to do
585 // Restrict container from end-users...
587 // doPrepareInternal() should have been called,
588 // so the Swift container should already exist...
589 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
590 // NoSuchContainerException not thrown: container must exist
592 // Make container private to end-users...
593 $status->merge( $this->setContainerAccess(
595 array( $this->auth
->username
), // read
596 array( $this->auth
->username
) // write
598 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
599 $contObj->make_private();
601 } catch ( CDNNotEnabledException
$e ) {
602 // CDN not enabled; nothing to see here
603 } catch ( CloudFilesException
$e ) { // some other exception?
604 $this->handleException( $e, $status, __METHOD__
, $params );
611 * @see FileBackendStore::doPublishInternal()
614 protected function doPublishInternal( $fullCont, $dir, array $params ) {
615 $status = Status
::newGood();
617 // Unrestrict container from end-users...
619 // doPrepareInternal() should have been called,
620 // so the Swift container should already exist...
621 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
622 // NoSuchContainerException not thrown: container must exist
624 // Make container public to end-users...
625 if ( $this->swiftAnonUser
!= '' ) {
626 $status->merge( $this->setContainerAccess(
628 array( $this->auth
->username
, $this->swiftAnonUser
), // read
629 array( $this->auth
->username
, $this->swiftAnonUser
) // write
632 $status->merge( $this->setContainerAccess(
634 array( $this->auth
->username
, '.r:*' ), // read
635 array( $this->auth
->username
) // write
638 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
639 $contObj->make_public();
641 } catch ( CDNNotEnabledException
$e ) {
642 // CDN not enabled; nothing to see here
643 } catch ( CloudFilesException
$e ) { // some other exception?
644 $this->handleException( $e, $status, __METHOD__
, $params );
651 * @see FileBackendStore::doCleanInternal()
654 protected function doCleanInternal( $fullCont, $dir, array $params ) {
655 $status = Status
::newGood();
657 // Only containers themselves can be removed, all else is virtual
659 return $status; // nothing to do
662 // (a) Check the container
664 $contObj = $this->getContainer( $fullCont, true );
665 } catch ( NoSuchContainerException
$e ) {
666 return $status; // ok, nothing to do
667 } catch ( CloudFilesException
$e ) { // some other exception?
668 $this->handleException( $e, $status, __METHOD__
, $params );
672 // (b) Delete the container if empty
673 if ( $contObj->object_count
== 0 ) {
675 $this->deleteContainer( $fullCont );
676 } catch ( NoSuchContainerException
$e ) {
677 return $status; // race?
678 } catch ( NonEmptyContainerException
$e ) {
679 return $status; // race? consistency delay?
680 } catch ( CloudFilesException
$e ) { // some other exception?
681 $this->handleException( $e, $status, __METHOD__
, $params );
690 * @see FileBackendStore::doFileExists()
691 * @return array|bool|null
693 protected function doGetFileStat( array $params ) {
694 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
695 if ( $srcRel === null ) {
696 return false; // invalid storage path
701 $contObj = $this->getContainer( $srcCont );
702 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
703 $this->addMissingMetadata( $srcObj, $params['src'] );
705 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
706 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
707 'size' => (int)$srcObj->content_length
,
708 'sha1' => $srcObj->metadata
['Sha1base36']
710 } catch ( NoSuchContainerException
$e ) {
711 } catch ( NoSuchObjectException
$e ) {
712 } catch ( CloudFilesException
$e ) { // some other exception?
714 $this->handleException( $e, null, __METHOD__
, $params );
721 * Fill in any missing object metadata and save it to Swift
723 * @param $obj CF_Object
724 * @param $path string Storage path to object
725 * @return bool Success
726 * @throws Exception cloudfiles exceptions
728 protected function addMissingMetadata( CF_Object
$obj, $path ) {
729 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
730 return true; // nothing to do
732 $status = Status
::newGood();
733 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
734 if ( $status->isOK() ) {
735 # Do not stat the file in getLocalCopy() to avoid infinite loops
736 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
738 $hash = $tmpFile->getSha1Base36();
739 if ( $hash !== false ) {
740 $obj->metadata
['Sha1base36'] = $hash;
741 $obj->sync_metadata(); // save to Swift
742 return true; // success
746 $obj->metadata
['Sha1base36'] = false;
747 return false; // failed
751 * @see FileBackend::getFileContents()
752 * @return bool|null|string
754 public function getFileContents( array $params ) {
755 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
756 if ( $srcRel === null ) {
757 return false; // invalid storage path
760 if ( !$this->fileExists( $params ) ) {
766 $sContObj = $this->getContainer( $srcCont );
767 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
768 $data = $obj->read( $this->headersFromParams( $params ) );
769 } catch ( NoSuchContainerException
$e ) {
770 } catch ( CloudFilesException
$e ) { // some other exception?
771 $this->handleException( $e, null, __METHOD__
, $params );
778 * @see FileBackendStore::doDirectoryExists()
781 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
783 $container = $this->getContainer( $fullCont );
784 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
785 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
786 } catch ( NoSuchContainerException
$e ) {
788 } catch ( CloudFilesException
$e ) { // some other exception?
789 $this->handleException( $e, null, __METHOD__
,
790 array( 'cont' => $fullCont, 'dir' => $dir ) );
793 return null; // error
797 * @see FileBackendStore::getDirectoryListInternal()
798 * @return SwiftFileBackendDirList
800 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
801 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
805 * @see FileBackendStore::getFileListInternal()
806 * @return SwiftFileBackendFileList
808 public function getFileListInternal( $fullCont, $dir, array $params ) {
809 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
813 * Do not call this function outside of SwiftFileBackendFileList
815 * @param $fullCont string Resolved container name
816 * @param $dir string Resolved storage directory with no trailing slash
817 * @param $after string|null Storage path of file to list items after
818 * @param $limit integer Max number of items to list
819 * @param $params Array Includes flag for 'topOnly'
820 * @return Array List of relative paths of dirs directly under $dir
822 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
824 if ( $after === INF
) {
825 return $dirs; // nothing more
827 wfProfileIn( __METHOD__
. '-' . $this->name
);
830 $container = $this->getContainer( $fullCont );
831 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
832 // Non-recursive: only list dirs right under $dir
833 if ( !empty( $params['topOnly'] ) ) {
834 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
835 foreach ( $objects as $object ) { // files and dirs
836 if ( substr( $object, -1 ) === '/' ) {
837 $dirs[] = $object; // directories end in '/'
840 // Recursive: list all dirs under $dir and its subdirs
842 // Get directory from last item of prior page
843 $lastDir = $this->getParentDir( $after ); // must be first page
844 $objects = $container->list_objects( $limit, $after, $prefix );
845 foreach ( $objects as $object ) { // files
846 $objectDir = $this->getParentDir( $object ); // directory of object
847 if ( $objectDir !== false ) { // file has a parent dir
848 // Swift stores paths in UTF-8, using binary sorting.
849 // See function "create_container_table" in common/db.py.
850 // If a directory is not "greater" than the last one,
851 // then it was already listed by the calling iterator.
852 if ( $objectDir > $lastDir ) {
854 do { // add dir and all its parent dirs
855 $dirs[] = "{$pDir}/";
856 $pDir = $this->getParentDir( $pDir );
857 } while ( $pDir !== false // sanity
858 && $pDir > $lastDir // not done already
859 && strlen( $pDir ) > strlen( $dir ) // within $dir
862 $lastDir = $objectDir;
866 if ( count( $objects ) < $limit ) {
867 $after = INF
; // avoid a second RTT
869 $after = end( $objects ); // update last item
871 } catch ( NoSuchContainerException
$e ) {
872 } catch ( CloudFilesException
$e ) { // some other exception?
873 $this->handleException( $e, null, __METHOD__
,
874 array( 'cont' => $fullCont, 'dir' => $dir ) );
877 wfProfileOut( __METHOD__
. '-' . $this->name
);
881 protected function getParentDir( $path ) {
882 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
886 * Do not call this function outside of SwiftFileBackendFileList
888 * @param $fullCont string Resolved container name
889 * @param $dir string Resolved storage directory with no trailing slash
890 * @param $after string|null Storage path of file to list items after
891 * @param $limit integer Max number of items to list
892 * @param $params Array Includes flag for 'topOnly'
893 * @return Array List of relative paths of files under $dir
895 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
897 if ( $after === INF
) {
898 return $files; // nothing more
900 wfProfileIn( __METHOD__
. '-' . $this->name
);
903 $container = $this->getContainer( $fullCont );
904 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
905 // Non-recursive: only list files right under $dir
906 if ( !empty( $params['topOnly'] ) ) { // files and dirs
907 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
908 foreach ( $objects as $object ) {
909 if ( substr( $object, -1 ) !== '/' ) {
910 $files[] = $object; // directories end in '/'
913 // Recursive: list all files under $dir and its subdirs
915 $objects = $container->list_objects( $limit, $after, $prefix );
918 if ( count( $objects ) < $limit ) {
919 $after = INF
; // avoid a second RTT
921 $after = end( $objects ); // update last item
923 } catch ( NoSuchContainerException
$e ) {
924 } catch ( CloudFilesException
$e ) { // some other exception?
925 $this->handleException( $e, null, __METHOD__
,
926 array( 'cont' => $fullCont, 'dir' => $dir ) );
929 wfProfileOut( __METHOD__
. '-' . $this->name
);
934 * @see FileBackendStore::doGetFileSha1base36()
937 protected function doGetFileSha1base36( array $params ) {
938 $stat = $this->getFileStat( $params );
940 return $stat['sha1'];
947 * @see FileBackendStore::doStreamFile()
950 protected function doStreamFile( array $params ) {
951 $status = Status
::newGood();
953 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
954 if ( $srcRel === null ) {
955 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
959 $cont = $this->getContainer( $srcCont );
960 } catch ( NoSuchContainerException
$e ) {
961 $status->fatal( 'backend-fail-stream', $params['src'] );
963 } catch ( CloudFilesException
$e ) { // some other exception?
964 $this->handleException( $e, $status, __METHOD__
, $params );
969 $output = fopen( 'php://output', 'wb' );
970 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
971 $obj->stream( $output, $this->headersFromParams( $params ) );
972 } catch ( CloudFilesException
$e ) { // some other exception?
973 $this->handleException( $e, $status, __METHOD__
, $params );
980 * @see FileBackendStore::getLocalCopy()
981 * @return null|TempFSFile
983 public function getLocalCopy( array $params ) {
984 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
985 if ( $srcRel === null ) {
989 # Check the recursion guard to avoid loops when filling metadata
990 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
996 $sContObj = $this->getContainer( $srcCont );
997 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
998 // Get source file extension
999 $ext = FileBackend
::extensionFromPath( $srcRel );
1000 // Create a new temporary file...
1001 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
1003 $handle = fopen( $tmpFile->getPath(), 'wb' );
1005 $obj->stream( $handle, $this->headersFromParams( $params ) );
1008 $tmpFile = null; // couldn't open temp file
1011 } catch ( NoSuchContainerException
$e ) {
1013 } catch ( CloudFilesException
$e ) { // some other exception?
1015 $this->handleException( $e, null, __METHOD__
, $params );
1022 * @see FileBackendStore::directoriesAreVirtual()
1025 protected function directoriesAreVirtual() {
1030 * Get headers to send to Swift when reading a file based
1031 * on a FileBackend params array, e.g. that of getLocalCopy().
1032 * $params is currently only checked for a 'latest' flag.
1034 * @param $params Array
1037 protected function headersFromParams( array $params ) {
1039 if ( !empty( $params['latest'] ) ) {
1040 $hdrs[] = 'X-Newest: true';
1046 * @see FileBackendStore::doExecuteOpHandlesInternal()
1047 * @return Array List of corresponding Status objects
1049 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1050 $statuses = array();
1052 $cfOps = array(); // list of CF_Async_Op objects
1053 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1054 $cfOps[$index] = $fileOpHandle->cfOp
;
1056 $batch = new CF_Async_Op_Batch( $cfOps );
1058 $cfOps = $batch->execute();
1059 foreach ( $cfOps as $index => $cfOp ) {
1060 $status = Status
::newGood();
1061 try { // catch exceptions; update status
1062 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1063 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1064 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1065 } catch ( CloudFilesException
$e ) { // some other exception?
1066 $this->handleException( $e, $status,
1067 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1069 $statuses[$index] = $status;
1076 * Set read/write permissions for a Swift container.
1078 * $readGrps is a list of the possible criteria for a request to have
1079 * access to read a container. Each item is one of the following formats:
1080 * - account:user : Grants access if the request is by the given user
1081 * - .r:<regex> : Grants access if the request is from a referrer host that
1082 * matches the expression and the request is not for a listing.
1083 * Setting this to '*' effectively makes a container public.
1084 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1085 * matches the expression and the request for a listing.
1087 * $writeGrps is a list of the possible criteria for a request to have
1088 * access to write to a container. Each item is of the following format:
1089 * - account:user : Grants access if the request is by the given user
1091 * @see http://swift.openstack.org/misc.html#acls
1093 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1094 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1096 * @param $contObj CF_Container Swift container
1097 * @param $readGrps Array List of read access routes
1098 * @param $writeGrps Array List of write access routes
1101 protected function setContainerAccess(
1102 CF_Container
$contObj, array $readGrps, array $writeGrps
1104 $creds = $contObj->cfs_auth
->export_credentials();
1106 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1108 // Note: 10 second timeout consistent with php-cloudfiles
1109 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1110 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1111 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1112 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1114 return $req->execute(); // should return 204
1118 * Purge the CDN cache of affected objects if CDN caching is enabled.
1119 * This is for Rackspace/Akamai CDNs.
1121 * @param $objects Array List of CF_Object items
1124 public function purgeCDNCache( array $objects ) {
1125 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1126 foreach ( $objects as $object ) {
1128 $object->purge_from_cdn();
1129 } catch ( CDNNotEnabledException
$e ) {
1130 // CDN not enabled; nothing to see here
1131 } catch ( CloudFilesException
$e ) {
1132 $this->handleException( $e, null, __METHOD__
,
1133 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1140 * Get an authenticated connection handle to the Swift proxy
1142 * @return CF_Connection|bool False on failure
1143 * @throws CloudFilesException
1145 protected function getConnection() {
1146 if ( $this->connException
instanceof CloudFilesException
) {
1147 if ( ( time() - $this->connErrorTime
) < 60 ) {
1148 throw $this->connException
; // failed last attempt; don't bother
1149 } else { // actually retry this time
1150 $this->connException
= null;
1151 $this->connErrorTime
= 0;
1154 // Session keys expire after a while, so we renew them periodically
1155 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1156 // Authenticate with proxy and get a session key...
1157 if ( !$this->conn ||
$reAuth ) {
1158 $this->sessionStarted
= 0;
1159 $this->connContainerCache
->clear();
1160 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1161 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1162 if ( is_array( $creds ) ) { // cache hit
1163 $this->auth
->load_cached_credentials(
1164 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1165 $this->sessionStarted
= time() - ceil( $this->authTTL
/2 ); // skew for worst case
1166 } else { // cache miss
1168 $this->auth
->authenticate();
1169 $creds = $this->auth
->export_credentials();
1170 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/2 ) ); // cache
1171 $this->sessionStarted
= time();
1172 } catch ( CloudFilesException
$e ) {
1173 $this->connException
= $e; // don't keep re-trying
1174 $this->connErrorTime
= time();
1175 throw $e; // throw it back
1178 if ( $this->conn
) { // re-authorizing?
1179 $this->conn
->close(); // close active cURL handles in CF_Http object
1181 $this->conn
= new CF_Connection( $this->auth
);
1187 * Get the cache key for a container
1189 * @param $username string
1192 private function getCredsCacheKey( $username ) {
1193 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1197 * @see FileBackendStore::doClearCache()
1199 protected function doClearCache( array $paths = null ) {
1200 $this->connContainerCache
->clear(); // clear container object cache
1204 * Get a Swift container object, possibly from process cache.
1205 * Use $reCache if the file count or byte count is needed.
1207 * @param $container string Container name
1208 * @param $bypassCache bool Bypass all caches and load from Swift
1209 * @return CF_Container
1210 * @throws CloudFilesException
1212 protected function getContainer( $container, $bypassCache = false ) {
1213 $conn = $this->getConnection(); // Swift proxy connection
1214 if ( $bypassCache ) { // purge cache
1215 $this->connContainerCache
->clear( $container );
1216 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1217 $this->primeContainerCache( array( $container ) ); // check persistent cache
1219 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1220 $contObj = $conn->get_container( $container );
1221 // NoSuchContainerException not thrown: container must exist
1222 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1223 if ( !$bypassCache ) {
1224 $this->setContainerCache( $container, // update persistent cache
1225 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1229 return $this->connContainerCache
->get( $container, 'obj' );
1233 * Create a Swift container
1235 * @param $container string Container name
1236 * @return CF_Container
1237 * @throws CloudFilesException
1239 protected function createContainer( $container ) {
1240 $conn = $this->getConnection(); // Swift proxy connection
1241 $contObj = $conn->create_container( $container );
1242 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1247 * Delete a Swift container
1249 * @param $container string Container name
1251 * @throws CloudFilesException
1253 protected function deleteContainer( $container ) {
1254 $conn = $this->getConnection(); // Swift proxy connection
1255 $this->connContainerCache
->clear( $container ); // purge
1256 $conn->delete_container( $container );
1260 * @see FileBackendStore::doPrimeContainerCache()
1263 protected function doPrimeContainerCache( array $containerInfo ) {
1265 $conn = $this->getConnection(); // Swift proxy connection
1266 foreach ( $containerInfo as $container => $info ) {
1267 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1268 $container, $info['count'], $info['bytes'] );
1269 $this->connContainerCache
->set( $container, 'obj', $contObj );
1271 } catch ( CloudFilesException
$e ) { // some other exception?
1272 $this->handleException( $e, null, __METHOD__
, array() );
1277 * Log an unexpected exception for this backend.
1278 * This also sets the Status object to have a fatal error.
1280 * @param $e Exception
1281 * @param $status Status|null
1282 * @param $func string
1283 * @param $params Array
1286 protected function handleException( Exception
$e, $status, $func, array $params ) {
1287 if ( $status instanceof Status
) {
1288 if ( $e instanceof AuthenticationException
) {
1289 $status->fatal( 'backend-fail-connect', $this->name
);
1291 $status->fatal( 'backend-fail-internal', $this->name
);
1294 if ( $e->getMessage() ) {
1295 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1297 wfDebugLog( 'SwiftBackend',
1298 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1299 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1305 * @see FileBackendStoreOpHandle
1307 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1308 /** @var CF_Async_Op */
1311 public $affectedObjects = array();
1313 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1314 $this->backend
= $backend;
1315 $this->params
= $params;
1316 $this->call
= $call;
1317 $this->cfOp
= $cfOp;
1322 * SwiftFileBackend helper class to page through listings.
1323 * Swift also has a listing limit of 10,000 objects for sanity.
1324 * Do not use this class from places outside SwiftFileBackend.
1326 * @ingroup FileBackend
1328 abstract class SwiftFileBackendList
implements Iterator
{
1330 protected $bufferIter = array();
1331 protected $bufferAfter = null; // string; list items *after* this path
1332 protected $pos = 0; // integer
1334 protected $params = array();
1336 /** @var SwiftFileBackend */
1338 protected $container; // string; container name
1339 protected $dir; // string; storage directory
1340 protected $suffixStart; // integer
1342 const PAGE_SIZE
= 9000; // file listing buffer size
1345 * @param $backend SwiftFileBackend
1346 * @param $fullCont string Resolved container name
1347 * @param $dir string Resolved directory relative to container
1348 * @param $params Array
1350 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1351 $this->backend
= $backend;
1352 $this->container
= $fullCont;
1354 if ( substr( $this->dir
, -1 ) === '/' ) {
1355 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1357 if ( $this->dir
== '' ) { // whole container
1358 $this->suffixStart
= 0;
1359 } else { // dir within container
1360 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1362 $this->params
= $params;
1366 * @see Iterator::key()
1369 public function key() {
1374 * @see Iterator::next()
1377 public function next() {
1378 // Advance to the next file in the page
1379 next( $this->bufferIter
);
1381 // Check if there are no files left in this page and
1382 // advance to the next page if this page was not empty.
1383 if ( !$this->valid() && count( $this->bufferIter
) ) {
1384 $this->bufferIter
= $this->pageFromList(
1385 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1386 ); // updates $this->bufferAfter
1391 * @see Iterator::rewind()
1394 public function rewind() {
1396 $this->bufferAfter
= null;
1397 $this->bufferIter
= $this->pageFromList(
1398 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1399 ); // updates $this->bufferAfter
1403 * @see Iterator::valid()
1406 public function valid() {
1407 if ( $this->bufferIter
=== null ) {
1408 return false; // some failure?
1410 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1415 * Get the given list portion (page)
1417 * @param $container string Resolved container name
1418 * @param $dir string Resolved path relative to container
1419 * @param $after string|null
1420 * @param $limit integer
1421 * @param $params Array
1422 * @return Traversable|Array|null Returns null on failure
1424 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1428 * Iterator for listing directories
1430 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1432 * @see Iterator::current()
1433 * @return string|bool String (relative path) or false
1435 public function current() {
1436 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1440 * @see SwiftFileBackendList::pageFromList()
1441 * @return Array|null
1443 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1444 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1449 * Iterator for listing regular files
1451 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1453 * @see Iterator::current()
1454 * @return string|bool String (relative path) or false
1456 public function current() {
1457 return substr( current( $this->bufferIter
), $this->suffixStart
);
1461 * @see SwiftFileBackendList::pageFromList()
1462 * @return Array|null
1464 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1465 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );