WebController.php 15 KB

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