WebController.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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 Packagist\WebBundle\Form\Model\SearchQuery;
  13. use Packagist\WebBundle\Form\Type\SearchQueryType;
  14. use Predis\Connection\ConnectionException;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  17. use Symfony\Component\HttpFoundation\JsonResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. /**
  22. * @author Jordi Boggiano <j.boggiano@seld.be>
  23. */
  24. class WebController extends Controller
  25. {
  26. /**
  27. * @Template()
  28. * @Route("/", name="home")
  29. */
  30. public function indexAction()
  31. {
  32. return array('page' => 'home');
  33. }
  34. /**
  35. * Rendered by views/Web/search_section.html.twig
  36. */
  37. public function searchFormAction(Request $req)
  38. {
  39. $form = $this->createForm(SearchQueryType::class, new SearchQuery(), [
  40. 'action' => $this->generateUrl('search.ajax'),
  41. ]);
  42. $filteredOrderBys = $this->getFilteredOrderedBys($req);
  43. $this->computeSearchQuery($req, $filteredOrderBys);
  44. $form->handleRequest($req);
  45. return $this->render('PackagistWebBundle:web:search_form.html.twig', array(
  46. 'searchQuery' => $req->query->get('search_query')['query'] ?? '',
  47. ));
  48. }
  49. /**
  50. * @Route("/search/", name="search.ajax", methods={"GET"})
  51. * @Route("/search.{_format}", requirements={"_format"="(html|json)"}, name="search", defaults={"_format"="html"}, methods={"GET"})
  52. */
  53. public function searchAction(Request $req)
  54. {
  55. if ($req->getRequestFormat() !== 'json') {
  56. return $this->render('PackagistWebBundle:web:search.html.twig', [
  57. 'packages' => [],
  58. ]);
  59. }
  60. $typeFilter = str_replace('%type%', '', $req->query->get('type'));
  61. $tagsFilter = $req->query->get('tags');
  62. $indexName = $this->container->getParameter('algolia.index_name');
  63. if (!$req->query->has('search_query') && !$typeFilter && !$tagsFilter) {
  64. return JsonResponse::create(array(
  65. 'error' => 'Missing search query, example: ?q=example'
  66. ), 400)->setCallback($req->query->get('callback'));
  67. }
  68. $form = $this->createForm(SearchQueryType::class, new SearchQuery());
  69. $filteredOrderBys = $this->getFilteredOrderedBys($req);
  70. $this->computeSearchQuery($req, $filteredOrderBys);
  71. $algolia = $this->get('packagist.algolia.client');
  72. $index = $algolia->initIndex($indexName);
  73. $query = '';
  74. $queryParams = [];
  75. // filter by type
  76. if ($typeFilter) {
  77. $queryParams['filters'][] = 'type:'.$typeFilter;
  78. }
  79. // filter by tags
  80. if ($tagsFilter) {
  81. $tags = array();
  82. foreach ((array) $tagsFilter as $tag) {
  83. $tags[] = 'tags:'.$tag;
  84. }
  85. $queryParams['filters'][] = '(' . implode(' OR ', $tags) . ')';
  86. }
  87. if (!empty($filteredOrderBys)) {
  88. return JsonResponse::create(array(
  89. 'status' => 'error',
  90. 'message' => 'Search sorting is not available anymore',
  91. ), 400)->setCallback($req->query->get('callback'));
  92. }
  93. $form->handleRequest($req);
  94. if ($form->isValid()) {
  95. $query = $form->getData()->getQuery();
  96. }
  97. $perPage = $req->query->getInt('per_page', 15);
  98. if ($perPage <= 0 || $perPage > 100) {
  99. if ($req->getRequestFormat() === 'json') {
  100. return JsonResponse::create(array(
  101. 'status' => 'error',
  102. 'message' => 'The optional packages per_page parameter must be an integer between 1 and 100 (default: 15)',
  103. ), 400)->setCallback($req->query->get('callback'));
  104. }
  105. $perPage = max(0, min(100, $perPage));
  106. }
  107. if (isset($queryParams['filters'])) {
  108. $queryParams['filters'] = implode(' AND ', $queryParams['filters']);
  109. }
  110. $queryParams['hitsPerPage'] = $perPage;
  111. $queryParams['page'] = $req->query->get('page', 1) - 1;
  112. try {
  113. $results = $index->search($query, $queryParams);
  114. } catch (\Throwable $e) {
  115. return JsonResponse::create(array(
  116. 'status' => 'error',
  117. 'message' => 'Could not connect to the search server',
  118. ), 500)->setCallback($req->query->get('callback'));
  119. }
  120. $result = array(
  121. 'results' => array(),
  122. 'total' => $results['nbHits'],
  123. );
  124. foreach ($results['hits'] as $package) {
  125. if (ctype_digit((string) $package['id'])) {
  126. $url = $this->generateUrl('view_package', array('name' => $package['name']), UrlGeneratorInterface::ABSOLUTE_URL);
  127. } else {
  128. $url = $this->generateUrl('view_providers', array('name' => $package['name']), UrlGeneratorInterface::ABSOLUTE_URL);
  129. }
  130. $row = array(
  131. 'name' => $package['name'],
  132. 'description' => $package['description'] ?: '',
  133. 'url' => $url,
  134. 'repository' => $package['repository'],
  135. );
  136. if (ctype_digit((string) $package['id'])) {
  137. $row['downloads'] = $package['meta']['downloads'];
  138. $row['favers'] = $package['meta']['favers'];
  139. } else {
  140. $row['virtual'] = true;
  141. }
  142. if (!empty($package['abandoned'])) {
  143. $row['abandoned'] = $package['replacementPackage'] ?? true;
  144. }
  145. $result['results'][] = $row;
  146. }
  147. if ($results['nbPages'] > $results['page'] + 1) {
  148. $params = array(
  149. '_format' => 'json',
  150. 'q' => $form->getData()->getQuery(),
  151. 'page' => $results['page'] + 2,
  152. );
  153. if ($tagsFilter) {
  154. $params['tags'] = (array) $tagsFilter;
  155. }
  156. if ($typeFilter) {
  157. $params['type'] = $typeFilter;
  158. }
  159. if ($perPage !== 15) {
  160. $params['per_page'] = $perPage;
  161. }
  162. $result['next'] = $this->generateUrl('search', $params, UrlGeneratorInterface::ABSOLUTE_URL);
  163. }
  164. return JsonResponse::create($result)->setCallback($req->query->get('callback'));
  165. }
  166. /**
  167. * @Route("/statistics", name="stats")
  168. * @Template
  169. * @Cache(smaxage=5)
  170. */
  171. public function statsAction()
  172. {
  173. $packages = $this->getDoctrine()
  174. ->getConnection()
  175. ->fetchAll('SELECT COUNT(*) count, YEAR(createdAt) year, MONTH(createdAt) month FROM `package` GROUP BY year, month');
  176. $versions = $this->getDoctrine()
  177. ->getConnection()
  178. ->fetchAll('SELECT COUNT(*) count, YEAR(releasedAt) year, MONTH(releasedAt) month FROM `package_version` GROUP BY year, month');
  179. $chart = array('versions' => array(), 'packages' => array(), 'months' => array());
  180. // prepare x axis
  181. $date = new \DateTime($packages[0]['year'] . '-' . $packages[0]['month'] . '-01');
  182. $now = new \DateTime;
  183. while ($date < $now) {
  184. $chart['months'][] = $month = $date->format('Y-m');
  185. $date->modify('+1month');
  186. }
  187. // prepare data
  188. $count = 0;
  189. foreach ($packages as $dataPoint) {
  190. $count += $dataPoint['count'];
  191. $chart['packages'][$dataPoint['year'] . '-' . str_pad($dataPoint['month'], 2, '0', STR_PAD_LEFT)] = $count;
  192. }
  193. $count = 0;
  194. foreach ($versions as $dataPoint) {
  195. $yearMonth = $dataPoint['year'] . '-' . str_pad($dataPoint['month'], 2, '0', STR_PAD_LEFT);
  196. $count += $dataPoint['count'];
  197. if (in_array($yearMonth, $chart['months'])) {
  198. $chart['versions'][$yearMonth] = $count;
  199. }
  200. }
  201. // fill gaps at the end of the chart
  202. if (count($chart['months']) > count($chart['packages'])) {
  203. $chart['packages'] += array_fill(0, count($chart['months']) - count($chart['packages']), !empty($chart['packages']) ? max($chart['packages']) : 0);
  204. }
  205. if (count($chart['months']) > count($chart['versions'])) {
  206. $chart['versions'] += array_fill(0, count($chart['months']) - count($chart['versions']), !empty($chart['versions']) ? max($chart['versions']) : 0);
  207. }
  208. $downloadsStartDate = '2012-04-13';
  209. try {
  210. $redis = $this->get('snc_redis.default');
  211. $downloads = $redis->get('downloads') ?: 0;
  212. $date = new \DateTime($downloadsStartDate.' 00:00:00');
  213. $today = new \DateTime('today 00:00:00');
  214. $dailyGraphStart = new \DateTime('-30days 00:00:00'); // 30 days before today
  215. $dlChart = $dlChartMonthly = array();
  216. while ($date <= $today) {
  217. if ($date > $dailyGraphStart) {
  218. $dlChart[$date->format('Y-m-d')] = 'downloads:'.$date->format('Ymd');
  219. }
  220. $dlChartMonthly[$date->format('Y-m')] = 'downloads:'.$date->format('Ym');
  221. $date->modify('+1day');
  222. }
  223. $dlChart = array(
  224. 'labels' => array_keys($dlChart),
  225. 'values' => $redis->mget(array_values($dlChart))
  226. );
  227. $dlChartMonthly = array(
  228. 'labels' => array_keys($dlChartMonthly),
  229. 'values' => $redis->mget(array_values($dlChartMonthly))
  230. );
  231. } catch (ConnectionException $e) {
  232. $downloads = 'N/A';
  233. $dlChart = $dlChartMonthly = null;
  234. }
  235. return array(
  236. 'chart' => $chart,
  237. 'packages' => !empty($chart['packages']) ? max($chart['packages']) : 0,
  238. 'versions' => !empty($chart['versions']) ? max($chart['versions']) : 0,
  239. 'downloads' => $downloads,
  240. 'downloadsChart' => $dlChart,
  241. 'maxDailyDownloads' => !empty($dlChart) ? max($dlChart['values']) : null,
  242. 'downloadsChartMonthly' => $dlChartMonthly,
  243. 'maxMonthlyDownloads' => !empty($dlChartMonthly) ? max($dlChartMonthly['values']) : null,
  244. 'downloadsStartDate' => $downloadsStartDate,
  245. );
  246. }
  247. /**
  248. * @Route("/statistics.json", name="stats_json", defaults={"_format"="json"}, methods={"GET"})
  249. */
  250. public function statsTotalsAction()
  251. {
  252. $downloads = $this->get('snc_redis.default_client')->get('downloads') ?: 0;
  253. $totals = ['downloads' => $downloads];
  254. return new JsonResponse(['totals' => $totals], 200);
  255. }
  256. /**
  257. * @param Request $req
  258. *
  259. * @return array
  260. */
  261. protected function getFilteredOrderedBys(Request $req)
  262. {
  263. $orderBys = $req->query->get('orderBys', array());
  264. if (!$orderBys) {
  265. $orderBys = $req->query->get('search_query');
  266. $orderBys = $orderBys['orderBys'] ?? array();
  267. }
  268. if ($orderBys) {
  269. $allowedSorts = array(
  270. 'downloads' => 1,
  271. 'favers' => 1
  272. );
  273. $allowedOrders = array(
  274. 'asc' => 1,
  275. 'desc' => 1,
  276. );
  277. $filteredOrderBys = array();
  278. foreach ($orderBys as $orderBy) {
  279. if (isset($orderBy['sort'])
  280. && isset($allowedSorts[$orderBy['sort']])
  281. && isset($orderBy['order'])
  282. && isset($allowedOrders[$orderBy['order']])) {
  283. $filteredOrderBys[] = $orderBy;
  284. }
  285. }
  286. } else {
  287. $filteredOrderBys = array();
  288. }
  289. return $filteredOrderBys;
  290. }
  291. /**
  292. * @param Request $req
  293. * @param array $filteredOrderBys
  294. */
  295. private function computeSearchQuery(Request $req, array $filteredOrderBys)
  296. {
  297. // transform q=search shortcut
  298. if ($req->query->has('q') || $req->query->has('orderBys')) {
  299. $searchQuery = array();
  300. $q = $req->query->get('q');
  301. if ($q !== null) {
  302. $searchQuery['query'] = $q;
  303. }
  304. if (!empty($filteredOrderBys)) {
  305. $searchQuery['orderBys'] = $filteredOrderBys;
  306. }
  307. $req->query->set(
  308. 'search_query',
  309. $searchQuery
  310. );
  311. }
  312. }
  313. }