Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

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