WebController.php 17 KB

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