WebController.php 15 KB

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