|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540 |
- <?php
-
- /**
- * Copyright distrib (2018)
- *
- * contact@opendistrib.net
- *
- * Ce logiciel est un programme informatique servant à aider les producteurs
- * à distribuer leur production en circuits courts.
- *
- * Ce logiciel est régi par la licence CeCILL soumise au droit français et
- * respectant les principes de diffusion des logiciels libres. Vous pouvez
- * utiliser, modifier et/ou redistribuer ce programme sous les conditions
- * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
- * sur le site "http://www.cecill.info".
- *
- * En contrepartie de l'accessibilité au code source et des droits de copie,
- * de modification et de redistribution accordés par cette licence, il n'est
- * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
- * seule une responsabilité restreinte pèse sur l'auteur du programme, le
- * titulaire des droits patrimoniaux et les concédants successifs.
- *
- * A cet égard l'attention de l'utilisateur est attirée sur les risques
- * associés au chargement, à l'utilisation, à la modification et/ou au
- * développement et à la reproduction du logiciel par l'utilisateur étant
- * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
- * manipuler et qui le réserve donc à des développeurs et des professionnels
- * avertis possédant des connaissances informatiques approfondies. Les
- * utilisateurs sont donc invités à charger et tester l'adéquation du
- * logiciel à leurs besoins dans des conditions permettant d'assurer la
- * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
- * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
- *
- * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
- * pris connaissance de la licence CeCILL, et que vous en avez accepté les
- * termes.
- */
-
- namespace frontend\controllers;
-
- use common\helpers\GlobalParam;
- use frontend\forms\OpinionForm;
- use frontend\forms\ProducerCodeForm;
- use GuzzleHttp\Client;
- use Yii;
- use frontend\forms\PasswordResetRequestForm;
- use frontend\forms\ResetPasswordForm;
- use frontend\forms\SignupForm;
- use common\forms\ContactForm;
- use yii\base\InvalidParamException;
- use yii\base\UserException;
- use yii\data\ActiveDataProvider;
- use yii\helpers\Html;
- use yii\web\BadRequestHttpException;
- use yii\filters\VerbFilter;
- use yii\filters\AccessControl;
- use common\forms\LoginForm;
- use yii\web\NotFoundHttpException;
-
- /**
- * Site controller
- */
- class SiteController extends FrontendController
- {
- /**
- * @inheritdoc
- */
- public function behaviors()
- {
- return [
- 'access' => [
- 'class' => AccessControl::class,
- 'only' => ['logout', 'signup'],
- 'rules' => [
- [
- 'actions' => ['signup'],
- 'allow' => true,
- 'roles' => ['?'],
- ],
- [
- 'actions' => ['logout'],
- 'allow' => true,
- 'roles' => ['@'],
- ],
- ],
- 'denyCallback' => function($rule, $action) {
- return $this->redirect('index');
- }
- ],
- 'verbs' => [
- 'class' => VerbFilter::class,
- 'actions' => [
- 'logout' => ['get'],
- ],
- ],
- ];
- }
-
- /**
- * @inheritdoc
- */
- public function actions()
- {
- return [
- 'captcha' => [
- 'class' => 'yii\captcha\CaptchaAction',
- 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
- ],
- ];
- }
-
- /**
- * Affiche la page d'erreur.
- *
- * @return mixed
- */
- public function actionError()
- {
- $exception = \Yii::$app->errorHandler->exception;
-
- if ($exception->getMessage() == 'Producteur introuvable'
- || \Yii::$app->getRequest()->getQueryParam('producer_not_found')) {
- return $this->render('error-404-producer', ['exception' => $exception]);
- }
-
- if ($exception !== null) {
- return $this->render('error', ['exception' => $exception]);
- }
- }
-
- /**
- * Affiche la page d'accueil.
- */
- public function actionIndex()
- {
- return $this->render('index');
- }
-
- public function actionService()
- {
- return $this->render('service', [
- 'producerDemoAccount' => $this->getProducerManager()->findOneProducerDemoAccount(),
- 'dataProviderPrices' => $this->getDataProviderPrices()
- ]);
- }
-
- public function getDataProviderPrices()
- {
- return new ActiveDataProvider([
- 'query' => $this->getProducerPriceRangeManager()->queryProducerPriceRanges()->query(),
- 'pagination' => [
- 'pageSize' => 100,
- ],
- ]);
- }
-
- /**
- * Liste les producteurs utilisant la plateforme.
- */
- public function actionProducers()
- {
- $dataProviderProducers = new ActiveDataProvider([
- 'query' => $this->getProducerManager()->queryProducersActive()->query(),
- 'pagination' => [
- 'pageSize' => 100,
- ],
- ]);
-
- return $this->render('producers', [
- 'dataProviderProducers' => $dataProviderProducers,
- 'producersArray' => $this->getProducerManager()->findProducersActive()
- ]);
- }
-
- public function actionAbout()
- {
- $aboutFewNumbers = Yii::$app->cache->getOrSet('about_few_numbers7', function () {
- $producerManager = $this->getProducerManager();
- $pointSaleManager = $this->getPointSaleManager();
- $userManager = $this->getUserManager();
- $orderManager = $this->getOrderManager();
-
- $countProducersActive = $producerManager->countProducersActiveWithTurnover();
- $timeSavedByProducersAverage = $producerManager->getTimeSavedByProducersAverage();
- $countProducersWithOptionTimeSaved = $producerManager->countProducersWithTimeSaved();
- $countPointSalesActive = $pointSaleManager->countPointSalesActiveLastThreeMonths();
- $countUsersActive = $userManager->countUsersActiveLastThreeMonths();
- $averageOrdersPerDay = $orderManager->countGlobalUserOrdersAverageLastSevenDays();
- $averageTurnover = $orderManager->getAverageTurnoverLastThreeMonths();
- $resultMatomoApiVisitSummary = json_decode(file_get_contents(Yii::$app->parameterBag->get('matomoApiVisitSummaryUrl')));
- $numberVisitsMonth = $resultMatomoApiVisitSummary->nb_uniq_visitors;
-
- return $this->renderPartial('_about_few_numbers', [
- 'countProducersActive' => $countProducersActive,
- 'countPointSalesActive' => $countPointSalesActive,
- 'countUsersActive' => $countUsersActive,
- 'averageOrdersPerDay' => $averageOrdersPerDay,
- 'averageTurnover' => $averageTurnover,
- 'numberVisitsMonth' => $numberVisitsMonth,
- 'timeSavedByProducersAverage' => $timeSavedByProducersAverage,
- 'countProducersWithOptionTimeSaved' => $countProducersWithOptionTimeSaved
- ]);
- }, 60 * 60 * 24);
-
- $producerManager = $this->getProducerManager();
-
- return $this->render('about', [
- 'countProducers' => $producerManager->countProducersActiveWithTurnover(),
- 'producersWithTestimonials' => $producerManager->findProducersWithTestimonials(),
- 'aboutFewNumbers' => $aboutFewNumbers
- ]);
- }
-
- public function actionSourceCode()
- {
- return $this->render('source_code');
- }
-
- /**
- * Liste les producteurs utilisant la plateforme.
- */
- public function actionAjaxProducers()
- {
- \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
- $producersArray = $this->getProducerManager()->findProducersActive();
- $producersArrayReturn = [];
-
- foreach($producersArray as $producer) {
- $producersArrayReturn[] = [
- 'id' => $producer->id,
- 'name' => Html::encode($producer->name),
- 'type' => Html::encode($producer->type),
- 'address' => Html::encode($producer->postcode.' '.$producer->city),
- 'latitude' => $producer->latitude,
- 'longitude' => $producer->longitude,
- 'link' => $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug])
- ];
- }
-
- return $producersArrayReturn;
- }
-
- /**
- * Affiche la page de connexion et traite le formulaire de connexion.
- */
- public function actionLogin()
- {
- if (!\Yii::$app->user->isGuest) {
- return \Yii::$app->getResponse()->redirect(['site/index']);
- }
-
- $model = new LoginForm();
- if ($model->load(Yii::$app->request->post()) && $model->login()) {
- $returnUrl = \Yii::$app->request->get('return_url');
-
- if ($returnUrl) {
- return $this->redirect($returnUrl);
- }
- else {
- $userProducerArray = $this->getUserProducerManager()->findUserProducersByUser(GlobalParam::getCurrentUser());
- if ($userProducerArray
- && is_array($userProducerArray)
- && count($userProducerArray) == 1) {
-
-
- $urlRedirect = $this->getUrlManagerProducer()
- ->createAbsoluteUrl([
- 'site/index',
- 'slug_producer' => $userProducerArray[0]->producer->slug
- ]);
-
- return $this->redirect($urlRedirect);
- }
- else {
- return $this->goBack();
- }
- }
- } else {
- return $this->render('@frontend/views/site/login', [
- 'model' => $model,
- ]);
- }
- }
-
- /**
- * Déconnecte l'utilisateur.
- */
- public function actionLogout()
- {
- \Yii::$app->user->logout();
-
- return $this->goHome();
- }
-
- /**
- * Affiche la page de contact et traite le formulaire s'il est soumis.
- */
- public function actionContact()
- {
- $model = new ContactForm();
- $messageSent = false;
- if ($model->load(Yii::$app->request->post()) && $model->validate()) {
- $model->sendEmail(Yii::$app->parameterBag->get('adminEmail'));
- $messageSent = true;
- }
-
- return $this->render('contact', [
- 'model' => $model,
- 'messageSent' => $messageSent,
- ]);
- }
-
- /**
- * Affiche la page d'inscription et traite son formulaire.
- */
- public function actionSignup()
- {
- $model = new SignupForm();
- $producerManager = $this->getProducerManager();
-
- if ($model->load(Yii::$app->request->post())) {
- $user = $model->signup();
-
- if ($user && Yii::$app->getUser()->login($user)) {
- if ($model->isProducer()) {
- $this->redirect(['site/signup-confirm']);
- }
- else {
- $producer = $producerManager->findOneProducerById($model->id_producer);
- if ($producer) {
- $this->redirect(['site/signup-confirm', 'idProducerRedirect' => $producer->id]);
- }
- else {
- $this->redirect(['site/index']);
- }
- }
- }
- }
-
- // Liste des producteurs disponibles
- $producersArray = $producerManager->populateProducerDropdown();
- $dataProducers = $producersArray['data'];
- $optionsProducers = $producersArray['options'];
-
- return $this->render('signup', [
- 'model' => $model,
- 'dataProducers' => $dataProducers,
- 'dataProviderPrices' => $this->getDataProviderPrices(),
- 'optionsProducers' => $optionsProducers,
- ]);
- }
-
- public function actionSignupConfirm($idProducerRedirect = null)
- {
- $producerManager = $this->getProducerManager();
- $user = $this->getUserCurrent();
- $producerRedirect = $idProducerRedirect ? $producerManager->findOneProducerById($idProducerRedirect) : null ;
-
- if(!$user) {
- throw new NotFoundHttpException('Page introuvable');
- }
-
- return $this->render('signup_confirm', [
- 'user' => $user,
- 'producerRedirect' => $producerRedirect
- ]);
- }
-
- /**
- * Affiche la page de demande de nouveau mot de passe.
- * Traitement du formulaire.
- */
- public function actionRequestPasswordReset()
- {
- $model = new PasswordResetRequestForm();
-
- if ($model->load(Yii::$app->request->post()) && $model->validate()) {
- if ($model->sendEmail()) {
- $this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe
- vient d\'être envoyé sur votre boîte mail.');
-
- return $this->goHome();
- }
- else {
- $this->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
- }
- }
-
- return $this->render('requestPasswordResetToken', [
- 'model' => $model,
- ]);
- }
-
- /**
- * Met à jour le mot de passe de l'utilisateur.
- */
- public function actionResetPassword($token)
- {
- try {
- $model = new ResetPasswordForm($token);
- } catch (InvalidParamException $e) {
- throw new BadRequestHttpException($e->getMessage());
- }
-
- if ($model->load($this->getRequest()->post())
- && $model->validate()
- && $model->resetPassword()) {
-
- $this->setFlash('success', 'Votre nouveau mot de passe vient d\'être sauvegardé.');
-
- return $this->goHome();
- }
-
- return $this->render('resetPassword', [
- 'model' => $model,
- ]);
- }
-
- /**
- * Affiche le formulaire de demande de code pour accéder à certains producteurs.
- */
- public function actionProducerCode(int $id)
- {
- $producerManager = $this->getProducerManager();
- $producer = $producerManager->findOneProducerById($id);
-
- if (!$producer) {
- throw new \yii\web\HttpException(404, 'Producteur introuvable');
- }
-
- $producerCodeForm = new ProducerCodeForm();
- $producerCodeForm->id_producer = $id;
-
- if ($producerCodeForm->load($this->getRequest()->post())
- && $producerCodeForm->validate()) {
-
- $this->getLogic()->setProducerContext($producer);
- $producerManager->addUser(GlobalParam::getCurrentUser(), $producer);
-
- $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
- }
-
- return $this->render('producer_code', [
- 'producer' => $producer,
- 'producerCodeForm' => $producerCodeForm,
- ]);
- }
-
- /**
- * Affiche la page de connexion / inscription pour accéder notamment au
- * formulaire de commande des producteurs.
- */
- public function actionProducer(int $id)
- {
- $loginForm = new LoginForm();
- $signupForm = new SignupForm();
- $producerManager = $this->getProducerManager();
- $producer = $producerManager->findOneProducerById($id);
- $this->getLogic()->setProducerContext($producer);
- $loginForm->id_producer = $id;
- $signupForm->id_producer = $id;
- $signupForm->option_user_producer = 'user';
- $returnUrl = $this->getRequest()->get('returnUrl', $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
-
- if (Yii::$app->user->isGuest) {
- if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) {
- if (!strlen($producer->code)) {
- $producerManager->addUser(GlobalParam::getCurrentUser(), $producer);
- }
-
- $this->redirect($returnUrl);
- }
-
- if ($signupForm->load($this->getRequest()->post())
- && ($user = $signupForm->signup())
- && Yii::$app->user->login($user)) {
-
- $this->redirect($returnUrl);
- }
- }
- else {
- $this->redirect($returnUrl);
- }
-
- return $this->render('producer', [
- 'loginForm' => $loginForm,
- 'signupForm' => $signupForm,
- 'producer' => $producer,
- ]);
- }
-
- /**
- * Indique à l'utilisateur que l'espace d'un producteur est hors ligne.
- */
- public function actionProducerOffline(int $id)
- {
- return $this->render('producer_offline', [
- 'producer' => $this->getProducerManager()->findOneProducerById($id),
- ]);
- }
-
- public function actionOpinion()
- {
- $opinionFormModel = new OpinionForm();
- $opinionSent = false;
- if ($opinionFormModel->load(Yii::$app->request->post()) && $opinionFormModel->validate()) {
- $this->getOpinionManager()->sendOpinionEmailAdmin($opinionFormModel, $this->getUserCurrent());
- $opinionSent = true;
- }
-
- return $this->render('opinion', [
- 'model' => $opinionFormModel,
- 'opinionSent' => $opinionSent
- ]);
- }
-
- /**
- * Affiche les mentions légales.
- */
- public function actionMentions()
- {
- return $this->render('mentions');
- }
-
- /**
- * Affiche les conditions générale de service.
- */
- public function actionCgv()
- {
- return $this->render('cgv');
- }
-
- /**
- * Affiche les précisions concernant l'utilisation du crédit.
- */
- public function actionCredit()
- {
- return $this->render('credit');
- }
- }
|