PearPackageExtractor.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Downloader;
  12. use Composer\Util\Filesystem;
  13. /**
  14. * Extractor for pear packages.
  15. *
  16. * Composer cannot rely on tar files structure when place it inside package target dir. Correct source files
  17. * disposition must be read from package.xml
  18. * This extract pear package source files to target dir.
  19. *
  20. * @author Alexey Prilipko <palex@farpost.com>
  21. */
  22. class PearPackageExtractor
  23. {
  24. private static $rolesWithoutPackageNamePrefix = array('php', 'script', 'www');
  25. /** @var Filesystem */
  26. private $filesystem;
  27. private $file;
  28. public function __construct($file)
  29. {
  30. if (!is_file($file)) {
  31. throw new \UnexpectedValueException('PEAR package file is not found at '.$file);
  32. }
  33. $this->filesystem = new Filesystem();
  34. $this->file = $file;
  35. }
  36. /**
  37. * Installs PEAR source files according to package.xml definitions and removes extracted files
  38. *
  39. * @param string $target target install location. all source installation would be performed relative to target path.
  40. * @param array $roles types of files to install. default role for PEAR source files are 'php'.
  41. * @param array $vars used for replacement tasks
  42. * @throws \RuntimeException
  43. * @throws \UnexpectedValueException
  44. */
  45. public function extractTo($target, array $roles = array('php' => '/', 'script' => '/bin'), $vars = array())
  46. {
  47. $extractionPath = $target.'/tarball';
  48. try {
  49. $archive = new \PharData($this->file);
  50. $archive->extractTo($extractionPath, null, true);
  51. if (!is_file($this->combine($extractionPath, '/package.xml'))) {
  52. throw new \RuntimeException('Invalid PEAR package. It must contain package.xml file.');
  53. }
  54. $fileCopyActions = $this->buildCopyActions($extractionPath, $roles, $vars);
  55. $this->copyFiles($fileCopyActions, $extractionPath, $target, $roles, $vars);
  56. $this->filesystem->removeDirectory($extractionPath);
  57. } catch (\Exception $exception) {
  58. throw new \UnexpectedValueException(sprintf('Failed to extract PEAR package %s to %s. Reason: %s', $this->file, $target, $exception->getMessage()), 0, $exception);
  59. }
  60. }
  61. /**
  62. * Perform copy actions on files
  63. *
  64. * @param array $files array of copy actions ('from', 'to') with relative paths
  65. * @param $source string path to source dir.
  66. * @param $target string path to destination dir
  67. * @param array $roles array [role => roleRoot] relative root for files having that role
  68. * @param array $vars list of values can be used for replacement tasks
  69. */
  70. private function copyFiles($files, $source, $target, $roles, $vars)
  71. {
  72. foreach ($files as $file) {
  73. $from = $this->combine($source, $file['from']);
  74. $to = $this->combine($target, $roles[$file['role']]);
  75. $to = $this->combine($to, $file['to']);
  76. $tasks = $file['tasks'];
  77. $this->copyFile($from, $to, $tasks, $vars);
  78. }
  79. }
  80. private function copyFile($from, $to, $tasks, $vars)
  81. {
  82. if (!is_file($from)) {
  83. throw new \RuntimeException('Invalid PEAR package. package.xml defines file that is not located inside tarball.');
  84. }
  85. $this->filesystem->ensureDirectoryExists(dirname($to));
  86. if (0 == count($tasks)) {
  87. $copied = copy($from, $to);
  88. } else {
  89. $content = file_get_contents($from);
  90. $replacements = array();
  91. foreach ($tasks as $task) {
  92. $pattern = $task['from'];
  93. $varName = $task['to'];
  94. if (isset($vars[$varName])) {
  95. if ($varName === 'php_bin' && false === strpos($to, '.bat')) {
  96. $replacements[$pattern] = preg_replace('{\.bat$}', '', $vars[$varName]);
  97. } else {
  98. $replacements[$pattern] = $vars[$varName];
  99. }
  100. }
  101. }
  102. $content = strtr($content, $replacements);
  103. $copied = file_put_contents($to, $content);
  104. }
  105. if (false === $copied) {
  106. throw new \RuntimeException(sprintf('Failed to copy %s to %s', $from, $to));
  107. }
  108. }
  109. /**
  110. * Builds list of copy and list of remove actions that would transform extracted PEAR tarball into installed package.
  111. *
  112. * @param string $source string path to extracted files
  113. * @param array $roles array [role => roleRoot] relative root for files having that role
  114. * @param array $vars list of values can be used for replacement tasks
  115. * @throws \RuntimeException
  116. * @return array array of 'source' => 'target', where source is location of file in the tarball (relative to source
  117. * path, and target is destination of file (also relative to $source path)
  118. */
  119. private function buildCopyActions($source, array $roles, $vars)
  120. {
  121. /** @var $package \SimpleXmlElement */
  122. $package = simplexml_load_string(file_get_contents($this->combine($source, 'package.xml')));
  123. if (false === $package) {
  124. throw new \RuntimeException('Package definition file is not valid.');
  125. }
  126. $packageSchemaVersion = $package['version'];
  127. if ('1.0' == $packageSchemaVersion) {
  128. $children = $package->release->filelist->children();
  129. $packageName = (string) $package->name;
  130. $packageVersion = (string) $package->release->version;
  131. $sourceDir = $packageName . '-' . $packageVersion;
  132. $result = $this->buildSourceList10($children, $roles, $sourceDir, '', null, $packageName);
  133. } elseif ('2.0' == $packageSchemaVersion || '2.1' == $packageSchemaVersion) {
  134. $children = $package->contents->children();
  135. $packageName = (string) $package->name;
  136. $packageVersion = (string) $package->version->release;
  137. $sourceDir = $packageName . '-' . $packageVersion;
  138. $result = $this->buildSourceList20($children, $roles, $sourceDir, '', null, $packageName);
  139. $namespaces = $package->getNamespaces();
  140. $package->registerXPathNamespace('ns', $namespaces['']);
  141. $releaseNodes = $package->xpath('ns:phprelease');
  142. $this->applyRelease($result, $releaseNodes, $vars);
  143. } else {
  144. throw new \RuntimeException('Unsupported schema version of package definition file.');
  145. }
  146. return $result;
  147. }
  148. private function applyRelease(&$actions, $releaseNodes, $vars)
  149. {
  150. foreach ($releaseNodes as $releaseNode) {
  151. $requiredOs = $releaseNode->installconditions && $releaseNode->installconditions->os && $releaseNode->installconditions->os->name ? (string) $releaseNode->installconditions->os->name : '';
  152. if ($requiredOs && $vars['os'] != $requiredOs) {
  153. continue;
  154. }
  155. if ($releaseNode->filelist) {
  156. foreach ($releaseNode->filelist->children() as $action) {
  157. if ('install' == $action->getName()) {
  158. $name = (string) $action['name'];
  159. $as = (string) $action['as'];
  160. if (isset($actions[$name])) {
  161. $actions[$name]['to'] = $as;
  162. }
  163. } elseif ('ignore' == $action->getName()) {
  164. $name = (string) $action['name'];
  165. unset($actions[$name]);
  166. } else {
  167. // unknown action
  168. }
  169. }
  170. }
  171. break;
  172. }
  173. }
  174. private function buildSourceList10($children, $targetRoles, $source, $target, $role, $packageName)
  175. {
  176. $result = array();
  177. // enumerating files
  178. foreach ($children as $child) {
  179. /** @var $child \SimpleXMLElement */
  180. if ($child->getName() == 'dir') {
  181. $dirSource = $this->combine($source, (string) $child['name']);
  182. $dirTarget = $child['baseinstalldir'] ?: $target;
  183. $dirRole = $child['role'] ?: $role;
  184. $dirFiles = $this->buildSourceList10($child->children(), $targetRoles, $dirSource, $dirTarget, $dirRole, $packageName);
  185. $result = array_merge($result, $dirFiles);
  186. } elseif ($child->getName() == 'file') {
  187. $fileRole = (string) $child['role'] ?: $role;
  188. if (isset($targetRoles[$fileRole])) {
  189. $fileName = (string) ($child['name'] ?: $child[0]); // $child[0] means text content
  190. $fileSource = $this->combine($source, $fileName);
  191. $fileTarget = $this->combine((string) $child['baseinstalldir'] ?: $target, $fileName);
  192. if (!in_array($fileRole, self::$rolesWithoutPackageNamePrefix)) {
  193. $fileTarget = $packageName . '/' . $fileTarget;
  194. }
  195. $result[(string) $child['name']] = array('from' => $fileSource, 'to' => $fileTarget, 'role' => $fileRole, 'tasks' => array());
  196. }
  197. }
  198. }
  199. return $result;
  200. }
  201. private function buildSourceList20($children, $targetRoles, $source, $target, $role, $packageName)
  202. {
  203. $result = array();
  204. // enumerating files
  205. foreach ($children as $child) {
  206. /** @var $child \SimpleXMLElement */
  207. if ('dir' == $child->getName()) {
  208. $dirSource = $this->combine($source, $child['name']);
  209. $dirTarget = $child['baseinstalldir'] ?: $target;
  210. $dirRole = $child['role'] ?: $role;
  211. $dirFiles = $this->buildSourceList20($child->children(), $targetRoles, $dirSource, $dirTarget, $dirRole, $packageName);
  212. $result = array_merge($result, $dirFiles);
  213. } elseif ('file' == $child->getName()) {
  214. $fileRole = (string) $child['role'] ?: $role;
  215. if (isset($targetRoles[$fileRole])) {
  216. $fileSource = $this->combine($source, (string) $child['name']);
  217. $fileTarget = $this->combine((string) ($child['baseinstalldir'] ?: $target), (string) $child['name']);
  218. $fileTasks = array();
  219. foreach ($child->children('http://pear.php.net/dtd/tasks-1.0') as $taskNode) {
  220. if ('replace' == $taskNode->getName()) {
  221. $fileTasks[] = array('from' => (string) $taskNode->attributes()->from, 'to' => (string) $taskNode->attributes()->to);
  222. }
  223. }
  224. if (!in_array($fileRole, self::$rolesWithoutPackageNamePrefix)) {
  225. $fileTarget = $packageName . '/' . $fileTarget;
  226. }
  227. $result[(string) $child['name']] = array('from' => $fileSource, 'to' => $fileTarget, 'role' => $fileRole, 'tasks' => $fileTasks);
  228. }
  229. }
  230. }
  231. return $result;
  232. }
  233. private function combine($left, $right)
  234. {
  235. return rtrim($left, '/') . '/' . ltrim($right, '/');
  236. }
  237. }