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 * @param $disposition string Content-Disposition header value
167 * @return string Truncated Content-Disposition header value to meet Swift limits
169 protected function truncDisp( $disposition ) {
171 foreach ( explode( ';', $disposition ) as $part ) {
172 $part = trim( $part );
173 $new = ( $res === '' ) ?
$part : "{$res};{$part}";
174 if ( strlen( $new ) <= 255 ) {
177 break; // too long; sigh
184 * @see FileBackendStore::doCreateInternal()
187 protected function doCreateInternal( array $params ) {
188 $status = Status
::newGood();
190 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
191 if ( $dstRel === null ) {
192 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
196 // (a) Check the destination container and object
198 $dContObj = $this->getContainer( $dstCont );
199 if ( empty( $params['overwrite'] ) &&
200 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
202 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
205 } catch ( NoSuchContainerException
$e ) {
206 $status->fatal( 'backend-fail-create', $params['dst'] );
208 } catch ( CloudFilesException
$e ) { // some other exception?
209 $this->handleException( $e, $status, __METHOD__
, $params );
213 // (b) Get a SHA-1 hash of the object
214 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
216 // (c) Actually create the object
218 // Create a fresh CF_Object with no fields preloaded.
219 // We don't want to preserve headers, metadata, and such.
220 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
221 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
222 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
223 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
224 // The MD5 here will be checked within Swift against its own MD5.
225 $obj->set_etag( md5( $params['content'] ) );
226 // Use the same content type as StreamFile for security
227 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
228 if ( !strlen( $obj->content_type
) ) { // special case
229 $obj->content_type
= 'unknown/unknown';
231 // Set the Content-Disposition header if requested
232 if ( isset( $params['disposition'] ) ) {
233 $obj->headers
['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
235 if ( !empty( $params['async'] ) ) { // deferred
236 $op = $obj->write_async( $params['content'] );
237 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
238 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
239 $status->value
->affectedObjects
[] = $obj;
241 } else { // actually write the object in Swift
242 $obj->write( $params['content'] );
243 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
244 $this->purgeCDNCache( array( $obj ) );
247 } catch ( CDNNotEnabledException
$e ) {
248 // CDN not enabled; nothing to see here
249 } catch ( BadContentTypeException
$e ) {
250 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
251 } catch ( CloudFilesException
$e ) { // some other exception?
252 $this->handleException( $e, $status, __METHOD__
, $params );
259 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
261 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
263 $cfOp->getLastResponse();
264 } catch ( BadContentTypeException
$e ) {
265 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
270 * @see FileBackendStore::doStoreInternal()
273 protected function doStoreInternal( array $params ) {
274 $status = Status
::newGood();
276 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
277 if ( $dstRel === null ) {
278 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
282 // (a) Check the destination container and object
284 $dContObj = $this->getContainer( $dstCont );
285 if ( empty( $params['overwrite'] ) &&
286 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
288 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
291 } catch ( NoSuchContainerException
$e ) {
292 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
294 } catch ( CloudFilesException
$e ) { // some other exception?
295 $this->handleException( $e, $status, __METHOD__
, $params );
299 // (b) Get a SHA-1 hash of the object
300 $sha1Hash = sha1_file( $params['src'] );
301 if ( $sha1Hash === false ) { // source doesn't exist?
302 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
305 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
307 // (c) Actually store the object
309 // Create a fresh CF_Object with no fields preloaded.
310 // We don't want to preserve headers, metadata, and such.
311 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
312 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
313 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
314 // The MD5 here will be checked within Swift against its own MD5.
315 $obj->set_etag( md5_file( $params['src'] ) );
316 // Use the same content type as StreamFile for security
317 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
318 if ( !strlen( $obj->content_type
) ) { // special case
319 $obj->content_type
= 'unknown/unknown';
321 // Set the Content-Disposition header if requested
322 if ( isset( $params['disposition'] ) ) {
323 $obj->headers
['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
325 if ( !empty( $params['async'] ) ) { // deferred
326 wfSuppressWarnings();
327 $fp = fopen( $params['src'], 'rb' );
330 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
332 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
333 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
334 $status->value
->resourcesToClose
[] = $fp;
335 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
336 $status->value
->affectedObjects
[] = $obj;
339 } else { // actually write the object in Swift
340 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
341 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
342 $this->purgeCDNCache( array( $obj ) );
345 } catch ( CDNNotEnabledException
$e ) {
346 // CDN not enabled; nothing to see here
347 } catch ( BadContentTypeException
$e ) {
348 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
349 } catch ( IOException
$e ) {
350 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
351 } catch ( CloudFilesException
$e ) { // some other exception?
352 $this->handleException( $e, $status, __METHOD__
, $params );
359 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
361 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
363 $cfOp->getLastResponse();
364 } catch ( BadContentTypeException
$e ) {
365 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
366 } catch ( IOException
$e ) {
367 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
372 * @see FileBackendStore::doCopyInternal()
375 protected function doCopyInternal( array $params ) {
376 $status = Status
::newGood();
378 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
379 if ( $srcRel === null ) {
380 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
384 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
385 if ( $dstRel === null ) {
386 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
390 // (a) Check the source/destination containers and destination object
392 $sContObj = $this->getContainer( $srcCont );
393 $dContObj = $this->getContainer( $dstCont );
394 if ( empty( $params['overwrite'] ) &&
395 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
397 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
400 } catch ( NoSuchContainerException
$e ) {
401 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
403 } catch ( CloudFilesException
$e ) { // some other exception?
404 $this->handleException( $e, $status, __METHOD__
, $params );
408 // (b) Actually copy the file to the destination
410 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
411 $hdrs = array(); // source file headers to override with new values
412 if ( isset( $params['disposition'] ) ) {
413 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
415 if ( !empty( $params['async'] ) ) { // deferred
416 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
417 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
418 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
419 $status->value
->affectedObjects
[] = $dstObj;
421 } else { // actually write the object in Swift
422 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
423 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
424 $this->purgeCDNCache( array( $dstObj ) );
427 } catch ( CDNNotEnabledException
$e ) {
428 // CDN not enabled; nothing to see here
429 } catch ( NoSuchObjectException
$e ) { // source object does not exist
430 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
431 } catch ( CloudFilesException
$e ) { // some other exception?
432 $this->handleException( $e, $status, __METHOD__
, $params );
439 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
441 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
443 $cfOp->getLastResponse();
444 } catch ( NoSuchObjectException
$e ) { // source object does not exist
445 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
450 * @see FileBackendStore::doMoveInternal()
453 protected function doMoveInternal( array $params ) {
454 $status = Status
::newGood();
456 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
457 if ( $srcRel === null ) {
458 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
462 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
463 if ( $dstRel === null ) {
464 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
468 // (a) Check the source/destination containers and destination object
470 $sContObj = $this->getContainer( $srcCont );
471 $dContObj = $this->getContainer( $dstCont );
472 if ( empty( $params['overwrite'] ) &&
473 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
475 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
478 } catch ( NoSuchContainerException
$e ) {
479 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
481 } catch ( CloudFilesException
$e ) { // some other exception?
482 $this->handleException( $e, $status, __METHOD__
, $params );
486 // (b) Actually move the file to the destination
488 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
489 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
490 $hdrs = array(); // source file headers to override with new values
491 if ( isset( $params['disposition'] ) ) {
492 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
494 if ( !empty( $params['async'] ) ) { // deferred
495 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
496 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
497 $status->value
->affectedObjects
[] = $srcObj;
498 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
499 $status->value
->affectedObjects
[] = $dstObj;
501 } else { // actually write the object in Swift
502 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
503 $this->purgeCDNCache( array( $srcObj ) );
504 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
505 $this->purgeCDNCache( array( $dstObj ) );
508 } catch ( CDNNotEnabledException
$e ) {
509 // CDN not enabled; nothing to see here
510 } catch ( NoSuchObjectException
$e ) { // source object does not exist
511 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
512 } catch ( CloudFilesException
$e ) { // some other exception?
513 $this->handleException( $e, $status, __METHOD__
, $params );
520 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
522 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
524 $cfOp->getLastResponse();
525 } catch ( NoSuchObjectException
$e ) { // source object does not exist
526 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
531 * @see FileBackendStore::doDeleteInternal()
534 protected function doDeleteInternal( array $params ) {
535 $status = Status
::newGood();
537 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
538 if ( $srcRel === null ) {
539 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
544 $sContObj = $this->getContainer( $srcCont );
545 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
546 if ( !empty( $params['async'] ) ) { // deferred
547 $op = $sContObj->delete_object_async( $srcRel );
548 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
549 $status->value
->affectedObjects
[] = $srcObj;
550 } else { // actually write the object in Swift
551 $sContObj->delete_object( $srcRel );
552 $this->purgeCDNCache( array( $srcObj ) );
554 } catch ( CDNNotEnabledException
$e ) {
555 // CDN not enabled; nothing to see here
556 } catch ( NoSuchContainerException
$e ) {
557 $status->fatal( 'backend-fail-delete', $params['src'] );
558 } catch ( NoSuchObjectException
$e ) {
559 if ( empty( $params['ignoreMissingSource'] ) ) {
560 $status->fatal( 'backend-fail-delete', $params['src'] );
562 } catch ( CloudFilesException
$e ) { // some other exception?
563 $this->handleException( $e, $status, __METHOD__
, $params );
570 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
572 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
574 $cfOp->getLastResponse();
575 } catch ( NoSuchContainerException
$e ) {
576 $status->fatal( 'backend-fail-delete', $params['src'] );
577 } catch ( NoSuchObjectException
$e ) {
578 if ( empty( $params['ignoreMissingSource'] ) ) {
579 $status->fatal( 'backend-fail-delete', $params['src'] );
585 * @see FileBackendStore::doPrepareInternal()
588 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
589 $status = Status
::newGood();
591 // (a) Check if container already exists
593 $contObj = $this->getContainer( $fullCont );
594 // NoSuchContainerException not thrown: container must exist
595 return $status; // already exists
596 } catch ( NoSuchContainerException
$e ) {
597 // NoSuchContainerException thrown: container does not exist
598 } catch ( CloudFilesException
$e ) { // some other exception?
599 $this->handleException( $e, $status, __METHOD__
, $params );
603 // (b) Create container as needed
605 $contObj = $this->createContainer( $fullCont );
606 if ( !empty( $params['noAccess'] ) ) {
607 // Make container private to end-users...
608 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
610 // Make container public to end-users...
611 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
613 if ( $this->swiftUseCDN
) { // Rackspace style CDN
614 $contObj->make_public( $this->swiftCDNExpiry
);
616 } catch ( CDNNotEnabledException
$e ) {
617 // CDN not enabled; nothing to see here
618 } catch ( CloudFilesException
$e ) { // some other exception?
619 $this->handleException( $e, $status, __METHOD__
, $params );
627 * @see FileBackendStore::doSecureInternal()
630 protected function doSecureInternal( $fullCont, $dir, array $params ) {
631 $status = Status
::newGood();
632 if ( empty( $params['noAccess'] ) ) {
633 return $status; // nothing to do
636 // Restrict container from end-users...
638 // doPrepareInternal() should have been called,
639 // so the Swift container should already exist...
640 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
641 // NoSuchContainerException not thrown: container must exist
643 // Make container private to end-users...
644 $status->merge( $this->setContainerAccess(
646 array( $this->auth
->username
), // read
647 array( $this->auth
->username
) // write
649 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
650 $contObj->make_private();
652 } catch ( CDNNotEnabledException
$e ) {
653 // CDN not enabled; nothing to see here
654 } catch ( CloudFilesException
$e ) { // some other exception?
655 $this->handleException( $e, $status, __METHOD__
, $params );
662 * @see FileBackendStore::doPublishInternal()
665 protected function doPublishInternal( $fullCont, $dir, array $params ) {
666 $status = Status
::newGood();
668 // Unrestrict container from end-users...
670 // doPrepareInternal() should have been called,
671 // so the Swift container should already exist...
672 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
673 // NoSuchContainerException not thrown: container must exist
675 // Make container public to end-users...
676 if ( $this->swiftAnonUser
!= '' ) {
677 $status->merge( $this->setContainerAccess(
679 array( $this->auth
->username
, $this->swiftAnonUser
), // read
680 array( $this->auth
->username
, $this->swiftAnonUser
) // write
683 $status->merge( $this->setContainerAccess(
685 array( $this->auth
->username
, '.r:*' ), // read
686 array( $this->auth
->username
) // write
689 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
690 $contObj->make_public();
692 } catch ( CDNNotEnabledException
$e ) {
693 // CDN not enabled; nothing to see here
694 } catch ( CloudFilesException
$e ) { // some other exception?
695 $this->handleException( $e, $status, __METHOD__
, $params );
702 * @see FileBackendStore::doCleanInternal()
705 protected function doCleanInternal( $fullCont, $dir, array $params ) {
706 $status = Status
::newGood();
708 // Only containers themselves can be removed, all else is virtual
710 return $status; // nothing to do
713 // (a) Check the container
715 $contObj = $this->getContainer( $fullCont, true );
716 } catch ( NoSuchContainerException
$e ) {
717 return $status; // ok, nothing to do
718 } catch ( CloudFilesException
$e ) { // some other exception?
719 $this->handleException( $e, $status, __METHOD__
, $params );
723 // (b) Delete the container if empty
724 if ( $contObj->object_count
== 0 ) {
726 $this->deleteContainer( $fullCont );
727 } catch ( NoSuchContainerException
$e ) {
728 return $status; // race?
729 } catch ( NonEmptyContainerException
$e ) {
730 return $status; // race? consistency delay?
731 } catch ( CloudFilesException
$e ) { // some other exception?
732 $this->handleException( $e, $status, __METHOD__
, $params );
741 * @see FileBackendStore::doFileExists()
742 * @return array|bool|null
744 protected function doGetFileStat( array $params ) {
745 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
746 if ( $srcRel === null ) {
747 return false; // invalid storage path
752 $contObj = $this->getContainer( $srcCont );
753 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
754 $this->addMissingMetadata( $srcObj, $params['src'] );
756 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
757 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
758 'size' => (int)$srcObj->content_length
,
759 'sha1' => $srcObj->metadata
['Sha1base36']
761 } catch ( NoSuchContainerException
$e ) {
762 } catch ( NoSuchObjectException
$e ) {
763 } catch ( CloudFilesException
$e ) { // some other exception?
765 $this->handleException( $e, null, __METHOD__
, $params );
772 * Fill in any missing object metadata and save it to Swift
774 * @param $obj CF_Object
775 * @param $path string Storage path to object
776 * @return bool Success
777 * @throws Exception cloudfiles exceptions
779 protected function addMissingMetadata( CF_Object
$obj, $path ) {
780 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
781 return true; // nothing to do
783 wfProfileIn( __METHOD__
);
784 $status = Status
::newGood();
785 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
786 if ( $status->isOK() ) {
787 # Do not stat the file in getLocalCopy() to avoid infinite loops
788 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
790 $hash = $tmpFile->getSha1Base36();
791 if ( $hash !== false ) {
792 $obj->metadata
['Sha1base36'] = $hash;
793 $obj->sync_metadata(); // save to Swift
794 wfProfileOut( __METHOD__
);
795 return true; // success
799 $obj->metadata
['Sha1base36'] = false;
800 wfProfileOut( __METHOD__
);
801 return false; // failed
805 * @see FileBackend::getFileContents()
806 * @return bool|null|string
808 public function getFileContents( array $params ) {
809 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
810 if ( $srcRel === null ) {
811 return false; // invalid storage path
814 if ( !$this->fileExists( $params ) ) {
820 $sContObj = $this->getContainer( $srcCont );
821 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
822 $data = $obj->read( $this->headersFromParams( $params ) );
823 } catch ( NoSuchContainerException
$e ) {
824 } catch ( CloudFilesException
$e ) { // some other exception?
825 $this->handleException( $e, null, __METHOD__
, $params );
832 * @see FileBackendStore::doDirectoryExists()
835 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
837 $container = $this->getContainer( $fullCont );
838 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
839 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
840 } catch ( NoSuchContainerException
$e ) {
842 } catch ( CloudFilesException
$e ) { // some other exception?
843 $this->handleException( $e, null, __METHOD__
,
844 array( 'cont' => $fullCont, 'dir' => $dir ) );
847 return null; // error
851 * @see FileBackendStore::getDirectoryListInternal()
852 * @return SwiftFileBackendDirList
854 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
855 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
859 * @see FileBackendStore::getFileListInternal()
860 * @return SwiftFileBackendFileList
862 public function getFileListInternal( $fullCont, $dir, array $params ) {
863 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
867 * Do not call this function outside of SwiftFileBackendFileList
869 * @param $fullCont string Resolved container name
870 * @param $dir string Resolved storage directory with no trailing slash
871 * @param $after string|null Storage path of file to list items after
872 * @param $limit integer Max number of items to list
873 * @param $params Array Includes flag for 'topOnly'
874 * @return Array List of relative paths of dirs directly under $dir
876 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
878 if ( $after === INF
) {
879 return $dirs; // nothing more
881 wfProfileIn( __METHOD__
. '-' . $this->name
);
884 $container = $this->getContainer( $fullCont );
885 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
886 // Non-recursive: only list dirs right under $dir
887 if ( !empty( $params['topOnly'] ) ) {
888 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
889 foreach ( $objects as $object ) { // files and dirs
890 if ( substr( $object, -1 ) === '/' ) {
891 $dirs[] = $object; // directories end in '/'
894 // Recursive: list all dirs under $dir and its subdirs
896 // Get directory from last item of prior page
897 $lastDir = $this->getParentDir( $after ); // must be first page
898 $objects = $container->list_objects( $limit, $after, $prefix );
899 foreach ( $objects as $object ) { // files
900 $objectDir = $this->getParentDir( $object ); // directory of object
901 if ( $objectDir !== false ) { // file has a parent dir
902 // Swift stores paths in UTF-8, using binary sorting.
903 // See function "create_container_table" in common/db.py.
904 // If a directory is not "greater" than the last one,
905 // then it was already listed by the calling iterator.
906 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
908 do { // add dir and all its parent dirs
909 $dirs[] = "{$pDir}/";
910 $pDir = $this->getParentDir( $pDir );
911 } while ( $pDir !== false // sanity
912 && strcmp( $pDir, $lastDir ) > 0 // not done already
913 && strlen( $pDir ) > strlen( $dir ) // within $dir
916 $lastDir = $objectDir;
920 if ( count( $objects ) < $limit ) {
921 $after = INF
; // avoid a second RTT
923 $after = end( $objects ); // update last item
925 } catch ( NoSuchContainerException
$e ) {
926 } catch ( CloudFilesException
$e ) { // some other exception?
927 $this->handleException( $e, null, __METHOD__
,
928 array( 'cont' => $fullCont, 'dir' => $dir ) );
931 wfProfileOut( __METHOD__
. '-' . $this->name
);
935 protected function getParentDir( $path ) {
936 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
940 * Do not call this function outside of SwiftFileBackendFileList
942 * @param $fullCont string Resolved container name
943 * @param $dir string Resolved storage directory with no trailing slash
944 * @param $after string|null Storage path of file to list items after
945 * @param $limit integer Max number of items to list
946 * @param $params Array Includes flag for 'topOnly'
947 * @return Array List of relative paths of files under $dir
949 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
951 if ( $after === INF
) {
952 return $files; // nothing more
954 wfProfileIn( __METHOD__
. '-' . $this->name
);
957 $container = $this->getContainer( $fullCont );
958 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
959 // Non-recursive: only list files right under $dir
960 if ( !empty( $params['topOnly'] ) ) { // files and dirs
961 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
962 foreach ( $objects as $object ) {
963 if ( substr( $object, -1 ) !== '/' ) {
964 $files[] = $object; // directories end in '/'
967 // Recursive: list all files under $dir and its subdirs
969 $objects = $container->list_objects( $limit, $after, $prefix );
972 if ( count( $objects ) < $limit ) {
973 $after = INF
; // avoid a second RTT
975 $after = end( $objects ); // update last item
977 } catch ( NoSuchContainerException
$e ) {
978 } catch ( CloudFilesException
$e ) { // some other exception?
979 $this->handleException( $e, null, __METHOD__
,
980 array( 'cont' => $fullCont, 'dir' => $dir ) );
983 wfProfileOut( __METHOD__
. '-' . $this->name
);
988 * @see FileBackendStore::doGetFileSha1base36()
991 protected function doGetFileSha1base36( array $params ) {
992 $stat = $this->getFileStat( $params );
994 return $stat['sha1'];
1001 * @see FileBackendStore::doStreamFile()
1004 protected function doStreamFile( array $params ) {
1005 $status = Status
::newGood();
1007 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1008 if ( $srcRel === null ) {
1009 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1013 $cont = $this->getContainer( $srcCont );
1014 } catch ( NoSuchContainerException
$e ) {
1015 $status->fatal( 'backend-fail-stream', $params['src'] );
1017 } catch ( CloudFilesException
$e ) { // some other exception?
1018 $this->handleException( $e, $status, __METHOD__
, $params );
1023 $output = fopen( 'php://output', 'wb' );
1024 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1025 $obj->stream( $output, $this->headersFromParams( $params ) );
1026 } catch ( CloudFilesException
$e ) { // some other exception?
1027 $this->handleException( $e, $status, __METHOD__
, $params );
1034 * @see FileBackendStore::getLocalCopy()
1035 * @return null|TempFSFile
1037 public function getLocalCopy( array $params ) {
1038 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1039 if ( $srcRel === null ) {
1043 // Blindly create a tmp file and stream to it, catching any exception if the file does
1044 // not exist. Also, doing a stat here will cause infinite loops when filling metadata.
1047 $sContObj = $this->getContainer( $srcCont );
1048 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1049 // Get source file extension
1050 $ext = FileBackend
::extensionFromPath( $srcRel );
1051 // Create a new temporary file...
1052 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1054 $handle = fopen( $tmpFile->getPath(), 'wb' );
1056 $obj->stream( $handle, $this->headersFromParams( $params ) );
1059 $tmpFile = null; // couldn't open temp file
1062 } catch ( NoSuchContainerException
$e ) {
1064 } catch ( NoSuchObjectException
$e ) {
1066 } catch ( CloudFilesException
$e ) { // some other exception?
1068 $this->handleException( $e, null, __METHOD__
, $params );
1075 * @see FileBackendStore::directoriesAreVirtual()
1078 protected function directoriesAreVirtual() {
1083 * Get headers to send to Swift when reading a file based
1084 * on a FileBackend params array, e.g. that of getLocalCopy().
1085 * $params is currently only checked for a 'latest' flag.
1087 * @param $params Array
1090 protected function headersFromParams( array $params ) {
1092 if ( !empty( $params['latest'] ) ) {
1093 $hdrs[] = 'X-Newest: true';
1099 * @see FileBackendStore::doExecuteOpHandlesInternal()
1100 * @return Array List of corresponding Status objects
1102 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1103 $statuses = array();
1105 $cfOps = array(); // list of CF_Async_Op objects
1106 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1107 $cfOps[$index] = $fileOpHandle->cfOp
;
1109 $batch = new CF_Async_Op_Batch( $cfOps );
1111 $cfOps = $batch->execute();
1112 foreach ( $cfOps as $index => $cfOp ) {
1113 $status = Status
::newGood();
1114 try { // catch exceptions; update status
1115 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1116 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1117 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1118 } catch ( CloudFilesException
$e ) { // some other exception?
1119 $this->handleException( $e, $status,
1120 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1122 $statuses[$index] = $status;
1129 * Set read/write permissions for a Swift container.
1131 * $readGrps is a list of the possible criteria for a request to have
1132 * access to read a container. Each item is one of the following formats:
1133 * - account:user : Grants access if the request is by the given user
1134 * - .r:<regex> : Grants access if the request is from a referrer host that
1135 * matches the expression and the request is not for a listing.
1136 * Setting this to '*' effectively makes a container public.
1137 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1138 * matches the expression and the request for a listing.
1140 * $writeGrps is a list of the possible criteria for a request to have
1141 * access to write to a container. Each item is of the following format:
1142 * - account:user : Grants access if the request is by the given user
1144 * @see http://swift.openstack.org/misc.html#acls
1146 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1147 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1149 * @param $contObj CF_Container Swift container
1150 * @param $readGrps Array List of read access routes
1151 * @param $writeGrps Array List of write access routes
1154 protected function setContainerAccess(
1155 CF_Container
$contObj, array $readGrps, array $writeGrps
1157 $creds = $contObj->cfs_auth
->export_credentials();
1159 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1161 // Note: 10 second timeout consistent with php-cloudfiles
1162 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1163 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1164 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1165 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1167 return $req->execute(); // should return 204
1171 * Purge the CDN cache of affected objects if CDN caching is enabled.
1172 * This is for Rackspace/Akamai CDNs.
1174 * @param $objects Array List of CF_Object items
1177 public function purgeCDNCache( array $objects ) {
1178 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1179 foreach ( $objects as $object ) {
1181 $object->purge_from_cdn();
1182 } catch ( CDNNotEnabledException
$e ) {
1183 // CDN not enabled; nothing to see here
1184 } catch ( CloudFilesException
$e ) {
1185 $this->handleException( $e, null, __METHOD__
,
1186 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1193 * Get an authenticated connection handle to the Swift proxy
1195 * @return CF_Connection|bool False on failure
1196 * @throws CloudFilesException
1198 protected function getConnection() {
1199 if ( $this->connException
instanceof CloudFilesException
) {
1200 if ( ( time() - $this->connErrorTime
) < 60 ) {
1201 throw $this->connException
; // failed last attempt; don't bother
1202 } else { // actually retry this time
1203 $this->connException
= null;
1204 $this->connErrorTime
= 0;
1207 // Session keys expire after a while, so we renew them periodically
1208 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1209 // Authenticate with proxy and get a session key...
1210 if ( !$this->conn ||
$reAuth ) {
1211 $this->sessionStarted
= 0;
1212 $this->connContainerCache
->clear();
1213 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1214 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1215 if ( is_array( $creds ) ) { // cache hit
1216 $this->auth
->load_cached_credentials(
1217 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1218 $this->sessionStarted
= time() - ceil( $this->authTTL
/2 ); // skew for worst case
1219 } else { // cache miss
1221 $this->auth
->authenticate();
1222 $creds = $this->auth
->export_credentials();
1223 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/2 ) ); // cache
1224 $this->sessionStarted
= time();
1225 } catch ( CloudFilesException
$e ) {
1226 $this->connException
= $e; // don't keep re-trying
1227 $this->connErrorTime
= time();
1228 throw $e; // throw it back
1231 if ( $this->conn
) { // re-authorizing?
1232 $this->conn
->close(); // close active cURL handles in CF_Http object
1234 $this->conn
= new CF_Connection( $this->auth
);
1240 * Close the connection to the Swift proxy
1244 protected function closeConnection() {
1245 if ( $this->conn
) {
1246 $this->conn
->close(); // close active cURL handles in CF_Http object
1247 $this->sessionStarted
= 0;
1248 $this->connContainerCache
->clear();
1253 * Get the cache key for a container
1255 * @param $username string
1258 private function getCredsCacheKey( $username ) {
1259 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1263 * @see FileBackendStore::doClearCache()
1265 protected function doClearCache( array $paths = null ) {
1266 $this->connContainerCache
->clear(); // clear container object cache
1270 * Get a Swift container object, possibly from process cache.
1271 * Use $reCache if the file count or byte count is needed.
1273 * @param $container string Container name
1274 * @param $bypassCache bool Bypass all caches and load from Swift
1275 * @return CF_Container
1276 * @throws CloudFilesException
1278 protected function getContainer( $container, $bypassCache = false ) {
1279 $conn = $this->getConnection(); // Swift proxy connection
1280 if ( $bypassCache ) { // purge cache
1281 $this->connContainerCache
->clear( $container );
1282 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1283 $this->primeContainerCache( array( $container ) ); // check persistent cache
1285 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1286 $contObj = $conn->get_container( $container );
1287 // NoSuchContainerException not thrown: container must exist
1288 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1289 if ( !$bypassCache ) {
1290 $this->setContainerCache( $container, // update persistent cache
1291 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1295 return $this->connContainerCache
->get( $container, 'obj' );
1299 * Create a Swift container
1301 * @param $container string Container name
1302 * @return CF_Container
1303 * @throws CloudFilesException
1305 protected function createContainer( $container ) {
1306 $conn = $this->getConnection(); // Swift proxy connection
1307 $contObj = $conn->create_container( $container );
1308 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1313 * Delete a Swift container
1315 * @param $container string Container name
1317 * @throws CloudFilesException
1319 protected function deleteContainer( $container ) {
1320 $conn = $this->getConnection(); // Swift proxy connection
1321 $this->connContainerCache
->clear( $container ); // purge
1322 $conn->delete_container( $container );
1326 * @see FileBackendStore::doPrimeContainerCache()
1329 protected function doPrimeContainerCache( array $containerInfo ) {
1331 $conn = $this->getConnection(); // Swift proxy connection
1332 foreach ( $containerInfo as $container => $info ) {
1333 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1334 $container, $info['count'], $info['bytes'] );
1335 $this->connContainerCache
->set( $container, 'obj', $contObj );
1337 } catch ( CloudFilesException
$e ) { // some other exception?
1338 $this->handleException( $e, null, __METHOD__
, array() );
1343 * Log an unexpected exception for this backend.
1344 * This also sets the Status object to have a fatal error.
1346 * @param $e Exception
1347 * @param $status Status|null
1348 * @param $func string
1349 * @param $params Array
1352 protected function handleException( Exception
$e, $status, $func, array $params ) {
1353 if ( $status instanceof Status
) {
1354 if ( $e instanceof AuthenticationException
) {
1355 $status->fatal( 'backend-fail-connect', $this->name
);
1357 $status->fatal( 'backend-fail-internal', $this->name
);
1360 if ( $e->getMessage() ) {
1361 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1363 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1364 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1365 $this->closeConnection(); // force a re-connect and re-auth next time
1367 wfDebugLog( 'SwiftBackend',
1368 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1369 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1375 * @see FileBackendStoreOpHandle
1377 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1378 /** @var CF_Async_Op */
1381 public $affectedObjects = array();
1383 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1384 $this->backend
= $backend;
1385 $this->params
= $params;
1386 $this->call
= $call;
1387 $this->cfOp
= $cfOp;
1392 * SwiftFileBackend helper class to page through listings.
1393 * Swift also has a listing limit of 10,000 objects for sanity.
1394 * Do not use this class from places outside SwiftFileBackend.
1396 * @ingroup FileBackend
1398 abstract class SwiftFileBackendList
implements Iterator
{
1400 protected $bufferIter = array();
1401 protected $bufferAfter = null; // string; list items *after* this path
1402 protected $pos = 0; // integer
1404 protected $params = array();
1406 /** @var SwiftFileBackend */
1408 protected $container; // string; container name
1409 protected $dir; // string; storage directory
1410 protected $suffixStart; // integer
1412 const PAGE_SIZE
= 9000; // file listing buffer size
1415 * @param $backend SwiftFileBackend
1416 * @param $fullCont string Resolved container name
1417 * @param $dir string Resolved directory relative to container
1418 * @param $params Array
1420 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1421 $this->backend
= $backend;
1422 $this->container
= $fullCont;
1424 if ( substr( $this->dir
, -1 ) === '/' ) {
1425 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1427 if ( $this->dir
== '' ) { // whole container
1428 $this->suffixStart
= 0;
1429 } else { // dir within container
1430 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1432 $this->params
= $params;
1436 * @see Iterator::key()
1439 public function key() {
1444 * @see Iterator::next()
1447 public function next() {
1448 // Advance to the next file in the page
1449 next( $this->bufferIter
);
1451 // Check if there are no files left in this page and
1452 // advance to the next page if this page was not empty.
1453 if ( !$this->valid() && count( $this->bufferIter
) ) {
1454 $this->bufferIter
= $this->pageFromList(
1455 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1456 ); // updates $this->bufferAfter
1461 * @see Iterator::rewind()
1464 public function rewind() {
1466 $this->bufferAfter
= null;
1467 $this->bufferIter
= $this->pageFromList(
1468 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1469 ); // updates $this->bufferAfter
1473 * @see Iterator::valid()
1476 public function valid() {
1477 if ( $this->bufferIter
=== null ) {
1478 return false; // some failure?
1480 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1485 * Get the given list portion (page)
1487 * @param $container string Resolved container name
1488 * @param $dir string Resolved path relative to container
1489 * @param $after string|null
1490 * @param $limit integer
1491 * @param $params Array
1492 * @return Traversable|Array|null Returns null on failure
1494 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1498 * Iterator for listing directories
1500 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1502 * @see Iterator::current()
1503 * @return string|bool String (relative path) or false
1505 public function current() {
1506 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1510 * @see SwiftFileBackendList::pageFromList()
1511 * @return Array|null
1513 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1514 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1519 * Iterator for listing regular files
1521 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1523 * @see Iterator::current()
1524 * @return string|bool String (relative path) or false
1526 public function current() {
1527 return substr( current( $this->bufferIter
), $this->suffixStart
);
1531 * @see SwiftFileBackendList::pageFromList()
1532 * @return Array|null
1534 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1535 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );