Completed
Push — master ( 0826f5...8a4d66 )
by Jan
03:23
created

UserController::new()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * part-db version 0.1
4
 * Copyright (C) 2005 Christoph Lechner
5
 * http://www.cl-projects.de/.
6
 *
7
 * part-db version 0.2+
8
 * Copyright (C) 2009 K. Jacobs and others (see authors.php)
9
 * http://code.google.com/p/part-db/
10
 *
11
 * Part-DB Version 0.4+
12
 * Copyright (C) 2016 - 2019 Jan Böhmer
13
 * https://github.com/jbtronics
14
 *
15
 * This program is free software; you can redistribute it and/or
16
 * modify it under the terms of the GNU General Public License
17
 * as published by the Free Software Foundation; either version 2
18
 * of the License, or (at your option) any later version.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23
 * GNU General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU General Public License
26
 * along with this program; if not, write to the Free Software
27
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
28
 */
29
30
namespace App\Controller;
31
32
use App\Entity\AttachmentType;
33
use App\Entity\Footprint;
34
use App\Entity\User;
35
use App\Form\BaseEntityAdminForm;
36
use App\Form\UserAdminForm;
37
use App\Form\UserSettingsType;
38
use App\Services\EntityExporter;
39
use App\Services\EntityImporter;
40
use App\Services\StructuralElementRecursionHelper;
41
use Doctrine\ORM\EntityManagerInterface;
42
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
43
use Symfony\Component\Asset\Packages;
44
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
45
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
46
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
47
use Symfony\Component\HttpFoundation\Request;
48
use Symfony\Component\HttpFoundation\Response;
49
use Symfony\Component\Routing\Annotation\Route;
50
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
51
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
52
use Symfony\Component\Serializer\SerializerInterface;
53
use Symfony\Component\Validator\Constraints\Length;
54
55
/**
56
 * @Route("/user")
57
 * Class UserController
58
 * @package App\Controller
59
 */
