WebController.php 14 KB

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