Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

654 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()
  293. {
  294. $model = new SignupForm();
  295. $producerModule = $this->getProducerModule();
  296. if ($model->load(Yii::$app->request->post())) {
  297. $user = $model->signup();
  298. if ($user && Yii::$app->getUser()->login($user)) {
  299. if ($model->isProducer()) {
  300. $this->redirect(['site/signup-confirm']);
  301. }
  302. else {
  303. $producer = $producerModule->findOneProducerById($model->id_producer);
  304. if ($producer) {
  305. $this->redirect(['site/signup-confirm', 'idProducerRedirect' => $producer->id]);
  306. }
  307. else {
  308. $this->redirect(['site/index']);
  309. }
  310. }
  311. }
  312. }
  313. // Liste des producteurs disponibles
  314. $producersArray = $producerModule->populateProducerDropdown();
  315. $dataProducers = $producersArray['data'];
  316. $optionsProducers = $producersArray['options'];
  317. $paidFeaturesArray = $this->getFeatureModule()->getRepository()->findPaidFeatures();
  318. return $this->render('signup', [
  319. 'model' => $model,
  320. 'dataProducers' => $dataProducers,
  321. 'dataProviderPrices' => $this->getDataProviderPrices(),
  322. 'paidFeaturesArray' => $paidFeaturesArray,
  323. 'optionsProducers' => $optionsProducers,
  324. ]);
  325. }
  326. public function actionSignupProducer()
  327. {
  328. $model = new SignupForm();
  329. $model->signup_producer_only = 'producer';
  330. $model->option_user_producer = 'producer';
  331. if ($model->load(Yii::$app->request->post())) {
  332. $user = $model->signup($this->getUserCurrent());
  333. if($user) {
  334. $this->redirect(['site/signup-confirm']);
  335. }
  336. }
  337. return $this->render('signup_producer', [
  338. 'model' => $model,
  339. 'dataProviderPrices' => $this->getDataProviderPrices(),
  340. 'paidFeaturesArray' => $this->getFeatureModule()->getRepository()->findPaidFeatures()
  341. ]);
  342. }
  343. public function actionSignupConfirm($idProducerRedirect = null)
  344. {
  345. $producerModule = $this->getProducerModule();
  346. $user = $this->getUserCurrent();
  347. $producerRedirect = $idProducerRedirect ? $producerModule->findOneProducerById($idProducerRedirect) : null ;
  348. if(!$user) {
  349. throw new NotFoundHttpException('Page introuvable');
  350. }
  351. return $this->render('signup_confirm', [
  352. 'user' => $user,
  353. 'producerRedirect' => $producerRedirect
  354. ]);
  355. }
  356. /**
  357. * Affiche la page de demande de nouveau mot de passe.
  358. * Traitement du formulaire.
  359. */
  360. public function actionRequestPasswordReset()
  361. {
  362. $model = new PasswordResetRequestForm();
  363. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  364. if ($model->sendEmail()) {
  365. $this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe
  366. vient d\'être envoyé sur votre boîte mail.');
  367. return $this->goHome();
  368. }
  369. else {
  370. $this->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
  371. }
  372. }
  373. return $this->render('requestPasswordResetToken', [
  374. 'model' => $model,
  375. ]);
  376. }
  377. /**
  378. * Met à jour le mot de passe de l'utilisateur.
  379. */
  380. public function actionResetPassword($token)
  381. {
  382. try {
  383. $model = new ResetPasswordForm($token);
  384. } catch (InvalidParamException $e) {
  385. throw new BadRequestHttpException($e->getMessage());
  386. }
  387. if ($model->load($this->getRequest()->post())
  388. && $model->validate()
  389. && $model->resetPassword()) {
  390. $this->setFlash('success', 'Votre nouveau mot de passe vient d\'être sauvegardé.');
  391. return $this->goHome();
  392. }
  393. return $this->render('resetPassword', [
  394. 'model' => $model,
  395. ]);
  396. }
  397. /**
  398. * Affiche le formulaire de demande de code pour accéder à certains producteurs.
  399. */
  400. public function actionProducerCode(int $id)
  401. {
  402. $producerModule = $this->getProducerModule();
  403. $producer = $producerModule->findOneProducerById($id);
  404. if (!$producer) {
  405. throw new \yii\web\HttpException(404, 'Producteur introuvable');
  406. }
  407. $producerCodeForm = new ProducerCodeForm();
  408. $producerCodeForm->id_producer = $id;
  409. if ($producerCodeForm->load($this->getRequest()->post())
  410. && $producerCodeForm->validate()) {
  411. $this->getLogic()->setProducerContext($producer);
  412. $producerModule->addUser(GlobalParam::getCurrentUser(), $producer);
  413. $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  414. }
  415. return $this->render('producer_code', [
  416. 'producer' => $producer,
  417. 'producerCodeForm' => $producerCodeForm,
  418. ]);
  419. }
  420. /**
  421. * Affiche la page de connexion / inscription pour accéder notamment au
  422. * formulaire de commande des producteurs.
  423. */
  424. public function actionProducer(int $id)
  425. {
  426. $loginForm = new LoginForm();
  427. $signupForm = new SignupForm();
  428. $producerModule = $this->getProducerModule();
  429. $producer = $producerModule->findOneProducerById($id);
  430. $this->getLogic()->setProducerContext($producer);
  431. $loginForm->id_producer = $id;
  432. $signupForm->id_producer = $id;
  433. $signupForm->option_user_producer = 'user';
  434. $returnUrl = $this->getRequest()->get('return_url', $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  435. if (Yii::$app->user->isGuest) {
  436. if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) {
  437. if (!strlen($producer->code)) {
  438. $producerModule->addUser(GlobalParam::getCurrentUser(), $producer);
  439. }
  440. $this->redirect($returnUrl);
  441. }
  442. if ($signupForm->load($this->getRequest()->post())
  443. && ($user = $signupForm->signup())
  444. && Yii::$app->user->login($user)) {
  445. $this->redirect($returnUrl);
  446. }
  447. }
  448. else {
  449. $this->redirect($returnUrl);
  450. }
  451. return $this->render('producer', [
  452. 'loginForm' => $loginForm,
  453. 'signupForm' => $signupForm,
  454. 'producer' => $producer,
  455. ]);
  456. }
  457. /**
  458. * Indique à l'utilisateur que l'espace d'un producteur est hors ligne.
  459. */
  460. public function actionProducerOffline(int $id)
  461. {
  462. return $this->render('producer_offline', [
  463. 'producer' => $this->getProducerModule()->findOneProducerById($id),
  464. ]);
  465. }
  466. public function actionOpinion()
  467. {
  468. $opinionFormModel = new OpinionForm();
  469. $opinionSent = false;
  470. if ($opinionFormModel->load(Yii::$app->request->post()) && $opinionFormModel->validate()) {
  471. $this->getOpinionModule()->getManager()
  472. ->sendOpinionEmailAdmin($opinionFormModel, $this->getUserCurrent());
  473. $opinionSent = true;
  474. $opinionFormModel = new OpinionForm();
  475. }
  476. return $this->render('opinion', [
  477. 'model' => $opinionFormModel,
  478. 'opinionSent' => $opinionSent
  479. ]);
  480. }
  481. /**
  482. * Affiche les mentions légales.
  483. */
  484. public function actionMentions()
  485. {
  486. return $this->render('mentions');
  487. }
  488. /**
  489. * Affiche les conditions générale de service.
  490. */
  491. public function actionCgv()
  492. {
  493. return $this->render('cgv');
  494. }
  495. /**
  496. * Affiche les précisions concernant l'utilisation de la cagnotte
  497. */
  498. public function actionCredit()
  499. {
  500. return $this->render('credit');
  501. }
  502. public function actionImageProducersLogos()
  503. {
  504. $image = @imagecreatetruecolor(1600, 1200);
  505. // fond en blanc
  506. $whiteBackground = imagecolorallocate($image, 255, 255, 255);
  507. imagefill($image,0,0,$whiteBackground);
  508. // logos des producteurs
  509. $producerModule = $this->getProducerModule();
  510. $producersArray = $producerModule->getRepository()->findProducersActive();
  511. shuffle($producersArray);
  512. $x = 50;
  513. $y = 0;
  514. foreach($producersArray as $producer) {
  515. if($producer->logo) {
  516. $logo = null;
  517. $srcLogo = dirname(__FILE__).'/../../producer/web/uploads/'.$producer->logo;
  518. $imageType = exif_imagetype($srcLogo);
  519. if($imageType == IMAGETYPE_PNG) {
  520. $logo = imagecreatefrompng($srcLogo);
  521. $backgroundBlack = imagecolorallocate($logo , 0, 0, 0);
  522. imagecolortransparent($logo, $backgroundBlack);
  523. }
  524. elseif($imageType == IMAGETYPE_JPEG) {
  525. $logo = imagecreatefromjpeg($srcLogo);
  526. }
  527. if($logo) {
  528. imagealphablending($logo, false);
  529. imagesavealpha($logo, true);
  530. list(
  531. $sourceImageWidth,
  532. $sourceImageHeight
  533. ) = getimagesize( $srcLogo);
  534. if($sourceImageWidth && $sourceImageHeight) {
  535. $targetImageWidth = 120;
  536. $targetImageHeight = 120;
  537. $sourceAspectRatio = $sourceImageWidth / $sourceImageHeight;
  538. $targetAspectRatio = $targetImageWidth / $targetImageHeight;
  539. if ($targetAspectRatio > $sourceAspectRatio) {
  540. $targetImageHeight = (int) ($targetImageWidth / $sourceAspectRatio);
  541. }
  542. else {
  543. $targetImageWidth = (int) ($targetImageHeight * $sourceAspectRatio);
  544. }
  545. $transparency = 0.7;
  546. imagefilter($logo, IMG_FILTER_COLORIZE, 0,0,0,127 * $transparency);
  547. imagecopyresampled($image, $logo, $x, $y + 60, 0, 0, $targetImageWidth, $targetImageHeight, $sourceImageWidth, $sourceImageHeight);
  548. $x += $targetImageWidth + 75;
  549. if($x > 1600) {
  550. $x = rand(-50, 50);
  551. $y += 200;
  552. }
  553. }
  554. }
  555. }
  556. }
  557. // noir et blanc
  558. imagefilter($image, IMG_FILTER_GRAYSCALE);
  559. // rendu de l'image
  560. header ('Content-Type: image/png');
  561. imagepng($image);
  562. imagedestroy($image);
  563. die();
  564. }
  565. }