Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

SiteController.php 22KB

8 anos atrás
8 anos atrás
8 anos atrás
8 anos atrás
8 anos atrás
1 ano atrás
8 anos atrás
8 anos atrás
1 ano atrás
8 anos atrás
1 ano atrás
1 ano atrás
1 ano atrás
1 ano atrás
1 ano atrás
8 anos atrás
8 anos atrás
8 anos atrás
8 anos atrás
1 ano atrás
1 ano atrás
8 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  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_numbers7', 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. $resultMatomoApiVisitSummary = json_decode(file_get_contents(Yii::$app->parameterBag->get('matomoApiVisitSummaryUrl')));
  186. $numberVisitsMonth = $resultMatomoApiVisitSummary->nb_uniq_visitors;
  187. return $this->renderPartial('_about_few_numbers', [
  188. 'countProducersActive' => $countProducersActive,
  189. 'countPointSalesActive' => $countPointSalesActive,
  190. 'countUsersActive' => $countUsersActive,
  191. 'averageOrdersPerDay' => $averageOrdersPerDay,
  192. 'averageTurnover' => $averageTurnover,
  193. 'numberVisitsMonth' => $numberVisitsMonth,
  194. 'timeSavedByProducersAverage' => $timeSavedByProducersAverage,
  195. 'countProducersWithOptionTimeSaved' => $countProducersWithOptionTimeSaved
  196. ]);
  197. }, 60 * 60 * 24);
  198. $producerModule = $this->getProducerModule();
  199. return $this->render('about', [
  200. 'countProducers' => $producerModule->countProducersActiveWithTurnover(),
  201. 'producersWithTestimonials' => $producerModule->findProducersWithTestimonials(),
  202. 'aboutFewNumbers' => $aboutFewNumbers
  203. ]);
  204. }
  205. /*public function actionSourceCode()
  206. {
  207. return $this->render('source_code');
  208. }*/
  209. /**
  210. * Liste les producteurs utilisant la plateforme.
  211. */
  212. public function actionAjaxProducers()
  213. {
  214. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  215. $producersArray = $this->getProducerModule()->findProducersActive();
  216. $producersArrayReturn = [];
  217. foreach($producersArray as $producer) {
  218. $producersArrayReturn[] = [
  219. 'id' => $producer->id,
  220. 'name' => Html::encode($producer->name),
  221. 'type' => Html::encode($producer->type),
  222. 'address' => Html::encode($producer->postcode.' '.$producer->city),
  223. 'latitude' => $producer->latitude,
  224. 'longitude' => $producer->longitude,
  225. 'link' => $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug])
  226. ];
  227. }
  228. return $producersArrayReturn;
  229. }
  230. /**
  231. * Affiche la page de connexion et traite le formulaire de connexion.
  232. */
  233. public function actionLogin()
  234. {
  235. if (!\Yii::$app->user->isGuest) {
  236. return \Yii::$app->getResponse()->redirect(['site/index']);
  237. }
  238. $model = new LoginForm();
  239. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  240. $returnUrl = \Yii::$app->request->get('return_url');
  241. if ($returnUrl) {
  242. return $this->redirect($returnUrl);
  243. }
  244. else {
  245. $userProducerArray = $this->getUserProducerModule()->findUserProducersByUser(GlobalParam::getCurrentUser());
  246. if ($userProducerArray
  247. && is_array($userProducerArray)
  248. && count($userProducerArray) == 1) {
  249. $urlRedirect = $this->getUrlManagerProducer()
  250. ->createAbsoluteUrl([
  251. 'site/index',
  252. 'slug_producer' => $userProducerArray[0]->producer->slug
  253. ]);
  254. return $this->redirect($urlRedirect);
  255. }
  256. else {
  257. return $this->goBack();
  258. }
  259. }
  260. } else {
  261. return $this->render('@frontend/views/site/login', [
  262. 'model' => $model,
  263. ]);
  264. }
  265. }
  266. /**
  267. * Déconnecte l'utilisateur.
  268. */
  269. public function actionLogout()
  270. {
  271. \Yii::$app->user->logout();
  272. return $this->goHome();
  273. }
  274. /**
  275. * Affiche la page de contact et traite le formulaire s'il est soumis.
  276. */
  277. public function actionContact()
  278. {
  279. $model = new ContactForm();
  280. $messageSent = false;
  281. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  282. $model->sendEmailAdmin();
  283. $messageSent = true;
  284. }
  285. return $this->render('contact', [
  286. 'model' => $model,
  287. 'messageSent' => $messageSent,
  288. ]);
  289. }
  290. /**
  291. * Affiche la page d'inscription et traite son formulaire.
  292. */
  293. public function actionSignup()
  294. {
  295. $model = new SignupForm();
  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. }
  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 du crédit.
  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. }