Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

655 lines
22KB

  1. <?php
  2. /**
  3. * Copyright Souke (2018)
  4. *
  5. * contact@souke.fr
  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. public function actionIndex()
  128. {
  129. $dataProviderProducers = new ActiveDataProvider([
  130. 'query' => $this->getProducerModule()->queryProducersActive('producer.date_creation', 'DESC')->query(),
  131. 'pagination' => [
  132. 'pageSize' => 100,
  133. ],
  134. ]);
  135. return $this->render('index', [
  136. 'dataProviderProducers' => $dataProviderProducers,
  137. 'producersArray' => $this->getProducerModule()->findProducersActive('producer.date_creation', 'DESC')
  138. ]);
  139. }
  140. public function actionIamproducer()
  141. {
  142. return $this->render('iamproducer', []);
  143. }
  144. public function actionService()
  145. {
  146. $paidFeaturesArray = $this->getFeatureModule()->getRepository()->findPaidFeatures();
  147. return $this->render('service', [
  148. 'producerDemoAccount' => $this->getProducerModule()->findOneProducerDemoAccount(),
  149. 'dataProviderPrices' => $this->getDataProviderPrices(),
  150. 'paidFeaturesArray' => $paidFeaturesArray
  151. ]);
  152. }
  153. public function getDataProviderPrices()
  154. {
  155. return new ActiveDataProvider([
  156. 'query' => $this->getProducerPriceRangeModule()->queryProducerPriceRanges()->query(),
  157. 'pagination' => [
  158. 'pageSize' => 100,
  159. ],
  160. ]);
  161. }
  162. public function actionProducers()
  163. {
  164. return $this->render('producer', [
  165. 'maximumNumberProducers' => $this->getSettingModule()->getAdminSettingBag()->get('maximumNumberProducers'),
  166. 'countProducersActive' => $this->getProducerModule()->getRepository()->countCacheProducersActiveWithTurnover()
  167. ]);
  168. }
  169. public function actionAbout()
  170. {
  171. $aboutFewNumbers = Yii::$app->cache->getOrSet('about_few_numbers3', function () {
  172. $producerModule = $this->getProducerModule();
  173. $pointSaleModule = $this->getPointSaleModule();
  174. $userModule = $this->getUserModule();
  175. $orderModule = $this->getOrderModule();
  176. $countProducersActive = $producerModule->getRepository()->countProducersActiveWithTurnover();
  177. $timeSavedByProducersAverage = $producerModule->getTimeSavedByProducersAverage();
  178. $countProducersWithOptionTimeSaved = $producerModule->countProducersWithTimeSaved();
  179. $countPointSalesActive = $pointSaleModule->countPointSalesActiveLastThreeMonths();
  180. $countUsersActive = $userModule->countUsersActiveLastThreeMonths();
  181. $averageOrdersPerDay = $orderModule->countGlobalUserOrdersAverageLastSevenDays();
  182. $turnoverLastThirtyDays = $orderModule->getRepository()->getTurnoverLastThirtyDays();
  183. $resultMatomoApiVisitSummary = json_decode(file_get_contents(Yii::$app->parameterBag->get('matomoApiVisitSummaryUrl')));
  184. $numberVisitsByDay = $resultMatomoApiVisitSummary->nb_uniq_visitors / 30;
  185. return $this->renderPartial('_about_few_numbers', [
  186. 'countProducersActive' => $countProducersActive,
  187. 'countPointSalesActive' => $countPointSalesActive,
  188. 'countUsersActive' => $countUsersActive,
  189. 'averageOrdersPerDay' => $averageOrdersPerDay,
  190. 'turnoverLastThirtyDays' => $turnoverLastThirtyDays,
  191. 'numberVisitsByDay' => $numberVisitsByDay,
  192. 'timeSavedByProducersAverage' => $timeSavedByProducersAverage,
  193. 'countProducersWithOptionTimeSaved' => $countProducersWithOptionTimeSaved
  194. ]);
  195. }, 60 * 60 * 24);
  196. $producerModule = $this->getProducerModule();
  197. return $this->render('about', [
  198. 'countProducers' => $producerModule->countProducersActiveWithTurnover(),
  199. 'producersWithTestimonials' => $producerModule->findProducersWithTestimonials(),
  200. 'aboutFewNumbers' => $aboutFewNumbers
  201. ]);
  202. }
  203. /*public function actionSourceCode()
  204. {
  205. return $this->render('source_code');
  206. }*/
  207. /**
  208. * Liste les producteurs utilisant la plateforme.
  209. */
  210. public function actionAjaxProducers()
  211. {
  212. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  213. $producersArray = $this->getProducerModule()->findProducersActive();
  214. $producersArrayReturn = [];
  215. foreach($producersArray as $producer) {
  216. $producersArrayReturn[] = [
  217. 'id' => $producer->id,
  218. 'name' => Html::encode($producer->name),
  219. 'type' => Html::encode($producer->type),
  220. 'address' => Html::encode($producer->postcode.' '.$producer->city),
  221. 'latitude' => $producer->latitude,
  222. 'longitude' => $producer->longitude,
  223. 'link' => $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug])
  224. ];
  225. }
  226. return $producersArrayReturn;
  227. }
  228. /**
  229. * Affiche la page de connexion et traite le formulaire de connexion.
  230. */
  231. public function actionLogin()
  232. {
  233. if (!\Yii::$app->user->isGuest) {
  234. return \Yii::$app->getResponse()->redirect(['site/index']);
  235. }
  236. $model = new LoginForm();
  237. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  238. $returnUrl = \Yii::$app->request->get('return_url');
  239. if ($returnUrl) {
  240. return $this->redirect($returnUrl);
  241. }
  242. else {
  243. $userProducerArray = $this->getUserProducerModule()->findUserProducersByUser(GlobalParam::getCurrentUser());
  244. if ($userProducerArray
  245. && is_array($userProducerArray)
  246. && count($userProducerArray) == 1) {
  247. $urlRedirect = $this->getUrlManagerProducer()
  248. ->createAbsoluteUrl([
  249. 'site/index',
  250. 'slug_producer' => $userProducerArray[0]->producer->slug
  251. ]);
  252. return $this->redirect($urlRedirect);
  253. }
  254. else {
  255. return $this->goBack();
  256. }
  257. }
  258. } else {
  259. return $this->render('@frontend/views/site/login', [
  260. 'model' => $model,
  261. ]);
  262. }
  263. }
  264. /**
  265. * Déconnecte l'utilisateur.
  266. */
  267. public function actionLogout()
  268. {
  269. \Yii::$app->user->logout();
  270. return $this->goHome();
  271. }
  272. /**
  273. * Affiche la page de contact et traite le formulaire s'il est soumis.
  274. */
  275. public function actionContact()
  276. {
  277. $model = new ContactForm();
  278. $messageSent = false;
  279. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  280. $model->sendEmailAdmin();
  281. $messageSent = true;
  282. $model = new ContactForm();
  283. }
  284. return $this->render('contact', [
  285. 'model' => $model,
  286. 'messageSent' => $messageSent,
  287. ]);
  288. }
  289. /**
  290. * Affiche la page d'inscription et traite son formulaire.
  291. */
  292. public function actionSignup(string $type = 'user')
  293. {
  294. $model = new SignupForm();
  295. $model->option_user_producer = $type;
  296. $producerModule = $this->getProducerModule();
  297. if ($model->load(Yii::$app->request->post())) {
  298. $user = $model->signup();
  299. if ($user && Yii::$app->getUser()->login($user)) {
  300. if ($model->isProducer()) {
  301. $this->redirect(['site/signup-confirm']);
  302. }
  303. else {
  304. $producer = $producerModule->findOneProducerById($model->id_producer);
  305. if ($producer) {
  306. $this->redirect(['site/signup-confirm', 'idProducerRedirect' => $producer->id]);
  307. }
  308. else {
  309. $this->redirect(['site/index']);
  310. }
  311. }
  312. }
  313. }
  314. // Liste des producteurs disponibles
  315. $producersArray = $producerModule->populateProducerDropdown();
  316. $dataProducers = $producersArray['data'];
  317. $optionsProducers = $producersArray['options'];
  318. $paidFeaturesArray = $this->getFeatureModule()->getRepository()->findPaidFeatures();
  319. return $this->render('signup', [
  320. 'model' => $model,
  321. 'dataProducers' => $dataProducers,
  322. 'dataProviderPrices' => $this->getDataProviderPrices(),
  323. 'paidFeaturesArray' => $paidFeaturesArray,
  324. 'optionsProducers' => $optionsProducers,
  325. ]);
  326. }
  327. public function actionSignupProducer()
  328. {
  329. $model = new SignupForm();
  330. $model->signup_producer_only = 'producer';
  331. $model->option_user_producer = 'producer';
  332. if ($model->load(Yii::$app->request->post())) {
  333. $user = $model->signup($this->getUserCurrent());
  334. if($user) {
  335. $this->redirect(['site/signup-confirm']);
  336. }
  337. }
  338. return $this->render('signup_producer', [
  339. 'model' => $model,
  340. 'dataProviderPrices' => $this->getDataProviderPrices(),
  341. 'paidFeaturesArray' => $this->getFeatureModule()->getRepository()->findPaidFeatures()
  342. ]);
  343. }
  344. public function actionSignupConfirm($idProducerRedirect = null)
  345. {
  346. $producerModule = $this->getProducerModule();
  347. $user = $this->getUserCurrent();
  348. $producerRedirect = $idProducerRedirect ? $producerModule->findOneProducerById($idProducerRedirect) : null ;
  349. if(!$user) {
  350. throw new NotFoundHttpException('Page introuvable');
  351. }
  352. return $this->render('signup_confirm', [
  353. 'user' => $user,
  354. 'producerRedirect' => $producerRedirect
  355. ]);
  356. }
  357. /**
  358. * Affiche la page de demande de nouveau mot de passe.
  359. * Traitement du formulaire.
  360. */
  361. public function actionRequestPasswordReset()
  362. {
  363. $model = new PasswordResetRequestForm();
  364. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  365. if ($model->sendEmail()) {
  366. $this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe
  367. vient d\'être envoyé sur votre boîte mail.');
  368. return $this->goHome();
  369. }
  370. else {
  371. $this->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
  372. }
  373. }
  374. return $this->render('requestPasswordResetToken', [
  375. 'model' => $model,
  376. ]);
  377. }
  378. /**
  379. * Met à jour le mot de passe de l'utilisateur.
  380. */
  381. public function actionResetPassword($token)
  382. {
  383. try {
  384. $model = new ResetPasswordForm($token);
  385. } catch (InvalidParamException $e) {
  386. throw new BadRequestHttpException($e->getMessage());
  387. }
  388. if ($model->load($this->getRequest()->post())
  389. && $model->validate()
  390. && $model->resetPassword()) {
  391. $this->setFlash('success', 'Votre nouveau mot de passe vient d\'être sauvegardé.');
  392. return $this->goHome();
  393. }
  394. return $this->render('resetPassword', [
  395. 'model' => $model,
  396. ]);
  397. }
  398. /**
  399. * Affiche le formulaire de demande de code pour accéder à certains producteurs.
  400. */
  401. public function actionProducerCode(int $id)
  402. {
  403. $producerModule = $this->getProducerModule();
  404. $producer = $producerModule->findOneProducerById($id);
  405. if (!$producer) {
  406. throw new \yii\web\HttpException(404, 'Producteur introuvable');
  407. }
  408. $producerCodeForm = new ProducerCodeForm();
  409. $producerCodeForm->id_producer = $id;
  410. if ($producerCodeForm->load($this->getRequest()->post())
  411. && $producerCodeForm->validate()) {
  412. $this->getLogic()->setProducerContext($producer);
  413. $producerModule->addUser(GlobalParam::getCurrentUser(), $producer);
  414. $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  415. }
  416. return $this->render('producer_code', [
  417. 'producer' => $producer,
  418. 'producerCodeForm' => $producerCodeForm,
  419. ]);
  420. }
  421. /**
  422. * Affiche la page de connexion / inscription pour accéder notamment au
  423. * formulaire de commande des producteurs.
  424. */
  425. public function actionProducer(int $id)
  426. {
  427. $loginForm = new LoginForm();
  428. $signupForm = new SignupForm();
  429. $producerModule = $this->getProducerModule();
  430. $producer = $producerModule->findOneProducerById($id);
  431. $this->getLogic()->setProducerContext($producer);
  432. $loginForm->id_producer = $id;
  433. $signupForm->id_producer = $id;
  434. $signupForm->option_user_producer = 'user';
  435. $returnUrl = $this->getRequest()->get('return_url', $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  436. if (Yii::$app->user->isGuest) {
  437. if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) {
  438. if (!strlen($producer->code)) {
  439. $producerModule->addUser(GlobalParam::getCurrentUser(), $producer);
  440. }
  441. $this->redirect($returnUrl);
  442. }
  443. if ($signupForm->load($this->getRequest()->post())
  444. && ($user = $signupForm->signup())
  445. && Yii::$app->user->login($user)) {
  446. $this->redirect($returnUrl);
  447. }
  448. }
  449. else {
  450. $this->redirect($returnUrl);
  451. }
  452. return $this->render('producer', [
  453. 'loginForm' => $loginForm,
  454. 'signupForm' => $signupForm,
  455. 'producer' => $producer,
  456. ]);
  457. }
  458. /**
  459. * Indique à l'utilisateur que l'espace d'un producteur est hors ligne.
  460. */
  461. public function actionProducerOffline(int $id)
  462. {
  463. return $this->render('producer_offline', [
  464. 'producer' => $this->getProducerModule()->findOneProducerById($id),
  465. ]);
  466. }
  467. public function actionOpinion()
  468. {
  469. $opinionFormModel = new OpinionForm();
  470. $opinionSent = false;
  471. if ($opinionFormModel->load(Yii::$app->request->post()) && $opinionFormModel->validate()) {
  472. $this->getOpinionModule()->getManager()
  473. ->sendOpinionEmailAdmin($opinionFormModel, $this->getUserCurrent());
  474. $opinionSent = true;
  475. $opinionFormModel = new OpinionForm();
  476. }
  477. return $this->render('opinion', [
  478. 'model' => $opinionFormModel,
  479. 'opinionSent' => $opinionSent
  480. ]);
  481. }
  482. /**
  483. * Affiche les mentions légales.
  484. */
  485. public function actionMentions()
  486. {
  487. return $this->render('mentions');
  488. }
  489. /**
  490. * Affiche les conditions générale de service.
  491. */
  492. public function actionCgv()
  493. {
  494. return $this->render('cgv');
  495. }
  496. /**
  497. * Affiche les précisions concernant l'utilisation de la cagnotte
  498. */
  499. public function actionCredit()
  500. {
  501. return $this->render('credit');
  502. }
  503. public function actionImageProducersLogos()
  504. {
  505. $image = @imagecreatetruecolor(1600, 1200);
  506. // fond en blanc
  507. $whiteBackground = imagecolorallocate($image, 255, 255, 255);
  508. imagefill($image,0,0,$whiteBackground);
  509. // logos des producteurs
  510. $producerModule = $this->getProducerModule();
  511. $producersArray = $producerModule->getRepository()->findProducersActive();
  512. shuffle($producersArray);
  513. $x = 50;
  514. $y = 0;
  515. foreach($producersArray as $producer) {
  516. if($producer->logo) {
  517. $logo = null;
  518. $srcLogo = dirname(__FILE__).'/../../producer/web/uploads/'.$producer->logo;
  519. $imageType = exif_imagetype($srcLogo);
  520. if($imageType == IMAGETYPE_PNG) {
  521. $logo = imagecreatefrompng($srcLogo);
  522. $backgroundBlack = imagecolorallocate($logo , 0, 0, 0);
  523. imagecolortransparent($logo, $backgroundBlack);
  524. }
  525. elseif($imageType == IMAGETYPE_JPEG) {
  526. $logo = imagecreatefromjpeg($srcLogo);
  527. }
  528. if($logo) {
  529. imagealphablending($logo, false);
  530. imagesavealpha($logo, true);
  531. list(
  532. $sourceImageWidth,
  533. $sourceImageHeight
  534. ) = getimagesize( $srcLogo);
  535. if($sourceImageWidth && $sourceImageHeight) {
  536. $targetImageWidth = 120;
  537. $targetImageHeight = 120;
  538. $sourceAspectRatio = $sourceImageWidth / $sourceImageHeight;
  539. $targetAspectRatio = $targetImageWidth / $targetImageHeight;
  540. if ($targetAspectRatio > $sourceAspectRatio) {
  541. $targetImageHeight = (int) ($targetImageWidth / $sourceAspectRatio);
  542. }
  543. else {
  544. $targetImageWidth = (int) ($targetImageHeight * $sourceAspectRatio);
  545. }
  546. $transparency = 0.7;
  547. imagefilter($logo, IMG_FILTER_COLORIZE, 0,0,0,127 * $transparency);
  548. imagecopyresampled($image, $logo, $x, $y + 60, 0, 0, $targetImageWidth, $targetImageHeight, $sourceImageWidth, $sourceImageHeight);
  549. $x += $targetImageWidth + 75;
  550. if($x > 1600) {
  551. $x = rand(-50, 50);
  552. $y += 200;
  553. }
  554. }
  555. }
  556. }
  557. }
  558. // noir et blanc
  559. imagefilter($image, IMG_FILTER_GRAYSCALE);
  560. // rendu de l'image
  561. header ('Content-Type: image/png');
  562. imagepng($image);
  563. imagedestroy($image);
  564. die();
  565. }
  566. }