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']
114 : 12*3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
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 // Set the Content-Disposition header if requested
214 if ( isset( $params['disposition'] ) ) {
215 $obj->headers
['Content-Disposition'] = $params['disposition'];
217 if ( !empty( $params['async'] ) ) { // deferred
218 $op = $obj->write_async( $params['content'] );
219 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
220 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
221 $status->value
->affectedObjects
[] = $obj;
223 } else { // actually write the object in Swift
224 $obj->write( $params['content'] );
225 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
226 $this->purgeCDNCache( array( $obj ) );
229 } catch ( CDNNotEnabledException
$e ) {
230 // CDN not enabled; nothing to see here
231 } catch ( BadContentTypeException
$e ) {
232 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
233 } catch ( CloudFilesException
$e ) { // some other exception?
234 $this->handleException( $e, $status, __METHOD__
, $params );
241 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
243 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
245 $cfOp->getLastResponse();
246 } catch ( BadContentTypeException
$e ) {
247 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
252 * @see FileBackendStore::doStoreInternal()
255 protected function doStoreInternal( array $params ) {
256 $status = Status
::newGood();
258 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
259 if ( $dstRel === null ) {
260 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
264 // (a) Check the destination container and object
266 $dContObj = $this->getContainer( $dstCont );
267 if ( empty( $params['overwrite'] ) &&
268 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
270 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
273 } catch ( NoSuchContainerException
$e ) {
274 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
276 } catch ( CloudFilesException
$e ) { // some other exception?
277 $this->handleException( $e, $status, __METHOD__
, $params );
281 // (b) Get a SHA-1 hash of the object
282 $sha1Hash = sha1_file( $params['src'] );
283 if ( $sha1Hash === false ) { // source doesn't exist?
284 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
287 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
289 // (c) Actually store the object
291 // Create a fresh CF_Object with no fields preloaded.
292 // We don't want to preserve headers, metadata, and such.
293 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
294 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
295 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
296 // The MD5 here will be checked within Swift against its own MD5.
297 $obj->set_etag( md5_file( $params['src'] ) );
298 // Use the same content type as StreamFile for security
299 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
300 if ( !strlen( $obj->content_type
) ) { // special case
301 $obj->content_type
= 'unknown/unknown';
303 // Set the Content-Disposition header if requested
304 if ( isset( $params['disposition'] ) ) {
305 $obj->headers
['Content-Disposition'] = $params['disposition'];
307 if ( !empty( $params['async'] ) ) { // deferred
308 wfSuppressWarnings();
309 $fp = fopen( $params['src'], 'rb' );
312 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
314 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
315 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
316 $status->value
->resourcesToClose
[] = $fp;
317 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
318 $status->value
->affectedObjects
[] = $obj;
321 } else { // actually write the object in Swift
322 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
323 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
324 $this->purgeCDNCache( array( $obj ) );
327 } catch ( CDNNotEnabledException
$e ) {
328 // CDN not enabled; nothing to see here
329 } catch ( BadContentTypeException
$e ) {
330 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
331 } catch ( IOException
$e ) {
332 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
333 } catch ( CloudFilesException
$e ) { // some other exception?
334 $this->handleException( $e, $status, __METHOD__
, $params );
341 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
343 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
345 $cfOp->getLastResponse();
346 } catch ( BadContentTypeException
$e ) {
347 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
348 } catch ( IOException
$e ) {
349 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
354 * @see FileBackendStore::doCopyInternal()
357 protected function doCopyInternal( array $params ) {
358 $status = Status
::newGood();
360 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
361 if ( $srcRel === null ) {
362 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
366 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
367 if ( $dstRel === null ) {
368 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
372 // (a) Check the source/destination containers and destination object
374 $sContObj = $this->getContainer( $srcCont );
375 $dContObj = $this->getContainer( $dstCont );
376 if ( empty( $params['overwrite'] ) &&
377 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
379 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
382 } catch ( NoSuchContainerException
$e ) {
383 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
385 } catch ( CloudFilesException
$e ) { // some other exception?
386 $this->handleException( $e, $status, __METHOD__
, $params );
390 // (b) Actually copy the file to the destination
392 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
393 $hdrs = array(); // source file headers to override with new values
394 if ( isset( $params['disposition'] ) ) {
395 $hdrs['Content-Disposition'] = $params['disposition'];
397 if ( !empty( $params['async'] ) ) { // deferred
398 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
399 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
400 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
401 $status->value
->affectedObjects
[] = $dstObj;
403 } else { // actually write the object in Swift
404 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
405 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
406 $this->purgeCDNCache( array( $dstObj ) );
409 } catch ( CDNNotEnabledException
$e ) {
410 // CDN not enabled; nothing to see here
411 } catch ( NoSuchObjectException
$e ) { // source object does not exist
412 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
413 } catch ( CloudFilesException
$e ) { // some other exception?
414 $this->handleException( $e, $status, __METHOD__
, $params );
421 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
423 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
425 $cfOp->getLastResponse();
426 } catch ( NoSuchObjectException
$e ) { // source object does not exist
427 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
432 * @see FileBackendStore::doMoveInternal()
435 protected function doMoveInternal( array $params ) {
436 $status = Status
::newGood();
438 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
439 if ( $srcRel === null ) {
440 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
444 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
445 if ( $dstRel === null ) {
446 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
450 // (a) Check the source/destination containers and destination object
452 $sContObj = $this->getContainer( $srcCont );
453 $dContObj = $this->getContainer( $dstCont );
454 if ( empty( $params['overwrite'] ) &&
455 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
457 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
460 } catch ( NoSuchContainerException
$e ) {
461 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
463 } catch ( CloudFilesException
$e ) { // some other exception?
464 $this->handleException( $e, $status, __METHOD__
, $params );
468 // (b) Actually move the file to the destination
470 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
471 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
472 $hdrs = array(); // source file headers to override with new values
473 if ( isset( $params['disposition'] ) ) {
474 $hdrs['Content-Disposition'] = $params['disposition'];
476 if ( !empty( $params['async'] ) ) { // deferred
477 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
478 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
479 $status->value
->affectedObjects
[] = $srcObj;
480 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
481 $status->value
->affectedObjects
[] = $dstObj;
483 } else { // actually write the object in Swift
484 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
485 $this->purgeCDNCache( array( $srcObj ) );
486 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
487 $this->purgeCDNCache( array( $dstObj ) );
490 } catch ( CDNNotEnabledException
$e ) {
491 // CDN not enabled; nothing to see here
492 } catch ( NoSuchObjectException
$e ) { // source object does not exist
493 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
494 } catch ( CloudFilesException
$e ) { // some other exception?
495 $this->handleException( $e, $status, __METHOD__
, $params );
502 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
504 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
506 $cfOp->getLastResponse();
507 } catch ( NoSuchObjectException
$e ) { // source object does not exist
508 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
513 * @see FileBackendStore::doDeleteInternal()
516 protected function doDeleteInternal( array $params ) {
517 $status = Status
::newGood();
519 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
520 if ( $srcRel === null ) {
521 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
526 $sContObj = $this->getContainer( $srcCont );
527 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
528 if ( !empty( $params['async'] ) ) { // deferred
529 $op = $sContObj->delete_object_async( $srcRel );
530 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
531 $status->value
->affectedObjects
[] = $srcObj;
532 } else { // actually write the object in Swift
533 $sContObj->delete_object( $srcRel );
534 $this->purgeCDNCache( array( $srcObj ) );
536 } catch ( CDNNotEnabledException
$e ) {
537 // CDN not enabled; nothing to see here
538 } catch ( NoSuchContainerException
$e ) {
539 $status->fatal( 'backend-fail-delete', $params['src'] );
540 } catch ( NoSuchObjectException
$e ) {
541 if ( empty( $params['ignoreMissingSource'] ) ) {
542 $status->fatal( 'backend-fail-delete', $params['src'] );
544 } catch ( CloudFilesException
$e ) { // some other exception?
545 $this->handleException( $e, $status, __METHOD__
, $params );
552 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
554 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
556 $cfOp->getLastResponse();
557 } catch ( NoSuchContainerException
$e ) {
558 $status->fatal( 'backend-fail-delete', $params['src'] );
559 } catch ( NoSuchObjectException
$e ) {
560 if ( empty( $params['ignoreMissingSource'] ) ) {
561 $status->fatal( 'backend-fail-delete', $params['src'] );
567 * @see FileBackendStore::doPrepareInternal()
570 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
571 $status = Status
::newGood();
573 // (a) Check if container already exists
575 $contObj = $this->getContainer( $fullCont );
576 // NoSuchContainerException not thrown: container must exist
577 return $status; // already exists
578 } catch ( NoSuchContainerException
$e ) {
579 // NoSuchContainerException thrown: container does not exist
580 } catch ( CloudFilesException
$e ) { // some other exception?
581 $this->handleException( $e, $status, __METHOD__
, $params );
585 // (b) Create container as needed
587 $contObj = $this->createContainer( $fullCont );
588 if ( !empty( $params['noAccess'] ) ) {
589 // Make container private to end-users...
590 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
592 // Make container public to end-users...
593 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
595 if ( $this->swiftUseCDN
) { // Rackspace style CDN
596 $contObj->make_public( $this->swiftCDNExpiry
);
598 } catch ( CDNNotEnabledException
$e ) {
599 // CDN not enabled; nothing to see here
600 } catch ( CloudFilesException
$e ) { // some other exception?
601 $this->handleException( $e, $status, __METHOD__
, $params );
609 * @see FileBackendStore::doSecureInternal()
612 protected function doSecureInternal( $fullCont, $dir, array $params ) {
613 $status = Status
::newGood();
614 if ( empty( $params['noAccess'] ) ) {
615 return $status; // nothing to do
618 // Restrict container from end-users...
620 // doPrepareInternal() should have been called,
621 // so the Swift container should already exist...
622 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
623 // NoSuchContainerException not thrown: container must exist
625 // Make container private to end-users...
626 $status->merge( $this->setContainerAccess(
628 array( $this->auth
->username
), // read
629 array( $this->auth
->username
) // write
631 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
632 $contObj->make_private();
634 } catch ( CDNNotEnabledException
$e ) {
635 // CDN not enabled; nothing to see here
636 } catch ( CloudFilesException
$e ) { // some other exception?
637 $this->handleException( $e, $status, __METHOD__
, $params );
644 * @see FileBackendStore::doPublishInternal()
647 protected function doPublishInternal( $fullCont, $dir, array $params ) {
648 $status = Status
::newGood();
650 // Unrestrict container from end-users...
652 // doPrepareInternal() should have been called,
653 // so the Swift container should already exist...
654 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
655 // NoSuchContainerException not thrown: container must exist
657 // Make container public to end-users...
658 if ( $this->swiftAnonUser
!= '' ) {
659 $status->merge( $this->setContainerAccess(
661 array( $this->auth
->username
, $this->swiftAnonUser
), // read
662 array( $this->auth
->username
, $this->swiftAnonUser
) // write
665 $status->merge( $this->setContainerAccess(
667 array( $this->auth
->username
, '.r:*' ), // read
668 array( $this->auth
->username
) // write
671 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
672 $contObj->make_public();
674 } catch ( CDNNotEnabledException
$e ) {
675 // CDN not enabled; nothing to see here
676 } catch ( CloudFilesException
$e ) { // some other exception?
677 $this->handleException( $e, $status, __METHOD__
, $params );
684 * @see FileBackendStore::doCleanInternal()
687 protected function doCleanInternal( $fullCont, $dir, array $params ) {
688 $status = Status
::newGood();
690 // Only containers themselves can be removed, all else is virtual
692 return $status; // nothing to do
695 // (a) Check the container
697 $contObj = $this->getContainer( $fullCont, true );
698 } catch ( NoSuchContainerException
$e ) {
699 return $status; // ok, nothing to do
700 } catch ( CloudFilesException
$e ) { // some other exception?
701 $this->handleException( $e, $status, __METHOD__
, $params );
705 // (b) Delete the container if empty
706 if ( $contObj->object_count
== 0 ) {
708 $this->deleteContainer( $fullCont );
709 } catch ( NoSuchContainerException
$e ) {
710 return $status; // race?
711 } catch ( NonEmptyContainerException
$e ) {
712 return $status; // race? consistency delay?
713 } catch ( CloudFilesException
$e ) { // some other exception?
714 $this->handleException( $e, $status, __METHOD__
, $params );
723 * @see FileBackendStore::doFileExists()
724 * @return array|bool|null
726 protected function doGetFileStat( array $params ) {
727 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
728 if ( $srcRel === null ) {
729 return false; // invalid storage path
734 $contObj = $this->getContainer( $srcCont );
735 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
736 $this->addMissingMetadata( $srcObj, $params['src'] );
738 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
739 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
740 'size' => (int)$srcObj->content_length
,
741 'sha1' => $srcObj->metadata
['Sha1base36']
743 } catch ( NoSuchContainerException
$e ) {
744 } catch ( NoSuchObjectException
$e ) {
745 } catch ( CloudFilesException
$e ) { // some other exception?
747 $this->handleException( $e, null, __METHOD__
, $params );
754 * Fill in any missing object metadata and save it to Swift
756 * @param $obj CF_Object
757 * @param $path string Storage path to object
758 * @return bool Success
759 * @throws Exception cloudfiles exceptions
761 protected function addMissingMetadata( CF_Object
$obj, $path ) {
762 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
763 return true; // nothing to do
765 wfProfileIn( __METHOD__
);
766 $status = Status
::newGood();
767 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
768 if ( $status->isOK() ) {
769 # Do not stat the file in getLocalCopy() to avoid infinite loops
770 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
772 $hash = $tmpFile->getSha1Base36();
773 if ( $hash !== false ) {
774 $obj->metadata
['Sha1base36'] = $hash;
775 $obj->sync_metadata(); // save to Swift
776 wfProfileOut( __METHOD__
);
777 return true; // success
781 $obj->metadata
['Sha1base36'] = false;
782 wfProfileOut( __METHOD__
);
783 return false; // failed
787 * @see FileBackend::getFileContents()
788 * @return bool|null|string
790 public function getFileContents( array $params ) {
791 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
792 if ( $srcRel === null ) {
793 return false; // invalid storage path
796 if ( !$this->fileExists( $params ) ) {
802 $sContObj = $this->getContainer( $srcCont );
803 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
804 $data = $obj->read( $this->headersFromParams( $params ) );
805 } catch ( NoSuchContainerException
$e ) {
806 } catch ( CloudFilesException
$e ) { // some other exception?
807 $this->handleException( $e, null, __METHOD__
, $params );
814 * @see FileBackendStore::doDirectoryExists()
817 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
819 $container = $this->getContainer( $fullCont );
820 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
821 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
822 } catch ( NoSuchContainerException
$e ) {
824 } catch ( CloudFilesException
$e ) { // some other exception?
825 $this->handleException( $e, null, __METHOD__
,
826 array( 'cont' => $fullCont, 'dir' => $dir ) );
829 return null; // error
833 * @see FileBackendStore::getDirectoryListInternal()
834 * @return SwiftFileBackendDirList
836 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
837 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
841 * @see FileBackendStore::getFileListInternal()
842 * @return SwiftFileBackendFileList
844 public function getFileListInternal( $fullCont, $dir, array $params ) {
845 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
849 * Do not call this function outside of SwiftFileBackendFileList
851 * @param $fullCont string Resolved container name
852 * @param $dir string Resolved storage directory with no trailing slash
853 * @param $after string|null Storage path of file to list items after
854 * @param $limit integer Max number of items to list
855 * @param $params Array Includes flag for 'topOnly'
856 * @return Array List of relative paths of dirs directly under $dir
858 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
860 if ( $after === INF
) {
861 return $dirs; // nothing more
863 wfProfileIn( __METHOD__
. '-' . $this->name
);
866 $container = $this->getContainer( $fullCont );
867 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
868 // Non-recursive: only list dirs right under $dir
869 if ( !empty( $params['topOnly'] ) ) {
870 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
871 foreach ( $objects as $object ) { // files and dirs
872 if ( substr( $object, -1 ) === '/' ) {
873 $dirs[] = $object; // directories end in '/'
876 // Recursive: list all dirs under $dir and its subdirs
878 // Get directory from last item of prior page
879 $lastDir = $this->getParentDir( $after ); // must be first page
880 $objects = $container->list_objects( $limit, $after, $prefix );
881 foreach ( $objects as $object ) { // files
882 $objectDir = $this->getParentDir( $object ); // directory of object
883 if ( $objectDir !== false ) { // file has a parent dir
884 // Swift stores paths in UTF-8, using binary sorting.
885 // See function "create_container_table" in common/db.py.
886 // If a directory is not "greater" than the last one,
887 // then it was already listed by the calling iterator.
888 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
890 do { // add dir and all its parent dirs
891 $dirs[] = "{$pDir}/";
892 $pDir = $this->getParentDir( $pDir );
893 } while ( $pDir !== false // sanity
894 && strcmp( $pDir, $lastDir ) > 0 // not done already
895 && strlen( $pDir ) > strlen( $dir ) // within $dir
898 $lastDir = $objectDir;
902 if ( count( $objects ) < $limit ) {
903 $after = INF
; // avoid a second RTT
905 $after = end( $objects ); // update last item
907 } catch ( NoSuchContainerException
$e ) {
908 } catch ( CloudFilesException
$e ) { // some other exception?
909 $this->handleException( $e, null, __METHOD__
,
910 array( 'cont' => $fullCont, 'dir' => $dir ) );
913 wfProfileOut( __METHOD__
. '-' . $this->name
);
917 protected function getParentDir( $path ) {
918 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
922 * Do not call this function outside of SwiftFileBackendFileList
924 * @param $fullCont string Resolved container name
925 * @param $dir string Resolved storage directory with no trailing slash
926 * @param $after string|null Storage path of file to list items after
927 * @param $limit integer Max number of items to list
928 * @param $params Array Includes flag for 'topOnly'
929 * @return Array List of relative paths of files under $dir
931 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
933 if ( $after === INF
) {
934 return $files; // nothing more
936 wfProfileIn( __METHOD__
. '-' . $this->name
);
939 $container = $this->getContainer( $fullCont );
940 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
941 // Non-recursive: only list files right under $dir
942 if ( !empty( $params['topOnly'] ) ) { // files and dirs
943 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
944 foreach ( $objects as $object ) {
945 if ( substr( $object, -1 ) !== '/' ) {
946 $files[] = $object; // directories end in '/'
949 // Recursive: list all files under $dir and its subdirs
951 $objects = $container->list_objects( $limit, $after, $prefix );
954 if ( count( $objects ) < $limit ) {
955 $after = INF
; // avoid a second RTT
957 $after = end( $objects ); // update last item
959 } catch ( NoSuchContainerException
$e ) {
960 } catch ( CloudFilesException
$e ) { // some other exception?
961 $this->handleException( $e, null, __METHOD__
,
962 array( 'cont' => $fullCont, 'dir' => $dir ) );
965 wfProfileOut( __METHOD__
. '-' . $this->name
);
970 * @see FileBackendStore::doGetFileSha1base36()
973 protected function doGetFileSha1base36( array $params ) {
974 $stat = $this->getFileStat( $params );
976 return $stat['sha1'];
983 * @see FileBackendStore::doStreamFile()
986 protected function doStreamFile( array $params ) {
987 $status = Status
::newGood();
989 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
990 if ( $srcRel === null ) {
991 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
995 $cont = $this->getContainer( $srcCont );
996 } catch ( NoSuchContainerException
$e ) {
997 $status->fatal( 'backend-fail-stream', $params['src'] );
999 } catch ( CloudFilesException
$e ) { // some other exception?
1000 $this->handleException( $e, $status, __METHOD__
, $params );
1005 $output = fopen( 'php://output', 'wb' );
1006 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1007 $obj->stream( $output, $this->headersFromParams( $params ) );
1008 } catch ( CloudFilesException
$e ) { // some other exception?
1009 $this->handleException( $e, $status, __METHOD__
, $params );
1016 * @see FileBackendStore::getLocalCopy()
1017 * @return null|TempFSFile
1019 public function getLocalCopy( array $params ) {
1020 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1021 if ( $srcRel === null ) {
1025 // Blindly create a tmp file and stream to it, catching any exception if the file does
1026 // not exist. Also, doing a stat here will cause infinite loops when filling metadata.
1029 $sContObj = $this->getContainer( $srcCont );
1030 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1031 // Get source file extension
1032 $ext = FileBackend
::extensionFromPath( $srcRel );
1033 // Create a new temporary file...
1034 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1036 $handle = fopen( $tmpFile->getPath(), 'wb' );
1038 $obj->stream( $handle, $this->headersFromParams( $params ) );
1041 $tmpFile = null; // couldn't open temp file
1044 } catch ( NoSuchContainerException
$e ) {
1046 } catch ( NoSuchObjectException
$e ) {
1048 } catch ( CloudFilesException
$e ) { // some other exception?
1050 $this->handleException( $e, null, __METHOD__
, $params );
1057 * @see FileBackendStore::directoriesAreVirtual()
1060 protected function directoriesAreVirtual() {
1065 * Get headers to send to Swift when reading a file based
1066 * on a FileBackend params array, e.g. that of getLocalCopy().
1067 * $params is currently only checked for a 'latest' flag.
1069 * @param $params Array
1072 protected function headersFromParams( array $params ) {
1074 if ( !empty( $params['latest'] ) ) {
1075 $hdrs[] = 'X-Newest: true';
1081 * @see FileBackendStore::doExecuteOpHandlesInternal()
1082 * @return Array List of corresponding Status objects
1084 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1085 $statuses = array();
1087 $cfOps = array(); // list of CF_Async_Op objects
1088 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1089 $cfOps[$index] = $fileOpHandle->cfOp
;
1091 $batch = new CF_Async_Op_Batch( $cfOps );
1093 $cfOps = $batch->execute();
1094 foreach ( $cfOps as $index => $cfOp ) {
1095 $status = Status
::newGood();
1096 try { // catch exceptions; update status
1097 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1098 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1099 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1100 } catch ( CloudFilesException
$e ) { // some other exception?
1101 $this->handleException( $e, $status,
1102 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1104 $statuses[$index] = $status;
1111 * Set read/write permissions for a Swift container.
1113 * $readGrps is a list of the possible criteria for a request to have
1114 * access to read a container. Each item is one of the following formats:
1115 * - account:user : Grants access if the request is by the given user
1116 * - .r:<regex> : Grants access if the request is from a referrer host that
1117 * matches the expression and the request is not for a listing.
1118 * Setting this to '*' effectively makes a container public.
1119 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1120 * matches the expression and the request for a listing.
1122 * $writeGrps is a list of the possible criteria for a request to have
1123 * access to write to a container. Each item is of the following format:
1124 * - account:user : Grants access if the request is by the given user
1126 * @see http://swift.openstack.org/misc.html#acls
1128 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1129 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1131 * @param $contObj CF_Container Swift container
1132 * @param $readGrps Array List of read access routes
1133 * @param $writeGrps Array List of write access routes
1136 protected function setContainerAccess(
1137 CF_Container
$contObj, array $readGrps, array $writeGrps
1139 $creds = $contObj->cfs_auth
->export_credentials();
1141 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1143 // Note: 10 second timeout consistent with php-cloudfiles
1144 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1145 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1146 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1147 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1149 return $req->execute(); // should return 204
1153 * Purge the CDN cache of affected objects if CDN caching is enabled.
1154 * This is for Rackspace/Akamai CDNs.
1156 * @param $objects Array List of CF_Object items
1159 public function purgeCDNCache( array $objects ) {
1160 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1161 foreach ( $objects as $object ) {
1163 $object->purge_from_cdn();
1164 } catch ( CDNNotEnabledException
$e ) {
1165 // CDN not enabled; nothing to see here
1166 } catch ( CloudFilesException
$e ) {
1167 $this->handleException( $e, null, __METHOD__
,
1168 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1175 * Get an authenticated connection handle to the Swift proxy
1177 * @return CF_Connection|bool False on failure
1178 * @throws CloudFilesException
1180 protected function getConnection() {
1181 if ( $this->connException
instanceof CloudFilesException
) {
1182 if ( ( time() - $this->connErrorTime
) < 60 ) {
1183 throw $this->connException
; // failed last attempt; don't bother
1184 } else { // actually retry this time
1185 $this->connException
= null;
1186 $this->connErrorTime
= 0;
1189 // Session keys expire after a while, so we renew them periodically
1190 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1191 // Authenticate with proxy and get a session key...
1192 if ( !$this->conn ||
$reAuth ) {
1193 $this->sessionStarted
= 0;
1194 $this->connContainerCache
->clear();
1195 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1196 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1197 if ( is_array( $creds ) ) { // cache hit
1198 $this->auth
->load_cached_credentials(
1199 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1200 $this->sessionStarted
= time() - ceil( $this->authTTL
/2 ); // skew for worst case
1201 } else { // cache miss
1203 $this->auth
->authenticate();
1204 $creds = $this->auth
->export_credentials();
1205 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/2 ) ); // cache
1206 $this->sessionStarted
= time();
1207 } catch ( CloudFilesException
$e ) {
1208 $this->connException
= $e; // don't keep re-trying
1209 $this->connErrorTime
= time();
1210 throw $e; // throw it back
1213 if ( $this->conn
) { // re-authorizing?
1214 $this->conn
->close(); // close active cURL handles in CF_Http object
1216 $this->conn
= new CF_Connection( $this->auth
);
1222 * Close the connection to the Swift proxy
1226 protected function closeConnection() {
1227 if ( $this->conn
) {
1228 $this->conn
->close(); // close active cURL handles in CF_Http object
1229 $this->sessionStarted
= 0;
1230 $this->connContainerCache
->clear();
1235 * Get the cache key for a container
1237 * @param $username string
1240 private function getCredsCacheKey( $username ) {
1241 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1245 * @see FileBackendStore::doClearCache()
1247 protected function doClearCache( array $paths = null ) {
1248 $this->connContainerCache
->clear(); // clear container object cache
1252 * Get a Swift container object, possibly from process cache.
1253 * Use $reCache if the file count or byte count is needed.
1255 * @param $container string Container name
1256 * @param $bypassCache bool Bypass all caches and load from Swift
1257 * @return CF_Container
1258 * @throws CloudFilesException
1260 protected function getContainer( $container, $bypassCache = false ) {
1261 $conn = $this->getConnection(); // Swift proxy connection
1262 if ( $bypassCache ) { // purge cache
1263 $this->connContainerCache
->clear( $container );
1264 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1265 $this->primeContainerCache( array( $container ) ); // check persistent cache
1267 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1268 $contObj = $conn->get_container( $container );
1269 // NoSuchContainerException not thrown: container must exist
1270 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1271 if ( !$bypassCache ) {
1272 $this->setContainerCache( $container, // update persistent cache
1273 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1277 return $this->connContainerCache
->get( $container, 'obj' );
1281 * Create a Swift container
1283 * @param $container string Container name
1284 * @return CF_Container
1285 * @throws CloudFilesException
1287 protected function createContainer( $container ) {
1288 $conn = $this->getConnection(); // Swift proxy connection
1289 $contObj = $conn->create_container( $container );
1290 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1295 * Delete a Swift container
1297 * @param $container string Container name
1299 * @throws CloudFilesException
1301 protected function deleteContainer( $container ) {
1302 $conn = $this->getConnection(); // Swift proxy connection
1303 $this->connContainerCache
->clear( $container ); // purge
1304 $conn->delete_container( $container );
1308 * @see FileBackendStore::doPrimeContainerCache()
1311 protected function doPrimeContainerCache( array $containerInfo ) {
1313 $conn = $this->getConnection(); // Swift proxy connection
1314 foreach ( $containerInfo as $container => $info ) {
1315 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1316 $container, $info['count'], $info['bytes'] );
1317 $this->connContainerCache
->set( $container, 'obj', $contObj );
1319 } catch ( CloudFilesException
$e ) { // some other exception?
1320 $this->handleException( $e, null, __METHOD__
, array() );
1325 * Log an unexpected exception for this backend.
1326 * This also sets the Status object to have a fatal error.
1328 * @param $e Exception
1329 * @param $status Status|null
1330 * @param $func string
1331 * @param $params Array
1334 protected function handleException( Exception
$e, $status, $func, array $params ) {
1335 if ( $status instanceof Status
) {
1336 if ( $e instanceof AuthenticationException
) {
1337 $status->fatal( 'backend-fail-connect', $this->name
);
1339 $status->fatal( 'backend-fail-internal', $this->name
);
1342 if ( $e->getMessage() ) {
1343 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1345 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1346 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1347 $this->closeConnection(); // force a re-connect and re-auth next time
1349 wfDebugLog( 'SwiftBackend',
1350 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1351 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1357 * @see FileBackendStoreOpHandle
1359 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1360 /** @var CF_Async_Op */
1363 public $affectedObjects = array();
1365 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1366 $this->backend
= $backend;
1367 $this->params
= $params;
1368 $this->call
= $call;
1369 $this->cfOp
= $cfOp;
1374 * SwiftFileBackend helper class to page through listings.
1375 * Swift also has a listing limit of 10,000 objects for sanity.
1376 * Do not use this class from places outside SwiftFileBackend.
1378 * @ingroup FileBackend
1380 abstract class SwiftFileBackendList
implements Iterator
{
1382 protected $bufferIter = array();
1383 protected $bufferAfter = null; // string; list items *after* this path
1384 protected $pos = 0; // integer
1386 protected $params = array();
1388 /** @var SwiftFileBackend */
1390 protected $container; // string; container name
1391 protected $dir; // string; storage directory
1392 protected $suffixStart; // integer
1394 const PAGE_SIZE
= 9000; // file listing buffer size
1397 * @param $backend SwiftFileBackend
1398 * @param $fullCont string Resolved container name
1399 * @param $dir string Resolved directory relative to container
1400 * @param $params Array
1402 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1403 $this->backend
= $backend;
1404 $this->container
= $fullCont;
1406 if ( substr( $this->dir
, -1 ) === '/' ) {
1407 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1409 if ( $this->dir
== '' ) { // whole container
1410 $this->suffixStart
= 0;
1411 } else { // dir within container
1412 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1414 $this->params
= $params;
1418 * @see Iterator::key()
1421 public function key() {
1426 * @see Iterator::next()
1429 public function next() {
1430 // Advance to the next file in the page
1431 next( $this->bufferIter
);
1433 // Check if there are no files left in this page and
1434 // advance to the next page if this page was not empty.
1435 if ( !$this->valid() && count( $this->bufferIter
) ) {
1436 $this->bufferIter
= $this->pageFromList(
1437 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1438 ); // updates $this->bufferAfter
1443 * @see Iterator::rewind()
1446 public function rewind() {
1448 $this->bufferAfter
= null;
1449 $this->bufferIter
= $this->pageFromList(
1450 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1451 ); // updates $this->bufferAfter
1455 * @see Iterator::valid()
1458 public function valid() {
1459 if ( $this->bufferIter
=== null ) {
1460 return false; // some failure?
1462 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1467 * Get the given list portion (page)
1469 * @param $container string Resolved container name
1470 * @param $dir string Resolved path relative to container
1471 * @param $after string|null
1472 * @param $limit integer
1473 * @param $params Array
1474 * @return Traversable|Array|null Returns null on failure
1476 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1480 * Iterator for listing directories
1482 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1484 * @see Iterator::current()
1485 * @return string|bool String (relative path) or false
1487 public function current() {
1488 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1492 * @see SwiftFileBackendList::pageFromList()
1493 * @return Array|null
1495 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1496 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1501 * Iterator for listing regular files
1503 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1505 * @see Iterator::current()
1506 * @return string|bool String (relative path) or false
1508 public function current() {
1509 return substr( current( $this->bufferIter
), $this->suffixStart
);
1513 * @see SwiftFileBackendList::pageFromList()
1514 * @return Array|null
1516 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1517 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );