Updater.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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 cebe\markdown\GithubMarkdown;
  13. use Composer\Package\AliasPackage;
  14. use Composer\Package\PackageInterface;
  15. use Composer\Repository\RepositoryInterface;
  16. use Composer\Repository\VcsRepository;
  17. use Composer\Repository\Vcs\GitHubDriver;
  18. use Composer\Repository\InvalidRepositoryException;
  19. use Composer\Util\ErrorHandler;
  20. use Composer\Util\RemoteFilesystem;
  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\VersionRepository;
  28. use Packagist\WebBundle\Entity\SuggestLink;
  29. use Symfony\Bridge\Doctrine\RegistryInterface;
  30. use Doctrine\DBAL\Connection;
  31. /**
  32. * @author Jordi Boggiano <j.boggiano@seld.be>
  33. */
  34. class Updater
  35. {
  36. const UPDATE_EQUAL_REFS = 1;
  37. const DELETE_BEFORE = 2;
  38. /**
  39. * Doctrine
  40. * @var RegistryInterface
  41. */
  42. protected $doctrine;
  43. /**
  44. * Supported link types
  45. * @var array
  46. */
  47. protected $supportedLinkTypes = array(
  48. 'require' => array(
  49. 'method' => 'getRequires',
  50. 'entity' => 'RequireLink',
  51. ),
  52. 'conflict' => array(
  53. 'method' => 'getConflicts',
  54. 'entity' => 'ConflictLink',
  55. ),
  56. 'provide' => array(
  57. 'method' => 'getProvides',
  58. 'entity' => 'ProvideLink',
  59. ),
  60. 'replace' => array(
  61. 'method' => 'getReplaces',
  62. 'entity' => 'ReplaceLink',
  63. ),
  64. 'devRequire' => array(
  65. 'method' => 'getDevRequires',
  66. 'entity' => 'DevRequireLink',
  67. ),
  68. );
  69. /**
  70. * Constructor
  71. *
  72. * @param RegistryInterface $doctrine
  73. */
  74. public function __construct(RegistryInterface $doctrine)
  75. {
  76. $this->doctrine = $doctrine;
  77. ErrorHandler::register();
  78. }
  79. /**
  80. * Update a project
  81. *
  82. * @param \Packagist\WebBundle\Entity\Package $package
  83. * @param RepositoryInterface $repository the repository instance used to update from
  84. * @param int $flags a few of the constants of this class
  85. */
  86. public function update(IOInterface $io, Config $config, Package $package, RepositoryInterface $repository, $flags = 0, array $existingVersions = null): Package
  87. {
  88. $rfs = new RemoteFilesystem($io, $config);
  89. $deleteDate = new \DateTime();
  90. $deleteDate->modify('-1day');
  91. $em = $this->doctrine->getManager();
  92. $apc = extension_loaded('apcu');
  93. $rootIdentifier = null;
  94. if ($repository instanceof VcsRepository) {
  95. $cfg = $repository->getRepoConfig();
  96. if (isset($cfg['url']) && preg_match('{\bgithub\.com\b}i', $cfg['url'])) {
  97. foreach ($package->getMaintainers() as $maintainer) {
  98. if (!($newGithubToken = $maintainer->getGithubToken())) {
  99. continue;
  100. }
  101. $valid = null;
  102. if ($apc) {
  103. $valid = apcu_fetch('is_token_valid_'.$maintainer->getUsernameCanonical());
  104. }
  105. if (true !== $valid) {
  106. $context = stream_context_create(['http' => ['header' => 'User-agent: packagist-token-check']]);
  107. $rate = json_decode(@file_get_contents('https://api.github.com/rate_limit?access_token='.$newGithubToken, false, $context), true);
  108. // invalid/outdated token, wipe it so we don't try it again
  109. if (!$rate && (strpos($http_response_header[0], '403') || strpos($http_response_header[0], '401'))) {
  110. $maintainer->setGithubToken(null);
  111. $em->flush($maintainer);
  112. continue;
  113. }
  114. }
  115. if ($apc) {
  116. apcu_store('is_token_valid_'.$maintainer->getUsernameCanonical(), true, 86400);
  117. }
  118. $io->setAuthentication('github.com', $newGithubToken, 'x-oauth-basic');
  119. break;
  120. }
  121. }
  122. if (!$repository->getDriver()) {
  123. throw new \RuntimeException('Driver could not be established for package '.$package->getName().' ('.$package->getRepository().')');
  124. }
  125. $rootIdentifier = $repository->getDriver()->getRootIdentifier();
  126. }
  127. $versions = $repository->getPackages();
  128. usort($versions, function ($a, $b) {
  129. $aVersion = $a->getVersion();
  130. $bVersion = $b->getVersion();
  131. if ($aVersion === '9999999-dev' || 'dev-' === substr($aVersion, 0, 4)) {
  132. $aVersion = 'dev';
  133. }
  134. if ($bVersion === '9999999-dev' || 'dev-' === substr($bVersion, 0, 4)) {
  135. $bVersion = 'dev';
  136. }
  137. $aIsDev = $aVersion === 'dev' || substr($aVersion, -4) === '-dev';
  138. $bIsDev = $bVersion === 'dev' || substr($bVersion, -4) === '-dev';
  139. // push dev versions to the end
  140. if ($aIsDev !== $bIsDev) {
  141. return $aIsDev ? 1 : -1;
  142. }
  143. // equal versions are sorted by date
  144. if ($aVersion === $bVersion) {
  145. return $a->getReleaseDate() > $b->getReleaseDate() ? 1 : -1;
  146. }
  147. // the rest is sorted by version
  148. return version_compare($aVersion, $bVersion);
  149. });
  150. $versionRepository = $this->doctrine->getRepository('PackagistWebBundle:Version');
  151. if ($flags & self::DELETE_BEFORE) {
  152. foreach ($package->getVersions() as $version) {
  153. $versionRepository->remove($version);
  154. }
  155. $em->flush();
  156. $em->refresh($package);
  157. }
  158. if (!$existingVersions) {
  159. $existingVersions = $versionRepository->getVersionMetadataForUpdate($package);
  160. }
  161. $processedVersions = [];
  162. $lastProcessed = null;
  163. $idsToMarkUpdated = [];
  164. foreach ($versions as $version) {
  165. if ($version instanceof AliasPackage) {
  166. continue;
  167. }
  168. if (isset($processedVersions[strtolower($version->getVersion())])) {
  169. $io->write('Skipping version '.$version->getPrettyVersion().' (duplicate of '.$processedVersions[strtolower($version->getVersion())]->getPrettyVersion().')', true, IOInterface::VERBOSE);
  170. continue;
  171. }
  172. $processedVersions[strtolower($version->getVersion())] = $version;
  173. $result = $this->updateInformation($versionRepository, $package, $existingVersions, $version, $flags, $rootIdentifier);
  174. $lastUpdated = $result['updated'];
  175. if ($lastUpdated) {
  176. $em->flush();
  177. $em->clear();
  178. $package = $em->merge($package);
  179. } else {
  180. $idsToMarkUpdated[] = $result['id'];
  181. }
  182. // mark the version processed so we can prune leftover ones
  183. unset($existingVersions[$result['version']]);
  184. }
  185. // mark versions that did not update as updated to avoid them being pruned
  186. $em->getConnection()->executeUpdate(
  187. 'UPDATE package_version SET updatedAt = :now, softDeletedAt = NULL WHERE id IN (:ids)',
  188. ['now' => date('Y-m-d H:i:s'), 'ids' => $idsToMarkUpdated],
  189. ['ids' => Connection::PARAM_INT_ARRAY]
  190. );
  191. // remove outdated versions
  192. foreach ($existingVersions as $version) {
  193. if (!is_null($version['softDeletedAt']) && new \DateTime($version['softDeletedAt']) < $deleteDate) {
  194. $versionRepository->remove($versionRepository->findOneById($version['id']));
  195. } else {
  196. // set it to be soft-deleted so next update that occurs after deleteDate (1day) if the
  197. // version is still missing it will be really removed
  198. $em->getConnection()->executeUpdate(
  199. 'UPDATE package_version SET softDeletedAt = :now WHERE id = :id',
  200. ['now' => date('Y-m-d H:i:s'), 'id' => $version['id']]
  201. );
  202. }
  203. }
  204. if (preg_match('{^(?:git://|git@|https?://)github.com[:/]([^/]+)/(.+?)(?:\.git|/)?$}i', $package->getRepository(), $match) && $repository instanceof VcsRepository) {
  205. $this->updateGitHubInfo($rfs, $package, $match[1], $match[2], $repository);
  206. } else {
  207. $this->updateReadme($io, $package, $repository);
  208. }
  209. $package->setUpdatedAt(new \DateTime);
  210. $package->setCrawledAt(new \DateTime);
  211. $em->flush();
  212. if ($repository->hadInvalidBranches()) {
  213. 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');
  214. }
  215. return $package;
  216. }
  217. /**
  218. * @return array with keys:
  219. * - updated (whether the version was updated or needs to be marked as updated)
  220. * - id (version id, can be null for newly created versions)
  221. * - version (normalized version from the composer package)
  222. * - object (Version instance if it was updated)
  223. */
  224. private function updateInformation(VersionRepository $versionRepo, Package $package, array $existingVersions, PackageInterface $data, $flags, $rootIdentifier)
  225. {
  226. $em = $this->doctrine->getManager();
  227. $version = new Version();
  228. $normVersion = $data->getVersion();
  229. $existingVersion = $existingVersions[strtolower($normVersion)] ?? null;
  230. if ($existingVersion) {
  231. $source = $existingVersion['source'];
  232. // update if the right flag is set, or the source reference has changed (re-tag or new commit on branch)
  233. if ($source['reference'] !== $data->getSourceReference() || ($flags & self::UPDATE_EQUAL_REFS)) {
  234. $version = $versionRepo->findOneById($existingVersion['id']);
  235. } elseif ($existingVersion['needs_author_migration']) {
  236. $version = $versionRepo->findOneById($existingVersion['id']);
  237. $version->setAuthorJson($version->getAuthorData());
  238. $version->getAuthors()->clear();
  239. return ['updated' => true, 'id' => $version->getId(), 'version' => strtolower($normVersion), 'object' => $version];
  240. } else {
  241. return ['updated' => false, 'id' => $existingVersion['id'], 'version' => strtolower($normVersion), 'object' => null];
  242. }
  243. }
  244. $version->setName($package->getName());
  245. $version->setVersion($data->getPrettyVersion());
  246. $version->setNormalizedVersion($normVersion);
  247. $version->setDevelopment($data->isDev());
  248. $em->persist($version);
  249. $descr = $this->sanitize($data->getDescription());
  250. $version->setDescription($descr);
  251. // update the package description only for the default branch
  252. if ($rootIdentifier === null || preg_replace('{dev-|(\.x)?-dev}', '', $version->getVersion()) === $rootIdentifier) {
  253. $package->setDescription($descr);
  254. }
  255. $version->setHomepage($data->getHomepage());
  256. $version->setLicense($data->getLicense() ?: array());
  257. $version->setPackage($package);
  258. $version->setUpdatedAt(new \DateTime);
  259. $version->setSoftDeletedAt(null);
  260. $version->setReleasedAt($data->getReleaseDate());
  261. if ($data->getSourceType()) {
  262. $source['type'] = $data->getSourceType();
  263. $source['url'] = $data->getSourceUrl();
  264. $source['reference'] = $data->getSourceReference();
  265. $version->setSource($source);
  266. } else {
  267. $version->setSource(null);
  268. }
  269. if ($data->getDistType()) {
  270. $dist['type'] = $data->getDistType();
  271. $dist['url'] = $data->getDistUrl();
  272. $dist['reference'] = $data->getDistReference();
  273. $dist['shasum'] = $data->getDistSha1Checksum();
  274. $version->setDist($dist);
  275. } else {
  276. $version->setDist(null);
  277. }
  278. if ($data->getType()) {
  279. $type = $this->sanitize($data->getType());
  280. $version->setType($type);
  281. if ($type !== $package->getType()) {
  282. $package->setType($type);
  283. }
  284. }
  285. $version->setTargetDir($data->getTargetDir());
  286. $version->setAutoload($data->getAutoload());
  287. $version->setExtra($data->getExtra());
  288. $version->setBinaries($data->getBinaries());
  289. $version->setIncludePaths($data->getIncludePaths());
  290. $version->setSupport($data->getSupport());
  291. if ($data->getKeywords()) {
  292. $keywords = array();
  293. foreach ($data->getKeywords() as $keyword) {
  294. $keywords[mb_strtolower($keyword, 'UTF-8')] = $keyword;
  295. }
  296. $existingTags = [];
  297. foreach ($version->getTags() as $tag) {
  298. $existingTags[mb_strtolower($tag->getName(), 'UTF-8')] = $tag;
  299. }
  300. foreach ($keywords as $tagKey => $keyword) {
  301. if (isset($existingTags[$tagKey])) {
  302. unset($existingTags[$tagKey]);
  303. continue;
  304. }
  305. $tag = Tag::getByName($em, $keyword, true);
  306. if (!$version->getTags()->contains($tag)) {
  307. $version->addTag($tag);
  308. }
  309. }
  310. foreach ($existingTags as $tag) {
  311. $version->getTags()->removeElement($tag);
  312. }
  313. } elseif (count($version->getTags())) {
  314. $version->getTags()->clear();
  315. }
  316. $version->getAuthors()->clear();
  317. $version->setAuthorJson([]);
  318. if ($data->getAuthors()) {
  319. $authors = [];
  320. foreach ($data->getAuthors() as $authorData) {
  321. $author = [];
  322. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  323. if (isset($authorData[$field])) {
  324. $author[$field] = trim($authorData[$field]);
  325. if ('' === $author[$field]) {
  326. unset($author[$field]);
  327. }
  328. }
  329. }
  330. // skip authors with no information
  331. if (!isset($authorData['email']) && !isset($authorData['name'])) {
  332. continue;
  333. }
  334. $authors[] = $author;
  335. }
  336. $version->setAuthorJson($authors);
  337. }
  338. // handle links
  339. foreach ($this->supportedLinkTypes as $linkType => $opts) {
  340. $links = array();
  341. foreach ($data->{$opts['method']}() as $link) {
  342. $constraint = $link->getPrettyConstraint();
  343. if (false !== strpos($constraint, ',') && false !== strpos($constraint, '@')) {
  344. $constraint = preg_replace_callback('{([><]=?\s*[^@]+?)@([a-z]+)}i', function ($matches) {
  345. if ($matches[2] === 'stable') {
  346. return $matches[1];
  347. }
  348. return $matches[1].'-'.$matches[2];
  349. }, $constraint);
  350. }
  351. $links[$link->getTarget()] = $constraint;
  352. }
  353. foreach ($version->{'get'.$linkType}() as $link) {
  354. // clear links that have changed/disappeared (for updates)
  355. if (!isset($links[$link->getPackageName()]) || $links[$link->getPackageName()] !== $link->getPackageVersion()) {
  356. $version->{'get'.$linkType}()->removeElement($link);
  357. $em->remove($link);
  358. } else {
  359. // clear those that are already set
  360. unset($links[$link->getPackageName()]);
  361. }
  362. }
  363. foreach ($links as $linkPackageName => $linkPackageVersion) {
  364. $class = 'Packagist\WebBundle\Entity\\'.$opts['entity'];
  365. $link = new $class;
  366. $link->setPackageName($linkPackageName);
  367. $link->setPackageVersion($linkPackageVersion);
  368. $version->{'add'.$linkType.'Link'}($link);
  369. $link->setVersion($version);
  370. $em->persist($link);
  371. }
  372. }
  373. // handle suggests
  374. if ($suggests = $data->getSuggests()) {
  375. foreach ($version->getSuggest() as $link) {
  376. // clear links that have changed/disappeared (for updates)
  377. if (!isset($suggests[$link->getPackageName()]) || $suggests[$link->getPackageName()] !== $link->getPackageVersion()) {
  378. $version->getSuggest()->removeElement($link);
  379. $em->remove($link);
  380. } else {
  381. // clear those that are already set
  382. unset($suggests[$link->getPackageName()]);
  383. }
  384. }
  385. foreach ($suggests as $linkPackageName => $linkPackageVersion) {
  386. $link = new SuggestLink;
  387. $link->setPackageName($linkPackageName);
  388. $link->setPackageVersion($linkPackageVersion);
  389. $version->addSuggestLink($link);
  390. $link->setVersion($version);
  391. $em->persist($link);
  392. }
  393. } elseif (count($version->getSuggest())) {
  394. // clear existing suggests if present
  395. foreach ($version->getSuggest() as $link) {
  396. $em->remove($link);
  397. }
  398. $version->getSuggest()->clear();
  399. }
  400. return ['updated' => true, 'id' => $version->getId(), 'version' => strtolower($normVersion), 'object' => $version];
  401. }
  402. /**
  403. * Update the readme for $package from $repository.
  404. *
  405. * @param IOInterface $io
  406. * @param Package $package
  407. * @param VcsRepository $repository
  408. */
  409. private function updateReadme(IOInterface $io, Package $package, VcsRepository $repository)
  410. {
  411. try {
  412. $driver = $repository->getDriver();
  413. $composerInfo = $driver->getComposerInformation($driver->getRootIdentifier());
  414. if (isset($composerInfo['readme'])) {
  415. $readmeFile = $composerInfo['readme'];
  416. } else {
  417. $readmeFile = 'README.md';
  418. }
  419. $ext = substr($readmeFile, strrpos($readmeFile, '.'));
  420. if ($ext === $readmeFile) {
  421. $ext = '.txt';
  422. }
  423. switch ($ext) {
  424. case '.txt':
  425. $source = $driver->getFileContent($readmeFile, $driver->getRootIdentifier());
  426. if (!empty($source)) {
  427. $package->setReadme('<pre>' . htmlspecialchars($source) . '</pre>');
  428. }
  429. break;
  430. case '.md':
  431. $source = $driver->getFileContent($readmeFile, $driver->getRootIdentifier());
  432. $parser = new GithubMarkdown();
  433. $readme = $parser->parse($source);
  434. if (!empty($readme)) {
  435. $package->setReadme($this->prepareReadme($readme));
  436. }
  437. break;
  438. }
  439. } catch (\Exception $e) {
  440. // we ignore all errors for this minor function
  441. $io->write(
  442. 'Can not update readme. Error: ' . $e->getMessage(),
  443. true,
  444. IOInterface::VERBOSE
  445. );
  446. }
  447. }
  448. private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo, VcsRepository $repository)
  449. {
  450. $baseApiUrl = 'https://api.github.com/repos/'.$owner.'/'.$repo;
  451. $driver = $repository->getDriver();
  452. if (!$driver instanceof GitHubDriver) {
  453. return;
  454. }
  455. $repoData = $driver->getRepoData();
  456. try {
  457. $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]];
  458. $readme = $rfs->getContents('github.com', $baseApiUrl.'/readme', false, $opts);
  459. } catch (\Exception $e) {
  460. if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) {
  461. return;
  462. }
  463. // 404s just mean no readme present so we proceed with the rest
  464. }
  465. if (!empty($readme)) {
  466. $package->setReadme($this->prepareReadme($readme, true, $owner, $repo));
  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. /**
  485. * Prepare the readme by stripping elements and attributes that are not supported .
  486. *
  487. * @param string $readme
  488. * @param bool $isGithub
  489. * @param null $owner
  490. * @param null $repo
  491. * @return string
  492. */
  493. private function prepareReadme($readme, $isGithub = false, $owner = null, $repo = null)
  494. {
  495. $elements = array(
  496. 'p',
  497. 'br',
  498. 'small',
  499. 'strong', 'b',
  500. 'em', 'i',
  501. 'strike',
  502. 'sub', 'sup',
  503. 'ins', 'del',
  504. 'ol', 'ul', 'li',
  505. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  506. 'dl', 'dd', 'dt',
  507. 'pre', 'code', 'samp', 'kbd',
  508. 'q', 'blockquote', 'abbr', 'cite',
  509. 'table', 'thead', 'tbody', 'th', 'tr', 'td',
  510. 'a', 'span',
  511. 'img',
  512. 'details', 'summary',
  513. );
  514. $attributes = array(
  515. 'img.src', 'img.title', 'img.alt', 'img.width', 'img.height', 'img.style',
  516. 'a.href', 'a.target', 'a.rel', 'a.id',
  517. 'td.colspan', 'td.rowspan', 'th.colspan', 'th.rowspan',
  518. '*.class', 'details.open'
  519. );
  520. // detect base path if the github readme is located in a subfolder like docs/README.md
  521. $basePath = '';
  522. if ($isGithub && preg_match('{^<div id="readme" [^>]+?data-path="([^"]+)"}', $readme, $match) && false !== strpos($match[1], '/')) {
  523. $basePath = dirname($match[1]);
  524. }
  525. if ($basePath) {
  526. $basePath .= '/';
  527. }
  528. $config = \HTMLPurifier_Config::createDefault();
  529. $config->set('HTML.AllowedElements', implode(',', $elements));
  530. $config->set('HTML.AllowedAttributes', implode(',', $attributes));
  531. $config->set('Attr.EnableID', true);
  532. $config->set('Attr.AllowedFrameTargets', ['_blank']);
  533. // add custom HTML tag definitions
  534. $def = $config->getHTMLDefinition(true);
  535. $def->addElement('details', 'Block', 'Flow', 'Common', array(
  536. 'open' => 'Bool#open',
  537. ));
  538. $def->addElement('summary', 'Inline', 'Inline', 'Common');
  539. $purifier = new \HTMLPurifier($config);
  540. $readme = $purifier->purify($readme);
  541. libxml_use_internal_errors(true);
  542. $dom = new \DOMDocument();
  543. $dom->loadHTML('<?xml encoding="UTF-8">' . $readme);
  544. // Links can not be trusted, mark them nofollow and convert relative to absolute links
  545. $links = $dom->getElementsByTagName('a');
  546. foreach ($links as $link) {
  547. $link->setAttribute('rel', 'nofollow noindex noopener external');
  548. if ('#' === substr($link->getAttribute('href'), 0, 1)) {
  549. $link->setAttribute('href', '#user-content-'.substr($link->getAttribute('href'), 1));
  550. } elseif ('mailto:' === substr($link->getAttribute('href'), 0, 7)) {
  551. // do nothing
  552. } elseif ($isGithub && false === strpos($link->getAttribute('href'), '//')) {
  553. $link->setAttribute(
  554. 'href',
  555. 'https://github.com/'.$owner.'/'.$repo.'/blob/HEAD/'.$basePath.$link->getAttribute('href')
  556. );
  557. }
  558. }
  559. if ($isGithub) {
  560. // convert relative to absolute images
  561. $images = $dom->getElementsByTagName('img');
  562. foreach ($images as $img) {
  563. if (false === strpos($img->getAttribute('src'), '//')) {
  564. $img->setAttribute(
  565. 'src',
  566. 'https://raw.github.com/'.$owner.'/'.$repo.'/HEAD/'.$basePath.$img->getAttribute('src')
  567. );
  568. }
  569. }
  570. }
  571. // remove first page element if it's a <h1> or <h2>, because it's usually
  572. // the project name or the `README` string which we don't need
  573. $first = $dom->getElementsByTagName('body')->item(0);
  574. if ($first) {
  575. $first = $first->childNodes->item(0);
  576. }
  577. if ($first && ('h1' === $first->nodeName || 'h2' === $first->nodeName)) {
  578. $first->parentNode->removeChild($first);
  579. }
  580. $readme = $dom->saveHTML();
  581. $readme = substr($readme, strpos($readme, '<body>')+6);
  582. $readme = substr($readme, 0, strrpos($readme, '</body>'));
  583. libxml_use_internal_errors(false);
  584. libxml_clear_errors();
  585. return str_replace("\r\n", "\n", $readme);
  586. }
  587. private function sanitize($str)
  588. {
  589. // remove escape chars
  590. $str = preg_replace("{\x1B(?:\[.)?}u", '', $str);
  591. return preg_replace("{[\x01-\x1A]}u", '', $str);
  592. }
  593. }