UserController.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 Doctrine\ORM\NoResultException;
  13. use FOS\UserBundle\Model\UserInterface;
  14. use Packagist\WebBundle\Entity\Package;
  15. use Packagist\WebBundle\Entity\User;
  16. use Packagist\WebBundle\Model\RedisAdapter;
  17. use Pagerfanta\Adapter\DoctrineORMAdapter;
  18. use Pagerfanta\Pagerfanta;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  20. use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
  21. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  22. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  23. use Symfony\Component\HttpFoundation\Request;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  26. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  27. /**
  28. * @author Jordi Boggiano <j.boggiano@seld.be>
  29. */
  30. class UserController extends Controller
  31. {
  32. /**
  33. * @Template()
  34. * @Route("/users/{name}/packages/", name="user_packages")
  35. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  36. */
  37. public function packagesAction(Request $req, User $user)
  38. {
  39. $packages = $this->getUserPackages($req, $user);
  40. return array(
  41. 'packages' => $packages,
  42. 'meta' => $this->getPackagesMetadata($packages),
  43. 'user' => $user,
  44. );
  45. }
  46. /**
  47. * @Route("/trigger-github-sync/", name="user_github_sync")
  48. */
  49. public function triggerGitHubSyncAction(Request $req)
  50. {
  51. $user = $this->getUser();
  52. if (!$user) {
  53. throw new \AccessDeniedException();
  54. }
  55. if (!$user->getGithubToken()) {
  56. $this->get('session')->getFlashBag()->set('error', 'You must connect your user account to github to sync packages.');
  57. return $this->redirectToRoute('fos_user_profile_show');
  58. }
  59. if (!$user->getGithubScope()) {
  60. $this->get('session')->getFlashBag()->set('error', 'Please log out and log in with GitHub again to make sure the correct GitHub permissions are granted.');
  61. return $this->redirectToRoute('fos_user_profile_show');
  62. }
  63. $this->get('scheduler')->scheduleUserScopeMigration($user->getId(), '', $user->getGithubScope());
  64. sleep(5);
  65. $this->get('session')->getFlashBag()->set('success', 'User sync scheduled. It might take a few seconds to run through, make sure you refresh then to check if any packages still need sync.');
  66. return $this->redirectToRoute('fos_user_profile_show');
  67. }
  68. /**
  69. * @Route("/spammers/{name}/", name="mark_spammer")
  70. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  71. * @Method({"POST"})
  72. */
  73. public function markSpammerAction(Request $req, User $user)
  74. {
  75. if (!$this->isGranted('ROLE_ANTISPAM')) {
  76. throw new AccessDeniedException('This user can not mark others as spammers');
  77. }
  78. $form = $this->createFormBuilder(array())->getForm();
  79. $form->submit($req->request->get('form'));
  80. if ($form->isValid()) {
  81. $user->addRole('ROLE_SPAMMER');
  82. $user->setEnabled(false);
  83. $this->get('fos_user.user_manager')->updateUser($user);
  84. $doctrine = $this->getDoctrine();
  85. $doctrine->getConnection()->executeUpdate(
  86. 'UPDATE package p JOIN maintainers_packages mp ON mp.package_id = p.id
  87. SET abandoned = 1, replacementPackage = "spam/spam", description = "", readme = "", indexedAt = NULL, dumpedAt = "2100-01-01 00:00:00"
  88. WHERE mp.user_id = :userId',
  89. ['userId' => $user->getId()]
  90. );
  91. /** @var VersionRepository $versionRepo */
  92. $versionRepo = $doctrine->getRepository('PackagistWebBundle:Version');
  93. $packages = $doctrine
  94. ->getRepository('PackagistWebBundle:Package')
  95. ->getFilteredQueryBuilder(array('maintainer' => $user->getId()), true)
  96. ->getQuery()->getResult();
  97. $providerManager = $this->get('packagist.provider_manager');
  98. foreach ($packages as $package) {
  99. foreach ($package->getVersions() as $version) {
  100. $versionRepo->remove($version);
  101. }
  102. $providerManager->deletePackage($package);
  103. }
  104. $this->getDoctrine()->getManager()->flush();
  105. $this->get('session')->getFlashBag()->set('success', $user->getUsername().' has been marked as a spammer');
  106. }
  107. return $this->redirect(
  108. $this->generateUrl("user_profile", array("name" => $user->getUsername()))
  109. );
  110. }
  111. /**
  112. * @param Request $req
  113. * @return Response
  114. */
  115. public function myProfileAction(Request $req)
  116. {
  117. $user = $this->container->get('security.token_storage')->getToken()->getUser();
  118. if (!is_object($user) || !$user instanceof UserInterface) {
  119. throw new AccessDeniedException('This user does not have access to this section.');
  120. }
  121. $packages = $this->getUserPackages($req, $user);
  122. return $this->container->get('templating')->renderResponse(
  123. 'FOSUserBundle:Profile:show.html.twig',
  124. array(
  125. 'packages' => $packages,
  126. 'meta' => $this->getPackagesMetadata($packages),
  127. 'user' => $user,
  128. )
  129. );
  130. }
  131. /**
  132. * @Template()
  133. * @Route("/users/{name}/", name="user_profile")
  134. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  135. */
  136. public function profileAction(Request $req, User $user)
  137. {
  138. $packages = $this->getUserPackages($req, $user);
  139. $data = array(
  140. 'packages' => $packages,
  141. 'meta' => $this->getPackagesMetadata($packages),
  142. 'user' => $user,
  143. );
  144. if ($this->isGranted('ROLE_ANTISPAM')) {
  145. $data['spammerForm'] = $this->createFormBuilder(array())->getForm()->createView();
  146. }
  147. return $data;
  148. }
  149. /**
  150. * @Template()
  151. * @Route("/users/{name}/favorites/", name="user_favorites")
  152. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  153. * @Method({"GET"})
  154. */
  155. public function favoritesAction(Request $req, User $user)
  156. {
  157. try {
  158. if (!$this->get('snc_redis.default')->isConnected()) {
  159. $this->get('snc_redis.default')->connect();
  160. }
  161. } catch (\Exception $e) {
  162. $this->get('session')->getFlashBag()->set('error', 'Could not connect to the Redis database.');
  163. $this->get('logger')->notice($e->getMessage(), array('exception' => $e));
  164. return array('user' => $user, 'packages' => array());
  165. }
  166. $paginator = new Pagerfanta(
  167. new RedisAdapter($this->get('packagist.favorite_manager'), $user, 'getFavorites', 'getFavoriteCount')
  168. );
  169. $paginator->setMaxPerPage(15);
  170. $paginator->setCurrentPage($req->query->get('page', 1), false, true);
  171. return array('packages' => $paginator, 'user' => $user);
  172. }
  173. /**
  174. * @Route("/users/{name}/favorites/", name="user_add_fav", defaults={"_format" = "json"})
  175. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  176. * @Method({"POST"})
  177. */
  178. public function postFavoriteAction(Request $req, User $user)
  179. {
  180. if ($user->getId() !== $this->getUser()->getId()) {
  181. throw new AccessDeniedException('You can only change your own favorites');
  182. }
  183. $package = $req->request->get('package');
  184. try {
  185. $package = $this->getDoctrine()
  186. ->getRepository('PackagistWebBundle:Package')
  187. ->findOneByName($package);
  188. } catch (NoResultException $e) {
  189. throw new NotFoundHttpException('The given package "'.$package.'" was not found.');
  190. }
  191. $this->get('packagist.favorite_manager')->markFavorite($user, $package);
  192. return new Response('{"status": "success"}', 201);
  193. }
  194. /**
  195. * @Route("/users/{name}/favorites/{package}", name="user_remove_fav", defaults={"_format" = "json"}, requirements={"package"="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+?"})
  196. * @ParamConverter("user", options={"mapping": {"name": "username"}})
  197. * @ParamConverter("package", options={"mapping": {"package": "name"}})
  198. * @Method({"DELETE"})
  199. */
  200. public function deleteFavoriteAction(User $user, Package $package)
  201. {
  202. if ($user->getId() !== $this->getUser()->getId()) {
  203. throw new AccessDeniedException('You can only change your own favorites');
  204. }
  205. $this->get('packagist.favorite_manager')->removeFavorite($user, $package);
  206. return new Response('{"status": "success"}', 204);
  207. }
  208. /**
  209. * @param Request $req
  210. * @param User $user
  211. * @return Pagerfanta
  212. */
  213. protected function getUserPackages($req, $user)
  214. {
  215. $packages = $this->getDoctrine()
  216. ->getRepository('PackagistWebBundle:Package')
  217. ->getFilteredQueryBuilder(array('maintainer' => $user->getId()), true);
  218. $paginator = new Pagerfanta(new DoctrineORMAdapter($packages, true));
  219. $paginator->setMaxPerPage(15);
  220. $paginator->setCurrentPage($req->query->get('page', 1), false, true);
  221. return $paginator;
  222. }
  223. }