Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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