Updater.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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}', $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. return ['updated' => true, 'id' => $version->getId(), 'version' => strtolower($normVersion), 'object' => $version];
  239. } else {
  240. return ['updated' => false, 'id' => $existingVersion['id'], 'version' => strtolower($normVersion), 'object' => null];
  241. }
  242. }
  243. $version->setName($package->getName());
  244. $version->setVersion($data->getPrettyVersion());
  245. $version->setNormalizedVersion($normVersion);
  246. $version->setDevelopment($data->isDev());
  247. $em->persist($version);
  248. $descr = $this->sanitize($data->getDescription());
  249. $version->setDescription($descr);
  250. // update the package description only for the default branch
  251. if ($rootIdentifier === null || preg_replace('{dev-|(\.x)?-dev}', '', $version->getVersion()) === $rootIdentifier) {
  252. $package->setDescription($descr);
  253. }
  254. $version->setHomepage($data->getHomepage());
  255. $version->setLicense($data->getLicense() ?: array());
  256. $version->setPackage($package);
  257. $version->setUpdatedAt(new \DateTime);
  258. $version->setSoftDeletedAt(null);
  259. $version->setReleasedAt($data->getReleaseDate());
  260. if ($data->getSourceType()) {
  261. $source['type'] = $data->getSourceType();
  262. $source['url'] = $data->getSourceUrl();
  263. $source['reference'] = $data->getSourceReference();
  264. $version->setSource($source);
  265. } else {
  266. $version->setSource(null);
  267. }
  268. if ($data->getDistType()) {
  269. $dist['type'] = $data->getDistType();
  270. $dist['url'] = $data->getDistUrl();
  271. $dist['reference'] = $data->getDistReference();
  272. $dist['shasum'] = $data->getDistSha1Checksum();
  273. $version->setDist($dist);
  274. } else {
  275. $version->setDist(null);
  276. }
  277. if ($data->getType()) {
  278. $type = $this->sanitize($data->getType());
  279. $version->setType($type);
  280. if ($type !== $package->getType()) {
  281. $package->setType($type);
  282. }
  283. }
  284. $version->setTargetDir($data->getTargetDir());
  285. $version->setAutoload($data->getAutoload());
  286. $version->setExtra($data->getExtra());
  287. $version->setBinaries($data->getBinaries());
  288. $version->setIncludePaths($data->getIncludePaths());
  289. $version->setSupport($data->getSupport());
  290. if ($data->getKeywords()) {
  291. $keywords = array();
  292. foreach ($data->getKeywords() as $keyword) {
  293. $keywords[mb_strtolower($keyword, 'UTF-8')] = $keyword;
  294. }
  295. $existingTags = [];
  296. foreach ($version->getTags() as $tag) {
  297. $existingTags[mb_strtolower($tag->getName(), 'UTF-8')] = $tag;
  298. }
  299. foreach ($keywords as $tagKey => $keyword) {
  300. if (isset($existingTags[$tagKey])) {
  301. unset($existingTags[$tagKey]);
  302. continue;
  303. }
  304. $tag = Tag::getByName($em, $keyword, true);
  305. if (!$version->getTags()->contains($tag)) {
  306. $version->addTag($tag);
  307. }
  308. }
  309. foreach ($existingTags as $tag) {
  310. $version->getTags()->removeElement($tag);
  311. }
  312. } elseif (count($version->getTags())) {
  313. $version->getTags()->clear();
  314. }
  315. $version->getAuthors()->clear();
  316. $version->setAuthorJson([]);
  317. if ($data->getAuthors()) {
  318. $authors = [];
  319. foreach ($data->getAuthors() as $authorData) {
  320. $author = [];
  321. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  322. if (isset($authorData[$field])) {
  323. $author[$field] = trim($authorData[$field]);
  324. if ('' === $author[$field]) {
  325. unset($author[$field]);
  326. }
  327. }
  328. }
  329. // skip authors with no information
  330. if (!isset($authorData['email']) && !isset($authorData['name'])) {
  331. continue;
  332. }
  333. $authors[] = $author;
  334. }
  335. $version->setAuthorJson($authors);
  336. }
  337. // handle links
  338. foreach ($this->supportedLinkTypes as $linkType => $opts) {
  339. $links = array();
  340. foreach ($data->{$opts['method']}() as $link) {
  341. $constraint = $link->getPrettyConstraint();
  342. if (false !== strpos($constraint, ',') && false !== strpos($constraint, '@')) {
  343. $constraint = preg_replace_callback('{([><]=?\s*[^@]+?)@([a-z]+)}i', function ($matches) {
  344. if ($matches[2] === 'stable') {
  345. return $matches[1];
  346. }
  347. return $matches[1].'-'.$matches[2];
  348. }, $constraint);
  349. }
  350. $links[$link->getTarget()] = $constraint;
  351. }
  352. foreach ($version->{'get'.$linkType}() as $link) {
  353. // clear links that have changed/disappeared (for updates)
  354. if (!isset($links[$link->getPackageName()]) || $links[$link->getPackageName()] !== $link->getPackageVersion()) {
  355. $version->{'get'.$linkType}()->removeElement($link);
  356. $em->remove($link);
  357. } else {
  358. // clear those that are already set
  359. unset($links[$link->getPackageName()]);
  360. }
  361. }
  362. foreach ($links as $linkPackageName => $linkPackageVersion) {
  363. $class = 'Packagist\WebBundle\Entity\\'.$opts['entity'];
  364. $link = new $class;
  365. $link->setPackageName($linkPackageName);
  366. $link->setPackageVersion($linkPackageVersion);
  367. $version->{'add'.$linkType.'Link'}($link);
  368. $link->setVersion($version);
  369. $em->persist($link);
  370. }
  371. }
  372. // handle suggests
  373. if ($suggests = $data->getSuggests()) {
  374. foreach ($version->getSuggest() as $link) {
  375. // clear links that have changed/disappeared (for updates)
  376. if (!isset($suggests[$link->getPackageName()]) || $suggests[$link->getPackageName()] !== $link->getPackageVersion()) {
  377. $version->getSuggest()->removeElement($link);
  378. $em->remove($link);
  379. } else {
  380. // clear those that are already set
  381. unset($suggests[$link->getPackageName()]);
  382. }
  383. }
  384. foreach ($suggests as $linkPackageName => $linkPackageVersion) {
  385. $link = new SuggestLink;
  386. $link->setPackageName($linkPackageName);
  387. $link->setPackageVersion($linkPackageVersion);
  388. $version->addSuggestLink($link);
  389. $link->setVersion($version);
  390. $em->persist($link);
  391. }
  392. } elseif (count($version->getSuggest())) {
  393. // clear existing suggests if present
  394. foreach ($version->getSuggest() as $link) {
  395. $em->remove($link);
  396. }
  397. $version->getSuggest()->clear();
  398. }
  399. return ['updated' => true, 'id' => $version->getId(), 'version' => strtolower($normVersion), 'object' => $version];
  400. }
  401. /**
  402. * Update the readme for $package from $repository.
  403. *
  404. * @param IOInterface $io
  405. * @param Package $package
  406. * @param VcsRepository $repository
  407. */
  408. private function updateReadme(IOInterface $io, Package $package, VcsRepository $repository)
  409. {
  410. try {
  411. $driver = $repository->getDriver();
  412. $composerInfo = $driver->getComposerInformation($driver->getRootIdentifier());
  413. if (isset($composerInfo['readme'])) {
  414. $readmeFile = $composerInfo['readme'];
  415. } else {
  416. $readmeFile = 'README.md';
  417. }
  418. $ext = substr($readmeFile, strrpos($readmeFile, '.'));
  419. if ($ext === $readmeFile) {
  420. $ext = '.txt';
  421. }
  422. switch ($ext) {
  423. case '.txt':
  424. $source = $driver->getFileContent($readmeFile, $driver->getRootIdentifier());
  425. if (!empty($source)) {
  426. $package->setReadme('<pre>' . htmlspecialchars($source) . '</pre>');
  427. }
  428. break;
  429. case '.md':
  430. $source = $driver->getFileContent($readmeFile, $driver->getRootIdentifier());
  431. $parser = new GithubMarkdown();
  432. $readme = $parser->parse($source);
  433. if (!empty($readme)) {
  434. $package->setReadme($this->prepareReadme($readme));
  435. }
  436. break;
  437. }
  438. } catch (\Exception $e) {
  439. // we ignore all errors for this minor function
  440. $io->write(
  441. 'Can not update readme. Error: ' . $e->getMessage(),
  442. true,
  443. IOInterface::VERBOSE
  444. );
  445. }
  446. }
  447. private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo, VcsRepository $repository)
  448. {
  449. $baseApiUrl = 'https://api.github.com/repos/'.$owner.'/'.$repo;
  450. $driver = $repository->getDriver();
  451. if (!$driver instanceof GitHubDriver) {
  452. return;
  453. }
  454. $repoData = $driver->getRepoData();
  455. try {
  456. $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]];
  457. $readme = $rfs->getContents('github.com', $baseApiUrl.'/readme', false, $opts);
  458. } catch (\Exception $e) {
  459. if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) {
  460. return;
  461. }
  462. // 404s just mean no readme present so we proceed with the rest
  463. }
  464. if (!empty($readme)) {
  465. $package->setReadme($this->prepareReadme($readme, true, $owner, $repo));
  466. }
  467. if (!empty($repoData['language'])) {
  468. $package->setLanguage($repoData['language']);
  469. }
  470. if (isset($repoData['stargazers_count'])) {
  471. $package->setGitHubStars($repoData['stargazers_count']);
  472. }
  473. if (isset($repoData['subscribers_count'])) {
  474. $package->setGitHubWatches($repoData['subscribers_count']);
  475. }
  476. if (isset($repoData['network_count'])) {
  477. $package->setGitHubForks($repoData['network_count']);
  478. }
  479. if (isset($repoData['open_issues_count'])) {
  480. $package->setGitHubOpenIssues($repoData['open_issues_count']);
  481. }
  482. }
  483. /**
  484. * Prepare the readme by stripping elements and attributes that are not supported .
  485. *
  486. * @param string $readme
  487. * @param bool $isGithub
  488. * @param null $owner
  489. * @param null $repo
  490. * @return string
  491. */
  492. private function prepareReadme($readme, $isGithub = false, $owner = null, $repo = null)
  493. {
  494. $elements = array(
  495. 'p',
  496. 'br',
  497. 'small',
  498. 'strong', 'b',
  499. 'em', 'i',
  500. 'strike',
  501. 'sub', 'sup',
  502. 'ins', 'del',
  503. 'ol', 'ul', 'li',
  504. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  505. 'dl', 'dd', 'dt',
  506. 'pre', 'code', 'samp', 'kbd',
  507. 'q', 'blockquote', 'abbr', 'cite',
  508. 'table', 'thead', 'tbody', 'th', 'tr', 'td',
  509. 'a', 'span',
  510. 'img',
  511. 'details', 'summary',
  512. );
  513. $attributes = array(
  514. 'img.src', 'img.title', 'img.alt', 'img.width', 'img.height', 'img.style',
  515. 'a.href', 'a.target', 'a.rel', 'a.id',
  516. 'td.colspan', 'td.rowspan', 'th.colspan', 'th.rowspan',
  517. '*.class', 'details.open'
  518. );
  519. // detect base path if the github readme is located in a subfolder like docs/README.md
  520. $basePath = '';
  521. if ($isGithub && preg_match('{^<div id="readme" [^>]+?data-path="([^"]+)"}', $readme, $match) && false !== strpos($match[1], '/')) {
  522. $basePath = dirname($match[1]);
  523. }
  524. if ($basePath) {
  525. $basePath .= '/';
  526. }
  527. $config = \HTMLPurifier_Config::createDefault();
  528. $config->set('HTML.AllowedElements', implode(',', $elements));
  529. $config->set('HTML.AllowedAttributes', implode(',', $attributes));
  530. $config->set('Attr.EnableID', true);
  531. $config->set('Attr.AllowedFrameTargets', ['_blank']);
  532. // add custom HTML tag definitions
  533. $def = $config->getHTMLDefinition(true);
  534. $def->addElement('details', 'Block', 'Flow', 'Common', array(
  535. 'open' => 'Bool#open',
  536. ));
  537. $def->addElement('summary', 'Inline', 'Inline', 'Common');
  538. $purifier = new \HTMLPurifier($config);
  539. $readme = $purifier->purify($readme);
  540. libxml_use_internal_errors(true);
  541. $dom = new \DOMDocument();
  542. $dom->loadHTML('<?xml encoding="UTF-8">' . $readme);
  543. // Links can not be trusted, mark them nofollow and convert relative to absolute links
  544. $links = $dom->getElementsByTagName('a');
  545. foreach ($links as $link) {
  546. $link->setAttribute('rel', 'nofollow noindex noopener external');
  547. if ('#' === substr($link->getAttribute('href'), 0, 1)) {
  548. $link->setAttribute('href', '#user-content-'.substr($link->getAttribute('href'), 1));
  549. } elseif ('mailto:' === substr($link->getAttribute('href'), 0, 7)) {
  550. // do nothing
  551. } elseif ($isGithub && false === strpos($link->getAttribute('href'), '//')) {
  552. $link->setAttribute(
  553. 'href',
  554. 'https://github.com/'.$owner.'/'.$repo.'/blob/HEAD/'.$basePath.$link->getAttribute('href')
  555. );
  556. }
  557. }
  558. if ($isGithub) {
  559. // convert relative to absolute images
  560. $images = $dom->getElementsByTagName('img');
  561. foreach ($images as $img) {
  562. if (false === strpos($img->getAttribute('src'), '//')) {
  563. $img->setAttribute(
  564. 'src',
  565. 'https://raw.github.com/'.$owner.'/'.$repo.'/HEAD/'.$basePath.$img->getAttribute('src')
  566. );
  567. }
  568. }
  569. }
  570. // remove first page element if it's a <h1> or <h2>, because it's usually
  571. // the project name or the `README` string which we don't need
  572. $first = $dom->getElementsByTagName('body')->item(0);
  573. if ($first) {
  574. $first = $first->childNodes->item(0);
  575. }
  576. if ($first && ('h1' === $first->nodeName || 'h2' === $first->nodeName)) {
  577. $first->parentNode->removeChild($first);
  578. }
  579. $readme = $dom->saveHTML();
  580. $readme = substr($readme, strpos($readme, '<body>')+6);
  581. $readme = substr($readme, 0, strrpos($readme, '</body>'));
  582. libxml_use_internal_errors(false);
  583. libxml_clear_errors();
  584. return str_replace("\r\n", "\n", $readme);
  585. }
  586. private function sanitize($str)
  587. {
  588. // remove escape chars
  589. $str = preg_replace("{\x1B(?:\[.)?}u", '', $str);
  590. return preg_replace("{[\x01-\x1A]}u", '', $str);
  591. }
  592. }