Updater.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. <?php
  2. /*
  3. * This file is part of Packagist.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. * Nils Adermann <naderman@naderman.de>
  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 Packagist\WebBundle\Package;
  12. use Composer\Package\AliasPackage;
  13. use Composer\Package\PackageInterface;
  14. use Composer\Repository\RepositoryInterface;
  15. use Composer\Repository\VcsRepository;
  16. use Composer\Repository\Vcs\GitHubDriver;
  17. use Composer\Repository\InvalidRepositoryException;
  18. use Composer\Util\ErrorHandler;
  19. use Composer\Util\RemoteFilesystem;
  20. use Composer\Json\JsonFile;
  21. use Composer\Config;
  22. use Composer\IO\IOInterface;
  23. use Packagist\WebBundle\Entity\Author;
  24. use Packagist\WebBundle\Entity\Package;
  25. use Packagist\WebBundle\Entity\Tag;
  26. use Packagist\WebBundle\Entity\Version;
  27. use Packagist\WebBundle\Entity\SuggestLink;
  28. use Symfony\Bridge\Doctrine\RegistryInterface;
  29. /**
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. */
  32. class Updater
  33. {
  34. const UPDATE_EQUAL_REFS = 1;
  35. const DELETE_BEFORE = 2;
  36. /**
  37. * Doctrine
  38. * @var RegistryInterface
  39. */
  40. protected $doctrine;
  41. /**
  42. * Supported link types
  43. * @var array
  44. */
  45. protected $supportedLinkTypes = array(
  46. 'require' => array(
  47. 'method' => 'getRequires',
  48. 'entity' => 'RequireLink',
  49. ),
  50. 'conflict' => array(
  51. 'method' => 'getConflicts',
  52. 'entity' => 'ConflictLink',
  53. ),
  54. 'provide' => array(
  55. 'method' => 'getProvides',
  56. 'entity' => 'ProvideLink',
  57. ),
  58. 'replace' => array(
  59. 'method' => 'getReplaces',
  60. 'entity' => 'ReplaceLink',
  61. ),
  62. 'devRequire' => array(
  63. 'method' => 'getDevRequires',
  64. 'entity' => 'DevRequireLink',
  65. ),
  66. );
  67. /**
  68. * Constructor
  69. *
  70. * @param RegistryInterface $doctrine
  71. */
  72. public function __construct(RegistryInterface $doctrine)
  73. {
  74. $this->doctrine = $doctrine;
  75. ErrorHandler::register();
  76. }
  77. /**
  78. * Update a project
  79. *
  80. * @param \Packagist\WebBundle\Entity\Package $package
  81. * @param RepositoryInterface $repository the repository instance used to update from
  82. * @param int $flags a few of the constants of this class
  83. * @param \DateTime $start
  84. */
  85. public function update(IOInterface $io, Config $config, Package $package, RepositoryInterface $repository, $flags = 0, \DateTime $start = null)
  86. {
  87. $rfs = new RemoteFilesystem($io, $config);
  88. $blacklist = '{^symfony/symfony (2.0.[456]|dev-charset|dev-console)}i';
  89. if (null === $start) {
  90. $start = new \DateTime();
  91. }
  92. $pruneDate = clone $start;
  93. $pruneDate->modify('-1min');
  94. $em = $this->doctrine->getManager();
  95. $apc = extension_loaded('apcu');
  96. if ($repository instanceof VcsRepository) {
  97. $cfg = $repository->getRepoConfig();
  98. if (isset($cfg['url']) && preg_match('{\bgithub\.com\b}', $cfg['url'])) {
  99. foreach ($package->getMaintainers() as $maintainer) {
  100. if (!($newGithubToken = $maintainer->getGithubToken())) {
  101. continue;
  102. }
  103. $valid = null;
  104. if ($apc) {
  105. $valid = apcu_fetch('is_token_valid_'.$maintainer->getUsernameCanonical());
  106. }
  107. if (true !== $valid) {
  108. $context = stream_context_create(['http' => ['header' => 'User-agent: packagist-token-check']]);
  109. $rate = json_decode(@file_get_contents('https://api.github.com/rate_limit?access_token='.$newGithubToken, false, $context), true);
  110. // invalid/outdated token, wipe it so we don't try it again
  111. if (!$rate && (strpos($http_response_header[0], '403') || strpos($http_response_header[0], '401'))) {
  112. $maintainer->setGithubToken(null);
  113. $em->flush($maintainer);
  114. continue;
  115. }
  116. }
  117. if ($apc) {
  118. apcu_store('is_token_valid_'.$maintainer->getUsernameCanonical(), true, 86400);
  119. }
  120. $io->setAuthentication('github.com', $newGithubToken, 'x-oauth-basic');
  121. break;
  122. }
  123. }
  124. }
  125. $versions = $repository->getPackages();
  126. usort($versions, function ($a, $b) {
  127. $aVersion = $a->getVersion();
  128. $bVersion = $b->getVersion();
  129. if ($aVersion === '9999999-dev' || 'dev-' === substr($aVersion, 0, 4)) {
  130. $aVersion = 'dev';
  131. }
  132. if ($bVersion === '9999999-dev' || 'dev-' === substr($bVersion, 0, 4)) {
  133. $bVersion = 'dev';
  134. }
  135. $aIsDev = $aVersion === 'dev' || substr($aVersion, -4) === '-dev';
  136. $bIsDev = $bVersion === 'dev' || substr($bVersion, -4) === '-dev';
  137. // push dev versions to the end
  138. if ($aIsDev !== $bIsDev) {
  139. return $aIsDev ? 1 : -1;
  140. }
  141. // equal versions are sorted by date
  142. if ($aVersion === $bVersion) {
  143. return $a->getReleaseDate() > $b->getReleaseDate() ? 1 : -1;
  144. }
  145. // the rest is sorted by version
  146. return version_compare($aVersion, $bVersion);
  147. });
  148. $versionRepository = $this->doctrine->getRepository('PackagistWebBundle:Version');
  149. if ($flags & self::DELETE_BEFORE) {
  150. foreach ($package->getVersions() as $version) {
  151. $versionRepository->remove($version);
  152. }
  153. $em->flush();
  154. $em->refresh($package);
  155. }
  156. $lastUpdated = true;
  157. $lastProcessed = null;
  158. foreach ($versions as $version) {
  159. if ($version instanceof AliasPackage) {
  160. continue;
  161. }
  162. if (preg_match($blacklist, $version->getName().' '.$version->getPrettyVersion())) {
  163. continue;
  164. }
  165. if ($lastProcessed && $lastProcessed->getVersion() === $version->getVersion()) {
  166. $io->write('Skipping version '.$version->getPrettyVersion().' (duplicate of '.$lastProcessed->getPrettyVersion().')', true, IOInterface::VERBOSE);
  167. continue;
  168. }
  169. $lastProcessed = $version;
  170. $lastUpdated = $this->updateInformation($package, $version, $flags);
  171. if ($lastUpdated) {
  172. $em->flush();
  173. }
  174. }
  175. if (!$lastUpdated) {
  176. $em->flush();
  177. }
  178. // remove outdated versions
  179. foreach ($package->getVersions() as $version) {
  180. if ($version->getUpdatedAt() < $pruneDate) {
  181. $versionRepository->remove($version);
  182. }
  183. }
  184. if (preg_match('{^(?:git://|git@|https?://)github.com[:/]([^/]+)/(.+?)(?:\.git|/)?$}i', $package->getRepository(), $match) && $repository instanceof VcsRepository) {
  185. $this->updateGitHubInfo($rfs, $package, $match[1], $match[2], $repository);
  186. }
  187. $package->setUpdatedAt(new \DateTime);
  188. $package->setCrawledAt(new \DateTime);
  189. $em->flush();
  190. if ($repository->hadInvalidBranches()) {
  191. throw new InvalidRepositoryException('Some branches contained invalid data and were discarded, it is advised to review the log and fix any issues present in branches');
  192. }
  193. }
  194. private function updateInformation(Package $package, PackageInterface $data, $flags)
  195. {
  196. $em = $this->doctrine->getManager();
  197. $version = new Version();
  198. $normVersion = $data->getVersion();
  199. $existingVersion = $package->getVersion($normVersion);
  200. if ($existingVersion) {
  201. $source = $existingVersion->getSource();
  202. // update if the right flag is set, or the source reference has changed (re-tag or new commit on branch)
  203. if ($source['reference'] !== $data->getSourceReference() || ($flags & self::UPDATE_EQUAL_REFS)) {
  204. $version = $existingVersion;
  205. } else {
  206. // mark it updated to avoid it being pruned
  207. $existingVersion->setUpdatedAt(new \DateTime);
  208. return false;
  209. }
  210. }
  211. $version->setName($package->getName());
  212. $version->setVersion($data->getPrettyVersion());
  213. $version->setNormalizedVersion($normVersion);
  214. $version->setDevelopment($data->isDev());
  215. $em->persist($version);
  216. $descr = $this->sanitize($data->getDescription());
  217. $version->setDescription($descr);
  218. $package->setDescription($descr);
  219. $version->setHomepage($data->getHomepage());
  220. $version->setLicense($data->getLicense() ?: array());
  221. $version->setPackage($package);
  222. $version->setUpdatedAt(new \DateTime);
  223. $version->setReleasedAt($data->getReleaseDate());
  224. if ($data->getSourceType()) {
  225. $source['type'] = $data->getSourceType();
  226. $source['url'] = $data->getSourceUrl();
  227. $source['reference'] = $data->getSourceReference();
  228. $version->setSource($source);
  229. } else {
  230. $version->setSource(null);
  231. }
  232. if ($data->getDistType()) {
  233. $dist['type'] = $data->getDistType();
  234. $dist['url'] = $data->getDistUrl();
  235. $dist['reference'] = $data->getDistReference();
  236. $dist['shasum'] = $data->getDistSha1Checksum();
  237. $version->setDist($dist);
  238. } else {
  239. $version->setDist(null);
  240. }
  241. if ($data->getType()) {
  242. $type = $this->sanitize($data->getType());
  243. $version->setType($type);
  244. if ($type !== $package->getType()) {
  245. $package->setType($type);
  246. }
  247. }
  248. $version->setTargetDir($data->getTargetDir());
  249. $version->setAutoload($data->getAutoload());
  250. $version->setExtra($data->getExtra());
  251. $version->setBinaries($data->getBinaries());
  252. $version->setIncludePaths($data->getIncludePaths());
  253. $version->setSupport($data->getSupport());
  254. if ($data->getKeywords()) {
  255. $keywords = array();
  256. foreach ($data->getKeywords() as $keyword) {
  257. $keywords[mb_strtolower($keyword, 'UTF-8')] = $keyword;
  258. }
  259. $existingTags = [];
  260. foreach ($version->getTags() as $tag) {
  261. $existingTags[mb_strtolower($tag->getName(), 'UTF-8')] = $tag;
  262. }
  263. foreach ($keywords as $tagKey => $keyword) {
  264. if (isset($existingTags[$tagKey])) {
  265. unset($existingTags[$tagKey]);
  266. continue;
  267. }
  268. $tag = Tag::getByName($em, $keyword, true);
  269. if (!$version->getTags()->contains($tag)) {
  270. $version->addTag($tag);
  271. }
  272. }
  273. foreach ($existingTags as $tag) {
  274. $version->getTags()->removeElement($tag);
  275. }
  276. } elseif (count($version->getTags())) {
  277. $version->getTags()->clear();
  278. }
  279. $authorRepository = $this->doctrine->getRepository('PackagistWebBundle:Author');
  280. $version->getAuthors()->clear();
  281. if ($data->getAuthors()) {
  282. foreach ($data->getAuthors() as $authorData) {
  283. $author = null;
  284. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  285. if (isset($authorData[$field])) {
  286. $authorData[$field] = trim($authorData[$field]);
  287. if ('' === $authorData[$field]) {
  288. $authorData[$field] = null;
  289. }
  290. } else {
  291. $authorData[$field] = null;
  292. }
  293. }
  294. // skip authors with no information
  295. if (!isset($authorData['email']) && !isset($authorData['name'])) {
  296. continue;
  297. }
  298. $author = $authorRepository->findOneBy(array(
  299. 'email' => $authorData['email'],
  300. 'name' => $authorData['name'],
  301. 'homepage' => $authorData['homepage'],
  302. 'role' => $authorData['role'],
  303. ));
  304. if (!$author) {
  305. $author = new Author();
  306. $em->persist($author);
  307. }
  308. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  309. if (isset($authorData[$field])) {
  310. $author->{'set'.$field}($authorData[$field]);
  311. }
  312. }
  313. // only update the author timestamp once a month at most as the value is kinda unused
  314. if ($author->getUpdatedAt() === null || $author->getUpdatedAt()->getTimestamp() < time() - 86400 * 30) {
  315. $author->setUpdatedAt(new \DateTime);
  316. }
  317. if (!$version->getAuthors()->contains($author)) {
  318. $version->addAuthor($author);
  319. }
  320. if (!$author->getVersions()->contains($version)) {
  321. $author->addVersion($version);
  322. }
  323. }
  324. }
  325. // handle links
  326. foreach ($this->supportedLinkTypes as $linkType => $opts) {
  327. $links = array();
  328. foreach ($data->{$opts['method']}() as $link) {
  329. $constraint = $link->getPrettyConstraint();
  330. if (false !== strpos($constraint, ',') && false !== strpos($constraint, '@')) {
  331. $constraint = preg_replace_callback('{([><]=?\s*[^@]+?)@([a-z]+)}i', function ($matches) {
  332. if ($matches[2] === 'stable') {
  333. return $matches[1];
  334. }
  335. return $matches[1].'-'.$matches[2];
  336. }, $constraint);
  337. }
  338. $links[$link->getTarget()] = $constraint;
  339. }
  340. foreach ($version->{'get'.$linkType}() as $link) {
  341. // clear links that have changed/disappeared (for updates)
  342. if (!isset($links[$link->getPackageName()]) || $links[$link->getPackageName()] !== $link->getPackageVersion()) {
  343. $version->{'get'.$linkType}()->removeElement($link);
  344. $em->remove($link);
  345. } else {
  346. // clear those that are already set
  347. unset($links[$link->getPackageName()]);
  348. }
  349. }
  350. foreach ($links as $linkPackageName => $linkPackageVersion) {
  351. $class = 'Packagist\WebBundle\Entity\\'.$opts['entity'];
  352. $link = new $class;
  353. $link->setPackageName($linkPackageName);
  354. $link->setPackageVersion($linkPackageVersion);
  355. $version->{'add'.$linkType.'Link'}($link);
  356. $link->setVersion($version);
  357. $em->persist($link);
  358. }
  359. }
  360. // handle suggests
  361. if ($suggests = $data->getSuggests()) {
  362. foreach ($version->getSuggest() as $link) {
  363. // clear links that have changed/disappeared (for updates)
  364. if (!isset($suggests[$link->getPackageName()]) || $suggests[$link->getPackageName()] !== $link->getPackageVersion()) {
  365. $version->getSuggest()->removeElement($link);
  366. $em->remove($link);
  367. } else {
  368. // clear those that are already set
  369. unset($suggests[$link->getPackageName()]);
  370. }
  371. }
  372. foreach ($suggests as $linkPackageName => $linkPackageVersion) {
  373. $link = new SuggestLink;
  374. $link->setPackageName($linkPackageName);
  375. $link->setPackageVersion($linkPackageVersion);
  376. $version->addSuggestLink($link);
  377. $link->setVersion($version);
  378. $em->persist($link);
  379. }
  380. } elseif (count($version->getSuggest())) {
  381. // clear existing suggests if present
  382. foreach ($version->getSuggest() as $link) {
  383. $em->remove($link);
  384. }
  385. $version->getSuggest()->clear();
  386. }
  387. if (!$package->getVersions()->contains($version)) {
  388. $package->addVersions($version);
  389. }
  390. return true;
  391. }
  392. private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo, VcsRepository $repository)
  393. {
  394. $baseApiUrl = 'https://api.github.com/repos/'.$owner.'/'.$repo;
  395. $driver = $repository->getDriver();
  396. if (!$driver instanceof GitHubDriver) {
  397. return;
  398. }
  399. $repoData = $driver->getRepoData();
  400. try {
  401. $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]];
  402. $readme = $rfs->getContents('github.com', $baseApiUrl.'/readme', false, $opts);
  403. } catch (\Exception $e) {
  404. if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) {
  405. return;
  406. }
  407. // 404s just mean no readme present so we proceed with the rest
  408. }
  409. if (!empty($readme)) {
  410. $elements = array(
  411. 'p',
  412. 'br',
  413. 'small',
  414. 'strong', 'b',
  415. 'em', 'i',
  416. 'strike',
  417. 'sub', 'sup',
  418. 'ins', 'del',
  419. 'ol', 'ul', 'li',
  420. 'h1', 'h2', 'h3',
  421. 'dl', 'dd', 'dt',
  422. 'pre', 'code', 'samp', 'kbd',
  423. 'q', 'blockquote', 'abbr', 'cite',
  424. 'table', 'thead', 'tbody', 'th', 'tr', 'td',
  425. 'a[href|target|rel|id]',
  426. 'img[src|title|alt|width|height|style]'
  427. );
  428. $config = \HTMLPurifier_Config::createDefault();
  429. $config->set('HTML.Allowed', implode(',', $elements));
  430. $config->set('Attr.EnableID', true);
  431. $config->set('Attr.AllowedFrameTargets', ['_blank']);
  432. $purifier = new \HTMLPurifier($config);
  433. $readme = $purifier->purify($readme);
  434. $dom = new \DOMDocument();
  435. $dom->loadHTML('<?xml encoding="UTF-8">' . $readme);
  436. // Links can not be trusted, mark them nofollow and convert relative to absolute links
  437. $links = $dom->getElementsByTagName('a');
  438. foreach ($links as $link) {
  439. $link->setAttribute('rel', 'nofollow noopener external');
  440. if ('#' === substr($link->getAttribute('href'), 0, 1)) {
  441. $link->setAttribute('href', '#user-content-'.substr($link->getAttribute('href'), 1));
  442. } elseif ('mailto:' === substr($link->getAttribute('href'), 0, 7)) {
  443. // do nothing
  444. } elseif (false === strpos($link->getAttribute('href'), '//')) {
  445. $link->setAttribute('href', 'https://github.com/'.$owner.'/'.$repo.'/blob/HEAD/'.$link->getAttribute('href'));
  446. }
  447. }
  448. // convert relative to absolute images
  449. $images = $dom->getElementsByTagName('img');
  450. foreach ($images as $img) {
  451. if (false === strpos($img->getAttribute('src'), '//')) {
  452. $img->setAttribute('src', 'https://raw.github.com/'.$owner.'/'.$repo.'/HEAD/'.$img->getAttribute('src'));
  453. }
  454. }
  455. // remove first title as it's usually the project name which we don't need
  456. if ($dom->getElementsByTagName('h1')->length) {
  457. $first = $dom->getElementsByTagName('h1')->item(0);
  458. $first->parentNode->removeChild($first);
  459. } elseif ($dom->getElementsByTagName('h2')->length) {
  460. $first = $dom->getElementsByTagName('h2')->item(0);
  461. $first->parentNode->removeChild($first);
  462. }
  463. $readme = $dom->saveHTML();
  464. $readme = substr($readme, strpos($readme, '<body>')+6);
  465. $readme = substr($readme, 0, strrpos($readme, '</body>'));
  466. $package->setReadme($readme);
  467. }
  468. if (!empty($repoData['language'])) {
  469. $package->setLanguage($repoData['language']);
  470. }
  471. if (isset($repoData['stargazers_count'])) {
  472. $package->setGitHubStars($repoData['stargazers_count']);
  473. }
  474. if (isset($repoData['subscribers_count'])) {
  475. $package->setGitHubWatches($repoData['subscribers_count']);
  476. }
  477. if (isset($repoData['network_count'])) {
  478. $package->setGitHubForks($repoData['network_count']);
  479. }
  480. if (isset($repoData['open_issues_count'])) {
  481. $package->setGitHubOpenIssues($repoData['open_issues_count']);
  482. }
  483. }
  484. private function sanitize($str)
  485. {
  486. // remove escape chars
  487. $str = preg_replace("{\x1B(?:\[.)?}u", '', $str);
  488. return preg_replace("{[\x01-\x1A]}u", '', $str);
  489. }
  490. }