60
class UserController extends AdminPages\BaseAdminController
61
{
62
63
    protected $entity_class = User::class;
64
    protected $twig_template = 'AdminPages/UserAdmin.html.twig';
65
    protected $form_class = UserAdminForm::class;
66
    protected $route_base = "user";
67
68
69
    /**
70
     * @Route("/{id}/edit", requirements={"id"="\d+"}, name="user_edit")
71
     * @Route("/{id}/", requirements={"id"="\d+"})
72
     */
73
    public function edit(User $entity, Request $request, EntityManagerInterface $em)
74
    {
75
        return $this->_edit($entity, $request, $em);
76
    }
77
78
    /**
79
     * @Route("/new", name="user_new")
80
     * @Route("/")
81
     *
82
     * @return \Symfony\Component\HttpFoundation\Response
83
     */
84
    public function new(Request $request, EntityManagerInterface $em, EntityImporter $importer)
85
    {
86
        return $this->_new($request, $em, $importer);
87
    }
88
89
    /**
90
     * @Route("/{id}", name="user_delete", methods={"DELETE"})
91
     */
92
    public function delete(Request $request, User $entity, StructuralElementRecursionHelper $recursionHelper)
93
    {
94
        return $this->_delete($request, $entity, $recursionHelper);
95
    }
96
97
    /**
98
     * @Route("/export", name="user_export_all")
99
     * @param Request $request
100
     * @param SerializerInterface $serializer
101
     * @param EntityManagerInterface $em
102
     * @return Response
103
     */
104
    public function exportAll(EntityManagerInterface $em, EntityExporter $exporter, Request $request)
105
    {
106
        return $this->_exportAll($em, $exporter, $request);
107
    }
108
109
    /**
110
     * @Route("/{id}/export", name="user_export")
111
     * @param Request $request
112
     * @param AttachmentType $entity
113
     */
114
    public function exportEntity(User $entity, EntityExporter $exporter, Request $request)
115
    {
116
        return $this->_exportEntity($entity, $exporter, $request);
117
    }
118
119
120
    /**
121
     * @Route("/info", name="user_info_self")
122
     * @Route("/{id}/info")
123
     */
124
    public function userInfo(?User $user, Packages $packages)
125
    {
126
        //If no user id was passed, then we show info about the current user
127
        if (null === $user) {
128
            $user = $this->getUser();
129
        } else {
130
            //Else we must check, if the current user is allowed to access $user
131
            $this->denyAccessUnlessGranted('read', $user);
132
        }
133
134
        if ($this->getParameter('use_gravatar')) {
135
            $avatar = $this->getGravatar($user->getEmail(), 200, 'identicon');
0 ignored issues
show
Bug introduced by
It seems like $user->getEmail() can also be of type null; however, parameter $email of App\Controller\UserController::getGravatar() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

135
            $avatar = $this->getGravatar(/** @scrutinizer ignore-type */ $user->getEmail(), 200, 'identicon');
Loading history...
136
        } else {
137
            $avatar = $packages->getUrl('/img/default_avatar.png');
138
        }
139
140
        return $this->render('Users/user_info.html.twig', [
141
            'user' => $user,
142
            'avatar' => $avatar,
143
        ]);
144
    }
145
146
    /**
147
     * @Route("/settings", name="user_settings")
148
     */
149
    public function userSettings(Request $request, EntityManagerInterface $em, UserPasswordEncoderInterface $passwordEncoder)
150
    {
151
        /**
152
         * @var User
153
         */
154
        $user = $this->getUser();
155
156
        //When user change its settings, he should be logged  in fully.
157
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
158
159
        /***************************
160
         * User settings form
161
         ***************************/
162
163
        $form = $this->createForm(UserSettingsType::class, $user);
164
165
        $form->handleRequest($request);
166
167
        if ($form->isSubmitted() && $form->isValid()) {
168
            $em->persist($user);
169
            $em->flush();
170
            $this->addFlash('success', 'user.settings.saved_flash');
171
        }
172
173
        /*****************************
174
         * Password change form
175
         ****************************/
176
177
        $pw_form = $this->createFormBuilder()
178
            ->add('old_password', PasswordType::class, [
179
                'label' => 'user.settings.pw_old.label',
180
                'constraints' => [new UserPassword()], ]) //This constraint checks, if the current user pw was inputted.
181
            ->add('new_password', RepeatedType::class, [
182
                'type' => PasswordType::class,
183
                'first_options' => ['label' => 'user.settings.pw_new.label'],
184
                'second_options' => ['label' => 'user.settings.pw_confirm.label'],
185
                'invalid_message' => 'password_must_match',
186
                'constraints' => [new Length([
187
                    'min' => 6,
188
                    'max' => 128,
189
                ])],
190
            ])
191
            ->add('submit', SubmitType::class, ['label' => 'save'])
192
            ->getForm();
193
194
        $pw_form->handleRequest($request);
195
196
        //Check if password if everything was correct, then save it to User and DB
197
        if ($pw_form->isSubmitted() && $pw_form->isValid()) {
198
            $password = $passwordEncoder->encodePassword($user, $pw_form['new_password']->getData());
0 ignored issues
show
Bug introduced by
It seems like $user can also be of type null; however, parameter $user of Symfony\Component\Securi...rface::encodePassword() does only seem to accept Symfony\Component\Security\Core\User\UserInterface, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

198
            $password = $passwordEncoder->encodePassword(/** @scrutinizer ignore-type */ $user, $pw_form['new_password']->getData());
Loading history...
199
            $user->setPassword($password);
200
            $em->persist($user);
201
            $em->flush();
202
            $this->addFlash('success', 'user.settings.pw_changed_flash');
203
        }
204
205
        /******************************
206
         * Output both forms
207
         *****************************/
208
209
        return $this->render('Users/user_settings.html.twig', [
210
            'settings_form' => $form->createView(),
211
            'pw_form' => $pw_form->createView(),
212
        ]);
213
    }
214
215
    /**
216
     * Get either a Gravatar URL or complete image tag for a specified email address.
217
     *
218
     * @param string $email The email address
219
     * @param string $s     Size in pixels, defaults to 80px [ 1 - 2048 ]
220
     * @param string $d     Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
221
     * @param string $r     Maximum rating (inclusive) [ g | pg | r | x ]
222
     * @param bool   $img   True to return a complete IMG tag False for just the URL
223
     * @param array  $atts  Optional, additional key/value attributes to include in the IMG tag
224
     *
225
     * @return string containing either just a URL or a complete image tag
226
     * @source https://gravatar.com/site/implement/images/php/
227
     */
228
    public function getGravatar(string $email, int $s = 80, string $d = 'mm', string $r = 'g', bool $img = false, array $atts = array())
229
    {
230
        $url = 'https://www.gravatar.com/avatar/';
231
        $url .= md5(strtolower(trim($email)));
232
        $url .= "?s=$s&d=$d&r=$r";
233
        if ($img) {
234
            $url = '<img src="'.$url.'"';
235
            foreach ($atts as $key => $val) {
236
                $url .= ' '.$key.'="'.$val.'"';
237
            }
238
            $url .= ' />';
239
        }
240
241
        return $url;
242
    }
243
}
244