ApiController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 Packagist\WebBundle\Package\Updater;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  23. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  24. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  25. use Symfony\Component\Console\Output\OutputInterface;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. /**
  30. * @author Jordi Boggiano <j.boggiano@seld.be>
  31. */
  32. class ApiController extends Controller
  33. {
  34. /**
  35. * @Template()
  36. * @Route("/packages.json", name="packages", defaults={"_format" = "json"})
  37. */
  38. public function packagesAction(Request $req)
  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->repository = $url;
  69. $errors = $this->get('validator')->validate($package)
  70. if (count($errors) > 0) {
  71. $errorsString = (string) $errors;
  72. return new JsonResponse(array('status' => 'error', 'message' => $errorsString), 406);
  73. }
  74. try {
  75. $em = $this->getDoctrine()->getManager();
  76. $em->persist($package);
  77. $em->flush();
  78. } catch (\Exception $e) {
  79. $this->get('logger')->crit($e->getMessage(), array('exception', $e));
  80. return new JsonResponse(array('status' => 'error', 'message' => 'Error saving package'), 500);
  81. }
  82. return new JsonResponse(array('status' => 'success'), 202);
  83. }
  84. /**
  85. * @Route("/api/update-package", name="generic_postreceive", defaults={"_format" = "json"})
  86. * @Route("/api/github", name="github_postreceive", defaults={"_format" = "json"})
  87. * @Route("/api/bitbucket", name="bitbucket_postreceive", defaults={"_format" = "json"})
  88. * @Method({"POST"})
  89. */
  90. public function updatePackageAction(Request $request)
  91. {
  92. // parse the payload
  93. $payload = json_decode($request->request->get('payload'), true);
  94. if (!$payload && $request->headers->get('Content-Type') === 'application/json') {
  95. $payload = json_decode($request->getContent(), true);
  96. }
  97. if (!$payload) {
  98. return new JsonResponse(array('status' => 'error', 'message' => 'Missing payload parameter'), 406);
  99. }
  100. if (isset($payload['repository']['url'])) { // github/gitlab/anything hook
  101. $urlRegex = '{^(?:ssh://git@|https?://|git://|git@)?(?P<host>[a-z0-9.-]+)[:/](?P<path>[\w.-]+/[\w.-]+?)(?:\.git)?$}i';
  102. $url = $payload['repository']['url'];
  103. } elseif (isset($payload['canon_url']) && isset($payload['repository']['absolute_url'])) { // bitbucket hook
  104. $urlRegex = '{^(?:https?://|git://|git@)?(?P<host>bitbucket\.org)[/:](?P<path>[\w.-]+/[\w.-]+?)(\.git)?/?$}i';
  105. $url = $payload['canon_url'].$payload['repository']['absolute_url'];
  106. } else {
  107. return new JsonResponse(array('status' => 'error', 'message' => 'Missing or invalid payload'), 406);
  108. }
  109. return $this->receivePost($request, $url, $urlRegex);
  110. }
  111. /**
  112. * @Route("/downloads/{name}", name="track_download", requirements={"name"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+"}, defaults={"_format" = "json"})
  113. * @Method({"POST"})
  114. */
  115. public function trackDownloadAction(Request $request, $name)
  116. {
  117. $result = $this->getPackageAndVersionId($name, $request->request->get('version_normalized'));
  118. if (!$result) {
  119. return new JsonResponse(array('status' => 'error', 'message' => 'Package not found'), 200);
  120. }
  121. $this->trackDownload($result['id'], $result['vid'], $request->getClientIp());
  122. return new JsonResponse(array('status' => 'success'), 201);
  123. }
  124. /**
  125. * Expects a json like:
  126. *
  127. * {
  128. * "downloads": [
  129. * {"name": "foo/bar", "version": "1.0.0.0"},
  130. * // ...
  131. * ]
  132. * }
  133. *
  134. * The version must be the normalized one
  135. *
  136. * @Route("/downloads/", name="track_download_batch", defaults={"_format" = "json"})
  137. * @Method({"POST"})
  138. */
  139. public function trackDownloadsAction(Request $request)
  140. {
  141. $contents = json_decode($request->getContent(), true);
  142. if (empty($contents['downloads']) || !is_array($contents['downloads'])) {
  143. 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);
  144. }
  145. $failed = array();
  146. foreach ($contents['downloads'] as $package) {
  147. $result = $this->getPackageAndVersionId($package['name'], $package['version']);
  148. if (!$result) {
  149. $failed[] = $package;
  150. continue;
  151. }
  152. $this->trackDownload($result['id'], $result['vid'], $request->getClientIp());
  153. }
  154. if ($failed) {
  155. return new JsonResponse(array('status' => 'partial', 'message' => 'Packages '.json_encode($failed).' not found'), 200);
  156. }
  157. return new JsonResponse(array('status' => 'success'), 201);
  158. }
  159. protected function getPackageAndVersionId($name, $version)
  160. {
  161. return $this->get('doctrine.dbal.default_connection')->fetchAssoc(
  162. 'SELECT p.id, v.id vid
  163. FROM package p
  164. LEFT JOIN package_version v ON p.id = v.package_id
  165. WHERE p.name = ?
  166. AND v.normalizedVersion = ?
  167. LIMIT 1',
  168. array($name, $version)
  169. );
  170. }
  171. protected function trackDownload($id, $vid, $ip)
  172. {
  173. $redis = $this->get('snc_redis.default');
  174. $manager = $this->get('packagist.download_manager');
  175. $throttleKey = 'dl:'.$id.':'.$ip.':'.date('Ymd');
  176. $requests = $redis->incr($throttleKey);
  177. if (1 === $requests) {
  178. $redis->expire($throttleKey, 86400);
  179. }
  180. if ($requests <= 10) {
  181. $manager->addDownload($id, $vid);
  182. }
  183. }
  184. /**
  185. * Perform the package update
  186. *
  187. * @param Request $request the current request
  188. * @param string $url the repository's URL (deducted from the request)
  189. * @param string $urlRegex the regex used to split the user packages into domain and path
  190. * @return Response
  191. */
  192. protected function receivePost(Request $request, $url, $urlRegex)
  193. {
  194. // try to parse the URL first to avoid the DB lookup on malformed requests
  195. if (!preg_match($urlRegex, $url)) {
  196. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not parse payload repository URL')), 406);
  197. }
  198. // find the user
  199. $user = $this->findUser($request);
  200. if (!$user) {
  201. return new Response(json_encode(array('status' => 'error', 'message' => 'Invalid credentials')), 403);
  202. }
  203. // try to find the user package
  204. $packages = $this->findPackagesByUrl($user, $url, $urlRegex);
  205. if (!$packages) {
  206. return new Response(json_encode(array('status' => 'error', 'message' => 'Could not find a package that matches this request (does user maintain the package?)')), 404);
  207. }
  208. // don't die if this takes a while
  209. set_time_limit(3600);
  210. // put both updating the database and scanning the repository in a transaction
  211. $em = $this->get('doctrine.orm.entity_manager');
  212. $updater = $this->get('packagist.package_updater');
  213. $config = Factory::createConfig();
  214. $io = new BufferIO('', OutputInterface::VERBOSITY_VERY_VERBOSE, new HtmlOutputFormatter(Factory::createAdditionalStyles()));
  215. $io->loadConfiguration($config);
  216. try {
  217. foreach ($packages as $package) {
  218. $em->transactional(function($em) use ($package, $updater, $io, $config) {
  219. // prepare dependencies
  220. $loader = new ValidatingArrayLoader(new ArrayLoader());
  221. // prepare repository
  222. $repository = new VcsRepository(array('url' => $package->getRepository()), $io, $config);
  223. $repository->setLoader($loader);
  224. // perform the actual update (fetch and re-scan the repository's source)
  225. $updater->update($io, $config, $package, $repository);
  226. // update the package entity
  227. $package->setAutoUpdated(true);
  228. $em->flush();
  229. });
  230. }
  231. } catch (\Exception $e) {
  232. if ($e instanceof InvalidRepositoryException) {
  233. $this->get('packagist.package_manager')->notifyUpdateFailure($package, $e, $io->getOutput());
  234. }
  235. return new Response(json_encode(array(
  236. 'status' => 'error',
  237. 'message' => '['.get_class($e).'] '.$e->getMessage(),
  238. 'details' => '<pre>'.$io->getOutput().'</pre>'
  239. )), 400);
  240. }
  241. return new JsonResponse(array('status' => 'success'), 202);
  242. }
  243. /**
  244. * Find a user by his username and API token
  245. *
  246. * @param Request $request
  247. * @return User|null the found user or null otherwise
  248. */
  249. protected function findUser(Request $request)
  250. {
  251. $username = $request->request->has('username') ?
  252. $request->request->get('username') :
  253. $request->query->get('username');
  254. $apiToken = $request->request->has('apiToken') ?
  255. $request->request->get('apiToken') :
  256. $request->query->get('apiToken');
  257. $user = $this->get('packagist.user_repository')
  258. ->findOneBy(array('username' => $username, 'apiToken' => $apiToken));
  259. return $user;
  260. }
  261. /**
  262. * Find a user package given by its full URL
  263. *
  264. * @param User $user
  265. * @param string $url
  266. * @param string $urlRegex
  267. * @return array the packages found
  268. */
  269. protected function findPackagesByUrl(User $user, $url, $urlRegex)
  270. {
  271. if (!preg_match($urlRegex, $url, $matched)) {
  272. return array();
  273. }
  274. $packages = array();
  275. foreach ($user->getPackages() as $package) {
  276. if (preg_match($urlRegex, $package->getRepository(), $candidate)
  277. && $candidate['host'] === $matched['host']
  278. && $candidate['path'] === $matched['path']
  279. ) {
  280. $packages[] = $package;
  281. }
  282. }
  283. return $packages;
  284. }
  285. }