ApiController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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\Controller;
  12. use Composer\Console\HtmlOutputFormatter;
  13. use Composer\Factory;
  14. use Composer\IO\BufferIO;
  15. use Composer\Package\Loader\ArrayLoader;
  16. use Composer\Package\Loader\ValidatingArrayLoader;
  17. use Composer\Repository\InvalidRepositoryException;
  18. use Composer\Repository\VcsRepository;
  19. use Packagist\WebBundle\Entity\Package;
  20. use Packagist\WebBundle\Entity\User;
  21. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  24. use Symfony\Component\Console\Output\OutputInterface;
  25. use Symfony\Component\HttpFoundation\JsonResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  29. /**
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. */
  32. class ApiController extends Controller
  33. {
  34. /**
  35. * @Route("/packages.json", name="packages", defaults={"_format" = "json"})
  36. * @Method({"GET"})
  37. */
  38. public function packagesAction()
  39. {
  40. // fallback if any of the dumped files exist
  41. $rootJson = $this->container->getParameter('kernel.root_dir').'/../web/packages_root.json';
  42. if (file_exists($rootJson)) {
  43. return new Response(file_get_contents($rootJson));
  44. }
  45. $rootJson = $this->container->getParameter('kernel.root_dir').'/../web/packages.json';
  46. if (file_exists($rootJson)) {
  47. return new Response(file_get_contents($rootJson));
  48. }
  49. $this->get('logger')->alert('packages.json is missing and the fallback controller is being hit, you need to use app/console packagist:dump');
  50. return new Response('Horrible misconfiguration or the dumper script messed up, you need to use app/console packagist:dump', 404);
  51. }
  52. /**
  53. * @Route("/api/create-package", name="generic_create", defaults={"_format" = "json"})
  54. * @Method({"POST"})
  55. */
  56. public function createPackageAction(Request $request)
  57. {
  58. $payload = json_decode($request->getContent(), true);
  59. if (!$payload) {
  60. return new JsonResponse(array('status' => 'error', 'message' => 'Missing payload parameter'), 406);
  61. }
  62. $url = $payload['repository']['url'];
  63. $package = new Package;
  64. $package->setEntityRepository($this->getDoctrine()->getRepository('PackagistWebBundle:Package'));
  65. $package->setRouter($this->get('router'));
  66. $user = $this->findUser($request);
  67. $package->addMaintainer($user);
  68. $package->setRepository($url);
  69. $errors = $this->get('validator')->validate($package);
  70. if (count($errors) > 0) {
  71. $errorArray = array();
  72. foreach ($errors as $error) {
  73. $errorArray[$error->getPropertyPath()] = $error->getMessage();
  74. }
  75. return new JsonResponse(array('status' => 'error', 'message' => $errorArray), 406);
  76. }
  77. try {
  78. $em = $this->getDoctrine()->getManager();
  79. $em->persist($package);
  80. $em->flush();
  81. } catch (\Exception $e) {
  82. $this->get('logger')->critical($e->getMessage(), array('exception', $e));
  83. return new JsonResponse(array('status' => 'error', 'message' => 'Error saving package'), 500);
  84. }
  85. return new JsonResponse(array('status' => 'success'), 202);
  86. }
  87. /**
  88. * @Route("/api/update-package", name="generic_postreceive", defaults={"_format" = "json"})
  89. * @Route("/api/github", name="github_postreceive", defaults={"_format" = "json"})
  90. * @Route("/api/bitbucket", name="bitbucket_postreceive", defaults={"_format" = "json"})
  91. * @Method({"POST"})
  92. */
  93. public function updatePackageAction(Request $request)
  94. {
  95. // parse the payload
  96. $payload = json_decode($request->request->get('payload'), true);
  97. if (!$payload && $request->headers->get('Content-Type') === 'application/json') {
  98. $payload = json_decode($request->getContent(), true);
  99. }
  100. if (!$payload) {
  101. return new JsonResponse(array('status' => 'error', 'message' => 'Missing payload parameter'), 406);
  102. }
  103. if (isset($payload['project']['git_http_url'])) { // gitlab event payload
  104. $urlRegex = '{^(?:ssh://git@|https?://|git://|git@)?(?P<host>[a-z0-9.-]+)(?::[0-9]+/|[:/])(?P<path>[\w.-]+(?:/[\w.-]+?)+)(?:\.git|/)?$}i';
  105. $url = $payload['project']['git_http_url'];
  106. } elseif (isset($payload['repository']['url'])) { // github/anything hook
  107. $urlRegex = '{^(?:ssh://git@|https?://|git://|git@)?(?P<host>[a-z0-9.-]+)(?::[0-9]+/|[:/])(?P<path>[\w.-]+(?:/[\w.-]+?)+)(?:\.git|/)?$}i';
  108. $url = $payload['repository']['url'];
  109. $url = str_replace('https://api.github.com/repos', 'https://github.com', $url);
  110. } elseif (isset($payload['repository']['links']['html']['href'])) { // bitbucket push event payload
  111. $urlRegex = '{^(?:https?://|git://|git@)?(?:api\.)?(?P<host>bitbucket\.org)[/:](?P<path>[\w.-]+/[\w.-]+?)(\.git)?/?$}i';
  112. $url = $payload['repository']['links']['html']['href'];
  113. } elseif (isset($payload['canon_url']) && isset($payload['repository']['absolute_url'])) { // bitbucket post hook (deprecated)
  114. $urlRegex = '{^(?:https?://|git://|git@)?(?P<host>bitbucket\.org)[/:](?P<path>[\w.-]+/[\w.-]+?)(\.git)?/?$}i';
  115. $url = $payload['canon_url'].$payload['repository']['absolute_url'];
  116. } else {
  117. return new JsonResponse(array('status' => 'error', 'message' => 'Missing or invalid payload'), 406);
  118. }
  119. return $this->receivePost($request, $url, $urlRegex);
  120. }
  121. /**
  122. * @Route(
  123. * "/api/packages/{package}",
  124. * name="api_edit_package",
  125. * requirements={"package"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?"},
  126. * defaults={"_format" = "json"}
  127. * )
  128. * @ParamConverter("package", options={"mapping": {"package": "name"}})
  129. * @Method({"PUT"})
  130. */
  131. public function editPackageAction(Request $request, Package $package)
  132. {
  133. $user = $this->findUser($request);
  134. if (!$package->getMaintainers()->contains($user) && !$this->isGranted('ROLE_EDIT_PACKAGES')) {
  135. throw new AccessDeniedException;
  136. }
  137. $payload = json_decode($request->request->get('payload'), true);
  138. if (!$payload && $request->headers->get('Content-Type') === 'application/json') {
  139. $payload = json_decode($request->getContent(), true);
  140. }
  141. $package->setRepository($payload['repository']);
  142. $errors = $this->get('validator')->validate($package, array("Update"));
  143. if (count($errors) > 0) {
  144. $errorArray = array();
  145. foreach ($errors as $error) {
  146. $errorArray[$error->getPropertyPath()] = $error->getMessage();
  147. }
  148. return new JsonResponse(array('status' => 'error', 'message' => $errorArray), 406);
  149. }
  150. $package->setCrawledAt(null);
  151. $em = $this->getDoctrine()->getManager();
  152. $em->persist($package);
  153. $em->flush();
  154. return new JsonResponse(array('status' => 'success'), 200);
  155. }
  156. /**
  157. * @Route("/downloads/{name}", name="track_download", requirements={"name"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+"}, defaults={"_format" = "json"})
  158. * @Method({"POST"})
  159. */
  160. public function trackDownloadAction(Request $request, $name)
  161. {
  162. $result = $this->getPackageAndVersionId($name, $request->request->get('version_normalized'));
  163. if (!$result) {
  164. return new JsonResponse(array('status' => 'error', 'message' => 'Package not found'), 200);
  165. }
  166. $this->get('packagist.download_manager')->addDownloads(['id' => $result['id'], 'vid' => $result['vid'], 'ip' => $request->getClientIp()]);
  167. return new JsonResponse(array('status' => 'success'), 201);
  168. }
  169. /**
  170. * Expects a json like:
  171. *
  172. * {
  173. * "downloads": [
  174. * {"name": "foo/bar", "version": "1.0.0.0"},
  175. * // ...
  176. * ]
  177. * }
  178. *
  179. * The version must be the normalized one
  180. *
  181. * @Route("/downloads/", name="track_download_batch", defaults={"_format" = "json"})
  182. * @Method({"POST"})
  183. */
  184. public function trackDownloadsAction(Request $request)
  185. {
  186. $contents = json_decode($request->getContent(), true);
  187. if (empty($contents['downloads']) || !is_array($contents['downloads'])) {
  188. return new JsonResponse(array('status' => 'error', 'message' => 'Invalid request format, must be a json object containing a downloads key filled with an array of name/version objects'), 200);
  189. }
  190. $failed = array();
  191. $ip = $request->headers->get('X-'.$this->container->getParameter('trusted_ip_header'));
  192. if (!$ip) {
  193. $ip = $request->getClientIp();
  194. }
  195. $jobs = [];
  196. foreach ($contents['downloads'] as $package) {
  197. $result = $this->getPackageAndVersionId($package['name'], $package['version']);
  198. if (!$result) {
  199. $failed[] = $package;
  200. continue;
  201. }
  202. $jobs[] = ['id' => $result['id'], 'vid' => $result['vid'], 'ip' => $ip];
  203. }
  204. $this->get('packagist.download_manager')->addDownloads($jobs);
  205. if ($failed) {
  206. return new JsonResponse(array('status' => 'partial', 'message' => 'Packages '.json_encode($failed).' not found'), 200);
  207. }
  208. return new JsonResponse(array('status' => 'success'), 201);
  209. }
  210. /**
  211. * @param string $name
  212. * @param string $version
  213. * @return array
  214. */
  215. protected function getPackageAndVersionId($name, $version)
  216. {
  217. return $this->get('doctrine.dbal.default_connection')->fetchAssoc(
  218. 'SELECT p.id, v.id vid
  219. FROM package p
  220. LEFT JOIN package_version v ON p.id = v.package_id
  221. WHERE p.name = ?
  222. AND v.normalizedVersion = ?
  223. LIMIT 1',
  224. array($name, $version)
  225. );
  226. }
  227. /**
  228. * Perform the package update
  229. *
  230. * @param Request $request the current request
  231. * @param string $url the repository's URL (deducted from the request)
  232. * @param string $urlRegex the regex used to split the user packages into domain and path
  233. * @return Response
  234. */
  235. protected function receivePost(Request $request, $url, $urlRegex)
  236. {
  237. // try to parse the URL first to avoid the DB lookup on malformed requests
  238. if (!preg_match($urlRegex, $url)) {
  239. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not parse payload repository URL')), 406);
  240. }
  241. // find the user
  242. $user = $this->findUser($request);
  243. if (!$user) {
  244. return new Response(json_encode(array('status' => 'error', 'message' => 'Invalid credentials')), 403);
  245. }
  246. // try to find the user package
  247. $packages = $this->findPackagesByUrl($user, $url, $urlRegex);
  248. if (!$packages) {
  249. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not find a package that matches this request (does user maintain the package?)')), 404);
  250. }
  251. // don't die if this takes a while
  252. set_time_limit(3600);
  253. // put both updating the database and scanning the repository in a transaction
  254. $em = $this->get('doctrine.orm.entity_manager');
  255. $updater = $this->get('packagist.package_updater');
  256. $config = Factory::createConfig();
  257. $io = new BufferIO('', OutputInterface::VERBOSITY_VERY_VERBOSE, new HtmlOutputFormatter(Factory::createAdditionalStyles()));
  258. $io->loadConfiguration($config);
  259. try {
  260. /** @var Package $package */
  261. foreach ($packages as $package) {
  262. $em->transactional(function($em) use ($package, $updater, $io, $config) {
  263. // prepare dependencies
  264. $loader = new ValidatingArrayLoader(new ArrayLoader());
  265. // prepare repository
  266. $repository = new VcsRepository(array('url' => $package->getRepository()), $io, $config);
  267. $repository->setLoader($loader);
  268. // perform the actual update (fetch and re-scan the repository's source)
  269. $updater->update($io, $config, $package, $repository);
  270. // update the package entity
  271. $package->setAutoUpdated(true);
  272. $em->flush($package);
  273. });
  274. }
  275. } catch (\Exception $e) {
  276. if ($e instanceof InvalidRepositoryException) {
  277. $this->get('packagist.package_manager')->notifyUpdateFailure($package, $e, $io->getOutput());
  278. }
  279. $this->get('logger')->error('Failed update of '.$package->getName(), ['exception' => $e]);
  280. return new Response(json_encode(array(
  281. 'status' => 'error',
  282. 'message' => '['.get_class($e).'] '.$e->getMessage(),
  283. 'details' => '<pre>'.$io->getOutput().'</pre>'
  284. )), 400);
  285. }
  286. return new JsonResponse(array('status' => 'success'), 202);
  287. }
  288. /**
  289. * Find a user by his username and API token
  290. *
  291. * @param Request $request
  292. * @return User|null the found user or null otherwise
  293. */
  294. protected function findUser(Request $request)
  295. {
  296. $username = $request->request->has('username') ?
  297. $request->request->get('username') :
  298. $request->query->get('username');
  299. $apiToken = $request->request->has('apiToken') ?
  300. $request->request->get('apiToken') :
  301. $request->query->get('apiToken');
  302. $user = $this->get('packagist.user_repository')
  303. ->findOneBy(array('username' => $username, 'apiToken' => $apiToken));
  304. return $user;
  305. }
  306. /**
  307. * Find a user package given by its full URL
  308. *
  309. * @param User $user
  310. * @param string $url
  311. * @param string $urlRegex
  312. * @return array the packages found
  313. */
  314. protected function findPackagesByUrl(User $user, $url, $urlRegex)
  315. {
  316. if (!preg_match($urlRegex, $url, $matched)) {
  317. return array();
  318. }
  319. $packages = array();
  320. foreach ($user->getPackages() as $package) {
  321. if (preg_match($urlRegex, $package->getRepository(), $candidate)
  322. && strtolower($candidate['host']) === strtolower($matched['host'])
  323. && strtolower($candidate['path']) === strtolower($matched['path'])
  324. ) {
  325. $packages[] = $package;
  326. }
  327. }
  328. return $packages;
  329. }
  330. }