Updater.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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\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. $deleteDate = clone $start;
  95. $deleteDate->modify('-1day');
  96. $em = $this->doctrine->getManager();
  97. $apc = extension_loaded('apcu');
  98. $rootIdentifier = null;
  99. if ($repository instanceof VcsRepository) {
  100. $cfg = $repository->getRepoConfig();
  101. if (isset($cfg['url']) && preg_match('{\bgithub\.com\b}', $cfg['url'])) {
  102. foreach ($package->getMaintainers() as $maintainer) {
  103. if (!($newGithubToken = $maintainer->getGithubToken())) {
  104. continue;
  105. }
  106. $valid = null;
  107. if ($apc) {
  108. $valid = apcu_fetch('is_token_valid_'.$maintainer->getUsernameCanonical());
  109. }
  110. if (true !== $valid) {
  111. $context = stream_context_create(['http' => ['header' => 'User-agent: packagist-token-check']]);
  112. $rate = json_decode(@file_get_contents('https://api.github.com/rate_limit?access_token='.$newGithubToken, false, $context), true);
  113. // invalid/outdated token, wipe it so we don't try it again
  114. if (!$rate && (strpos($http_response_header[0], '403') || strpos($http_response_header[0], '401'))) {
  115. $maintainer->setGithubToken(null);
  116. $em->flush($maintainer);
  117. continue;
  118. }
  119. }
  120. if ($apc) {
  121. apcu_store('is_token_valid_'.$maintainer->getUsernameCanonical(), true, 86400);
  122. }
  123. $io->setAuthentication('github.com', $newGithubToken, 'x-oauth-basic');
  124. break;
  125. }
  126. }
  127. $rootIdentifier = $repository->getDriver()->getRootIdentifier();
  128. }
  129. $versions = $repository->getPackages();
  130. usort($versions, function ($a, $b) {
  131. $aVersion = $a->getVersion();
  132. $bVersion = $b->getVersion();
  133. if ($aVersion === '9999999-dev' || 'dev-' === substr($aVersion, 0, 4)) {
  134. $aVersion = 'dev';
  135. }
  136. if ($bVersion === '9999999-dev' || 'dev-' === substr($bVersion, 0, 4)) {
  137. $bVersion = 'dev';
  138. }
  139. $aIsDev = $aVersion === 'dev' || substr($aVersion, -4) === '-dev';
  140. $bIsDev = $bVersion === 'dev' || substr($bVersion, -4) === '-dev';
  141. // push dev versions to the end
  142. if ($aIsDev !== $bIsDev) {
  143. return $aIsDev ? 1 : -1;
  144. }
  145. // equal versions are sorted by date
  146. if ($aVersion === $bVersion) {
  147. return $a->getReleaseDate() > $b->getReleaseDate() ? 1 : -1;
  148. }
  149. // the rest is sorted by version
  150. return version_compare($aVersion, $bVersion);
  151. });
  152. $versionRepository = $this->doctrine->getRepository('PackagistWebBundle:Version');
  153. if ($flags & self::DELETE_BEFORE) {
  154. foreach ($package->getVersions() as $version) {
  155. $versionRepository->remove($version);
  156. }
  157. $em->flush();
  158. $em->refresh($package);
  159. }
  160. $lastUpdated = true;
  161. $lastProcessed = null;
  162. foreach ($versions as $version) {
  163. if ($version instanceof AliasPackage) {
  164. continue;
  165. }
  166. if (preg_match($blacklist, $version->getName().' '.$version->getPrettyVersion())) {
  167. continue;
  168. }
  169. if ($lastProcessed && $lastProcessed->getVersion() === $version->getVersion()) {
  170. $io->write('Skipping version '.$version->getPrettyVersion().' (duplicate of '.$lastProcessed->getPrettyVersion().')', true, IOInterface::VERBOSE);
  171. continue;
  172. }
  173. $lastProcessed = $version;
  174. $lastUpdated = $this->updateInformation($package, $version, $flags, $rootIdentifier);
  175. if ($lastUpdated) {
  176. $em->flush();
  177. }
  178. }
  179. if (!$lastUpdated) {
  180. $em->flush();
  181. }
  182. // remove outdated versions
  183. foreach ($package->getVersions() as $version) {
  184. if ($version->getUpdatedAt() < $pruneDate) {
  185. if (!is_null($version->getSoftDeletedAt()) && $version->getSoftDeletedAt() < $deleteDate) {
  186. $versionRepository->remove($version);
  187. } else {
  188. // set it to be soft-deleted so next update that occurs after deleteDate (1day) if the
  189. // version is still missing it will be really removed
  190. $version->setSoftDeletedAt(new \DateTime);
  191. }
  192. }
  193. }
  194. if (preg_match('{^(?:git://|git@|https?://)github.com[:/]([^/]+)/(.+?)(?:\.git|/)?$}i', $package->getRepository(), $match) && $repository instanceof VcsRepository) {
  195. $this->updateGitHubInfo($rfs, $package, $match[1], $match[2], $repository);
  196. } else {
  197. $this->updateReadme($io, $package, $repository);
  198. }
  199. $package->setUpdatedAt(new \DateTime);
  200. $package->setCrawledAt(new \DateTime);
  201. $em->flush();
  202. if ($repository->hadInvalidBranches()) {
  203. 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');
  204. }
  205. }
  206. private function updateInformation(Package $package, PackageInterface $data, $flags, $rootIdentifier)
  207. {
  208. $em = $this->doctrine->getManager();
  209. $version = new Version();
  210. $normVersion = $data->getVersion();
  211. $existingVersion = $package->getVersion($normVersion);
  212. if ($existingVersion) {
  213. $source = $existingVersion->getSource();
  214. // update if the right flag is set, or the source reference has changed (re-tag or new commit on branch)
  215. if ($source['reference'] !== $data->getSourceReference() || ($flags & self::UPDATE_EQUAL_REFS)) {
  216. $version = $existingVersion;
  217. } else {
  218. // mark it updated to avoid it being pruned
  219. $existingVersion->setUpdatedAt(new \DateTime);
  220. $existingVersion->setSoftDeletedAt(null);
  221. return false;
  222. }
  223. }
  224. $version->setName($package->getName());
  225. $version->setVersion($data->getPrettyVersion());
  226. $version->setNormalizedVersion($normVersion);
  227. $version->setDevelopment($data->isDev());
  228. $em->persist($version);
  229. $descr = $this->sanitize($data->getDescription());
  230. $version->setDescription($descr);
  231. // update the package description only for the default branch
  232. if ($rootIdentifier === null || preg_replace('{dev-|-dev}', '', $version->getVersion()) === $rootIdentifier) {
  233. $package->setDescription($descr);
  234. }
  235. $version->setHomepage($data->getHomepage());
  236. $version->setLicense($data->getLicense() ?: array());
  237. $version->setPackage($package);
  238. $version->setUpdatedAt(new \DateTime);
  239. $version->setReleasedAt($data->getReleaseDate());
  240. if ($data->getSourceType()) {
  241. $source['type'] = $data->getSourceType();
  242. $source['url'] = $data->getSourceUrl();
  243. $source['reference'] = $data->getSourceReference();
  244. $version->setSource($source);
  245. } else {
  246. $version->setSource(null);
  247. }
  248. if ($data->getDistType()) {
  249. $dist['type'] = $data->getDistType();
  250. $dist['url'] = $data->getDistUrl();
  251. $dist['reference'] = $data->getDistReference();
  252. $dist['shasum'] = $data->getDistSha1Checksum();
  253. $version->setDist($dist);
  254. } else {
  255. $version->setDist(null);
  256. }
  257. if ($data->getType()) {
  258. $type = $this->sanitize($data->getType());
  259. $version->setType($type);
  260. if ($type !== $package->getType()) {
  261. $package->setType($type);
  262. }
  263. }
  264. $version->setTargetDir($data->getTargetDir());
  265. $version->setAutoload($data->getAutoload());
  266. $version->setExtra($data->getExtra());
  267. $version->setBinaries($data->getBinaries());
  268. $version->setIncludePaths($data->getIncludePaths());
  269. $version->setSupport($data->getSupport());
  270. if ($data->getKeywords()) {
  271. $keywords = array();
  272. foreach ($data->getKeywords() as $keyword) {
  273. $keywords[mb_strtolower($keyword, 'UTF-8')] = $keyword;
  274. }
  275. $existingTags = [];
  276. foreach ($version->getTags() as $tag) {
  277. $existingTags[mb_strtolower($tag->getName(), 'UTF-8')] = $tag;
  278. }
  279. foreach ($keywords as $tagKey => $keyword) {
  280. if (isset($existingTags[$tagKey])) {
  281. unset($existingTags[$tagKey]);
  282. continue;
  283. }
  284. $tag = Tag::getByName($em, $keyword, true);
  285. if (!$version->getTags()->contains($tag)) {
  286. $version->addTag($tag);
  287. }
  288. }
  289. foreach ($existingTags as $tag) {
  290. $version->getTags()->removeElement($tag);
  291. }
  292. } elseif (count($version->getTags())) {
  293. $version->getTags()->clear();
  294. }
  295. $authorRepository = $this->doctrine->getRepository('PackagistWebBundle:Author');
  296. $version->getAuthors()->clear();
  297. if ($data->getAuthors()) {
  298. foreach ($data->getAuthors() as $authorData) {
  299. $author = null;
  300. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  301. if (isset($authorData[$field])) {
  302. $authorData[$field] = trim($authorData[$field]);
  303. if ('' === $authorData[$field]) {
  304. $authorData[$field] = null;
  305. }
  306. } else {
  307. $authorData[$field] = null;
  308. }
  309. }
  310. // skip authors with no information
  311. if (!isset($authorData['email']) && !isset($authorData['name'])) {
  312. continue;
  313. }
  314. $author = $authorRepository->findOneBy(array(
  315. 'email' => $authorData['email'],
  316. 'name' => $authorData['name'],
  317. 'homepage' => $authorData['homepage'],
  318. 'role' => $authorData['role'],
  319. ));
  320. if (!$author) {
  321. $author = new Author();
  322. $em->persist($author);
  323. }
  324. foreach (array('email', 'name', 'homepage', 'role') as $field) {
  325. if (isset($authorData[$field])) {
  326. $author->{'set'.$field}($authorData[$field]);
  327. }
  328. }
  329. // only update the author timestamp once a month at most as the value is kinda unused
  330. if ($author->getUpdatedAt() === null || $author->getUpdatedAt()->getTimestamp() < time() - 86400 * 30) {
  331. $author->setUpdatedAt(new \DateTime);
  332. }
  333. if (!$version->getAuthors()->contains($author)) {
  334. $version->addAuthor($author);
  335. }
  336. if (!$author->getVersions()->contains($version)) {
  337. $author->addVersion($version);
  338. }
  339. }
  340. }
  341. // handle links
  342. foreach ($this->supportedLinkTypes as $linkType => $opts) {
  343. $links = array();
  344. foreach ($data->{$opts['method']}() as $link) {
  345. $constraint = $link->getPrettyConstraint();
  346. if (false !== strpos($constraint, ',') && false !== strpos($constraint, '@')) {
  347. $constraint = preg_replace_callback('{([><]=?\s*[^@]+?)@([a-z]+)}i', function ($matches) {
  348. if ($matches[2] === 'stable') {
  349. return $matches[1];
  350. }
  351. return $matches[1].'-'.$matches[2];
  352. }, $constraint);
  353. }
  354. $links[$link->getTarget()] = $constraint;
  355. }
  356. foreach ($version->{'get'.$linkType}() as $link) {
  357. // clear links that have changed/disappeared (for updates)
  358. if (!isset($links[$link->getPackageName()]) || $links[$link->getPackageName()] !== $link->getPackageVersion()) {
  359. $version->{'get'.$linkType}()->removeElement($link);
  360. $em->remove($link);
  361. } else {
  362. // clear those that are already set
  363. unset($links[$link->getPackageName()]);
  364. }
  365. }
  366. foreach ($links as $linkPackageName => $linkPackageVersion) {
  367. $class = 'Packagist\WebBundle\Entity\\'.$opts['entity'];
  368. $link = new $class;
  369. $link->setPackageName($linkPackageName);
  370. $link->setPackageVersion($linkPackageVersion);
  371. $version->{'add'.$linkType.'Link'}($link);
  372. $link->setVersion($version);
  373. $em->persist($link);
  374. }
  375. }
  376. // handle suggests
  377. if ($suggests = $data->getSuggests()) {
  378. foreach ($version->getSuggest() as $link) {
  379. // clear links that have changed/disappeared (for updates)
  380. if (!isset($suggests[$link->getPackageName()]) || $suggests[$link->getPackageName()] !== $link->getPackageVersion()) {
  381. $version->getSuggest()->removeElement($link);
  382. $em->remove($link);
  383. } else {
  384. // clear those that are already set
  385. unset($suggests[$link->getPackageName()]);
  386. }
  387. }
  388. foreach ($suggests as $linkPackageName => $linkPackageVersion) {
  389. $link = new SuggestLink;
  390. $link->setPackageName($linkPackageName);
  391. $link->setPackageVersion($linkPackageVersion);
  392. $version->addSuggestLink($link);
  393. $link->setVersion($version);
  394. $em->persist($link);
  395. }
  396. } elseif (count($version->getSuggest())) {
  397. // clear existing suggests if present
  398. foreach ($version->getSuggest() as $link) {
  399. $em->remove($link);
  400. }
  401. $version->getSuggest()->clear();
  402. }
  403. if (!$package->getVersions()->contains($version)) {
  404. $package->addVersions($version);
  405. }
  406. return true;
  407. }
  408. /**
  409. * Update the readme for $package from $repository.
  410. *
  411. * @param IOInterface $io
  412. * @param Package $package
  413. * @param VcsRepository $repository
  414. */
  415. private function updateReadme(IOInterface $io, Package $package, VcsRepository $repository)
  416. {
  417. try {
  418. $driver = $repository->getDriver();
  419. $composerInfo = $driver->getComposerInformation($driver->getRootIdentifier());
  420. if (isset($composerInfo['readme'])) {
  421. $readmeFile = $composerInfo['readme'];
  422. } else {
  423. $readmeFile = 'README.md';
  424. }
  425. $ext = substr($readmeFile, strrpos($readmeFile, '.'));
  426. if ($ext === $readmeFile) {
  427. $ext = '.txt';
  428. }
  429. switch ($ext) {
  430. case '.txt':
  431. $source = $driver->getFileContent($readmeFile, $driver->getRootIdentifier());
  432. if (!empty($source)) {
  433. $package->setReadme('<pre>' . htmlspecialchars($source) . '</pre>');
  434. }
  435. break;
  436. case '.md':
  437. $source = $driver->getFileContent($readmeFile, $driver->getRootIdentifier());
  438. $parser = new GithubMarkdown();
  439. $readme = $parser->parse($source);
  440. if (!empty($readme)) {
  441. $package->setReadme($this->prepareReadme($readme));
  442. }
  443. break;
  444. }
  445. } catch (\Exception $e) {
  446. // we ignore all errors for this minor function
  447. $io->write(
  448. 'Can not update readme. Error: ' . $e->getMessage(),
  449. true,
  450. IOInterface::VERBOSE
  451. );
  452. }
  453. }
  454. private function updateGitHubInfo(RemoteFilesystem $rfs, Package $package, $owner, $repo, VcsRepository $repository)
  455. {
  456. $baseApiUrl = 'https://api.github.com/repos/'.$owner.'/'.$repo;
  457. $driver = $repository->getDriver();
  458. if (!$driver instanceof GitHubDriver) {
  459. return;
  460. }
  461. $repoData = $driver->getRepoData();
  462. try {
  463. $opts = ['http' => ['header' => ['Accept: application/vnd.github.v3.html']]];
  464. $readme = $rfs->getContents('github.com', $baseApiUrl.'/readme', false, $opts);
  465. } catch (\Exception $e) {
  466. if (!$e instanceof \Composer\Downloader\TransportException || $e->getCode() !== 404) {
  467. return;
  468. }
  469. // 404s just mean no readme present so we proceed with the rest
  470. }
  471. if (!empty($readme)) {
  472. $package->setReadme($this->prepareReadme($readme, true, $owner, $repo));
  473. }
  474. if (!empty($repoData['language'])) {
  475. $package->setLanguage($repoData['language']);
  476. }
  477. if (isset($repoData['stargazers_count'])) {
  478. $package->setGitHubStars($repoData['stargazers_count']);
  479. }
  480. if (isset($repoData['subscribers_count'])) {
  481. $package->setGitHubWatches($repoData['subscribers_count']);
  482. }
  483. if (isset($repoData['network_count'])) {
  484. $package->setGitHubForks($repoData['network_count']);
  485. }
  486. if (isset($repoData['open_issues_count'])) {
  487. $package->setGitHubOpenIssues($repoData['open_issues_count']);
  488. }
  489. }
  490. /**
  491. * Prepare the readme by stripping elements and attributes that are not supported .
  492. *
  493. * @param string $readme
  494. * @param bool $isGithub
  495. * @param null $owner
  496. * @param null $repo
  497. * @return string
  498. */
  499. private function prepareReadme($readme, $isGithub = false, $owner = null, $repo = null)
  500. {
  501. $elements = array(
  502. 'p',
  503. 'br',
  504. 'small',
  505. 'strong', 'b',
  506. 'em', 'i',
  507. 'strike',
  508. 'sub', 'sup',
  509. 'ins', 'del',
  510. 'ol', 'ul', 'li',
  511. 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
  512. 'dl', 'dd', 'dt',
  513. 'pre', 'code', 'samp', 'kbd',
  514. 'q', 'blockquote', 'abbr', 'cite',
  515. 'table', 'thead', 'tbody', 'th', 'tr', 'td',
  516. 'a', 'span',
  517. 'img',
  518. );
  519. $attributes = array(
  520. 'img.src', 'img.title', 'img.alt', 'img.width', 'img.height', 'img.style',
  521. 'a.href', 'a.target', 'a.rel', 'a.id',
  522. 'td.colspan', 'td.rowspan', 'th.colspan', 'th.rowspan',
  523. '*.class'
  524. );
  525. $config = \HTMLPurifier_Config::createDefault();
  526. $config->set('HTML.AllowedElements', implode(',', $elements));
  527. $config->set('HTML.AllowedAttributes', implode(',', $attributes));
  528. $config->set('Attr.EnableID', true);
  529. $config->set('Attr.AllowedFrameTargets', ['_blank']);
  530. $purifier = new \HTMLPurifier($config);
  531. $readme = $purifier->purify($readme);
  532. $dom = new \DOMDocument();
  533. $dom->loadHTML('<?xml encoding="UTF-8">' . $readme);
  534. // Links can not be trusted, mark them nofollow and convert relative to absolute links
  535. $links = $dom->getElementsByTagName('a');
  536. foreach ($links as $link) {
  537. $link->setAttribute('rel', 'nofollow noindex noopener external');
  538. if ('#' === substr($link->getAttribute('href'), 0, 1)) {
  539. $link->setAttribute('href', '#user-content-'.substr($link->getAttribute('href'), 1));
  540. } elseif ('mailto:' === substr($link->getAttribute('href'), 0, 7)) {
  541. // do nothing
  542. } elseif ($isGithub && false === strpos($link->getAttribute('href'), '//')) {
  543. $link->setAttribute(
  544. 'href',
  545. 'https://github.com/'.$owner.'/'.$repo.'/blob/HEAD/'.$link->getAttribute('href')
  546. );
  547. }
  548. }
  549. if ($isGithub) {
  550. // convert relative to absolute images
  551. $images = $dom->getElementsByTagName('img');
  552. foreach ($images as $img) {
  553. if (false === strpos($img->getAttribute('src'), '//')) {
  554. $img->setAttribute(
  555. 'src',
  556. 'https://raw.github.com/'.$owner.'/'.$repo.'/HEAD/'.$img->getAttribute('src')
  557. );
  558. }
  559. }
  560. }
  561. // remove first page element if it's a <h1> or <h2>, because it's usually
  562. // the project name or the `README` string which we don't need
  563. $first = $dom->getElementsByTagName('body')->item(0);
  564. if ($first) {
  565. $first = $first->childNodes->item(0);
  566. }
  567. if ($first && ('h1' === $first->nodeName || 'h2' === $first->nodeName)) {
  568. $first->parentNode->removeChild($first);
  569. }
  570. $readme = $dom->saveHTML();
  571. $readme = substr($readme, strpos($readme, '<body>')+6);
  572. $readme = substr($readme, 0, strrpos($readme, '</body>'));
  573. return str_replace("\r\n", "\n", $readme);
  574. }
  575. private function sanitize($str)
  576. {
  577. // remove escape chars
  578. $str = preg_replace("{\x1B(?:\[.)?}u", '', $str);
  579. return preg_replace("{[\x01-\x1A]}u", '', $str);
  580. }
  581. }