Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: fd4836b4cd
Fetching contributors…

Cannot retrieve contributors at this time

file 727 lines (643 sloc) 20.429 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
* This is a PHP implementation of the {@link
* https://wiki.ucop.edu/display/Curation/BagIt BagIt specification}. Really,
* it is a port of {@link https://github.com/ahankinson/pybagit/ PyBagIt} for
* PHP.
*
* PHP version 5
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
* required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* @category FileUtils
* @package Bagit
* @author Eric Rochester <erochest@gmail.com>
* @author Wayne Graham <wayne.graham@gmail.com>
* @copyright 2011 The Board and Visitors of the University of Virginia
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0
* @version 0.1
* @link https://github.com/erochest/BagItPHP
*
*/


require_once 'Archive/Tar.php';
require_once 'bagit_fetch.php';
require_once 'bagit_manifest.php';
require_once 'bagit_utils.php';


/**
* This is a class for all bag exceptions.
*
* @category FileUtils
* @package Bagit
* @subpackage Exception
* @author Eric Rochester <erochest@gmail.com>
* @author Wayne Graham <wayne.graham@gmail.com>
* @copyright 2011 The Board and Visitors of the University of Virginia
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0
* @version Release: <package_version>
* @link https://github.com/erochest/BagItPHP
*/
class BagItException extends Exception
{

}


/**
* This is the main class for interacting with a bag.
*
* @category FileUtils
* @package Bagit
* @author Eric Rochester <erochest@gmail.com>
* @author Wayne Graham <wayne.graham@gmail.com>
* @copyright 2011 The Board and Visitors of the University of Virginia
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache 2.0
* @version Release: <package_version>
* @link https://github.com/erochest/BagItPHP
*/
class BagIt
{

    //{{{ properties

    /**
* The bag as passed into the constructor. This could be a directory or a
* file name, and it may not exist.
*
* @var string
*/
    var $bag;

    /**
* Absolute path to the bag directory.
*
* @var string
*/
    var $bagDirectory;

    /**
* True if the bag is extended.
*
* @var boolean
*/
    var $extended;

    /**
* The version information declared in 'bagit.txt'.
*
* @var array
*/
    var $bagVersion;

    /**
* The tag file encoding declared in 'bagit.txt'. Default is 'utf-8'.
*
* @var string
*/
    var $tagFileEncoding;

    /**
* Absolute path to the bagit file.
*
* @var string
*/
    var $bagitFile;

    /**
* Information about the 'manifest-(sha1|md5).txt'.
*
* @var BagItManifest
*/
    var $manifest;

    /**
* Information about the 'tagmanifest-{sha1,md5}.txt' or null.
*
* @var BagItManifest
*/
    var $tagManifest;

    /**
* Information about files that need to be downloaded, listed in fetch.txt.
*
* @var BagItFetch
*/
    var $fetch;

    /**
* Absolute path to the 'bag-info.txt' file or null.
*
* @var string
*/
    var $bagInfoFile;

    /**
* A dictionary array containing the 'bag-info.txt' file contents.
*
* @var array
*/
    var $bagInfoData;

    /**
* If the bag came from a compressed file, this contains either 'tgz' or
* 'zip' to indicate the file's compression format.
*
* @var string
*/
    var $bagCompression;

    /**
* An array of all bag validation errors. Each entries is a two-element
* array containing the path of the file and the error message.
*
* @var array
*/
    var $bagErrors;

    //}}}

    //{{{ Public Methods

    /**
* Define a new BagIt instance.
*
* @param string $bag Either a non-existing folder name (will create
* a new bag here); an existing folder name (this will treat it as a bag
* and create any missing files or folders needed); or an existing
* compressed file (this will un-compress it to a temporary directory and
* treat it as a bag).
* @param boolean $validate This will validate all files in the bag,
* including running checksums on all of them. Default is false.
* @param boolean $extended This will ensure that optional 'bag-info.txt',
* 'fetch.txt', and 'tagmanifest-{sha1,md5}.txt' are created. Default is
* true.
* @param boolean $fetch If true, it will download all files in
* 'fetch.txt'. Default is false.
* @param array $bagInfoData If given, this sets the bagInfoData
* property.
*/
    public function __construct(
        $bag, $validate=false, $extended=true, $fetch=false, $bagInfoData=null
    ) {
        $this->bag = $bag;
        $this->extended = $extended || (! is_null($bagInfoData));
        $this->bagVersion = array('major' => 0, 'minor' => 96);
        $this->tagFileEncoding = 'UTF-8';
        $this->bagDirectory = null;
        $this->bagitFile = null;
        $this->manifest = null;
        $this->tagManifest = null;
        $this->fetch = null;
        $this->bagInfoFile = null;
        $this->bagInfoData = $bagInfoData;
        $this->bagCompression = null;
        $this->bagErrors = array();

        if (file_exists($this->bag)) {
            $this->_openBag();
        } else {
            $this->_createBag();
        }

        if ($fetch) {
            $this->fetch->download();
        }

        if ($validate) {
            $this->validate();
        }
    }

    /**
* Test if a Bag is valid
*
* @return boolean True if no validation errors occurred.
*/
    public function isValid()
    {
        return (count($this->bagErrors) == 0);
    }

    /**
* Test if a bag has optional files
*
* @return boolean True if the bag contains the optional files
* 'bag-info.txt', 'fetch.txt', or 'tagmanifest-{sha1,md5}.txt'.
*/
    function isExtended()
    {
        return $this->extended;
    }

    /**
* Return the info keys
*
* @return array A dictionary array containing these keys: 'version',
* 'encoding', 'hash'.
*/
    function getBagInfo()
    {
        $major = $this->bagVersion['major'];
        $minor = $this->bagVersion['minor'];

        $info = array(
            'version' => "$major.$minor",
            'encoding' => $this->tagFileEncoding,
            'hash' => $this->getHashEncoding()
        );
        return $info;
    }

    /**
* Get the absolute path of the bag's data directory
*
* @return string The absolute path to the bag's data directory.
*/
    function getDataDirectory()
    {
        return "{$this->bagDirectory}/data";
    }

    /**
* Determine hash encoding
*
* @return string The bag's checksum encoding scheme.
*/
    function getHashEncoding()
    {
        return $this->manifest->getHashEncoding();
    }

    /**
* Sets the bag's checksum hash algorithm.
*
* @param string $hashAlgorithm The bag's checksum hash algorithm. Must be
* either 'sha1' or 'md5'.
*
* @return void
*/
    function setHashEncoding($hashAlgorithm)
    {
        $hashAlgorithm = strtolower($hashAlgorithm);
        if ($hashAlgorithm != 'md5' && $hashAlgorithm != 'sha1') {
            throw new InvalidArgumentException("Invalid hash algorithim: '$hashAlgorithm'.");
        }

        $this->manifest->setHashEncoding($hashAlgorithm);
        if ($this->tagManifest !== null) {
            $this->manifest->setHashEncoding($hashAlgorithm);
        }
    }

    /**
* Return an array of all files in the data directory
*
* @return array An array of absolute paths for all of the files in the
* data directory.
*/
    function getBagContents()
    {
        return rls($this->getDataDirectory());
    }

    /**
* Return errors for a bag
*
* @param boolean $validate If true, then it will run this->validate() to
* verify the integrity first. Default is false.
*
* @return array An array of all bag errors.
*/
    function getBagErrors($validate=false)
    {
        if ($validate) {
            $this->validate();
        }
        return $this->bagErrors;
    }

    /**
* Runs the bag validator on the contents of the bag. This verifies the
* presence of required iles and folders and verifies the checksum for
* each file.
*
* For the results of validation, check isValid() and getBagErrors().
*
* @return array The list of bag errors.
*/
    function validate()
    {
        $errors = array();

        BagIt_validateExists($this->bagitFile, $errors);
        BagIt_validateExists($this->getDataDirectory(), $errors);
        $this->manifest->validate($errors);

        $this->bagErrors = $errors;
        return $this->bagErrors;
    }

    /**
* This method is used whenever something is added to or removed from the
* bag. It performs these steps:
*
* <ul>
* <li>Ensures that required files are present;</li>
* <li>Sanitizes file names;</li>
* <li>Makes sure that checksums are up-to-date;</li>
* <li>Adds checksums and file entries for new files;</li>
* <li>Removes checksums and file entries for missing files; and</li>
* <li>If it's an extended bag, makes sure that those files are also
* up-to-date.</li>
* </ul>
*
* @return void
*/
    function update()
    {
        // Clear the manifests.
        $this->manifest->clear();
        if ($this->tagManifest !== null) {
            $this->tagManifest->clear();
        }

        // Clean up the file names in the data directory.
        $dataFiles = rls($this->getDataDirectory());
        foreach ($dataFiles as $dataFile) {
            $baseName = basename($dataFile);
            if ($baseName == '.' || $baseName == '..') {
                continue;
            }

            $cleanName = BagIt_sanitizeFileName($baseName);
            if ($baseName != $cleanName) {
                $dirName = dirname($dataFile);
                rename($dataFile, "$dirName/$cleanName");
            }
        }

        if ($this->extended || count($this->bagInfoData) > 0) {
            $this->_writeBagInfo();
        }

        // Update the manifests.
        $this->manifest->update(rls($this->getDataDirectory()));
        if ($this->tagManifest !== null) {
            $bagdir = $this->bagDirectory;
            $tagFiles = array(
                "$bagdir/bagit.txt",
                "$bagdir/bag-info.txt",
                $this->fetch->fileName,
                $this->manifest->getFileName()
            );
            $this->tagManifest->update($tagFiles);
        }
    }

    /**
* This copies the file specified into the bag at the place given.
*
* $dest should begin with "data/", but if it doesn't that will be added.
*
* @param string $src The file name for the source file.
* @param string $dest The file name for the destination file. This should
* be relative to the bag directory.
*
* @return void
*/
    function addFile($src, $dest)
    {
        $dataPref = 'data' . DIRECTORY_SEPARATOR;
        $prefLen = strlen($dataPref);
        if ((strncasecmp($dest, $dataPref, $prefLen) != 0)
            && (strncasecmp($dest, $dataPref, $prefLen) != 0)
        ) {
            $dest = $dataPref . $dest;
        }

        $fulldest = "{$this->bagDirectory}/$dest";
        $dirname = dirname($fulldest);
        if (! is_dir($dirname)) {
            mkdir($dirname, 0777, true);
        }

        copy($src, $fulldest);
    }


    /**
* Compresses the bag into a file.
*
* @param string $destination The file to put the bag into.
* @param string $method Either 'tgz' or 'zip'. Default is 'tgz'.
*
* @return void
*/
    function package($destination, $method='tgz')
    {
        $method = strtolower($method);
        if ($method != 'zip' && $method != 'tgz') {
            throw new BagItException("Invalid compression method: '$method'.");
        }

        if (substr_compare($destination, ".$method", -4, 4, true) != 0) {
            $destination = "$destination.$method";
        }

        BagIt_compressBag(
            $this->bagDirectory,
            $destination,
            $method
        );
    }

    /**
* This tests whether bagInfoData has a key.
*
* @param string $key The key to test for existence of.
*
* @return bool
* @author Eric Rochester <erochest@virginia.edu>
**/
    public function hasBagInfoData($key)
    {
        $this->_ensureBagInfoData();
        return array_key_exists(strtolower($key), $this->bagInfoData);
    }

    /**
* This inserts a value into bagInfoData.
*
* @param string $key This is the key to insert into the data.
* @param string $value This is the value to associate with the key.
*
* @return void
* @author Eric Rochester <erochest@virginia.edu>
**/
    public function setBagInfoData($key, $value)
    {
        $this->_ensureBagInfoData();
        $this->bagInfoData[strtolower($key)] = $value;
    }

    /**
* This returns the value for a key from bagInfoData.
*
* @param string $key This is the key to get the value associated with.
*
* @return string|null
* @author Eric Rochester <erochest@virginia.edu>
**/
    public function getBagInfoData($key)
    {
        $this->_ensureBagInfoData();
        $key = strtolower($key);
        return array_key_exists($key, $this->bagInfoData) ? $this->bagInfoData[$key] : null;
    }

    //}}}

    //{{{ Private Methods

    /**
* Open an existing bag. This expects $bag to be set.
*
* @return void
*/
    private function _openBag()
    {
        if ($this->_isCompressed()) {
            $this->bagDirectory = BagIt_uncompressBag($this->bag);
        } else {
            $this->bagDirectory = realpath($this->bag);
        }

        $this->bagitFile = "{$this->bagDirectory}/bagit.txt";
        list($version, $fileEncoding, $errors) = BagIt_readBagItFile(
            $this->bagitFile
        );
        $this->bagVersion = $version;
        $this->tagFileEncoding = $fileEncoding;
        $this->bagErrors = array_merge($this->bagErrors, $errors);

        $files = scandir($this->bagDirectory);
        if (count($files) > 0) {
            $bagdir = $this->bagDirectory;
            $manifestFile = findFirstExisting(
                array("$bagdir/manifest-sha1.txt", "$bagdir/manifest-md5.txt"),
                "$bagdir/manifest-sha1.txt"
            );
            try {
                $this->manifest = new BagItManifest(
                    $manifestFile,
                    $this->bagDirectory . '/',
                    $this->tagFileEncoding
                );
            } catch (Exception $exc) {
                array_push(
                    $this->bagErrors,
                    array('manifest', "Error reading $manifestFile.")
                );
            }

            if ($this->isExtended()) {
                $manifestFile = findFirstExisting(
                    array("$bagdir/tagmanifest-sha1.txt",
                    "$bagdir/tagmanifest-md5.txt"),
                    "$bagdir/tagmanifest-sha1.txt"
                );
                $this->tagManifest = new BagItManifest(
                    $manifestFile,
                    $this->bagDirectory . '/',
                    $this->tagFileEncoding
                );

                try {
                    $this->fetch = new BagItFetch(
                        "{$this->bagDirectory}/fetch.txt",
                        $this->tagFileEncoding
                    );
                } catch (Exception $exc) {
                    array_push(
                        $this->bagErrors,
                        array('fetch', 'Error reading fetch file.')
                    );
                }

                $this->bagInfoFile = "{$this->bagDirectory}/bag-info.txt";
                $this->_readBagInfo();
            }
        }
    }

    /**
* Create a new bag. This expects $bag to be set.
*
* @return void
*/
    private function _createBag()
    {
        mkdir($this->bag);
        $this->bagDirectory = realpath($this->bag);

        mkdir($this->getDataDirectory());

        $this->bagitFile = $this->bagDirectory . '/bagit.txt';
        $this->manifest = new BagItManifest(
            "{$this->bagDirectory}/manifest-sha1.txt",
            $this->bagDirectory . '/',
            $this->tagFileEncoding
        );

        $major = $this->bagVersion['major'];
        $minor = $this->bagVersion['minor'];
        $bagItData
            = "BagIt-Version: $major.$minor\n" .
              "Tag-File-Character-Encoding: {$this->tagFileEncoding}\n";
        writeFileText($this->bagitFile, $this->tagFileEncoding, $bagItData);

        $this->_createExtendedBag();
    }

    /**
* This creates the files for an extended bag.
*
* @return void
*/
    private function _createExtendedBag()
    {
        if ($this->extended) {
            $hashEncoding = $this->getHashEncoding();
            $this->tagManifest = new BagItManifest(
                "{$this->bagDirectory}/tagmanifest-$hashEncoding.txt",
                $this->bagDirectory . '/',
                $this->tagFileEncoding
            );

            $fetchFile = $this->bagDirectory . '/fetch.txt';
            $this->fetch = new BagItFetch($fetchFile, $this->tagFileEncoding);

            $this->bagInfoFile = $this->bagDirectory . '/bag-info.txt';
            touch($this->bagInfoFile);
            if (is_null($this->bagInfoData)) {
                $this->bagInfoData = array();
            }
        }
    }

    /**
* This reads the bag-info.txt file into an array dictionary.
*
* @return void
*/
    private function _readBagInfo()
    {
        try {
            $lines = readLines($this->bagInfoFile, $this->tagFileEncoding);
            $this->bagInfoData = BagIt_parseBagInfo($lines);
        } catch (Exception $exc) {
            array_push(
                $this->bagErrors,
                array('baginfo', 'Error reading bag info file.')
            );
        }
    }

    /**
* This writes the bag-info.txt file with the contents of bagInfoData.
*
* @return void
* @author Eric Rochester <erochest@virginia.edu>
**/
    private function _writeBagInfo()
    {
        $lines = array();

        if (count($this->bagInfoData)) {
            foreach ($this->bagInfoData as $label => $value) {
                array_push($lines, "$label: $value\n");
            }
        }

        writeFileText($this->bagInfoFile, $this->tagFileEncoding, join('', $lines));
    }

    /**
* Tests if a bag is compressed
*
* @return True if this is a compressed bag.
*/
    private function _isCompressed()
    {
        if (is_dir($this->bag)) {
            return false;
        } else {
            $bag = strtolower($this->bag);
            if (endsWith($bag, '.zip')) {
                $this->bagCompression = 'zip';
                return true;
            } else if (endsWith($bag, '.tar.gz') || endsWith($bag, '.tgz')) {
                $this->bagCompression = 'tgz';
                return true;
            }
        }
        return false;
    }

    /**
* This makes sure that bagInfoData is not null.
*
* @return array
* @author Eric Rochester <erochest@virginia.edu>
**/
    private function _ensureBagInfoData()
    {
        if (is_null($this->bagInfoData)) {
            $this->bagInfoData = array();
        }
        return $this->bagInfoData;
    }

    //}}}

}

/* Functional wrappers/facades. */

/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* c-hanging-comment-ender-p: nil
* End:
*/


?>
Something went wrong with that request. Please try again.