2 namespace wcf\system\package
;
3 use wcf\data\package\Package
;
4 use wcf\system\database\util\PreparedStatementConditionBuilder
;
5 use wcf\system\package\validation\PackageValidationException
;
13 * Represents the archive of a package.
16 * @copyright 2001-2019 WoltLab GmbH
17 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
18 * @package WoltLabSuite\Core\System\Package
20 class PackageArchive
{
22 * path to package archive
28 * package object of an existing package
40 * general package information
43 protected $packageInfo = [];
49 protected $authorInfo = [];
52 * list of requirements
55 protected $requirements = [];
58 * list of optional packages
61 protected $optionals = [];
64 * list of excluded packages
67 protected $excludedPackages = [];
70 * list of compatible API versions
74 protected $compatibility = [];
77 * list of instructions
80 protected $instructions = [
86 * default name of the package.xml file
89 const INFO_FILE
= 'package.xml';
92 * marker for the void instruction
95 const VOID_MARKER
= "===void===";
98 * Creates a new PackageArchive object.
100 * @param string $archive
101 * @param Package $package
103 public function __construct($archive, Package
$package = null) {
104 $this->archive
= $archive; // be careful: this is a string within this class,
105 // but an object in the packageStartInstallForm.class!
106 $this->package
= $package;
110 * Sets associated package object.
112 * @param Package $package
114 public function setPackage(Package
$package) {
115 $this->package
= $package;
119 * Returns the name of the package archive.
123 public function getArchive() {
124 return $this->archive
;
128 * Returns the object of the package archive.
132 public function getTar() {
137 * Opens the package archive and reads package information.
139 public function openArchive() {
140 // check whether archive exists and is a TAR archive
141 if (!file_exists($this->archive
)) {
142 throw new PackageValidationException(PackageValidationException
::FILE_NOT_FOUND
, ['archive' => $this->archive
]);
145 // open archive and read package information
146 $this->tar
= new Tar($this->archive
);
147 $this->readPackageInfo();
151 * Extracts information about this package (parses package.xml).
153 protected function readPackageInfo() {
154 // search package.xml in package archive
155 // throw error message if not found
156 if ($this->tar
->getIndexByFilename(self
::INFO_FILE
) === false) {
157 throw new PackageValidationException(PackageValidationException
::MISSING_PACKAGE_XML
, ['archive' => $this->archive
]);
160 // extract package.xml, parse XML
161 // and compile an array with XML::getElementTree()
164 $xml->loadXML(self
::INFO_FILE
, $this->tar
->extractToString(self
::INFO_FILE
));
166 catch (\Exception
$e) { // bugfix to avoid file caching problems
167 $xml->loadXML(self
::INFO_FILE
, $this->tar
->extractToString(self
::INFO_FILE
));
171 $xpath = $xml->xpath();
172 /** @var \DOMElement $package */
173 $package = $xpath->query('/ns:package')->item(0);
176 $packageName = $package->getAttribute('name');
177 if (!Package
::isValidPackageName($packageName)) {
178 // package name is not a valid package identifier
179 throw new PackageValidationException(PackageValidationException
::INVALID_PACKAGE_NAME
, ['packageName' => $packageName]);
182 $this->packageInfo
['name'] = $packageName;
184 // get package information
185 $packageInformation = $xpath->query('./ns:packageinformation', $package)->item(0);
186 $elements = $xpath->query('child::*', $packageInformation);
187 /** @var \DOMElement $element */
188 foreach ($elements as $element) {
189 switch ($element->tagName
) {
191 case 'packagedescription':
194 if (!isset($this->packageInfo
[$element->tagName
])) $this->packageInfo
[$element->tagName
] = [];
196 $languageCode = 'default';
197 if ($element->hasAttribute('language')) {
198 $languageCode = $element->getAttribute('language');
201 // fix case-sensitive names
202 $name = $element->tagName
;
203 if ($name == 'packagename') $name = 'packageName';
204 else if ($name == 'packagedescription') $name = 'packageDescription';
206 $this->packageInfo
[$name][$languageCode] = $element->nodeValue
;
209 case 'isapplication':
210 $this->packageInfo
['isApplication'] = intval($element->nodeValue
);
213 case 'applicationdirectory':
214 if (preg_match('~^[a-z0-9\-\_]+$~', $element->nodeValue
)) {
215 $this->packageInfo
['applicationDirectory'] = $element->nodeValue
;
220 $this->packageInfo
['packageURL'] = $element->nodeValue
;
224 if (!Package
::isValidVersion($element->nodeValue
)) {
225 throw new PackageValidationException(PackageValidationException
::INVALID_PACKAGE_VERSION
, ['packageVersion' => $element->nodeValue
]);
228 $this->packageInfo
['version'] = $element->nodeValue
;
232 DateUtil
::validateDate($element->nodeValue
);
234 $this->packageInfo
['date'] = @strtotime
($element->nodeValue
);
239 // get author information
240 $authorInformation = $xpath->query('./ns:authorinformation', $package)->item(0);
241 $elements = $xpath->query('child::*', $authorInformation);
242 foreach ($elements as $element) {
243 $tagName = ($element->tagName
== 'authorurl') ?
'authorURL' : $element->tagName
;
244 $this->authorInfo
[$tagName] = $element->nodeValue
;
247 // get required packages
248 $elements = $xpath->query('child::ns:requiredpackages/ns:requiredpackage', $package);
249 foreach ($elements as $element) {
250 if (!Package
::isValidPackageName($element->nodeValue
)) {
251 throw new PackageValidationException(PackageValidationException
::INVALID_PACKAGE_NAME
, ['packageName' => $element->nodeValue
]);
255 $data = ['name' => $element->nodeValue
];
256 $attributes = $xpath->query('attribute::*', $element);
257 foreach ($attributes as $attribute) {
258 $data[$attribute->name
] = $attribute->value
;
261 $this->requirements
[$element->nodeValue
] = $data;
264 // get optional packages
265 $elements = $xpath->query('child::ns:optionalpackages/ns:optionalpackage', $package);
266 foreach ($elements as $element) {
267 if (!Package
::isValidPackageName($element->nodeValue
)) {
268 throw new PackageValidationException(PackageValidationException
::INVALID_PACKAGE_NAME
, ['packageName' => $element->nodeValue
]);
272 $data = ['name' => $element->nodeValue
];
273 $attributes = $xpath->query('attribute::*', $element);
274 foreach ($attributes as $attribute) {
275 $data[$attribute->name
] = $attribute->value
;
278 $this->optionals
[] = $data;
281 // get excluded packages
282 $elements = $xpath->query('child::ns:excludedpackages/ns:excludedpackage', $package);
283 foreach ($elements as $element) {
284 if (!Package
::isValidPackageName($element->nodeValue
)) {
285 throw new PackageValidationException(PackageValidationException
::INVALID_PACKAGE_NAME
, ['packageName' => $element->nodeValue
]);
289 $data = ['name' => $element->nodeValue
];
290 $attributes = $xpath->query('attribute::*', $element);
291 foreach ($attributes as $attribute) {
292 $data[$attribute->name
] = $attribute->value
;
295 $this->excludedPackages
[] = $data;
298 // get api compatibility
299 $elements = $xpath->query('child::ns:compatibility/ns:api', $package);
300 foreach ($elements as $element) {
301 if (!$element->hasAttribute('version')) continue;
303 $version = $element->getAttribute('version');
304 if (!preg_match('~^(?:201[7-9]|20[2-9][0-9])$~', $version)) {
305 throw new PackageValidationException(PackageValidationException
::INVALID_API_VERSION
, ['version' => $version]);
308 $this->compatibility
[] = $version;
311 // API compatibility implies an exclude of `com.woltlab.wcf` in version `6.0.0 Alpha 1`, unless a lower version is explicitly excluded.
312 if (!empty($this->compatibility
)) {
313 $excludeCore60 = '6.0.0 Alpha 1';
316 foreach ($this->excludedPackages
as $excludedPackage) {
317 if ($excludedPackage['name'] === 'com.woltlab.wcf') {
318 $coreExclude = $excludedPackage['version'];
323 if (!$coreExclude || Package
::compareVersion($coreExclude, $excludeCore60, '>')) {
325 $this->excludedPackages
= array_filter($this->excludedPackages
, function($exclude) {
326 return $exclude['name'] !== 'com.woltlab.wcf';
330 $this->excludedPackages
[] = [
331 'name' => 'com.woltlab.wcf',
332 'version' => $excludeCore60,
338 $elements = $xpath->query('./ns:instructions', $package);
339 foreach ($elements as $element) {
340 $instructionData = [];
341 $instructions = $xpath->query('./ns:instruction', $element);
342 /** @var \DOMElement $instruction */
343 foreach ($instructions as $instruction) {
345 $attributes = $xpath->query('attribute::*', $instruction);
346 foreach ($attributes as $attribute) {
347 $data[$attribute->name
] = $attribute->value
;
350 $instructionData[] = [
351 'attributes' => $data,
352 'pip' => $instruction->getAttribute('type'),
353 'value' => $instruction->nodeValue
357 $fromVersion = $element->getAttribute('fromversion');
358 $type = $element->getAttribute('type');
360 $void = $xpath->query('./ns:void', $element);
361 if ($void->length
> 1) {
362 throw new PackageValidationException(PackageValidationException
::VOID_NOT_ALONE
);
364 else if ($void->length
== 1) {
365 if (!empty($instructionData)) {
366 throw new PackageValidationException(PackageValidationException
::VOID_NOT_ALONE
);
368 if ($type == 'install') {
369 throw new PackageValidationException(PackageValidationException
::VOID_ON_INSTALL
);
372 $instructionData[] = [
373 'pip' => self
::VOID_MARKER
,
378 if ($type == 'install') {
379 $this->instructions
['install'] = $instructionData;
382 $this->instructions
['update'][$fromVersion] = $instructionData;
386 // add com.woltlab.wcf to package requirements
387 if (!isset($this->requirements
['com.woltlab.wcf']) && $this->packageInfo
['name'] != 'com.woltlab.wcf') {
388 $this->requirements
['com.woltlab.wcf'] = ['name' => 'com.woltlab.wcf'];
391 // during installations, `Package::$packageVersion` can be `null` which causes issues
392 // in `PackageArchive::filterUpdateInstructions()`; as update instructions are not needed
393 // for installations, not filtering update instructions is okay
394 if ($this->package
!== null && $this->package
->packageVersion
!== null) {
395 $this->filterUpdateInstructions();
398 // set default values
399 if (!isset($this->packageInfo
['isApplication'])) $this->packageInfo
['isApplication'] = 0;
400 if (!isset($this->packageInfo
['packageURL'])) $this->packageInfo
['packageURL'] = '';
404 * Filters update instructions.
406 protected function filterUpdateInstructions() {
407 $validFromVersion = null;
408 foreach ($this->instructions
['update'] as $fromVersion => $update) {
409 if (Package
::checkFromversion($this->package
->packageVersion
, $fromVersion)) {
410 $validFromVersion = $fromVersion;
415 if ($validFromVersion === null) {
416 $this->instructions
['update'] = [];
419 $this->instructions
['update'] = $this->instructions
['update'][$validFromVersion];
424 * Downloads the package archive.
426 * @return string path to the dowloaded file
428 public function downloadArchive() {
431 // file transfer via hypertext transfer protocol.
432 $this->archive
= FileUtil
::downloadFileFromHttp($this->archive
, $prefix);
435 $this->archive
= self
::unzipPackageArchive($this->archive
);
437 return $this->archive
;
441 * Closes and deletes the tar archive of this package.
443 public function deleteArchive() {
444 if ($this->tar
instanceof Tar
) {
448 @unlink
($this->archive
);
452 * Returns true if the package archive supports a new installation.
456 public function isValidInstall() {
457 return !empty($this->instructions
['install']);
461 * Checks if the new package is compatible with
462 * the package that is about to be updated.
464 * @param Package $package
465 * @return boolean isValidUpdate
467 public function isValidUpdate(Package
$package = null) {
468 if ($this->package
=== null && $package !== null) {
469 $this->setPackage($package);
471 // re-evaluate update data
472 $this->filterUpdateInstructions();
475 // Check name of the installed package against the name of the update. Both must be identical.
476 if ($this->packageInfo
['name'] != $this->package
->package
) {
480 // Check if the version number of the installed package is lower than the version number to which
481 // it's about to be updated.
482 if (Package
::compareVersion($this->packageInfo
['version'], $this->package
->packageVersion
) != 1) {
486 // Check if the package provides an instructions block for the update from the installed package version
487 if (empty($this->instructions
['update'])) {
495 * Checks if the current package is already installed, as it is not
496 * possible to install non-applications multiple times within the
501 public function isAlreadyInstalled() {
502 $sql = "SELECT COUNT(*)
503 FROM wcf".WCF_N
."_package
505 $statement = WCF
::getDB()->prepareStatement($sql);
506 $statement->execute([$this->packageInfo
['name']]);
508 return $statement->fetchSingleColumn() > 0;
512 * Returns true if the package is an application and has an unique abbreviation.
516 public function hasUniqueAbbreviation() {
517 if (!$this->packageInfo
['isApplication']) {
521 $sql = "SELECT COUNT(*)
522 FROM wcf".WCF_N
."_package
523 WHERE isApplication = ?
525 $statement = WCF
::getDB()->prepareStatement($sql);
526 $statement->execute([
528 '%.'.Package
::getAbbreviation($this->packageInfo
['name'])
531 return $statement->fetchSingleColumn() > 0;
535 * Returns information about the author of this package archive.
537 * @param string $name name of the requested information
540 public function getAuthorInfo($name) {
541 if (isset($this->authorInfo
[$name])) return $this->authorInfo
[$name];
546 * Returns information about this package.
548 * @param string $name name of the requested information
551 public function getPackageInfo($name) {
552 if (isset($this->packageInfo
[$name])) return $this->packageInfo
[$name];
557 * Returns a localized information about this package.
559 * @param string $name
562 public function getLocalizedPackageInfo($name) {
563 if (isset($this->packageInfo
[$name][WCF
::getLanguage()->getFixedLanguageCode()])) {
564 return $this->packageInfo
[$name][WCF
::getLanguage()->getFixedLanguageCode()];
566 else if (isset($this->packageInfo
[$name]['default'])) {
567 return $this->packageInfo
[$name]['default'];
570 if (!empty($this->packageInfo
[$name])) {
571 return reset($this->packageInfo
[$name]);
578 * Returns a list of all requirements of this package.
582 public function getRequirements() {
583 return $this->requirements
;
587 * Returns a list of all delivered optional packages of this package.
591 public function getOptionals() {
592 return $this->optionals
;
596 * Returns a list of excluded packages.
600 public function getExcludedPackages() {
601 return $this->excludedPackages
;
605 * Returns the list of compatible API versions.
610 public function getCompatibleVersions() {
611 return $this->compatibility
;
615 * Returns the package installation instructions.
619 public function getInstallInstructions() {
620 return $this->instructions
['install'];
624 * Returns the package update instructions.
628 public function getUpdateInstructions() {
629 return $this->instructions
['update'];
633 * Checks which package requirements do already exist in right version.
634 * Returns a list with all existing requirements.
638 public function getAllExistingRequirements() {
639 $existingRequirements = [];
640 $existingPackages = [];
641 if ($this->package
!== null) {
642 $sql = "SELECT package.*
643 FROM wcf".WCF_N
."_package_requirement requirement
644 LEFT JOIN wcf".WCF_N
."_package package
645 ON (package.packageID = requirement.requirement)
646 WHERE requirement.packageID = ?";
647 $statement = WCF
::getDB()->prepareStatement($sql);
648 $statement->execute([$this->package
->packageID
]);
649 while ($row = $statement->fetchArray()) {
650 $existingRequirements[$row['package']] = $row;
656 $requirements = $this->getRequirements();
657 foreach ($requirements as $requirement) {
658 if (isset($existingRequirements[$requirement['name']])) {
659 $existingPackages[$requirement['name']] = [];
660 $existingPackages[$requirement['name']][$existingRequirements[$requirement['name']]['packageID']] = $existingRequirements[$requirement['name']];
663 $packageNames[] = $requirement['name'];
667 // check whether the required packages do already exist
668 if (!empty($packageNames)) {
669 $conditions = new PreparedStatementConditionBuilder();
670 $conditions->add("package.package IN (?)", [$packageNames]);
672 $sql = "SELECT package.*
673 FROM wcf".WCF_N
."_package package
675 $statement = WCF
::getDB()->prepareStatement($sql);
676 $statement->execute($conditions->getParameters());
677 while ($row = $statement->fetchArray()) {
678 // check required package version
679 if (isset($requirements[$row['package']]['minversion']) && Package
::compareVersion($row['packageVersion'], $requirements[$row['package']]['minversion']) == -1) {
683 if (!isset($existingPackages[$row['package']])) {
684 $existingPackages[$row['package']] = [];
687 $existingPackages[$row['package']][$row['packageID']] = $row;
691 return $existingPackages;
695 * Checks which package requirements do already exist in database.
696 * Returns a list with the existing requirements.
700 public function getExistingRequirements() {
703 foreach ($this->requirements
as $requirement) {
704 $packageNames[] = $requirement['name'];
707 // check whether the required packages do already exist
708 $existingPackages = [];
709 if (!empty($packageNames)) {
710 $conditions = new PreparedStatementConditionBuilder();
711 $conditions->add("package IN (?)", [$packageNames]);
714 FROM wcf".WCF_N
."_package
716 $statement = WCF
::getDB()->prepareStatement($sql);
717 $statement->execute($conditions->getParameters());
718 while ($row = $statement->fetchArray()) {
719 if (!isset($existingPackages[$row['package']])) {
720 $existingPackages[$row['package']] = [];
723 $existingPackages[$row['package']][$row['packageVersion']] = $row;
726 // sort multiple packages by version number
727 foreach ($existingPackages as $packageName => $instances) {
728 uksort($instances, [Package
::class, 'compareVersion']);
730 // get package with highest version number (get last package)
731 $existingPackages[$packageName] = array_pop($instances);
735 return $existingPackages;
739 * Returns a list of all open requirements of this package.
743 public function getOpenRequirements() {
744 // get all existing requirements
745 $existingPackages = $this->getExistingRequirements();
747 // check for open requirements
748 $openRequirements = [];
749 foreach ($this->requirements
as $requirement) {
750 if (isset($existingPackages[$requirement['name']])) {
751 // package does already exist
752 // maybe an update is necessary
753 if (isset($requirement['minversion'])) {
754 if (Package
::compareVersion($existingPackages[$requirement['name']]['packageVersion'], $requirement['minversion']) >= 0) {
755 // package does already exist in needed version
756 // skip installation of requirement
760 $requirement['existingVersion'] = $existingPackages[$requirement['name']]['packageVersion'];
767 $requirement['packageID'] = $existingPackages[$requirement['name']]['packageID'];
768 $requirement['action'] = 'update';
771 // package does not exist
772 // new installation is necessary
773 $requirement['packageID'] = 0;
774 $requirement['action'] = 'install';
777 $openRequirements[$requirement['name']] = $requirement;
780 return $openRequirements;
784 * Extracts the requested file in the package archive to the temp folder
785 * and returns the path to the extracted file.
787 * @param string $filename
788 * @param string $tempPrefix
790 * @throws PackageValidationException
792 public function extractTar($filename, $tempPrefix = 'package_') {
793 // search the requested tar archive in our package archive.
794 // throw error message if not found.
795 if (($fileIndex = $this->tar
->getIndexByFilename($filename)) === false) {
796 throw new PackageValidationException(PackageValidationException
::FILE_NOT_FOUND
, [
797 'archive' => $this->archive
,
798 'targetArchive' => $filename
802 // requested tar archive was found
803 $fileInfo = $this->tar
->getFileInfo($fileIndex);
804 $filename = FileUtil
::getTemporaryFilename($tempPrefix, preg_replace('!^.*?(\.(?:tar\.gz|tgz|tar))$!i', '\\1', $fileInfo['filename']));
805 $this->tar
->extract($fileIndex, $filename);
811 * Unzips compressed package archives and returns the temporary file name.
813 * @param string $archive filename
816 public static function unzipPackageArchive($archive) {
817 if (!FileUtil
::isURL($archive)) {
818 $tar = new Tar($archive);
820 if ($tar->isZipped()) {
821 $tmpName = FileUtil
::getTemporaryFilename('package_');
822 if (FileUtil
::uncompressFile($archive, $tmpName)) {
832 * Returns a list of packages which exclude this package.
836 public function getConflictedExcludingPackages() {
837 $conflictedPackages = [];
838 $sql = "SELECT package.*, package_exclusion.*
839 FROM wcf".WCF_N
."_package_exclusion package_exclusion
840 LEFT JOIN wcf".WCF_N
."_package package
841 ON (package.packageID = package_exclusion.packageID)
842 WHERE excludedPackage = ?";
843 $statement = WCF
::getDB()->prepareStatement($sql);
844 $statement->execute([$this->packageInfo
['name']]);
845 while ($row = $statement->fetchArray()) {
846 if (!empty($row['excludedPackageVersion'])) {
847 if (Package
::compareVersion($this->packageInfo
['version'], $row['excludedPackageVersion'], '<')) {
852 $conflictedPackages[$row['packageID']] = new Package(null, $row);
855 return $conflictedPackages;
859 * Returns a list of packages which are excluded by this package.
863 public function getConflictedExcludedPackages() {
864 $conflictedPackages = [];
865 if (!empty($this->excludedPackages
)) {
866 $excludedPackages = [];
867 foreach ($this->excludedPackages
as $excludedPackageData) {
868 $excludedPackages[$excludedPackageData['name']] = $excludedPackageData['version'];
871 $conditions = new PreparedStatementConditionBuilder();
872 $conditions->add("package IN (?)", [array_keys($excludedPackages)]);
875 FROM wcf".WCF_N
."_package
877 $statement = WCF
::getDB()->prepareStatement($sql);
878 $statement->execute($conditions->getParameters());
879 while ($row = $statement->fetchArray()) {
880 if (!empty($excludedPackages[$row['package']])) {
881 if (Package
::compareVersion($row['packageVersion'], $excludedPackages[$row['package']], '<')) {
884 $row['excludedPackageVersion'] = $excludedPackages[$row['package']];
887 $conflictedPackages[$row['packageID']] = new Package(null, $row);
891 return $conflictedPackages;
895 * Returns a list of instructions for installation or update.
897 * @param string $type
900 public function getInstructions($type) {
901 if (isset($this->instructions
[$type])) {
902 return $this->instructions
[$type];
909 * Returns a list of php requirements for current package.
914 public function getPhpRequirements() {