You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

655 lines
22KB

  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace frontend\controllers;
  38. use common\helpers\GlobalParam;
  39. use frontend\forms\OpinionForm;
  40. use frontend\forms\ProducerCodeForm;
  41. use GuzzleHttp\Client;
  42. use Yii;
  43. use frontend\forms\PasswordResetRequestForm;
  44. use frontend\forms\ResetPasswordForm;
  45. use frontend\forms\SignupForm;
  46. use common\forms\ContactForm;
  47. use yii\base\InvalidParamException;
  48. use yii\base\UserException;
  49. use yii\data\ActiveDataProvider;
  50. use yii\helpers\Html;
  51. use yii\web\BadRequestHttpException;
  52. use yii\filters\VerbFilter;
  53. use yii\filters\AccessControl;
  54. use common\forms\LoginForm;
  55. use yii\web\NotFoundHttpException;
  56. /**
  57. * Site controller
  58. */
  59. class SiteController extends FrontendController
  60. {
  61. /**
  62. * @inheritdoc
  63. */
  64. public function behaviors()
  65. {
  66. return [
  67. 'access' => [
  68. 'class' => AccessControl::class,
  69. 'only' => ['logout', 'signup', 'signup-producer'],
  70. 'rules' => [
  71. [
  72. 'actions' => ['signup'],
  73. 'allow' => true,
  74. 'roles' => ['?'],
  75. ],
  76. [
  77. 'actions' => ['signup-producer'],
  78. 'allow' => true,
  79. 'roles' => ['@'],
  80. ],
  81. [
  82. 'actions' => ['logout'],
  83. 'allow' => true,
  84. 'roles' => ['@'],
  85. ],
  86. ],
  87. 'denyCallback' => function($rule, $action) {
  88. return $this->redirect('index');
  89. }
  90. ],
  91. 'verbs' => [
  92. 'class' => VerbFilter::class,
  93. 'actions' => [
  94. 'logout' => ['get'],
  95. ],
  96. ],
  97. ];
  98. }
  99. /**
  100. * @inheritdoc
  101. */
  102. public function actions()
  103. {
  104. return [
  105. 'captcha' => [
  106. 'class' => 'yii\captcha\CaptchaAction',
  107. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  108. ],
  109. ];
  110. }
  111. /**
  112. * Affiche la page d'erreur.
  113. *
  114. * @return mixed
  115. */
  116. public function actionError()
  117. {
  118. $exception = \Yii::$app->errorHandler->exception;
  119. if ($exception->getMessage() == 'Producteur introuvable'
  120. || \Yii::$app->getRequest()->getQueryParam('producer_not_found')) {
  121. return $this->render('error-404-producer', ['exception' => $exception]);
  122. }
  123. if ($exception !== null) {
  124. return $this->render('error', ['exception' => $exception]);
  125. }
  126. }
  127. /**
  128. * Affiche la page d'accueil.
  129. */
  130. public function actionIndex()
  131. {
  132. return $this->render('index', [
  133. 'maximumNumberProducers' => $this->getSettingModule()->getAdminSettingBag()->get('maximumNumberProducers'),
  134. 'countProducersActive' => $this->getProducerModule()->getRepository()->countCacheProducersActiveWithTurnover()
  135. ]);
  136. }
  137. public function actionService()
  138. {
  139. $paidFeaturesArray = $this->getFeatureModule()->getRepository()->findPaidFeatures();
  140. return $this->render('service', [
  141. 'producerDemoAccount' => $this->getProducerModule()->findOneProducerDemoAccount(),
  142. 'dataProviderPrices' => $this->getDataProviderPrices(),
  143. 'paidFeaturesArray' => $paidFeaturesArray
  144. ]);
  145. }
  146. public function getDataProviderPrices()
  147. {
  148. return new ActiveDataProvider([
  149. 'query' => $this->getProducerPriceRangeModule()->queryProducerPriceRanges()->query(),
  150. 'pagination' => [
  151. 'pageSize' => 100,
  152. ],
  153. ]);
  154. }
  155. /**
  156. * Liste les producteurs utilisant la plateforme.
  157. */
  158. public function actionProducers()
  159. {
  160. $dataProviderProducers = new ActiveDataProvider([
  161. 'query' => $this->getProducerModule()->queryProducersActive()->query(),
  162. 'pagination' => [
  163. 'pageSize' => 100,
  164. ],
  165. ]);
  166. return $this->render('producers', [
  167. 'dataProviderProducers' => $dataProviderProducers,
  168. 'producersArray' => $this->getProducerModule()->findProducersActive()
  169. ]);
  170. }
  171. public function actionAbout()
  172. {
  173. $aboutFewNumbers = Yii::$app->cache->getOrSet('about_few_numbers10', function () {
  174. $producerModule = $this->getProducerModule();
  175. $pointSaleModule = $this->getPointSaleModule();
  176. $userModule = $this->getUserModule();
  177. $orderModule = $this->getOrderModule();
  178. $countProducersActive = $producerModule->getRepository()->countProducersActiveWithTurnover();
  179. $timeSavedByProducersAverage = $producerModule->getTimeSavedByProducersAverage();
  180. $countProducersWithOptionTimeSaved = $producerModule->countProducersWithTimeSaved();
  181. $countPointSalesActive = $pointSaleModule->countPointSalesActiveLastThreeMonths();
  182. $countUsersActive = $userModule->countUsersActiveLastThreeMonths();
  183. $averageOrdersPerDay = $orderModule->countGlobalUserOrdersAverageLastSevenDays();
  184. // $averageTurnover = $orderModule->getAverageTurnoverLastThreeMonths();
  185. $turnoverLastThirtyDays = $orderModule->getRepository()->getTurnoverLastThirtyDays();
  186. $resultMatomoApiVisitSummary = json_decode(file_get_contents(Yii::$app->parameterBag->get('matomoApiVisitSummaryUrl')));
  187. $numberVisitsByDay = intval($resultMatomoApiVisitSummary->nb_uniq_visitors / 30);
  188. return $this->renderPartial('_about_few_numbers', [
  189. 'countProducersActive' => $countProducersActive,
  190. 'countPointSalesActive' => $countPointSalesActive,
  191. 'countUsersActive' => $countUsersActive,
  192. 'averageOrdersPerDay' => $averageOrdersPerDay,
  193. //'averageTurnover' => $averageTurnover,
  194. 'turnoverLastThirtyDays' => $turnoverLastThirtyDays,
  195. 'numberVisitsByDay' => $numberVisitsByDay,
  196. 'timeSavedByProducersAverage' => $timeSavedByProducersAverage,
  197. 'countProducersWithOptionTimeSaved' => $countProducersWithOptionTimeSaved
  198. ]);
  199. }, 60 * 60 * 24);
  200. $producerModule = $this->getProducerModule();
  201. return $this->render('about', [
  202. 'countProducers' => $producerModule->countProducersActiveWithTurnover(),
  203. 'producersWithTestimonials' => $producerModule->findProducersWithTestimonials(),
  204. 'aboutFewNumbers' => $aboutFewNumbers
  205. ]);
  206. }
  207. /*public function actionSourceCode()
  208. {
  209. return $this->render('source_code');
  210. }*/
  211. /**
  212. * Liste les producteurs utilisant la plateforme.
  213. */
  214. public function actionAjaxProducers()
  215. {
  216. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  217. $producersArray = $this->getProducerModule()->findProducersActive();
  218. $producersArrayReturn = [];
  219. foreach($producersArray as $producer) {
  220. $producersArrayReturn[] = [
  221. 'id' => $producer->id,
  222. 'name' => Html::encode($producer->name),
  223. 'type' => Html::encode($producer->type),
  224. 'address' => Html::encode($producer->postcode.' '.$producer->city),
  225. 'latitude' => $producer->latitude,
  226. 'longitude' => $producer->longitude,
  227. 'link' => $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug])
  228. ];
  229. }
  230. return $producersArrayReturn;
  231. }
  232. /**
  233. * Affiche la page de connexion et traite le formulaire de connexion.
  234. */
  235. public function actionLogin()
  236. {
  237. if (!\Yii::$app->user->isGuest) {
  238. return \Yii::$app->getResponse()->redirect(['site/index']);
  239. }
  240. $model = new LoginForm();
  241. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  242. $returnUrl = \Yii::$app->request->get('return_url');
  243. if ($returnUrl) {
  244. return $this->redirect($returnUrl);
  245. }
  246. else {
  247. $userProducerArray = $this->getUserProducerModule()->findUserProducersByUser(GlobalParam::getCurrentUser());
  248. if ($userProducerArray
  249. && is_array($userProducerArray)
  250. && count($userProducerArray) == 1) {
  251. $urlRedirect = $this->getUrlManagerProducer()
  252. ->createAbsoluteUrl([
  253. 'site/index',
  254. 'slug_producer' => $userProducerArray[0]->producer->slug
  255. ]);
  256. return $this->redirect($urlRedirect);
  257. }
  258. else {
  259. return $this->goBack();
  260. }
  261. }
  262. } else {
  263. return $this->render('@frontend/views/site/login', [
  264. 'model' => $model,
  265. ]);
  266. }
  267. }
  268. /**
  269. * Déconnecte l'utilisateur.
  270. */
  271. public function actionLogout()
  272. {
  273. \Yii::$app->user->logout();
  274. return $this->goHome();
  275. }
  276. /**
  277. * Affiche la page de contact et traite le formulaire s'il est soumis.
  278. */
  279. public function actionContact()
  280. {
  281. $model = new ContactForm();
  282. $messageSent = false;
  283. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  284. $model->sendEmailAdmin();
  285. $messageSent = true;
  286. }
  287. return $this->render('contact', [
  288. 'model' => $model,
  289. 'messageSent' => $messageSent,
  290. ]);
  291. }
  292. /**
  293. * Affiche la page d'inscription et traite son formulaire.
  294. */
  295. public function actionSignup()
  296. {
  297. $model = new SignupForm();
  298. $producerModule = $this->getProducerModule();
  299. if ($model->load(Yii::$app->request->post())) {
  300. $user = $model->signup();
  301. if ($user && Yii::$app->getUser()->login($user)) {
  302. if ($model->isProducer()) {
  303. $this->redirect(['site/signup-confirm']);
  304. }
  305. else {
  306. $producer = $producerModule->findOneProducerById($model->id_producer);
  307. if ($producer) {
  308. $this->redirect(['site/signup-confirm', 'idProducerRedirect' => $producer->id]);
  309. }
  310. else {
  311. $this->redirect(['site/index']);
  312. }
  313. }
  314. }
  315. }
  316. // Liste des producteurs disponibles
  317. $producersArray = $producerModule->populateProducerDropdown();
  318. $dataProducers = $producersArray['data'];
  319. $optionsProducers = $producersArray['options'];
  320. $paidFeaturesArray = $this->getFeatureModule()->getRepository()->findPaidFeatures();
  321. return $this->render('signup', [
  322. 'model' => $model,
  323. 'dataProducers' => $dataProducers,
  324. 'dataProviderPrices' => $this->getDataProviderPrices(),
  325. 'paidFeaturesArray' => $paidFeaturesArray,
  326. 'optionsProducers' => $optionsProducers,
  327. ]);
  328. }
  329. public function actionSignupProducer()
  330. {
  331. $model = new SignupForm();
  332. $model->signup_producer_only = 'producer';
  333. $model->option_user_producer = 'producer';
  334. if ($model->load(Yii::$app->request->post())) {
  335. $user = $model->signup($this->getUserCurrent());
  336. if($user) {
  337. $this->redirect(['site/signup-confirm']);
  338. }
  339. }
  340. return $this->render('signup_producer', [
  341. 'model' => $model,
  342. 'dataProviderPrices' => $this->getDataProviderPrices(),
  343. 'paidFeaturesArray' => $this->getFeatureModule()->getRepository()->findPaidFeatures()
  344. ]);
  345. }
  346. public function actionSignupConfirm($idProducerRedirect = null)
  347. {
  348. $producerModule = $this->getProducerModule();
  349. $user = $this->getUserCurrent();
  350. $producerRedirect = $idProducerRedirect ? $producerModule->findOneProducerById($idProducerRedirect) : null ;
  351. if(!$user) {
  352. throw new NotFoundHttpException('Page introuvable');
  353. }
  354. return $this->render('signup_confirm', [
  355. 'user' => $user,
  356. 'producerRedirect' => $producerRedirect
  357. ]);
  358. }
  359. /**
  360. * Affiche la page de demande de nouveau mot de passe.
  361. * Traitement du formulaire.
  362. */
  363. public function actionRequestPasswordReset()
  364. {
  365. $model = new PasswordResetRequestForm();
  366. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  367. if ($model->sendEmail()) {
  368. $this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe
  369. vient d\'être envoyé sur votre boîte mail.');
  370. return $this->goHome();
  371. }
  372. else {
  373. $this->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
  374. }
  375. }
  376. return $this->render('requestPasswordResetToken', [
  377. 'model' => $model,
  378. ]);
  379. }
  380. /**
  381. * Met à jour le mot de passe de l'utilisateur.
  382. */
  383. public function actionResetPassword($token)
  384. {
  385. try {
  386. $model = new ResetPasswordForm($token);
  387. } catch (InvalidParamException $e) {
  388. throw new BadRequestHttpException($e->getMessage());
  389. }
  390. if ($model->load($this->getRequest()->post())
  391. && $model->validate()
  392. && $model->resetPassword()) {
  393. $this->setFlash('success', 'Votre nouveau mot de passe vient d\'être sauvegardé.');
  394. return $this->goHome();
  395. }
  396. return $this->render('resetPassword', [
  397. 'model' => $model,
  398. ]);
  399. }
  400. /**
  401. * Affiche le formulaire de demande de code pour accéder à certains producteurs.
  402. */
  403. public function actionProducerCode(int $id)
  404. {
  405. $producerModule = $this->getProducerModule();
  406. $producer = $producerModule->findOneProducerById($id);
  407. if (!$producer) {
  408. throw new \yii\web\HttpException(404, 'Producteur introuvable');
  409. }
  410. $producerCodeForm = new ProducerCodeForm();
  411. $producerCodeForm->id_producer = $id;
  412. if ($producerCodeForm->load($this->getRequest()->post())
  413. && $producerCodeForm->validate()) {
  414. $this->getLogic()->setProducerContext($producer);
  415. $producerModule->addUser(GlobalParam::getCurrentUser(), $producer);
  416. $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  417. }
  418. return $this->render('producer_code', [
  419. 'producer' => $producer,
  420. 'producerCodeForm' => $producerCodeForm,
  421. ]);
  422. }
  423. /**
  424. * Affiche la page de connexion / inscription pour accéder notamment au
  425. * formulaire de commande des producteurs.
  426. */
  427. public function actionProducer(int $id)
  428. {
  429. $loginForm = new LoginForm();
  430. $signupForm = new SignupForm();
  431. $producerModule = $this->getProducerModule();
  432. $producer = $producerModule->findOneProducerById($id);
  433. $this->getLogic()->setProducerContext($producer);
  434. $loginForm->id_producer = $id;
  435. $signupForm->id_producer = $id;
  436. $signupForm->option_user_producer = 'user';
  437. $returnUrl = $this->getRequest()->get('return_url', $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  438. if (Yii::$app->user->isGuest) {
  439. if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) {
  440. if (!strlen($producer->code)) {
  441. $producerModule->addUser(GlobalParam::getCurrentUser(), $producer);
  442. }
  443. $this->redirect($returnUrl);
  444. }
  445. if ($signupForm->load($this->getRequest()->post())
  446. && ($user = $signupForm->signup())
  447. && Yii::$app->user->login($user)) {
  448. $this->redirect($returnUrl);
  449. }
  450. }
  451. else {
  452. $this->redirect($returnUrl);
  453. }
  454. return $this->render('producer', [
  455. 'loginForm' => $loginForm,
  456. 'signupForm' => $signupForm,
  457. 'producer' => $producer,
  458. ]);
  459. }
  460. /**
  461. * Indique à l'utilisateur que l'espace d'un producteur est hors ligne.
  462. */
  463. public function actionProducerOffline(int $id)
  464. {
  465. return $this->render('producer_offline', [
  466. 'producer' => $this->getProducerModule()->findOneProducerById($id),
  467. ]);
  468. }
  469. public function actionOpinion()
  470. {
  471. $opinionFormModel = new OpinionForm();
  472. $opinionSent = false;
  473. if ($opinionFormModel->load(Yii::$app->request->post()) && $opinionFormModel->validate()) {
  474. $this->getOpinionModule()->getManager()
  475. ->sendOpinionEmailAdmin($opinionFormModel, $this->getUserCurrent());
  476. $opinionSent = true;
  477. }
  478. return $this->render('opinion', [
  479. 'model' => $opinionFormModel,
  480. 'opinionSent' => $opinionSent
  481. ]);
  482. }
  483. /**
  484. * Affiche les mentions légales.
  485. */
  486. public function actionMentions()
  487. {
  488. return $this->render('mentions');
  489. }
  490. /**
  491. * Affiche les conditions générale de service.
  492. */
  493. public function actionCgv()
  494. {
  495. return $this->render('cgv');
  496. }
  497. /**
  498. * Affiche les précisions concernant l'utilisation du crédit.
  499. */
  500. public function actionCredit()
  501. {
  502. return $this->render('credit');
  503. }
  504. public function actionImageProducersLogos()
  505. {
  506. $image = @imagecreatetruecolor(1600, 1200);
  507. // fond en blanc
  508. $whiteBackground = imagecolorallocate($image, 255, 255, 255);
  509. imagefill($image,0,0,$whiteBackground);
  510. // logos des producteurs
  511. $producerModule = $this->getProducerModule();
  512. $producersArray = $producerModule->getRepository()->findProducersActive();
  513. shuffle($producersArray);
  514. $x = 50;
  515. $y = 0;
  516. foreach($producersArray as $producer) {
  517. if($producer->logo) {
  518. $logo = null;
  519. $srcLogo = dirname(__FILE__).'/../../producer/web/uploads/'.$producer->logo;
  520. $imageType = exif_imagetype($srcLogo);
  521. if($imageType == IMAGETYPE_PNG) {
  522. $logo = imagecreatefrompng($srcLogo);
  523. $backgroundBlack = imagecolorallocate($logo , 0, 0, 0);
  524. imagecolortransparent($logo, $backgroundBlack);
  525. }
  526. elseif($imageType == IMAGETYPE_JPEG) {
  527. $logo = imagecreatefromjpeg($srcLogo);
  528. }
  529. if($logo) {
  530. imagealphablending($logo, false);
  531. imagesavealpha($logo, true);
  532. list(
  533. $sourceImageWidth,
  534. $sourceImageHeight
  535. ) = getimagesize( $srcLogo);
  536. if($sourceImageWidth && $sourceImageHeight) {
  537. $targetImageWidth = 120;
  538. $targetImageHeight = 120;
  539. $sourceAspectRatio = $sourceImageWidth / $sourceImageHeight;
  540. $targetAspectRatio = $targetImageWidth / $targetImageHeight;
  541. if ($targetAspectRatio > $sourceAspectRatio) {
  542. $targetImageHeight = (int) ($targetImageWidth / $sourceAspectRatio);
  543. }
  544. else {
  545. $targetImageWidth = (int) ($targetImageHeight * $sourceAspectRatio);
  546. }
  547. $transparency = 0.7;
  548. imagefilter($logo, IMG_FILTER_COLORIZE, 0,0,0,127 * $transparency);
  549. imagecopyresampled($image, $logo, $x, $y + 60, 0, 0, $targetImageWidth, $targetImageHeight, $sourceImageWidth, $sourceImageHeight);
  550. $x += $targetImageWidth + 75;
  551. if($x > 1600) {
  552. $x = rand(-50, 50);
  553. $y += 200;
  554. }
  555. }
  556. }
  557. }
  558. }
  559. // noir et blanc
  560. imagefilter($image, IMG_FILTER_GRAYSCALE);
  561. // rendu de l'image
  562. header ('Content-Type: image/png');
  563. imagepng($image);
  564. imagedestroy($image);
  565. die();
  566. }
  567. }