Updater.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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. foreach ($versions as $version) {
  158. if ($version instanceof AliasPackage) {
  159. continue;
  160. }
  161. if (preg_match($blacklist, $version->getName().' '.$version->getPrettyVersion())) {
  162. continue;
  163. }
  164. $lastUpdated = $this->updateInformation($package, $version, $flags);
  165. if ($lastUpdated) {
  166. $em->flush();
  167. }
  168. }
  169. if (!$lastUpdated) {
  170. $em->flush();
  171. }
  172. // remove outdated versions
  173. foreach ($package->getVersions() as $version) {
  174. if ($version->getUpdatedAt() < $pruneDate) {
  175. $versionRepository->remove($version);
  176. }
  177. }
  178. if (preg_match('{^(?:git://|git@|https?://)github.com[:/]([^/]+)/(.+?)(?:\.git|/)?$}i', $package->getRepository(), $match) && $repository instanceof VcsRepository) {
  179. $this->updateGitHubInfo($rfs, $package, $match[1], $match[2], $repository);
  180. }
  181. $package->setUpdatedAt(new \DateTime);
  182. $package->setCrawledAt(new \DateTime);
  183. $em->flush($package);
  184. if ($repository->hadInvalidBranches()) {
  185. 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');
  186. }
  187. }
  188. private function updateInformation(Package $package, PackageInterface $data, $flags)
  189. {
  190. $em = $this->doctrine->getManager();
  191. $version = new Version();
  192. $normVersion = $data->getVersion();
  193. $existingVersion = $package->getVersion($normVersion);
  194. if ($existingVersion) {
  195. $source = $existingVersion->getSource();
  196. // update if the right flag is set, or the source reference has changed (re-tag or new commit on branch)
  197. if ($source['reference'] !== $data->getSourceReference() || ($flags & self::UPDATE_EQUAL_REFS)) {
  198. $version = $existingVersion;
  199. } else {
  200. // mark it updated to avoid it being pruned
  201. $existingVersion->setUpdatedAt(new \DateTime);
  202. return false;
  203. }
  204. }
  205. $version->setName($package->getName());
  206. $version->setVersion($data->getPrettyVersion());
  207. $version->setNormalizedVersion($normVersion);
  208. $version->setDevelopment($data->isDev());
  209. $em->persist($version);
  210. $descr = $this->sanitize($data->getDescription());
  211. $version->setDescription($descr);
  212. $package->setDescription($descr);
  213. $version->setHomepage($data->getHomepage());
  214. $version->setLicense($data->getLicense() ?: array());
  215. $version->setPackage($package);
  216. $version->setUpdatedAt(new \DateTime);
  217. $version->setReleasedAt($data->getReleaseDate());
  218. if ($data->getSourceType()) {
  219. $source['type'] = $data->getSourceType();
  220. $source['url'] = $data->getSourceUrl();
  221. $source['reference'] = $data->getSourceReference();
  222. $version->setSource($source);
  223. } else {
  224. $version->setSource(null);
  225. }
  226. if ($data->getDistType()) {
  227. $dist['type'] = $data->getDistType();
  228. $dist['url'] = $data->getDistUrl();
  229. $dist['reference'] = $data->getDistReference();
  230. $dist['shasum'] = $data->getDistSha1Checksum();
  231. $version->setDist($dist);
  232. } else {
  233. $version->setDist(null);
  234. }
  235. if ($data->getType()) {
  236. $type = $this->sanitize($data->getType());
  237. $version->setType($type);
  238. if ($type !== $package->getType()) {
  239. $package->setType($type);
  240. }
  241. }
  242. $version->setTargetDir($data->getTargetDir());
  243. $version->setAutoload($data->getAutoload());
  244. $version->setExtra($data->getExtra());
  245. $version->setBinaries($data->getBinaries());
  246. $version->setIncludePaths($data->getIncludePaths());
  247. $version->setSupport($data->getSupport());
  248. $version->getTags()->clear();
  249. if ($data->getKeywords()) {
  250. $keywords = array();
  251. foreach ($data->getKeywords() as $keyword) {
  252. $keywords[mb_strtolower($keyword, 'UTF-8')] = $keyword;
  253. }
  254. foreach ($keywords as $keyword) {
  255. $tag = Tag::getByName($em, $keyword, true);
  256. if (!$version->getTags()->contains($tag)) {
  257. $version->addTag($tag);
  258. }
  259. }
  260. }
  261. $authorRepository = $this->doctrine->getRepository('PackagistWebBundle:Author');
  262. $version->getAuthors()->clear();
  263. if ($data->getAuthors()) {
  264. foreach ($data->getAuthors() as $authorData) {
  265. $author = null;
  266. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  267. if (isset($authorData[$field])) {
  268. $authorData[$field] = trim($authorData[$field]);
  269. if ('' === $authorData[$field]) {
  270. $authorData[$field] = null;
  271. }
  272. } else {
  273. $authorData[$field] = null;
  274. }
  275. }
  276. // skip authors with no information
  277. if (!isset($authorData['email']) && !isset($authorData['name'])) {
  278. continue;
  279. }
  280. $author = $authorRepository->findOneBy(array(
  281. 'email' => $authorData['email'],
  282. 'name' => $authorData['name'],
  283. 'homepage' => $authorData['homepage'],
  284. 'role' => $authorData['role'],
  285. ));
  286. if (!$author) {
  287. $author = new Author();
  288. $em->persist($author);
  289. }
  290. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  291. if (isset($authorData[$field])) {
  292. $author->{'set'.$field}($authorData[$field]);
  293. }
  294. }
  295. // only update the author timestamp once a month at most as the value is kinda unused
  296. if ($author->getUpdatedAt() === null || $author->getUpdatedAt()->getTimestamp() < time() - 86400 * 30) {
  297. $author->setUpdatedAt(new \DateTime);
  298. }
  299. if (!$version->getAuthors()->contains($author)) {
  300. $version->addAuthor($author);
  301. }
  302. if (!$author->getVersions()->contains($version)) {
  303. $author->addVersion($version);
  304. }
  305. }
  306. }
  307. // handle links
  308. foreach ($this->supportedLinkTypes as $linkType => $opts) {
  309. $links = array();
  310. foreach ($data->{$opts['method']}() as $link) {
  311. $constraint = $link->getPrettyConstraint();
  312. if (false !== strpos($constraint, ',') && false !== strpos($constraint, '@')) {
  313. $constraint = preg_replace_callback('{([><]=?\s*[^@]+?)@([a-z]+)}i', function ($matches) {
  314. if ($matches[2] === 'stable') {
  315. return $matches[1];
  316. }
  317. return $matches[1].'-'.$matches[2];
  318. }, $constraint);
  319. }
  320. $links[$link->getTarget()] = $constraint;
  321. }
  322. foreach ($version->{'get'.$linkType}() as $link) {
  323. // clear links that have changed/disappeared (for updates)
  324. if (!isset($links[$link->getPackageName()]) || $links[$link->getPackageName()] !== $link->getPackageVersion()) {
  325. $version->{'get'.$linkType}()->removeElement($link);
  326. $em->remove($link);
  327. } else {
  328. // clear those that are already set
  329. unset($links[$link->getPackageName()]);
  330. }
  331. }
  332. foreach ($links as $linkPackageName => $linkPackageVersion) {
  333. $class = 'Packagist\WebBundle\Entity\\'.$opts['entity'];
  334. $link = new $class;
  335. $link->setPackageName($linkPackageName);
  336. $link->setPackageVersion($linkPackageVersion);
  337. $version->{'add'.$linkType.'Link'}($link);
  338. $link->setVersion($version);
  339. $em->persist($link);
  340. }
  341. }
  342. // handle suggests
  343. if ($suggests = $data->getSuggests()) {
  344. foreach ($version->getSuggest() as $link) {
  345. // clear links that have changed/disappeared (for updates)
  346. if (!isset($suggests[$link->getPackageName()]) || $suggests[$link->getPackageName()] !== $link->getPackageVersion()) {
  347. $version->getSuggest()->removeElement($link);
  348. $em->remove($link);
  349. } else {
  350. // clear those that are already set
  351. unset($suggests[$link->getPackageName()]);
  352. }
  353. }
  354. foreach ($suggests as $linkPackageName => $linkPackageVersion) {
  355. $link = new SuggestLink;
  356. $link->setPackageName($linkPackageName);
  357. $link->setPackageVersion($linkPackageVersion);
  358. $version->addSuggestLink($link);
  359. $link->setVersion($version);
  360. $em->persist($link);
  361. }
  362. } elseif (count($version->getSuggest())) {
  363. // clear existing suggests if present
  364. foreach ($version->getSuggest() as $link) {
  365. $em->remove($link);
  366. }
  367. $version->getSuggest()->clear();
  368. }
  369. if (!$package->getVersions()->contains($version)) {
  370. $package->addVersions($version);
  371. }
  372. return true;
  373. }
  374. private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo, VcsRepository $repository)
  375. {
  376. $baseApiUrl = 'https://api.github.com/repos/'.$owner.'/'.$repo;
  377. $driver = $repository->getDriver();
  378. if (!$driver instanceof GitHubDriver) {
  379. return;
  380. }
  381. $repoData = $driver->getRepoData();
  382. try {
  383. $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]];
  384. $readme = $rfs->getContents('github.com', $baseApiUrl.'/readme', false, $opts);
  385. } catch (\Exception $e) {
  386. if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) {
  387. return;
  388. }
  389. // 404s just mean no readme present so we proceed with the rest
  390. }
  391. if (!empty($readme)) {
  392. $elements = array(
  393. 'p',
  394. 'br',
  395. 'small',
  396. 'strong', 'b',
  397. 'em', 'i',
  398. 'strike',
  399. 'sub', 'sup',
  400. 'ins', 'del',
  401. 'ol', 'ul', 'li',
  402. 'h1', 'h2', 'h3',
  403. 'dl', 'dd', 'dt',
  404. 'pre', 'code', 'samp', 'kbd',
  405. 'q', 'blockquote', 'abbr', 'cite',
  406. 'table', 'thead', 'tbody', 'th', 'tr', 'td',
  407. 'a[href|target|rel|id]',
  408. 'img[src|title|alt|width|height|style]'
  409. );
  410. $config = \HTMLPurifier_Config::createDefault();
  411. $config->set('HTML.Allowed', implode(',', $elements));
  412. $config->set('Attr.EnableID', true);
  413. $config->set('Attr.AllowedFrameTargets', ['_blank']);
  414. $purifier = new \HTMLPurifier($config);
  415. $readme = $purifier->purify($readme);
  416. $dom = new \DOMDocument();
  417. $dom->loadHTML('<?xml encoding="UTF-8">' . $readme);
  418. // Links can not be trusted, mark them nofollow and convert relative to absolute links
  419. $links = $dom->getElementsByTagName('a');
  420. foreach ($links as $link) {
  421. $link->setAttribute('rel', 'nofollow');
  422. if ('#' === substr($link->getAttribute('href'), 0, 1)) {
  423. $link->setAttribute('href', '#user-content-'.substr($link->getAttribute('href'), 1));
  424. } elseif (false === strpos($link->getAttribute('href'), '//')) {
  425. $link->setAttribute('href', 'https://github.com/'.$owner.'/'.$repo.'/blob/HEAD/'.$link->getAttribute('href'));
  426. }
  427. }
  428. // convert relative to absolute images
  429. $images = $dom->getElementsByTagName('img');
  430. foreach ($images as $img) {
  431. if (false === strpos($img->getAttribute('src'), '//')) {
  432. $img->setAttribute('src', 'https://raw.github.com/'.$owner.'/'.$repo.'/HEAD/'.$img->getAttribute('src'));
  433. }
  434. }
  435. // remove first title as it's usually the project name which we don't need
  436. if ($dom->getElementsByTagName('h1')->length) {
  437. $first = $dom->getElementsByTagName('h1')->item(0);
  438. $first->parentNode->removeChild($first);
  439. } elseif ($dom->getElementsByTagName('h2')->length) {
  440. $first = $dom->getElementsByTagName('h2')->item(0);
  441. $first->parentNode->removeChild($first);
  442. }
  443. $readme = $dom->saveHTML();
  444. $readme = substr($readme, strpos($readme, '<body>')+6);
  445. $readme = substr($readme, 0, strrpos($readme, '</body>'));
  446. $package->setReadme($readme);
  447. }
  448. if (!empty($repoData['language'])) {
  449. $package->setLanguage($repoData['language']);
  450. }
  451. if (isset($repoData['stargazers_count'])) {
  452. $package->setGitHubStars($repoData['stargazers_count']);
  453. }
  454. if (isset($repoData['subscribers_count'])) {
  455. $package->setGitHubWatches($repoData['subscribers_count']);
  456. }
  457. if (isset($repoData['network_count'])) {
  458. $package->setGitHubForks($repoData['network_count']);
  459. }
  460. if (isset($repoData['open_issues_count'])) {
  461. $package->setGitHubOpenIssues($repoData['open_issues_count']);
  462. }
  463. }
  464. private function sanitize($str)
  465. {
  466. // remove escape chars
  467. $str = preg_replace("{\x1B(?:\[.)?}u", '', $str);
  468. return preg_replace("{[\x01-\x1A]}u", '', $str);
  469. }
  470. }